title: Multiply all numbers in a string

text:
# Question
Title: Multiply all numbers in a string
# Winner: Chilemagic, a massive 21 bytes!

You may continue to submit your answer, however you can no longer win. Original post kept:

---

Your goal is to find all numbers in a string, and multiply each one individually by a value input by the user

* You will not need to worry about decimals
* The user will input a number and a string
* The user must type the number and string at some point, **however** the method the program reads it does not matter. It can be with stdin, reading a text file, etc, however the user must press the 9 button on their keyboard (for example) at some point
* Anything that can compile and run is acceptable

# Example:

Sentence input: This 1 is22a 3352sentence 50

Number input: 3

Output: This 3 is66a 10056sentence 150

---

* This contest ends on September 6th, 2014 (7 days from posting).
* This is a , so the shortest code wins

# Answer
> 24 votes
## Update - Perl - 17

```
s/\d+/$&*$^I/ge

```

15 characters + 2 for `-i` and `-p` flags.

We can use the `-i` flag to input a file extension, but since we aren't reading any files, we can use it to get the number and it the variable `$^I` will get assigned to it.

Run with:

```
perl -e'print"This 1 is22a 3352sentence 50"' | perl -i3 -pe's/\d+/$&*$^I/ge'

```

## Perl - 21

Updated as per @Dennis's comment.

```
$n=<>;s/\d+/$&*$n/ge

```

Run with `-p` flag.

## Example run:

```
perl -e'print"This 1 is22a 3352sentence 50\n3"' | perl -pe'$n=<>;s/\d+/$&*$n/ge'

```

## Explanation:

`$n=<>;` read in the number

`-p` prints the output

`s/\d+/$&*$n/ge` Read the input with \<\> and search for one or more digits and replace them with the digits times the number. `g` is global, `e` is `eval` the replace potion of the s///. `$&` contains what was matched and it multiplied by the number, `$n`.

You can read more about `s///` in perlop and more about Perl regexes in perlre.

## Another solution:

@F.Hauri pointed out you can also use the `s` switch to assign the `$n` variable to 4. I'm not sure how many characters this counts as but I'll leave it here:

```
perl -spe 's/\d+/$&*$n/ge' -- -n=4 <<<'This 1 is22a 3352sentence 50'

```

# Answer
> 9 votes
# JavaScript (ES6) - ~~48~~ 44 chars

Thanks to @bebe for saving one character. Update: 8/Mar/16, removed another four characters

```
b=(p=prompt)();p(p().replace(/\d+/g,y=>y*b))

```

**Ungolfed**:

```
var sentence = prompt(),
    num = parseInt(prompt(), 10); // base 10

sentence = sentence.replace(/\d+/g, digit => digit * num);

alert(sentence);

```

### 43 chars:

```
(p=prompt)(p(b=p()).replace(/\d+/g,y=>y*b))

```
~~```
b=(p=prompt)();p(p().replace(/\d+/g,y=>y*b))

```~~

Requires number input first and then sentence. Cut one char more here thanks @bebe again!

# Answer
> 7 votes
## Python 2 (79)

```
import re
n=input()
s=input()
print re.sub('\d+',lambda x:`int(x.group())*n`,s)

```

### Sample run

Input:
```
$ python mult.py
3
"This 1 is22a 3352sentence 50"

```
Output:
```
This 3 is66a 10056sentence 150

```

Online demo: http://ideone.com/V6jpyQ

# Answer
> 4 votes
# Python 2 - 126

```
import re
n=input()
s=input()
for i in list(re.finditer('\d+',s))[::-1]:s=s[:i.start()]+`int(i.group())*n`+s[i.end():]
print s

```

First input: integer `n`.

Second input: string `s` (with quotation marks, e.g. `"abc42"`).

# Answer
> 4 votes
# CJam, ~~47~~ ~~33~~ 30 bytes

```
q_A,sNerN%\[_A,s-Ner~](f*]zs1>

```

Reads the number and the string (in that order and separated by a single space) from STDIN.

Try it online.

### Example run

```
$ cjam multiply.cjam <<< '7 N0 R3GUL4R 3XPR35510N5 1N CJ4M M4K3 M3 4 54D P4ND4'
N0 R21GUL28R 21XPR248570N35 7N CJ28M M28K21 M21 28 378D P28ND28

```

### How it works

```
q                                 " Read from STDIN (“Q”) and push a second copy.         ";
  A,s                             " Push “0123456789” (thanks, @aditsu).                  ";
 _   NerN%                        " Replace digits with linefeeds and split at linefeeds. ";
          \ _A,s-Ner              " Replace non-digits with linefeeds.                    ";
                    ~             " Evaluate the resulting string.                        ";
           [         ]            " Collect the results in an array.                      ";
                      (f*         " Multiply all other integers by the first.             ";
                         ]z       " Interleave the elements of both arrays.               ";
                           s1>    " Flatten the result and discard the leading space.     ";

```

# Answer
> 4 votes
# Bash+coreutils, 38 bytes

```
eval echo `sed "s/[0-9]\+/$\[$1*&]/g"`

```

Reads input string from STDIN and multiplier as a command-line parameter.

### Output:

```
$ ./multstr.sh 3 <<< "This 1 is22a 3352sentence 50"
This 3 is66a 10056sentence 150
$

```

# Answer
> 3 votes
# C# in LINQPad, 124

Straightforward. Please use **CTRL+2** in LINQPad (Language: C# Statements).

```
var s=Console.ReadLine();var k=int.Parse(Console.ReadLine());new Regex("\\d+").Replace(s,t=>""+int.Parse(t.Value)*k).Dump();

```

If the multiplier is given as first input parameter, it can be done in 116 characters:

```
var k=int.Parse(Console.ReadLine());new Regex("\\d+").Replace(Console.ReadLine(),t=>""+int.Parse(t.Value)*k).Dump();

```

---

**EDIT:**

Thanks to Abbas's comment below, this can even be golfed more by using Regex static method, rather than instantiate it:

```
var k=int.Parse(Console.ReadLine());Regex.Replace(Console.ReadLine(),"\\d+",t=>""+int.Parse(t.Value)*k).Dump();

```

# Answer
> 2 votes
# Mathematica ~~71~~ 61

With 10 chars saved thanks to Martin Buttner.

Spaces in code are for readability.

`f` is a function in which `s` is the input string and `n` is the number to multiply discovered string numbers by.

```
 StringReplace[#, a : DigitCharacter .. :> ToString[#2 FromDigits@a]] &

```

---

## Examples

```
 s="This 1 is22a 3352sentence 50"

```

Integer

```
StringReplace[#, a : DigitCharacter .. :> ToString[#2 FromDigits@a]] &@@{s, 3}

```

> "This 3 is66a 10056sentence 150"

---

Rational number

```
StringReplace[#, a : DigitCharacter .. :> ToString[#2 FromDigits@a]] &@@{s, -7.13}

```

> "This -7.13 is-156.86a -23899.8sentence -356.5"

---

Complex Number

```
StringReplace[#, a : DigitCharacter .. :> ToString[#2 FromDigits@a]] &@@{s, -5 + 3 I}

```

> "This -5 + 3 I is-110 + 66 Ia -16760 + 10056 Isentence -250 + 150 I"

# Answer
> 2 votes
# Cobra - 171

```
use System.Text.RegularExpressions
class P
    def main
        a=int.parse(Console.readLine?'')
        print Regex.replace(Console.readLine,'\d+',do(m as Match)="[int.parse('[m]')*a]")

```

# Answer
> 2 votes
# Python 3 - 141

I don't think I can golf this any more...

```
import re
n=input()
f=input()
o=''
p=0
for i in re.finditer('\d+',f):o+=f[p:i.start()]+str(int(i.group())*int(n));p=i.end()
o+=f[p:]
print(o)

```

Example:

```
3     # This is input
h3110 # This is input
h9330 # This is output

10
hello100 hello100
hello1000 hello1000

```

# Answer
> 2 votes
## Ruby 40

```
a,b=$*
p a.gsub(/\d+/){|s|s.to_i*b.to_i}

```

Input from stdin.

Example run:

```
$ ruby mult.rb "This 1 is22a 3352sentence 50" 3
"This 3 is66a 10056sentence 150"

```

Online demo: http://ideone.com/4BiHC8

# Answer
> 2 votes
# Lua: ~~73~~ 69 characters

```
r=io.read
s=r()n=r()s=s:gsub("%d+",function(m)return m*n end)print(s)

```

Sample run:

```
bash-4.3$ lua -e 'r=io.read;s=r()n=r()s=s:gsub("%d+",function(m)return m*n end)print(s)' <<< $'This 1 is22a 3352sentence 50\n3'
This 3 is66a 10056sentence 150

```

# Answer
> 2 votes
## JavaScript, ES6, 43 characters

This is my first attempt at golfing!

```
(p=prompt)(p(n=p()).replace(/\d+/g,y=>y*n))

```

Run this in latest Firefox's Console. The first input is the number and the second input is the string from which the numbers are to be multiplied with the first input number.

The final prompt lists the output.

# Answer
> 2 votes
# Vyxal `s`, 8 bytes

```
⁽±Ḋƛ⌊⁰*∨

```

Try it Online!

# Answer
> 1 votes
# Perl - 48 chars

```
$n=<>;print/\d/?$_*$n:$_ for(<>=~/(\d+)|(\D+)/g)

```

Read a number on the first line, then read a sentence and break it into chunks of either digits or non digits. Print the non digits as they are, and the numbers get multiplied.

# Answer
> 1 votes
# CJam - 35

```
li:X;lN+{_sA,s-,{])\_!!{iX*}*oo}*}/

```

Try it at http://cjam.aditsu.net/

Sample input:

```
7
CJ4M W1LL H4V3 R3GUL4R 3XPR35510N5 L4T3R

```

Sample output:

```
CJ28M W7LL H28V21 R21GUL28R 21XPR248570N35 L28T21R

```

**Explanation:**

The program goes through each character, collecting the digits on the stack, and for each non-digit it first prints the collected number (if any) multiplied by the numeric input, then prints the character.

`li:X;` reads the numeric input and stores it in X
`lN+` reads the string and appends a newline (it helps with trailing numbers)
`{…}/` for each character in the string
\- `_s` copies the character and converts to string
\- `A,s-,` removes all the digits and counts the remaining characters; the result will be 0 if the character was a digit or 1 if not
\- `{…}*` executes the block if the count was 1 (i.e. non-digit); for digits it does nothing, so they remain on the stack
-- `]` collects the characters from the stack into an array (i.e. a string); the characters are any digits from the previous iterations, plus the current character
-- `)\` separates the last item (the current character) and moves it before the (remaining) string
-- `_!!` copies the string and converts it to a boolean value - 0 if empty, 1 if not
-- `{…}*` executes the block if the string was not empty, i.e. we had some digits before the current non-digit character
--- `iX*` converts the string to integer and multiplies by X
-- `o` prints the top of the stack - either the multiplied number or the empty string if we didn't have a number
-- `o` (the 2nd one) prints the new top of the stack - the current non-digit character

# Answer
> 1 votes
# J - 63 char

Program reads in the number, and then the sentence.

```
;(*&.".&(1!:1]1)^:(0{i)(<@);.1~1,2~:/\i=.e.&'0123456789')1!:1]1

```

Explained by explosion:

```
;(*&.".&(1!:1]1)^:(0{i)(<@);.1~1,2~:/\i=.e.&'0123456789')1!:1]1
                                                         1!:1]1  NB. read sentence
                                         e.&'0123456789'         NB. is digit? bool vector
                                      i=.                        NB. save to i
                                 2  /\                           NB. between adjacent chars:
                                  ~:                             NB.  true if not equal
                               1,                                NB. pad to sentence length
 (                         ;.1~                         )        NB. cut the sentence
                ^:(0{i)                                          NB. if cut is digits:
  *&.".                                                          NB.  multiply as number
       &(1!:1]1)                                                 NB.  with user input
;                                                                NB. rejoin sentence

```

If we get to use J's PCRE library and make the sentence come first, we can knock this down to **54 characters**:

```
;_2(,*&.".&(1!:1]1)&.>)/\'\d+'(rxmatches rxcut])1!:1]1

```

Explained by explosion:

```
                                                1!:1]1  NB. read in sentence
                         '\d+'(rxmatches       )        NB. all /\d+/ matches
                              (          rxcut])        NB. cut by those matches
 _2                     \                               NB. on each nonmatch-match pair:
   (               &.>)/                                NB.  take the match
     *&.".                                              NB.  multiply as number
          &(1!:1]1)                                     NB.  by user input
   (,                 )                                 NB.  prepend nonmatch
;                                                       NB. rejoin sentence

```

J is bad at this, what can I say. It's a inconvenient because J's so nonimperative.

Some examples:

```
   ;(*&.".&(1!:1]1)^:(0{i)(<@);.1~1,2~:/\i=.e.&'0123456789')1!:1]1
3
This 1 is22a 3352sentence 50
This 3 is66a 10056sentence 150
   ;(*&.".&(1!:1]1)^:(0{i)(<@);.1~1,2~:/\i=.e.&'0123456789')1!:1]1
100
N0 R3GUL4R 3XPR35510N5 1N J M4K35 M3 54D ALS0
N0 R300GUL400R 300XPR3551000N500 100N J M400K3500 M300 5400D ALS0
   0!:0 <'system\main\regex.ijs'  NB. this is usually preloaded by J on startup anyway
   ;_2(,*&.".&(1!:1]1)&.>)/\'\d+'(rxmatches rxcut])1!:1]1
TH4T'5 M4RG1N411Y B3TT3R
0
TH0T'0 M0RG0N0Y B0TT0R

```

# Answer
> 1 votes
# Haskell (161)

## Golfed

```
main=do{n<-getLine;l<-getContents;let{g c(t,s)|c>'/'&&c<':'=(c:t,s)|t/=""=([],c:(show.(*(read n)).read$t)++s)|True=(t,c:s)};putStr.tail.snd.foldr g("","")$' ':l}

```

## Ungolfed

```
modify :: (Show a, Read a) => (a -> a) -> String -> String
modify f = show . f . read

main=do
  number <- fmap read $ getLine    -- get number
  l <- getContents                 -- get input

  -- if the current character is a digit, add it to the digits
  -- if the current character isn't a digit, and we have collected
  --    some digits, modify them and add them to the string
  -- otherwise add the current characters to the string

  let go current (digits , string)
        | current `elem` ['0'..'9'] = (current : digits, string)
        | not (null digits)         = ([], current:(modify (*number) digits) ++ string)
        | otherwise                 = (digits, current:string)

  -- since the result of `go` is a pair, take the second value,
  -- remove the head (it's a space, in order to convert digits at the start)
  -- and print it
  putStr . tail . snd . foldr go ("","")$' ':l

```

Unfortunately, Haskell doesn't have a Regex library in its Prelude.

# Answer
> 1 votes
# flex(-lexer) (94 89 characters)

```
 int m;main(c,v)char**v;{m=atoi(*++v);yylex();}
%%
[0-9]+ {printf("%d",m*atoi(yytext));}

```

Ungolfed version which doesn't segfault if you forget the command-line argument (not much longer):

```
%{
#define YY_DECL int y(int m)
%}
%option noyywrap noinput nounput
%%
[0-9]+ {printf("%d",m*atoi(yytext));}
%%
int main(int argc, char** argv) {
  return (argc > 1) ? y(atoi(argv[1])) : 1;
}

```

Compile with:

```
flex -o m.c m.l
cc -o m m.c -lfl

```

or:

```
flex --noyywrap -o m.c m.l
cc -o m m.c

```

Eg:

```
$ ./m 163
This 1 is22a 3352sentence 50
This 163 is3586a 546376sentence 8150

```

# Answer
> 1 votes
# `Groovy` \- 124

```
Scanner s=new Scanner(System.in)
def x=s.nextLine()
def n=s.nextInt()
x=x.replaceAll(/\d+/,{it->it.toInteger()*n})
println x

```

*Click on the title to see the runnable example*

# Examples Tried:

> This 1 is22a 3352sentence 50
> 3
> This 3 is66a 10056sentence 150

---

> This 1 is22a 3352sentence 50
> 42
> This 42 is924a 140784sentence 2100

# Answer
> 1 votes
# Japt, 9 bytes

```
r"%d+"_*V

```

Try it

# Answer
> 0 votes
# GNU Awk: 86 characters

```
s{n=split(s RS,a,/[^0-9]+/,d);while(++i<n)printf"%s%s",a[i]==""?"":a[i]*$1,d[i]}{s=$0}

```

Sample run:

```
bash-4.3$ awk 's{n=split(s RS,a,/[^0-9]+/,d);while(++i<n)printf"%s%s",a[i]==""?"":a[i]*$1,d[i]}{s=$0}' <<< $'This 1 is22a 3352sentence 50\n3'
This 3 is66a 10056sentence 150

```

# Answer
> 0 votes
# PHP - 75/115 68/109

Two versions, newer php versions can do this:

```
echo preg_replace_callback("/\d+/",function($m){return$m[0]*$f;},$s);

```

Older php versions: I did not count the newline, added those for readability.

```
function a($s){echo preg_replace_callback("/\d+/",b,$s);}
function b($i){global$f;return$i[0]*$f;}
a($s,$f);

```

Example input+output

```
$s = "ab11cd22"; // string
$f =  3; // -> output: ab36cd69
$f = -2; // -> output: ab-24cd-46

```

Kinda difficult, the words 'function' and 'preg\_replace\_callback' take up a lot of chars.
The space after `global` and `return` arent needed if followed by a $var (-2 chars)

# Answer
> 0 votes
## C (~~142~~ 134 characters)

```
main(a,b)char**b;{char*c=b++[2],*d="0123456789";for(;*c;c+=strspn(c
,d))write(1,c,a=strcspn(c,d)),dprintf(1,"%d",atoi(*b)*atoi(c+=a));}

```

Newline inserted for enhanced legibility. Pass the factor as the first, the string as the second command line option. This implementation requires the `dprintf` function which is part of POSIX.1 2008 and might not be available on Windows. Here is the unminified source:

```
/*
 * Multiply all numbers in a string by a number.
 * http://codegolf.stackexchange.com/q/37110/134
 * Solution by user FUZxxl
 */

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>

extern int
main(int count, char **argv)
{
    char *str = argv++[2], *digits = "0123456789";

    while (*str) {          /* as long as we have not reached the end */
        count = strcspn(str, digits);
        write(1, str, count);

        dprintf(1, "%d", atoi(*argv) * atoi(str += count));
        str += strspn(str, digits);
    }
}

```

## Improvements

* 142 → 134: Use `strspn` and `strcspn` instead of looping over the string.

# Answer
> 0 votes
## Clojure - 141 140 128 chars

I'm a Clojure newbie, but FWIW:

```
(let[[a b]*command-line-args*](println ((fn[s n](clojure.string/replace s #"\d+"#(str(*(read-string %)(read-string n)))))a b)))

```

Sample run:

```
bash$ java -jar clojure-1.6.0.jar multstr.clj "This 1 is22a 3352sentence 50" 3
This 3 is66a 10056sentence 150

```

Ungolfed (ugly but hopefully somewhat easier to read):

```
(let [[a b] *command-line-args*]
    (println ( (fn [s n]
                    (clojure.string/replace
                        s
                        #"\d+"
                        #(str (* (read-string %) (read-string n)))))
                    a b)))

```

# Answer
> 0 votes
# Two answer: +

## Pure bash (~262)

First, there is an *not so short* **pure** bash version (no fork, no external binaries)!

```
mn () {
    if [[ $1 =~ ^(.*[^0-9]|)([0-9]+)([^0-9].*|)$ ]]; then
        local num=${BASH_REMATCH[2]} rhs="${BASH_REMATCH[3]}";
        mn "${BASH_REMATCH[1]}" ${2:-3} l;
        echo -n "$[num*${2:-3}]$rhs";
    else
        echo -n "$1";
    fi;
    [ "$3" ] || echo
}

```

Let's show:

```
mn "This 1 is22a 3352sentence 50" 42
This 42 is924a 140784sentence 2100

```

(Which is a totally improbable sentence)

## Perl little obfuscated (for fun only)

This version (based on @Chilemagic's answer) is not shorter, but designed as a ***totem*** script:

> `cat <<eof >mn.pl`

```
#!/usr/bin/perl          -sp
                      eval eval'"'
                      .('['^'(')
           .'/\\'.'\\'.('`'|'$').'+'.'/\\$\&'
                        .'*\\$'
                      .('`'|'.').'/'
                      .('`'|"'")
                      .('`'|'%').'"'

```

> `eof
>  chmod +x mn.pl`

Sample run:

```
./mn.pl -n=2 <<<$'This 1 is22a 3352sentence 50\n21.'
This 2 is44a 6704sentence 100
42.

```

# Answer
> 0 votes
# Python 89

```
import re,sys
j,n,s=sys.argv
print re.sub('(\d+)',lambda m:str(int(m.group())*int(n)),s)

```

eg:

```
# python numberstring.py 3 '1shoop da2 w007p!'
3shoop da6 w21p!

```

# Answer
> 0 votes
# Rebol - 117

```
n: do input d: charset"0123456789"parse s: input[any[b: some d e:(e: insert b n * do take/part b e):e | skip]]print s

```

Ungolfed:

```
n: do input
d: charset "0123456789"

parse s: input [
    any [
        b: some d e: (e: insert b n * do take/part b e) :e
        | skip
    ]
]

print s

```

# Answer
> 0 votes
## Python - 142

```
import re
s=raw_input()
i=int(raw_input())
print ''.join([x[0]+str(int(x[1])*i) for x in filter(None,re.findall('(\D*)(\d*)',s)) if x[0]!=''])

```

# Answer
> 0 votes
## Java 218

Someone had to do java. The input string are 2 token on the command line.

java M 'This 1 is22a 3352sentence 50' 3

```
public class M{
    public static void main(String[]a) {
        int m=new Integer(a[1]),n=0,b=0;
        String s="";
        for(char c:a[0].toCharArray()){
            if(c<48|c>57)s=b>(b=0)?s+m*n+c:s+c;
            else n=b*n+c-38-(b=10);
        }
        System.out.println(b>0?s+m*n:s);
    }
}

```

# Answer
> 0 votes
# Haskell, 70

too bad I'm too late IMHO this is pretty good for this specific question and language. the other Haskell solution here is 161 characters..

```
[]%n=""
s%n=f s(reads s)n
f _((a,b):_)n=show(a*n)++b%n
f(x:s)_ n=x:s%n

```

this works by using the `reads` function which parses a string Partially. for example, `reads "34abc" = [(34, "abc")]`. this obviously makes it perfect for this challenge.

usage:

```
*Main> " This 1 is22a 3352sentence 50"%3
" This3 is66a10056sentence150"

```

---
Tags: code-golf
---


title: Difference of three input integers

text:
# Question
Title: Difference of three input integers
Implement a function diff that takes as input three integers x, y, and z. It should return whether subtracting one of these numbers from another gives the third.

```
Test cases:
diff(5, 3, 2) yields True because 5 - 3 = 2
diff(2, 3, 5) yields True because 5 - 3 = 2
diff(2, 5, 3) yields True because 5 - 3 = 2
diff(-2, 3, 5) yields True because 3 - 5 is -2
diff(-5, -3, -2) # -5 - -2 is -3
diff(2, 3, -5) yields False
diff(10, 6, 4) yields True because 10 - 6 = 4
diff(10, 6, 3) yields False

```

You don't have to name the function, you may implement default input methods the examples above are not a strict guideline.

# Answer
# Jelly, ~~5~~ 3 bytes

Thanks to @Sp3000 for saving two bytes!

Code, uses quite the same algorithm as @xnor's great answer:

```
SfḤ

```

Explanation:

```
S     # Sum of the argument list
  Ḥ   # Double the list
 f    # Filter, remove everything that isn't equal to the sum of the list

```

This gives `[]` as falsy, and anything else as truthy.

Try it online!
> 14 votes

# Answer
## Python 3, 21 bytes

```
lambda*l:sum(l)/2in l

```

If two numbers add to the other, the sum of all three will be double that other number, so half the sum will be an element of the list. Python 3 is needed to avoid floor-division, unless the numbers are given like `3.0` rather than `3`.
> 51 votes

# Answer
## ES6, 31 bytes

```
(a,b,c)=>a+b==c|b+c==a|c+a==b

```

Add 5 bytes if you need to name the function `diff`.

Edit: Saved 2 bytes thanks to @Alex L.
> 7 votes

# Answer
# JavaScript ES6, ~~38~~ ~~34~~ 33 bytes

```
x=>x.some(a=>2*a==x[0]+x[1]+x[2])

```

Very simple anonymous function, and borrows from the Python answer. Takes input `x` as an array; returns `true` or `false`. Bytes shaved to Molarmanful and jrich

A 38-byte program, taking each number as an argument:

```
(a,b,c)=>[a,b,c].some(t=>t==(a+b+c)/2)

```
> 4 votes

# Answer
# Oracle SQL 11.2, 49 bytes

```
SELECT 1 FROM DUAL WHERE(:1+:2+:3)/2IN(:1,:2,:3);

```

Rewrite of @xnor solution, kudos to him.
> 3 votes

# Answer
# Perl 6, ~~20~~ 19 bytes

I have two functions equal in byte count, so I'll put both. Appreciate whichever tickles your fancy.

```
{@_∋@_.sum div 2}
{@_∋+~(@_.sum/2)}

```

Usage: assign either one to a variable from which you can call it.
EDIT: Thanks @b2gills for the byte reduction
> 3 votes

# Answer
# J, 6 bytes

```
+/e.+:

```

Try it with J.js.

### How it works

```
+/e.+:    Monadic verb. Argument: A
    +:    Double the elements of A.
+/        Compute the sum of the elements of A.
  e.      Test for membership.

```
> 3 votes

# Answer
# APL, ~~8~~ 5 bytes

```
+/∊+⍨

```

This is a monadic function train that accepts an array and returns a boolean (0/1 in APL). It uses the same algorithm as xnor's Python 3 answer.

Explanation:

```
   +⍨  ⍝ Double the input (+⍨x is the same as x+x)
  ∊    ⍝ Test the membership of
+/     ⍝ The sum of the input

```

Try it online

Saved 3 bytes thanks to Dennis!
> 3 votes

# Answer
# DUP, 31 chars / 39 bytes

```
[2ø2ø2ø++2/\%3ø^=3ø2ø=3ø3ø=||.]

```

`Try it here!`

My first DUP submission ever! *Unicode is your oyster.*

It's an anonymous function/lambda. Usage:

```
5 3 2[2ø2ø2ø++2/\%3ø^=3ø2ø=3ø3ø=||.]!

```

# Explanation

```
[                               {start lambda}
 2ø2ø2ø                         {duplicate 3 inputnums}
       ++                       {push sum(3 popped stack items)}
         2/\%                   {push (popped stack item)/2}
             3ø^=3ø2ø=3ø3ø=     {for all 3 inputs, -1 if inputnum=sum/2; else 0}
                           ||   {check if any of the 3 resulting values are truthy}
                             .  {output top of stack (boolean value)}
                              ] {end lambda}

```
> 3 votes

# Answer
## Java 7, 81

```
boolean d(int[]a){int s=0,t=1;for(int b:a)s+=b;for(int b:a)t*=2*b-s;return t==0;}

```
> 3 votes

# Answer
# Java 8 (lambda function), 29 bytes

```
// Lambda Signature: (int, int, int) -> boolean

(a,b,c)->a+b==c|a+c==b|b+c==a

```

Java code golf solutions are usually only short when the program does not have to be a fully functional program. (\*cough cough\* class declaration, main method)
> 3 votes

# Answer
# Pyth, 6 bytes

```
/Q/sQ2

```

Try it online!

Expects input as a list of integers. Outputs 0 if no number can be built by subtracting the other two and \>0 if at least one can.

### Explanation:

Same algorithm as the answer of @xnor

```
/Q/sQ2

   sQ     # Sum all elements in the list
  /  2    # Divide the sum by 2
/Q        # Count Occurences of above number in the list

```
> 2 votes

# Answer
## Perl, 24 + 4 = 28 bytes

```
$^+=$_/2 for@F;$_=$^~~@F

```

Requires `-paX` flags to run, prints `1` as True and nothing as False:

`-X` disables all warnings.

```
$ perl -paXe'$^+=$_/2 for@F;$_=$^~~@F' <<< '5 3 7'
$ perl -paXe'$^+=$_/2 for@F;$_=$^~~@F' <<< '5 3 8'
1

```
> 2 votes

# Answer
# MATL, 5 bytes

Using @xnor's great approach:

```
s2/Gm

```

**Try it online!**

```
s    % implicitly input array of three numbers. Compute their sum
2/   % divide by 2
G    % push input again
m    % ismember function: true if sum divided by 2 equals some element of the input

```

---

**Brute-force approach, 12 bytes**:

```
Y@TT-1h*!s~a

```

**Try it online!**

```
Y@       % input array of three numbers. Matrix with all
         % permutations, each one on a different row
TT-1h    % vector [1,1,-1]
*        % multiply with broadcast
!s       % transpose, sum of each column (former row)
~a       % true if any value is 0

```
> 2 votes

# Answer
# 05AB1E, 4 bytes

```
DO;¢

```

Using 0 as falsy and \> 0 as truthy. Uses CP-1252 encoding.
> 2 votes

# Answer
# Kona 16 chars

```
{((+/x)%2)_in x}

```

Takes a vector from the stack, sums them, divides by 2 and determines if it's in the vector. Returns 1 as truthy and 0 as falsey.

Called via

```
> {((+/x)%2)_in x} [(2;3;5)]
1
> {((+/x)%2)_in x} [(2;3;4)]
0

```
> 2 votes

# Answer
# CJam, 10 ~~12~~ bytes

```
l~:d_:+2/&

```

2 bytes removed thanks to @MartinBüttner.

This displays a number as truthy result, and no output as falsy result.

**Try it here**

```
l~     e# read line and evaluate. Pushes the array
:d     e# convert array to double
_      e# duplicate
:+     e# fold addition on the array. Computes sum of the array
2/     e# divide sum by 2
&      e# setwise and (intersection)

```
> 2 votes

# Answer
# jq, 17 characters

(Yet another rewrite of xnor's Python 3 answer. Upvotes should go to that one.)

```
contains([add/2])

```

Input: array of 3 integers.

Sample run:

```
bash-4.3$ jq 'contains([add/2])' <<< '[5, 3, 2]'
true

bash-4.3$ jq 'contains([add/2])' <<< '[2, 3, -5]'
false

```

On-line test:

## jq, 18 characters

(17 characters code + 1 character command line option.)

```
contains([add/2])

```

Input: list of 3 integers.

Sample run:

```
bash-4.3$ jq -s 'contains([add/2])' <<< '5 3 2'
true

bash-4.3$ jq -s 'contains([add/2])' <<< '2 3 -5'
false

```
> 2 votes

# Answer
# , 7 chars / 9 bytes

```
ï⒮≔⨭ï/2

```

`Try it here (Firefox only).`

Meh. I'm still finding better ways. It's just @xnor's awesome algorithm.
> 2 votes

# Answer
## Seriously, 6 bytes

```
,;Σ½íu

```

Outputs 0 if false and a positive integer otherwise.
> 2 votes

# Answer
# Mathematica, ~~20~~ 19 bytes

```
MemberQ[2{##},+##]&

```

Works similarly to most of the other answers.
> 2 votes

# Answer
# Haskell, 20 bytes

```
(\l->sum l/2`elem`l)

```

Using xnor's solution.
> 2 votes

# Answer
# , 23 bytes

```
sum(x<-scan())%in%(2*x)

```

Try it online!

Shameless port of xnor's answer.
> 2 votes

# Answer
# Prolog (SWI), 35 bytes

```
\A:-permutation([X,Y,E],A),X-Y=:=E.

```

Try it online!
> 2 votes

# Answer
# Jolf, 6 bytes

Try it here!

```
 hx½ux
_hx    the input array
   ½ux  has half the sum of the array

```

This is xnor's awesome solution to the problem, but in Jolf.
> 1 votes

# Answer
# Pylons, 8

Yet another implementation of xnor's algorithm.

```
i:As2A/_

```

How it works:

```
i    # Get command line input.
:A   # Initialize a constant A.
  s  # Set A to the sum of the stack.
2    # Push 2 to the stack.
A    # Push A to the stack.
/    # Divide A/2
_    # Check if the top of the stack is in the previous elements.
     # Print the stack on quit.

```
> 1 votes

# Answer
# SpecBAS - 36 bytes

Uses xnors formula

```
1 INPUT a,b,c: ?(a+b+c)/2 IN [a,b,c]

```

outputs 1 if true and 0 if false
> 1 votes

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

```
;Oм_O

```

-1 byte by creating a port of *@xnor*'s Python 3 algorithm.

Try it online or verify all test cases.

**Explanation:**

```
·        # Halve every item in the input-array
         #  i.e. [10,6,4] → [5.0,3.0,2.0]
 O       # Sum this array
         #  i.e. [5.0,3.0,2.0] → 10.0
  м_O    # Output 1 if the input-array contain this sum, 0 otherwise
         #  i.e. [10,6,4] and 10.0 → 1

```

I'm pretty sure `м_O` can be shortened, but I'm not sure which command(s) I have to use for it..
> 1 votes

---
Tags: code-golf, arithmetic
---


title: Increment every number in a string

text:
# Question
Title: Increment every number in a string
Given a string containing decimal numbers:

`teststring134this 123test string54 100`

increment every number in this string by one to give the new string

`teststring135this 124test string55 101`.

The string can be provided as:

* a command line argument
* STDIN
* a hard-coded variable or function argument

Cover all possible positions for a number:

* as a prefix for a word; `123test``124test`
* as a suffix for a word; `test123``test124`
* inside a word; `te123st``te124st`
* alone `test 123 test``test 124 test`

Here's a non-golfed solution in Python:

```
NUMBERS = '0123456789'

def increment(s):
    out = ''

    number = ''
    for c in s:
        if c in NUMBERS:
            number += c
        else:
            if number != '':
                out += str(int(number) + 1)
                number = ''
            out += c

    if number != '':
        out += str(int(number) + 1)
        number = ''

    return out

print "\"%s\"" % (increment('teststring134this 123test string54 100'))

```

This is a `code-golf` question, shortest code wins.

# Answer
# Perl, 14 bytes

```
s/\d+/$&+1/ge

```

Requires the `-p` switch, which I have counted as one byte.

### Example run

```
$ perl -p <(echo 's/\d+/$&+1/ge') <<< 'teststring134this 123test string54 100'
teststring135this 124test string55 101

```
> 23 votes

# Answer
## Ruby, ~~30~~ 24 bytes

```
$><<s.gsub(/\d+/,&:next)

```

Expects the input to be stored in `s`.
> 13 votes

# Answer
# JavaScript (ES6) - 28

```
H=k=>k.replace(/\d+/g,k=>++k)

```

Run by using `H("test 123 234t")`.
> 11 votes

# Answer
# Vim - 13 keystrokes

```
0qqqqq^Al@qq@q

```

Expects the input to be the current line.

Or for finitely many numbers (e.g. 999) in 8 + ceil(log(n)) keystrokes:

```
0qq^Alq999@q

```
> 11 votes

# Answer
# Python 2 - 59

Supply the string as the variable `n`

```
import re;print re.sub('\d+',lambda x:`int(x.group())+1`,n)

```
> 8 votes

# Answer
## Perl, 23

Assumes the input string is assigned to `$_`

```
s/\d+/@{[$&+1]}/g;print

```
> 8 votes

# Answer
# C99 - 86 (GCC 4.9.0 and Visual C++ 2013)

**Edit: Both GCC 4.9.0 (with -std=c99) and Visual C++ 2013 successfully build (with warnings) the same code without the includes. I didn't know you could do that! Thanks for the hint.**

**Edit: It didn't even occur to me that I should write it to the screen on the fly instead of creating the string and then printing it. That makes a huge difference. Thanks Dennis!**

This is using a hard coded string but the contents of the string are not counted towards the total (the ="" is counted).

```
main(i){for(char*q,*s="test123test999test-1test";i=strtol(s,&q,0),*s;q>s?printf("%d",i+1,s=q):putchar(*s++));}

```

Basically it runs through the string one character at a time checking each to see if it is an integer. If it is then it increments the integer and writes it to the output otherwise it copies the current character to the output.

This leaks the hardcoded string because it increments s.
> 6 votes

# Answer
## J (20)

Expects the input to be stored in the variable `a`.

```
'\d+'>:&.".rxapply a

```

Test:

```
   a=:'teststring134this 123test string54 100'
   '\d+'>:&.".rxapply a
teststring135this 124test string55 101

```
> 5 votes

# Answer
# (f?)lex (39)

File `inc.l`:

```
%%
[0-9]+ printf("%d",atoi(yytext)+1);

```

Compile:

```
$ flex inc.l
$ gcc lex.yy.c -o inc -lfl

```

Run:

```
$ echo 'teststring134this 123test string54 100' | ./inc
teststring135this 124test string55 101

$ i='(-: 2 empty bottles of beer :-)'
$ tty=$(tty)
$ for n in {2..5} ; do i=$(./inc<<<$i|tee $tty) ; done
(-: 3 empty bottles of beer :-)
(-: 4 empty bottles of beer :-)
(-: 5 empty bottles of beer :-)
(-: 6 empty bottles of beer :-)

```

I did not test this with the original `lex`. Comments are welcome.
> 5 votes

# Answer
# Emacs - 20 characters

```
C-M-% [0-9]+ RET \,(1+ \#0) RET !

```

Requires text to be processed to be present in the current buffer. I counted C-M-% as one character here since it can be entered with one keystroke when holding down three modifiers.
> 3 votes

# Answer
# Racket 74

```
(define(f x)(regexp-replace* #px"\\d+"x(λ(m)(~a(+ 1(string->number m))))))

```
> 3 votes

# Answer
# GNU sed, 304 (including 1 for -r flag)

I close-voted this question as a possible duplicate, but this is perhaps contrary to that because this answer can't be trivially changed to work there. By far the longest answer though.

Inspired by this example from the sed documentation, though it needed some work to handle multiple numbers in a string:

```
:d
s/9([^0-9]+|$)/_\1/g
td
s/8(_*)([^0-9]+|$)/9\1\2/g
s/7(_*)([^0-9]+|$)/8\1\2/g
s/6(_*)([^0-9]+|$)/7\1\2/g
s/5(_*)([^0-9]+|$)/6\1\2/g
s/4(_*)([^0-9]+|$)/5\1\2/g
s/3(_*)([^0-9]+|$)/4\1\2/g
s/2(_*)([^0-9]+|$)/3\1\2/g
s/1(_*)([^0-9]+|$)/2\1\2/g
s/0(_*)([^0-9]+|$)/1\1\2/g
s/(^|[^0-9_]+)(_+)/\11\2/g
y/_/0/

```

### Output:

```
$ for s in "teststring134this 123test string54 100" "123test" "test123" "te123st" "test 123 test" ; do echo "$s" | sed -rf incr.sed ; done
teststring135this 124test string55 101
124test
test124
te124st
test 124 test
$

```

Note this temporarily inserts `_` characters, so could lead to incorrect results if there are `_` in the input stream. As a mitigation to this, we can replace the `_` in the sed script with some non-printable character (e.g. ASCII 0x07 BEL), and assume the input stream contains only printable ASCII. This seems to work fine when I test it.
> 3 votes

# Answer
## Lua - 68 characters

```
d='(%D-)'for k,i,j in s:gmatch(d..'(%d+)'..d)do io.write(k,i+1,j)end

```

Expects the input to be stored in s.
> 2 votes

# Answer
## CJam, ~~67 58 53~~ ~~48~~ 31 characters

This question is like the worst question for CJam. No regex, no pattern matching, no exception catching. But here we go *(#YOLO)*

```
Sl+_A,sNerN%\[_A,s-Ner~]:)]zs1>

```

This one splits the string in group of just alphabets and just digits. The increments each digit and stitches back the two array taking one element of each at a time.

---

Previous solution:

```
L_l{:Ci57-zA<:RC*+:N\R!N*NNW?i):NL?+RLC?@R*}/NL?

```

Try it online here

How it works:

Basic idea is to keep storing the character separately in a string if it is a digit and dump the incremented value to the final string once we get a non digit character.

```
L_                                               "Push two empty strings to stack,"
                                                 "first representing the final string"
                                                 "and second, the current ongoing number";
  l{                                       }/    "Run this block for each character of input string";
    :Ci                                          "Store the character to C and convert to"
                                                 "its ASCII equivalent integer";
       57-zA<:R                                  "Subtract 57 from the integer and compare"
                                                 "its absolute value with 10. Numeric character"
                                                 "would result to true here. Store the result in R";
               C*+:N                             "Take either 0 or 1 characters from C based"
                                                 "on value of R, add it to the second string"
                                                 "from first step. Also store the value in N";
                    \                            "Switch the strings. Now the string containing"
                                                 "the final result string is at top of stack";
                     R!N*                        "If the character was not a digit and N contains a number in it";
                         NNW?i):NL?+             "Convert N to number and increment it."
                                                 "If N is blank, take 0 instead. Put the final"
                                                 "value back in N and add it to the final result string";
                                    RLC?         "If the character was not a digit, push it to stack";
                                        @R*      "Put the ongoing numeric string back to top of stack";
                                             NL? "This is to handle the case when the last number"
                                                 "is not followed by a string, so stack will"
                                                 "have a string at top. Push the value of N to stack in that case";

```
> 2 votes

# Answer
# Cobra - 88

```
do(s='')=RegularExpressions.Regex.replace(s,'\d+',do(m as Match)='[int.parse("[m]")+1]')

```
> 1 votes

# Answer
# C# - 178 169 157 characters

This assumes that numbers like 999 are allowed to overflow to 000 and that -+,.E are not part of a number.

```
class T{static void Main(){var a="".ToCharArray();for(int b=1,c,i=a.Length;i-->0;b=48>c|c>57?7:b>0?c>56?a[i]='0':++a[i]*0:b)c=a[i];System.Console.Write(a);}}

```

Better readable form:

```
class T
{
    static void Main()
    {
        var a="7teststring134this 123test string59 100".ToCharArray();

        for (int b=3, c, i=a.Length; i-->0;
            b=48>c|c>57
                ?7
                :b>2
                    ?c>56?a[i]='0':++a[i]*0
                    :b
        ) c=a[i];

        System.Console.Write(a);
        System.Console.ReadKey();
    }
}

```

I'm new here, never tried code golf before, just gave it a try :)

I wonder if anyone has ideas to get it even shorter...

To participate with C# it would be nice if we could omit all the necessary framework around the actual code - then this would only have 82 chars, and that without calling any powerful system functions.

---

The same with pointers (182 chars):

```
class T
{
    unsafe static void Main()
    {
        char[] a="7teststring134this 123test string59 100".ToCharArray();

        int b=3;
        fixed (char* s=&a[0])
            for (var p=s+a.Length; p-->s; )
                b=*p<48|*p>57
                    ?7
                    :b>2
                        ?*p>56?*p='0':++*p*0
                        :b;

        System.Console.Write(a);
        System.Console.ReadKey();
    }
}

```

---

Now without overflowing, this correctly handles the 999 case (223 chars):

```
class T
{
    static void Main()
    {
        var s=new System.Text.StringBuilder("9999teststring134this 123test string99 100");

        for (int b=3, c, i=s.Length; i-->0; )
        {
            c=s[i];
            b=48>c|c>57
                ?b>8?8:7
                :b>2
                    ?c>56?c-(s[i]='0'):++s[i]*0
                    :b;
            if (b>8&i<1|b==8) s.Insert(i+9-b, '1');
        }

        System.Console.Write(s);
        System.Console.ReadKey();
    }
}

```

---

Another different older one, it reads from standard input and uses recursion:

```
namespace System {
    using C=Console;
    class T {
        class t {
            byte b=1;
            string s="";
            void R() {
                var c=C.Read();
                if (c>31) {
                    R();
                    if (48>c|c>57) b=1;
                    else if (b==1) c=c==57?48:++c*b--;
                    s=(char)c+s;
                }
            }
            public t() {
                R();
                C.Write(s);
            }
        }
        static void Main() {
            new t();
            C.ReadKey();
        }
    }
}

```

Note: `Console.ReadKey();` and the string itself should not be counted.

I improved this already multiple times, see comments. There is still room for more improvements, I would say :) And sorry for the length, but I think the different versions are interesting enough to keep them...
> 1 votes

# Answer
# Groovy, 38 bytes

```
{it.replaceAll(/\d+/,{(it as int)+1})}

```

Uggghhh... I absolutely hate the words `replace` and `all`, they ruin all regex golfs for me.
> 1 votes

# Answer
# AWK, 40 bytes

```
BEGIN{RS="[0-9]+";ORS=e}$0=$0(RT?RT+1:e)

```

Try it online!

Parses each substring of numbers as a record separator (default is a newline, "\n"). Adds one to the record text (RT), that is the number that previously matched to the regex. Except for the last RT, which is null. That's what the last condition is about. Otherwise, there would be a `1` appended to the end of the output.
> 1 votes

# Answer
# Vyxal `s`, 8 bytes

```
⁽±Ḋƛ±[⌊›

```

Try it Online!

Who needs regex amiright?

## Explained

```
⁽±Ḋƛ±[⌊›
⁽±Ḋ      # Group the input by whether each item is numeric
   ƛ     # To each group:
    ±[   #   If it's numeric:
      ⌊› #     Cast to int and increment
# -s flag sums into a single string.

```
> 1 votes

# Answer
# Perl 6, 13 bytes

```
{S:g{\d+}+=1}

```

Try it online!

Very simple regex substitution that just increments each instance of a series of digits
> 1 votes

# Answer
# Brachylog, 17 bytes

```
~c{ịᵐc+₁ṫ|ịˢĖ&}ᵐc

```

Try it online!

### Explanation

```
~c{ịᵐc+₁ṫ|ịˢĖ&}ᵐc
~c                 Partition the input string such that
  {           }ᵐ   this predicate can be applied to each substring:
                    Either:
   ịᵐ                Convert each character to a number (i.e. they are all digits)
     c               Concatenate the digits into a single number
      +₁             Add 1
        ṫ            Convert back to a string
         |          Or:
          ịˢ         Find all characters that can be converted to a number
            Ė        Assert that that list is empty (i.e. none of them are digits)
             &       Return the substring unchanged
                c  Concatenate the results back into a single string

```
> 1 votes

# Answer
## **PHP - 91 Bytes**

```
<?$i=fgets(STDIN);for($n=0;$n<strlen($i);$n++)if(is_numeric($i[$n]))$i[$n]=$i[$n]+1;echo$i;

```

I don't wanted to use regular expressions. PHP isn't capable to directly increment a string offset, so, I needed to add some bytes on the increment step. This one line script remembers me a very dark age of the PHP scripting...
> 0 votes

# Answer
# K, 56

```
{" "/:{,/$(`$a)^`$$1+"I"$a:_[;x]@&~~':x in .Q.n}'" "\:x}

```
> 0 votes

# Answer
sed and bash - 40 (including invocation and pipes)

```
$ cat << EOF |sed 's/[0-9]\+/$((\0+1))/g;s/^/echo /'|bash
teststring134this 123test string54 100
123test
test123
te123st
test 123 test
EOF

```

Outputs:

```
teststring135this 124test string55 101
124test
test124
te124st
test 124 test

```
> 0 votes

# Answer
# Java 7, 119 bytes

```
void c(String s){for(String x:s.split("(?=[^\\d]+)|(?<=[^\\d]+)"))System.out.print(x.matches("\\d+")?new Long(x)+1:x);}

```

If the requirement is a program instead of just a function, then it's **149 bytes:**

```
class M{public static void main(String[]a){for(String x:a[0].split("(?=[^\\d]+)|(?<=[^\\d]+)"))System.out.print(x.matches("\\d+")?new Long(x)+1:x);}}

```

**Ungolfed & test code:**

Try it here.

```
class M{
  static void c(String s){
    for(String x : s.split("(?=[^\\d]+)|(?<=[^\\d]+)")){
      System.out.print(x.matches("\\d+")
                        ? new Long(x) + 1
                        : x);
    }
  }

  public static void main(String[] a){
    c("123test");
    System.out.println();
    c("test123");
    System.out.println();
    c("te123st");
    System.out.println();
    c("test 123 test");
    System.out.println();
    c("7teststring134this 123test string59 100");
  }
}

```

**Output:**

```
124test
test124
te124st
test 124 test
8teststring135this 124test string60 101

```
> 0 votes

# Answer
# DASH, 16 bytes

```
rstr[R"\d+""g"+1

```

This returns a function/partial application.

Usage:

```
rstr[R"\d+""g"+1]"test 123 234t"

```

# Explanation

```
rstr[          #. replace any parts of the input
  R "\d+" "g"  #. matching /\d+/g
  +1           #. with its incremented form
]

```
> 0 votes

# Answer
# Gema, 14 characters

```
<D>=@add{$1;1}

```

Sample run:

```
bash-4.3$ gema '<D>=@add{$1;1}' <<< 'teststring134this 123test string54 100'
teststring135this 124test string55 101

```
> 0 votes

# Answer
# CJam, 18 bytes

```
q_A,s-_:(:`ers~]:)

```

Try it here.

### Explanation

```
q         e# Read input.
_A,s-     e# Duplicate and remove digits.
_         e# Duplicate.
:(:`      e# Decrement and get the string representation of each character.
er        e# Map the characters to the decremented string representation.
s~        e# Flatten to string and evaluate.
]:)       e# Wrap in an array and increment each element.

```
> 0 votes

# Answer
## R, 83 bytes

Late to the party. Assumes input is stored in variable `x`. It's probably not needed to use `regmatches` to solve this but I couldn't figure out vectorized replacements without any external packages.

```
paste0(el(r(x,m<-gregexpr("\\d+",x),T)),c(as.numeric(el(r(x,m)))+1,""),collapse="")

```

**Ungolfed and explained**

```
r=regmatches                                        # Alias for regmatch
y=r(x<-scan(,""),m<-gregexpr("\\d+",x))             # return match digits
i=r(x,m,T)                                          # return inverted match (non-digits)
paste0(el(i),c(as.numeric(el(y))+1,""),collapse="") # join digits+1 and non-digits, element-wise

```

**Example output**

```
input:
"teststring135this 124test string55 101"

output:
[1] "teststring136this 125test string56 102"

```
> 0 votes

# Answer
# C# (Visual C# Interactive Compiler) with command-line option `/u:System.Text.RegularExpressions.Regex;System.Int32`, 40 bytes

```
Replace(n,"\\d+",m=>Parse(m.Value)+1+"")

```

Expects input to be in a variable named n.

Try it online!
> 0 votes

# Answer
# Stax, 9 bytes

```
ü╜≥NÇNX╪ÿ

```

Run and debug it

regex
> 0 votes

# Answer
# Pip, 8 bytes

```
aR+XD_+1

```

Try It Online!

### Explanation

> Who needs regex amiright?
> \- Lyxal

Pip, that's who. Pip needs regex.

```
aR+XD_+1
a         Command-line input
 R        Replace
   XD       Regex matching a digit
  +         one or more times
          with
     _      The match
      +1    plus 1

```

(`U_` also works for the callback function, but then there would have to be a space after `XD`, so it's the same bytecount.)
> 0 votes

# Answer
# Haskell, 81 bytes

```
(""!)
n!(c:t)|'/'<c&&c<':'=(n++[c])!t|n==""=c:n!t
""!s=s
n!s=show(1+read n)++""!s

```

Try it online!

### Explanation

Define the `!` operator to take two arguments. The first, `n`, is a string where we track the current run of digits. The second, `s`, is the remainder of the input string. The actual submission function is `!` with `""` bound as its first argument:

```
(""!)

```

The rest of the program defines `!`.

```
n!(c:t)

```

If the string is not empty, separate it into its first character `c` and tail `t`, and try to match one of the following cases:

```
|'/'<c&&c<':'

```

If `c` is a digit character...

```
=(n++[c])!t

```

... then append it to `n` and recurse with that new value of `n` and `t`.

```
|n==""

```

Otherwise, if `n` is empty (and `c` is a non-digit character)...

```
=c:n!t

```

... then prepend `c` to the result of a recursive call with the same (empty) `n` and `t`.

So far, we've covered the following cases:

* Nonempty `s`, first character is a digit
* Nonempty `s`, first character is not a digit, empty `n`

We still need to cover the following cases:

* Nonempty `s`, first character is not a digit, nonempty `n`
* Empty `s`, empty `n`
* Empty `s`, nonempty `n`

Noting that the middle one of the three is the only remaining case where `n` is empty, we address that one next:

```
""!s=s

```

If both `n` and `s` are empty, return `s` (empty string).

Finally, we combine the last two cases as "`n` is nonempty and `s` does not start with a digit":

```
n!s=show(1+read n)++""!s

```

Read `n` as an integer, add 1, convert back to a string, and concatenate to a recursive call with empty `n` and the same `s`.
> 0 votes

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


title: It's time for a clock challenge!

text:
# Question
Title: It's time for a clock challenge!
I'd like you to build me a clock that displays time in this format:

```
18 ----------
19 --------------------------------------------------

```

This displays '18:10'. The current hour and the next hour are shown at the front of the line, followed by a space and a number of dashes: on the first line the number of minutes that have passed in this hour, and the second line shows how many more minutes to go in this hour.

# To clarify

* The clock should display the system's time. If fetching the time from another source is more convenient, that's fine too. It *may not* be supplied as input.
* At `18:00`, the top line is just `18` (Trailing spaces allowed but not required)
* At `18:59`, the bottom line is `19 -`
* The hours \< 10 are either pre-padded with a `0` (`01 -----`) or right-aligned ( `1 -----`). A left-aligned single digit is not allowed, not even if the dashes start at the right place (`1 -----` is invalid).
* The clock should display the hours in a 24h-format.
* Although it's called the 24h format, there is not actually a `24` on it. During the 23rd hour, the second line starts with `00` or  `0`.
* The display needs to be updated at least once a minute, but that doesn't have to happen at exactly `00` seconds. You may update more frequently / continuously if that is more convenient, but the result must of course still be legible - not one smear all over the screen.

# Input

None.

# Output

* As described above. Trailing spaces to pad the clock to 60-ish positions is allowed on both lines, a trailing newline is also allowed.
* The screen needs to be cleared when displaying the next minute: either with a clear-screen command or by adding no less than 30 newlines.

# Additional rules

# Answer
> 2 votes
# MATL, 41 bytes

*Thanks to @Kundor for noticing a mistake, now corrected*

```
`XxFT"4&Z'@+24\OH&YAO'-'60@*5&Z'-|Y"hhD]T

```

Try it at MATL online! But note that the program is killed after 30 seconds, so it's difficult to catch any changes in the output.

### How it works

```
`           % Do...while
  Xx        %   Clear screen
  FT        %   Push [0 1]
  "         %   For each k in [0 1]
    4&Z'    %     Push current hour
    @+      %     Add k
    24\     %     Modulo 24. This transforms 24 into 0
    OH&YA   %     Convert to base-10 string with 2 digits
    O       %     Push 0. Concatenating with chars will convert this to char,
            %     and char(0) will be displayed as a space
    '-'     %     Push '-'
    60@*    %     Push 60*k
    5&Z'    %     Push current minute
    -|      %     Absolute difference. This gives current minute for k==0,
            %     or 60 minus that for k==1
    Y"      %     Repeat '-' that many times
    hh      %     Concatenate the top three elements into a string
    D      %      Display
  ]         %   End
  T         %   Push true
            % End (implicit). Since the top of the stack contains true, this
            % gives an infinite loop

```

# Answer
> 11 votes
# TI-Basic, 94 bytes

```
"
Repeat 99<length(Ans
Ans+"-
End
Ans→Str1
Repeat 0
getTime
ClrDraw
Ans{Ans(1)≠24,1,1
Text(0,0,Ans(1),sub(Str1,1,1+Ans(2
Text(6,0,Ans(1)+1,sub(Str1,1,61-Ans(2
End

```

Relatively straightforward. That's a string with one space at the beginning. The hours are right-aligned. This only works on TI-84+ calculators since the TI-83 does not have an internal clock.

Edit: Thanks @kundor for noticing that I didn't close the last loop. Fixed now (+2 bytes).

Edit #2: First hour should be zero, not twenty-four. Corrected at a cost of +14 bytes.

# Answer
> 9 votes
## Batch, 197 bytes

```
@echo off
set/ah=100+%time:~0,2%,m=1%time:~3,2%
cls
call:l
set/ah=(h-3)%%24+100,m=260-m
call:l
timeout/t>nul 60
%0
:l
set s=%h:~1%
for /l %%i in (101,1,%m%)do call set s=%%s%%-
echo %s%

```

Note: 10th line has a trailing space. For me, `%time%` formats hours with a leading space but minutes with a leading zero. I decided a leading zero was an easier output format, since all I have to do for that is to add 100 hours and remove the first digit. Minutes are trickier as `08` or `09` will cause octal parse errors, so I prefix a `1` effectively adding 100 minutes, adjusting for this by offsetting the loop appropriately, which is a byte shorter than subtracting the 100.

# Answer
> 7 votes
## Python 3.6, ~~110~~ ~~114~~ 112 bytes

```
from time import*
while[sleep(9)]:h,m=localtime()[3:5];print('\n'*50+'%2d '%h+'-'*m+f'\n{-~h%24:2} '+'-'*(60-m))

```

This uses the new f-string formatting to save one byte (`f'\n{h+1:2} '` vs `'\n%2d '%(h+1)`.) You can change `[sleep(9)]` to  `1` to save 8 bytes, but then it just spams the screen.

Saved one byte changing `while 1:...;sleep 60` to `while[sleep(60)]:...`, thanks to TuukkaX.

I had to use 5 more bytes to get the next hour displayed after 23 to be 0, instead of 24, as OP just commented. :-(

Recovered one byte by only sleeping 9 seconds instead of 60.

Saved two bytes using a bit-fiddling to shorten `(h+1)%24`, borrowed from Value Ink's Ruby answer.

# Answer
> 5 votes
# Ruby, ~~98~~ ~~95~~ 91 bytes

Updates every 5 seconds. Only works in Unix-style terminals.

```
loop{t=Time.now;puts`clear`+"%02d %s
%02d "%[h=t.hour,?-*m=t.min,-~h%24]+?-*(60-m);sleep 5}

```

Windows command prompt version, ~~95~~ 92 bytes:

```
loop{t=Time.now;puts"\e[H\e[2J%02d %s
%02d "%[h=t.hour,?-*m=t.min,-~h%24]+?-*(60-m);sleep 5}

```

# Answer
> 4 votes
# Perl 6, 113 bytes

```
loop {$_=DateTime.now;.put for |('' xx 30),|([\+](.hour,1)».fmt('%2s')Z('-' Xx[\-](.minute,60)».abs));sleep 60}

```

Try it once with a one second timeout.

Or try an altered version that outputs the result of running for several hours.

## Expanded:

```
loop {                  # keep repeating forever

  $_ = DateTime.now;    # assign an object representing the current time

    .put                # print with trailing newline
                        # ( adds a space between numbers and dashes )

  for                   # for each of the following

    |(                  # make it a slip so that it is all part of one list

      '' xx 30          # 30 empty strings (30 empty lines)
    ),

    |(

        [\+](           # triangle produce
          .hour,        # the hour
          1             # the hour plus one

        )».fmt( '%2s' ) # both formatted to two element string ( space padded )

      Z                 # zipped with

        (
            '-'         # a dash

          Xx            # cross (X) using string repeat (x) operator

            [\-](       # triangle produce
              .minute,  # the minute
              60        # the minute minus 60

            )».abs      # absolute value of both
        )
    );

  sleep 60              # wait until the next minute
}

```

# Answer
> 4 votes
## Java 8, 313 300 299 bytes

```
import java.time.*;()->{for(int c=0,h=LocalDateTime.now().getHour(),m=LocalDateTime.now().getMinute(),i;;)if(c>30){c=0;String l="",u,d;for(i=0;i++<60;)l+="-";u=l.substring(0,m);d=l.substring(m);System.out.println((h<10?"0":"")+h+" "+u+"\n"+(h<9?"0":"")+(h+1)+" "+d);}else{c++;System.out.println();}}

```

This only updates every 30 iterations of the while loop. The other 29 iterations just print new lines.

**Updated**

Saved 13 14 bytes due to Kevin Cruijssen's help! Thanks!

# Answer
> 4 votes
# QBasic, ~~120~~ ~~127~~ 121 bytes

~~Don't run this for very long or your laptop will catch fire.~~ Now 99.several9s% more CPU-efficient.

```
CLS
m=TIMER\60
h=m\60
m=m MOD 60
FOR i=1TO 2
?USING"## ";h MOD 24;
FOR j=1TO m
?"-";
NEXT
?
h=h+1
m=60-m
NEXT
SLEEP 1
RUN

```

### Ungolfed and explanation

```
DO
    CLS
    totalMinutes = TIMER \ 60
    hour = totalMinutes \ 60
    minute = totalMinutes MOD 60

    FOR row = 1 TO 2
        PRINT USING "## "; hour MOD 24;
        FOR j = 1 TO minute
            PRINT "-";
        NEXT j
        PRINT

        hour = hour + 1
        minute = 60 - minute
    NEXT row

    SLEEP 1
LOOP

```

We start by clearing the screen, then get the current hours and minutes from `TIMER`, which returns the number of seconds since midnight.

This is the first time I've tried `PRINT USING`, so I was delighted to discover that it doesn't suffer from the usual QBasic quirk that positive numbers are printed with a leading space. `##` as the format specifier ensures that single-digit numbers are right-aligned and padded with a space, as required. We have to use a loop for the hyphens, unfortunately, since QBasic does not have a string repetition function. (If I'm mistaken, please let me know!)

All the `PRINT` statements end with `;` to suppress the newline; but after the hyphens, we need a newline; thus, the solitary `?` after the inner `FOR` loop.

The `SLEEP 1` is now necessary. Without it, the screen gets cleared so quickly after printing that it's just a flickering mess. (I used `LOCATE 1` instead of `CLS` at first for that reason, until I realized that `CLS` with `SLEEP` is shorter anyway.) `RUN` restarts the program from the top--the shortest way to get an infinite loop.

# Answer
> 4 votes
## C, ~~176~~ ~~162~~ ~~161~~ ~~160~~ 156 bytes

This is a **gross** abuse of pointers but compiles and runs as specified. Be sure to compile without optimization otherwise you are likely to hit a segfault.

```
main(){int*localtime(),b[9],*t;memset(b,45,60);for(;;)time(&t),t=localtime(&t),usleep(printf("\e[2J%.2d %.*s\n%.2d %.*s\n",t[2],t[1],b,t[2]+1,60-t[1],b));}

```

### Ungolfed:

```
#import<time.h>
main()
{
 int *t,b[60];
 memset(b,45,60);
 for(;;) {
  time(&t);
  t=localtime(&t);
  usleep(printf("\e[2J%.2d %.*s\n%.2d %.*s\n",t[2],t[1],b,t[2]+1,60-t[1],b));
 }
}

```

# Answer
> 3 votes
## Python 2, ~~131~~ ~~129~~ 127 bytes

```
from time import*
while[sleep(9)]:exec(strftime("a='%H';b=int('%M')"));print "\n"*30+a+" "+"-"*b+"\n"+`int(a)+1`+" "+"-"*(60-b)

```

saved a byte thanks to @TuukkaX

# Answer
> 3 votes
# JavaScript (ES6), 162 bytes

Updates once per second

```
setInterval(c=>{c.clear(d=new Date,m=d.getMinutes(),h=d.getHours(),H=_=>`0${h++}`.slice(-2)),c.log(H()+` ${'-'.repeat(m)}
${H()} `+'-'.repeat(60-m))},1e3,console)
```

# Answer
> 3 votes
## C ~~251~~ ~~267~~ 251 bytes

```
 #include<time.h>f(){time_t t;struct tm *t1;h,m,i;while(1){time(&t);t1=localtime(&t);h=t1->tm_hour;m=t1->tm_min;printf("%d ",h);for(i=1;i<=m;i++)printf("-");puts("");printf("%d ",h+1);for(i=0;i<=59-m;i++)printf("-");puts("");sleep(1);system("clear");}}

```

Ungolfed version

```
#include<time.h>
void f()
{
 time_t t;
 struct tm *t1;
 int h,m,i;

 while(1)
 {
  time(&t);
  t1=localtime(&t);
  h=t1->tm_hour;
  m=t1->tm_min;

  printf("%d ",h);
  for(i=1;i<=m;i++)
   printf("-");

  puts("");
  printf("%d ",h+1);

  for(i=0;i<=59-m;i++)
   printf("-");

  puts("");

  sleep(1);
  system("clear");
 }
}

```

Gets the work done! Can definitely be shortened in some way. Assume `unistd.h` file is included.

@Neil Thanks for the info.

@Seth Thanks, for saving 8 bytes.

# Answer
> 3 votes
# PHP, ~~104~~ 105 bytes

```
<? for(;;sleep(6))printf("%'
99s%2d %'-".($m=date(i))."s
%2d %'-".(60-$m).s,"",$h=date(H),"",++$h%24,"");

```

showcase for `printf`´s custom padding characters:
`"%'-Ns"`=left pad string with `-` to `N` characters.

will print 99 newlines (every 6 seconds) instead of clearing the screen.

First newline must be a single character. So, on Windows, it must be replaced with `\n`.

# Answer
> 3 votes
First time golfing...

# Powershell, 116 bytes (was 122)

```
while($d=date){$f="{0:D2}";$h=$d.Hour;$m=$d.Minute;cls;"$($f-f$h)$("-"*$m)`n$($f-f(++$h%24))$("-"*(60-$m))";Sleep 9}

```

Edit: From @AdmBorkBork's advice, changed Get-Date to date, and Clear to cls, for a saving of 6 bytes.

# Answer
> 2 votes
# GameMaker Language, 134 bytes

```
s=" "while 1{s+="-"a=current_hour b=current_minute draw_text(0,0,string(a)+string_copy(s,1,b+1)+"#"+string(a+1)+string_copy(s,0,61-b)}

```

In the settings, you must be ignoring non-fatal errors in order for this to work. Also, in GML, `#` is equivalent to `\n` in most languages.

# Answer
> 2 votes
# Raku (aka Perl 6), 104 bytes

```
DateTime.now.&{"\ec{.hour.fmt: '%2s'} {'-'x.minute}\n{(.hour+1).fmt: '%2s'} {'-'x 60-.minute}"}.say xx*

```

Needs to be run on a ANSI compatible terminal so that the control sequence for resetting the terminal works.

Pretty basic (because the more obfuscated approaches I tried turned out longer):

* `DateTime.now.&{" "}.say xx*`: Transform the current time into a string (see below) and say it, and repeat all of that an infinite number of times. The string is built like this:
* `\ec`: ANSI control code `<ESC>c` for resetting the terminal, which clears the screen.
* `{.hour.fmt: '%2s'}`: hour, right-aligned to 2 columns
* : space
* `{'-'x.minute}`: dash repeated times the minute
* `\n`: newline
* `{(.hour+1).fmt: '%2s'}`: next hour, right-aligned to 2 columns
* : space
* `{'-'x 60-.minute}`: dash repeated times 60 minus the minute

# Answer
> 2 votes
# PHP, ~~112~~ 120 bytes

```
for(;;sleep(9))echo($s=str_pad)($h=date(H),99,"\n",0).$s(" ",1+$m=date(i),"-")."\n".$s(++$h%24,2,0,0).$s(" ",61-$m,"-");

```

As there's no way to clear the screen (that I can find) I had to go with a pile of newlines. Also the question being updated to "at least" once a minute saves a byte with `9` instead of `60`.

edit: @Titus noticed a bug in the padding of the second hour. Fixing it cost 8 bytes.

# Answer
> 2 votes
## Python 3.5, ~~127~~ 120 ~~117~~ bytes

```
from time import*
while[sleep(9)]:h,m=localtime()[3:5];print('\n'*88,*['%2d '%x+'-'*y+'\n'for x,y in[(h,m),(h+1,60-m)]])

```

# Answer
> 2 votes
# Python, ~~115~~ 113 bytes

saved a couple of bytes thanks to @kundor and @Phlarx

```
import time
while 1:h,m=time.localtime()[3:5];print("\x1b[0;H{:02} {}\n{:02} {} ".format(h,"-"*m,h+1,"-"*(60-m)))

```

# Answer
> 2 votes
## AWK, 190 bytes

```
#!/bin/awk -f
func p(x,y,c){printf("%2s ",x)
for(j=0;j<y;j++)printf(c)
print}BEGIN{for(;;){split(strftime("%H %M"),t)
m=t[2]
if(o!=m){p(a,30,"\n")
p(t[1],m,"-")
p((t[1]+1)%24,60-m,"-")}o=m}}

```

Since `AWK` doesn't have a built-in `sleep` function, I simply have it continually check the clock to see if the minute has changed yet. The key thing is that it works... right? :)

# Answer
> 2 votes
# BASH, 165 141 155 bytes

```
while :
do
clear
m=`date +%-M`
a=`printf %${m}s`
b=`printf %$((60-m))s`
h=`date +%H`
echo $h ${a// /-}
printf "%02d %s" $((10#$h+1)) ${b// /-}
sleep 9
done

```

# Answer
> 2 votes
## C# *Interactive* (138 Bytes)

```
while(true){var d=DateTime.Now;Console.WriteLine($"{d.Hour:00} {new string('-',d.Minute)}\n{d.Hour+1:00} {new string('-',60-d.Minute)}");}

```

# Answer
> 2 votes
# Bash (3 and 4): 90 bytes

```
d=(`sed s/./-/g<$0`);let `date +h=%H,m=%M`;echo $h ${d:0:m}'
'$[++h%24] ${d:m}
sleep 5
$0

```

Due to the use of `$0`, this script must be put into a file, not pasted into an interactive bash shell.

The first command sets `$d` to 60 hyphens; it relies on the fact that the first line of this script is 60 characters long. This is three characters shorter than the next best thing I could come up with:

```
d=`printf %060d|tr 0 -`

```

If you don't want this to run your box out of PIDs or memory eventually, you can add `eval` to the beginning of the last line, which would make this 95 bytes.

# Answer
> 2 votes
# Prolog (SWI), 154 bytes

```
S+N:-get_time(A),format_time(atom(O),S,A),atom_number(O,N).
:-repeat,"%H"+H,"%M"+M,format("~t~d~2+ ~|~45t~*+
~|~t~d~2+ ~|~45t~*+
",[H,H,M,M]),\+sleep(60).

```

Try it online!

Welp, what a mess.

# Answer
> 1 votes
# Gura, 138 bytes

```
k(a,b)={if(a<10){a="0"+a;}println(a," ","-"*b)};repeat{t=datetime.now();k(t.hour,t.min);k(t.hour+1,60-t.min);os.sleep(60);print("\n"*30);}

```

Pretty short and straightforward :)

# Answer
> 1 votes
Ok, haven't done a code golf in a while, so here goes my sad attempt :)

# Unix Korn Shell: ~~177~~ ~~171~~ 170 bytes

```
while :
do
clear
h=`date +%H`
m=`date +%M`
d=-----
d=$d$d$d$d
d=$d$d$d
a=`echo $d|cut -b-$m`
let m=60-$m
b=`echo $d|cut -b-$m`
let i=h+1
echo "$h $a\n$i $b"
sleep 9
done

```

# Answer
> 1 votes
# Processing, ~~204~~ ~~200~~ ~~198~~ 197 bytes

*5 bytes saved thanks to @L. Serné by using smarter ternaries*

```
void draw(){int i;String s=((i=hour())>9?i:" "+i)+" ";for(i=0;i<minute();i++)s+="-";s+="\n"+((i=hour()+1)>9?i>23?" 0":i:" "+i)+" ";for(i=0;i<60-minute();i++)s+="-";print(s);for(;i++<99;)println();}

```

This outputs 30+ newlines for each update (which takes place when the frame gets updated)

### Ungolfed

```
void draw(){
  int i;
  String s=((i=hour())>9?i:" "+i)+" ";
  for(i=0;i<minute();i++)
    s+="-";
  s+="\n"+((i=hour()+1)>9?i>23?" 0":i:" "+i)+" ";
  for(i=0;i<60-minute();i++)
    s+="-";print(s);
  for(;i++<99;)
    println();
}

```

# Answer
> 1 votes
# Mathematica, 235 bytes

```
d=UpdateInterval;e=Dynamic;f=Refresh;g=AbsoluteTime;Grid[Partition[Riffle[e[f[Floor@Mod[g[]/3600+#,24],d->1]]&/@{0,1},With[{t=#},e[f[""<>Array["-"&,If[t==60,60-#,#]]&@Setting@Floor@Mod[g[]/60+#,60],d->1]]]&/@{0,60}],2],Alignment->Left]

```

# Answer
> 1 votes
## Python3.5 ~~104~~ ~~127~~ 125 bytes.

~~from time import\* while\[sleep(9)\]:h,m=localtime()\[3:5\];print("{:02d} {}".format(h,m\*'-'),end='\n'\*30)~~

Riffing off Gurupad Mamadapur's answer above.

edit: xnor is right. This isn't a valid answer. - This misses the second line completely.

edit2: Instead, to at least have an answer that works:

~~from time import\* while\[sleep(9)\]:h,m=localtime()\[3:5\];print("{:02d} {}\n{:02d} {}".format(h,m\*'-',h+1,(60-m)\*'-'),end='\n'\*30)~~

edit3: Saved two bytes by moving the \n\*30 to the format instead of the end='\n'\*30

```
from time import*
while[sleep(9)]:h,m=localtime()[3:5];print("{}{:02d} {}\n{:02d} {}".format('\n'*30,h,m*'-',h+1,(60-m)*'-'))

```

# Answer
> 1 votes
## C#, ~~192~~ ~~185~~ ~~176~~ ~~172~~ 169 bytes

*Saved 3 bytes thanks to @nurchi*

```
using System;()=>{for(;;){Console.Clear();var t=DateTime.Now;int h=t.Hour,m=t.Minute;Console.Write($"{h:00} {new string('-',m)}\n{++h%24:00} {new string('-',60-m)}");}};

```

Uses C# 6 features which I don't have access to so cannot test it properly yet.

Full version showing how it works and is called including a `Thread.Sleep` so the input can actually be seen. Note that this version shows the use of `Console.Write`s overload to use `String.Format` and doesn't use string interpolation like the golfed version above.

```
using System;

class P
{
    static void Main()
    {
        Action a = () =>
        {
            for (;;)
            {
                Console.Clear();

                var t = DateTime.Now;
                int h = t.Hour,m=t.Minute;

                Console.Write("{0:00} {1}\n{2:00} {3}", h, new string('-', m), ++h % 24, new string('-', 60 - m));

                System.Threading.Thread.Sleep(500);
            }
        };

        a();
    }
}

```

# Answer
> 1 votes
## Guile, ~~146~~, 143 bytes

```
(while(sleep 9)(let*((t(gmtime(current-time)))(h(tm:hour t))(m(tm:min t)))(format #t "~d ~v,,'-t~%~d ~v,,'-t~%" h m(modulo(1+ h)24)(- 60 m))))

```

Shaved off three bytes thanks to ceilingcat.

# Answer
> 1 votes
# C, 239 bytes

```
#include<time.h>
#include<unistd.h>
#define F printf(
void d(n,p){for(;n--;F"%c",p));}int main(){time_t*t;for(;;){d(30,10);time(t);int*m=localtime(t);F"%2d ",m[2]);d(m[1],45);F"\n%2d ",(m[2]+1)%24);d(60-m[1],45);F"\n");sleep(1);}return 0;}

```

Inspired by Seth's and Abel's entries, this will output 0 instead of 24 for the next hour, as required, and will use 30 lines to clear the screen.

# Answer
> 1 votes
# SmileBASIC, 55 bytes

```
TMREAD OUT H,M,
CLS?H,"-"*M?(H+1)MOD 24,"-"*(60-M)EXEC.

```

Explanation:

```
TMREAD OUT HOUR,MINUTE,
CLS
PRINT HOUR,"-"*MINUTE
PRINT (HOUR+1) MOD 24,"-"*(60-MINUTE)
EXEC 0 'runs the code stored in slot 0 (the default)

```

Note: SmileBASIC only has 50 columns of text, so it won't look good...

# Answer
> 1 votes
**C# 181 176**

```
for(;;){Console.Clear();var t=DateTime.Now;var h=t.Hour;var m=t.Minute;Console.Write("{0,2} {1}\n{2,2} {3}",h,"".PadLeft(m,'-'),++h%24,"".PadLeft(60-m,'-'));Thread.Sleep(100);}

```

This code assumes that the `using System.Threading;` line is included.

Full class:

```
class Program
{
    static void Main(string[] args)
    {
        Console.Title = string.Format("Started the app at: {0}", DateTime.Now.TimeOfDay);
        //new Timer((o) => { Console.Clear(); var t = DateTime.Now; var h = t.Hour; var m = t.Minute; Console.Write("{0,2} {1}\n{2,2} {3}", h, "".PadLeft(m, '-'), ++h % 24, "".PadLeft(60 - m, '-')); }, null, 0, 60000);

        for (; ; ) { Console.Clear(); var t = DateTime.Now; var h = t.Hour; var m = t.Minute; Console.Write("{0,2} {1}\n{2,2} {3}", h, "".PadLeft(m, '-'), ++h % 24, "".PadLeft(60 - m, '-')); Thread.Sleep(100); }

        Console.ReadKey(true);
    }
}

```

# Answer
> 0 votes
# tcl, 164

```
while 1 {scan [clock f [clock se] -f %T] %d:%d h m
puts "[format %2s $h] [string repe - $m]\n[format %2s [expr ($h+1)%24]] [string repe - [expr 60-$m]]"
after 9999}

```

demo

# Answer
> 0 votes
## Bash + Coreutils, 114 bytes

```
while sleep 9; do date +'%k %_M'|{ read h m;printf %02d:%${m}s\n$((h+1)):%$((60-m))s\n" $h|tr " :"  "- "; }; done

```

# Answer
> 0 votes
# JavaScript (V8), 145 bytes

```
setInterval(c=>[m=(c.clear(),d=new Date()).getMinutes(),60-m].map((m,i)=>c.log(((d.getHours()+i)%24+' ').padStart(3)+'-'.repeat(m))),6e4,console)

```

Ungolfed

```
setInterval(console => {
  console.clear();
  const date = new Date();
  const hour = date.getHours();
  const min = date.getMinutes();
  [
    min,
    60 - min
  ].map((min, i) => console.log(
    ((hour + i) % 24 + ' ').padStart(3) +
    '-'.repeat(min)
  ));
}, 60 * 1000, console);

```

---
Tags: code-golf, string, ascii-art, date
---


title: Any lips images

text:
# Question
Title: Any lips images
# Introduction

The **\\$n\\$-ellipse** is a generalization of the ellipse with possibly more than two foci. Specifically, given \\$n\\$ points on the plane, called foci, the \\$n\\$-ellipse is the set of points of the plane whose sum of distances to the \\$n\\$ foci is equal to a constant \\$t\\$.

This challenge is about plotting the \\$n\\$-ellipse together with its **interior**; that is, the set of points whose sum of distances to the \\$n\\$ foci is **less than or equal to** equal to \\$t\\$. Note that the resulting set is always convex.

To simplify, only points with **integer coordinates** need to be considered.

# The challenge

**Input**:

* Number of points \\$n\\$: positive integer;
* List of \\$n\\$ foci (possibly repeated) with integer coordinates, \\$(x\_1, y\_1)\\$, ..., \\$(x\_n, y\_n)\\$;
* Threshold \\$t\\$: positive integer.

**Output**:

An **image** representing all points \\$P\\$ with integer coordinates such the sum of Euclidean distances from \\$P\\$ to the \\$n\\$ foci is less than or equal to \\$t\\$.

Each pixel in the image should correspond to a point with integer coordinates; that is, **pixel size** is \\$1 \times 1\\$. Alternatively, you can use a **finer resolution** (smaller pixels), or vector graphics.

The image should consistently use **two different colours** for points satisfying the condition ("active" pixels) or not satisfying it ("inactive").

# Additional rules

* Graphical output is required, in any format. (ASCII art is not allowed because of size limitations and aspect ratio).
* Both axes should have the **same scale**. The \\$x\\$ axis should be horizontal, and can consistently increase left to right or right to left. Similarly, the \\$y\\$ axis should be vertical and can consistently increase upwards or downwards.
* Axis labels, auxiliary grid lines and similar elements are allowed.
* The output image can have an arbitrarily large "**frame**" of inactive pixels around the set of active pixels.
* The set of active points is guaranteed to be **non-empty**.
* Input format is flexible as usual. A program or a function can be provided. Standard loopholes are forbidden.
* The code should work in theory for inputs containing arbitrarily large numbers. In practice, it is acceptable if the program is limited by time, memory or data-type restrictions.
* Shortest code in bytes wins.

# Test cases

Input is shown as a list of \\$n\\$ foci defined as coordinate pairs, followed by \\$t\\$, and an optional comment.

In the output images, \\$x\\$ axis increases left to right, \\$y\\$ axis increases upwards.

```
(5,8), 100  % A circle

```

```
(0,0), (70, 150), 220  % An ellipse

```

```
(-100, 0), (100, 0), (100, 0), 480  % Repeated point

```

```
(-90, -90), (-90, 90), (90, -90), (90, 90), (90, -90), 670  % Repeated; arbitrary order

```

```
(200, 600), (320, -60), (-350, 220), (-410, 130), (40, -140), 2100

```

```
(-250, -250), (-250, 250), (250, -250), 1000

```

```
(-250, -250), (-250, 250), (250, -250), 1200

```

```
(-390, 0), (-130, 120), (130, -120), (390, 0), 1180  % Finally, a pair of lips?

```

# Answer
# Jelly, ~~36~~ 35 bytes

```
«/_⁹r»/+¥,þ/_Ɱ⁸²§½S>⁹µ;L;ZL$;1ṚK”P;

```

Try it online!

A full program that takes a list of lists of integers as the first argument, representing the foci, and the threshold as an integer as its second argument. Prints a PBM file to STDOUT.

### Example

* First argument: `(0,0), (7, 15)`
* Second argument: `220`
* Output (converted to PNG):
> 6 votes

# Answer
# Python 3 \+ numpy + pylab, ~~168~~ ~~163~~ 156 bytes

```
import numpy,pylab
f,t=eval(input())
s=max(map(abs,sum(f,())))+t
k=numpy.r_[-s:s+1]
pylab.imsave('a.png',sum(((k-x)**2+(k[:,None]-y)**2)**.5for x,y in f)>t)

```

Outputs to a file called `a.png`, the y-axis increases downwards.

**Sample outputs** (click for full-res versions)

`[(5, 8)], 100`:

`[(0, 0), (70, 150)], 220`:

`[(-90, -90), (-90, 90), (90, -90), (90, 90), (90, -90)], 670`:

`[(-390, 0), (-130, 120), (130, -120), (390, 0)], 1180`:

# Python 2, 152 bytes

```
f,t=input()
s=max(map(abs,sum(f,())))+t
w=s*2+1
k=range(-s,s+1)
print'P1',w,w
for y in k:
 for x in k:print+(sum(((a-x)**2+(b-y)**2)**.5for a,b in f)>t)

```

Try it online!

Outputs a PBM file to STDOUT. Sample output:
> 8 votes

# Answer
# APL (Dyalog Unicode), 67 bytes (SBCS)

`⎕IO←0`

```
+{(⎕NEW'Bitmap'(⊂'Cbits'(⍵≥+⌿⍺∘.(.5*⍨-+.×-)(⊢,-)⍳2×⍵ ⍵))).MakePNG}⊢

```

## NB

* This image is very low contrast (made from a boolean matrix) - the output can be white interior shape on black background by multiplying the boolean matrix:

+{(⎕NEW'Bitmap'(⊂'Cbits'(16777215×~⍵≥+⌿⍺∘.(.5\*⍨-+.×-)(⊢,-)⍳2×⍵ ⍵))).MakePNG}⊢
* Images are transposed compared to many other solutions, but you can flip the indices of each focus
* Only works on Dyalog for Windows

## Explanation

This function is a 3-train (fork), the arguments to the inner function are the results of the outer functions:

```
+

```

`+` (plus): Translate the image by adding distance to the foci (please comment if this is a misinterpretation of the challenge)

(right): given two arguments (left and right), return the right argument

APL is parsed (glossing over some binding rules) as Brackets, long Right scope, short Left scope. We break it down as follows:

```
⍳2×⍵ ⍵

```

Indices from 0 to 2×⍵ in 2 dimensions (our integer pixels)

```
(⊢,-)⍳2×⍵

```

`(⊢,-)` (Same catenate negate) to cover positive and negative coordinates

```
(.5*⍨-+.×-)

```

Euclidean distance from focus to pixel...

```
⍺∘.(.5*⍨-+.×-)

```

... applied between each focus and every pixel

```
+⌿⍺∘.(.5*⍨-+.×-)

```

Sum the distances between all foci and each pixel (n-ellipse)

```
⍵≥+⌿⍺∘.(.5*⍨-+.×-)

```

Boolean matrix where 1 indicates interior (active) pixels (i.e. sum of distances between foci and pixel is less than *t*)

```
(⎕NEW'Bitmap'(⊂'Cbits'(*boolean matrix*))).MakePNG

```

Output signed integer PNG. This can be written to file using

```
∇  WritePNG png;tn
   tn←'img.png'⎕NCREATE 0
   png ⎕NAPPEND tn 83
   ⎕NUNTIE tn
∇

```

## Output Images

First is to demonstrate, the written PNG has very low contrast

```
f ← +{(⎕NEW'Bitmap'(⊂'Cbits'(⍵≥+⌿⍺∘.(.5*⍨-+.×-)(⊢,-)⍳2×⍵ ⍵))).MakePNG}⊢
WritePNG 5 8 f 100

```

Below I'm using the black and white version.

```
WritePNG (0 0)(70 150) f 220

```

```
WritePNG (¯100 0)(100 0)(100 0) f 480

```

Very resource hungry algorithm so I did a low res version of this

```
WritePNG (20 60)(32 ¯6)(¯35 22)(¯41 13)(4 ¯14) f 210

```
> 7 votes

# Answer
## JavaScript (ES7), ~~212~~ 196 bytes

```
with(Math)f=(c,l,...p)=>{m=l-max(...p)
c.height=c.width=s=min(...p)+l+m
for(i=0;i<s;i++)for(j=0;j<s;j++){for(d=k=0;1/p[k];)d+=hypot(p[k++]+m-i,p[k++]+m-j)
d>l||c.getContext`2d`.fillRect(i,j,1,1)}}

eval(`f(c,${e.value})`)
```

```
input{position:fixed}
```

```
<input id=e oninput=eval(`f(c,${e.value})`) value="100,-25,-25,-25,25,25,-25"><canvas id=c>
```

Outputs via first parameter which is a canvas element to draw on, second parameter is the threshold, then the remaining parameters are the loci. Edit: Saved 16 bytes thanks to @Arnauld, however the code is now dead slow and will trigger slow script warnings for large thresholds.
> 6 votes

# Answer
# Haskell \+ Gloss, 165 bytes

```
import Graphics.Gloss
i=fromIntegral
h t=[i(-t)*3..i t*3]
d f t=display(InWindow""(t*3,t*3)(0,0))red$Line[(x,y)|x<-h t,y<-h t,i t>sum[sqrt$(x-u)^2+(y-v)^2|(u,v)<-f]]

```

Draws the shapes to the screen. It sometimes draws the images REALLY BIG, so I have cropped accordingly.

`main = d [(5,8)] 100`

`main = d [(0,0), (70, 150)] 220`

`main = d [(-100, 0), (100, 0), (100, 0)] 480`

`main = d [(-250, -250), (-250, 250), (250, -250)] 1000`
> 6 votes

# Answer
# Red, 300 bytes

```
Red[]f: func[p t][a: :absolute
m: last sort collect[foreach n p[keep a n/x keep a n/y]]s: t + m * 2
u: as-pair s s i: make image! reduce[u]k: 0 repeat y s[repeat x s[d: 0
foreach a p[d: d +(sqrt x - t - m - a/x ** 2 +(y - t - m - a/y ** 2))]k: k + 1
if d <= t[i/:k: 0.0.255]]]save/as %1.jpg i 'jpeg]

```

`f [5x8] 100`

`f [0x0 70x150] 220`

`f [-100x0 100x0 100x0] 480`

`f [200x600 320x-60 -350x220 -410x130 40x-140] 2100`

`f [-390x0 -130x120 130x-120 390x0] 1180`

Note: I scaled all the images to 256x256 pixels and croped the last two images so that they don't take too much space - they had a large "frame"
> 4 votes

# Answer
# Applescript + grapher, 601

This will almost certainly be the longest answer, but I thought this would be a fun challenge in Applescript.

```
on f(l, t)
set y to 0
tell application "Grapher" to activate
tell application "System Events"
keystroke "n" using command down
keystroke return
keystroke "a" using command down
repeat with d in l
keystroke "sqrt((x-"&d's item 1&")^2)+(y-"&d's item 2&")^2))+"
set y to y+d's item 2
end repeat
click application process "Grapher"'s menu bar 1's menu bar item 8's menu 1's menu item 3
set c to l's items count
keystroke "             "&(y-t)/c as text&" "&(y+t)/c as text&"     "
keystroke "c" using command down
keystroke "             "
keystroke "v" using command down
keystroke return&"0<"&t as text&return
end tell
end f

```

This is an applescript function. It may be called as follows for the testcases:

```
my f({{5, 8}}, 100)
my f({{0, 0}, {70, 150}}, 220)
my f({{-100, 0}, {100, 0}, {100, 0}}, 480)
my f({{-90, -90}, {-90, 90}, {90, -90}, {90, 90}, {90, -90}}, 670)
my f({{200, 600}, {320, -60}, {-350, 220}, {-410, 130}, {40, -140}}, 2100)
my f({{-250, -250}, {-250, 250}, {250, -250}}, 1000)
my f({{-250, -250}, {-250, 250}, {250, -250}}, 1200)
my f({{-390, 0}, {-130, 120}, {130, -120}, {390, 0}}, 1180)

```

Output looks like this, e.g. for the 5th testcase:
> 4 votes

# Answer
# MATLAB + DIPimage toolbox, ~~133~~ ~~121~~ ~~117~~ 111 bytes

(shaved off ~~12~~ 16 bytes thanks to flawr and LuisMendo)

```
function s(c,r),c=c-min(c)+r;a=zeros(max(c)+r);l='corner';for x=c',a=a+hypot(xx(a,l)-x(1),yy(a,l)-x(2));end,a>r

```

Use:

```
c = [-390, 0; -130, 120; 130, -120; 390, 0];
r = 1180;
s(c,r)

```

In a more readable fashion:

```
function s(c,r)
c=c-min(c)+r;           % offset coordinates so all points within shape have non-negative coordinates
a=zeros(max(c)+r);      % compute image size and create empty output image
l='corner';             % long argument used twice below
for x=c'
   a=a+hypot(xx(a,l)-x(1),yy(a,l)-x(2)); % add distance to each point
end
a>r                     % threshold and display (leaving semi-colon off causes graphical display of image)

```
> 4 votes

# Answer
# Desmos, ~~50~~ 49 bytes

```
\sum_{n=1}^c \sqrt{(x-a[n].x)^2+(y-a[n].y)^2}<=t

```

-1 byte from finding a new quirk in Desmos' syntax while working on another problem.

View it online

It just kinda... works. Input `n` in the variable `c`, `t` in the variable `t`, and the points as an array `a` of coordinates.

Lips example:

Guitar pick example:

Note: If you try to copy the equation from the editor, you'll find a bunch of `\left`s and `\right`s and such. These have been golfed out of this answer, as you can paste this text in and it works. The editor automatically re-adds those when parsing input from the clipboard, but it accepts the code without them.

Note two: I'm not 100% sure if this counts due to the infill being transparent, but hopefully it's ok. If not, there's a couple options:

1. Stack a bunch of whole bunch of these equations on top of each other. I tried this and it turns out that a quirk of their rendering engine is that the fill color can never drop below #010101, while the outline is at #000000. Additionally, the area is a little larger than would be ideal because the outline looks like part of the fill.
2. Rewrite the n-ellipse equation in parametric form. I don't know if this is possible or not, but if it is, Desmos's enhanced visual options for parametric equations allows us to remove the outline.
> 3 votes

# Answer
# Bash \+ Standard utilities (but no graphics library), ~~194~~ ~~190~~ 186 bytes

```
t=$1
shift
L=H=$1
for n do
L=$[n<L?n:L]
H=$[n>H?n:H]
done
echo P2 $[L-=t,H+=t+1,H-L] $[H-L] 1
for((x=y=L;y<H;++x>=H?x=L,y++:0)){ bc -l<<<`printf "sqrt(($x- %d)^2+($y- %d)^2)+" $@`0\>$t;}

```

Try it online! (If you do, though, try a tiny example: even the circle test times out on TIO.)

---

Input is passed in the arguments: first \\$t\\$, then \\$x\_1\\$, \\$y\_1\\$, \\$x\_2\\$, \\$y\_2\\$, ..., \\$x\_n\\$, \\$y\_n\\$.

Output is a PGM image on stdout. Save it in a file named `something.pgm` and view it in your favorite graphics program.

The x-axis goes from left to right, and the y-axis goes from top to bottom. White is the background, and black is the n-ellipse being drawn.

For example, to view the first example (the circle), you could execute:

```
lips 100 5 8 > lips-circle.pgm

```

(where the program is named `lips`). Then open the image`lips-circle.pgm`. Here's the result:

Here's the second test, the output of `lips 220 0 0 70 150 > lips-ellipse.pgm`:

Next is `lips 480 -100 0 100 0 100 0 > lips-repeatedpoint.pgm`:

Here is `lips 670 -90 -90 -90 90 90 -90 90 90 90 -90 > lips-repeated-arbitaryOrder.pgm`:

The next test is `lips 2100 200 600 320 -60 -350 220 -410 130 40 -140 > lips-shape1.pgm`:

---

*This script is very slow (but runnable). I will post more sample images as my computer gets around to finishing them :) ....*

*Well, after waiting overnight again, the other tests are finally done!*

---

Here's the guitar pick: `lips 1000 -250 -250 -250 250 250 -250 > lips-guitarpick.pgm`

The next test is `lips 1200 -250 -250 -250 250 250 -250 > lips-shape2.pgm`:

And finally the pair of lips! `lips 1180 -390 0 -130 120 130 -120 390 0 > lips-pairOfLips.pgm`:
> 2 votes

# Answer
# Shadertoy (GLSL) 125 bytes + input data

```
vec2 a[]=vec2[](vec2(-390, 0),vec2(-130,120),vec2(130,-120),vec2(390,0));
float d=1180.;

void mainImage(out vec4 o,vec2 c){c-=iResolution.xy/2.;o-=o;for(int i=0;i<a.length();o.a+=length(c-a[i++]));o.b=step(o.a,d);}

```

Shadertoy link for the last testcase.

As the input array's size is known, this could be further reduced by replacing the `a.length()` by `n`.
> 2 votes

# Answer
# Desmos, 39 bytes

```

\distance((x,y),\ans_0).\total<=\ans_1

```

The other Desmos answer to this challenge is invalid because it assumes that the input is stored in hardcoded variables, which is heavily discouraged.

Instead, this program takes input through `\ans`, which is an acceptable form of input.

Input the list of points in the first line, and the threshold in the second line.

Try It On Desmos!

Try It On Desmos! - Prettified
> 2 votes

---
Tags: code-golf, number, graphical-output
---


title: Polyglot Quiz (Robbers' thread)

text:
# Question
Title: Polyglot Quiz (Robbers' thread)
*This is the robbers' thread. For the main rules to this challenge see the cops' thread*

In this challenge, robbers will choose a cop's *vulnerable* or *safe* post and try to figure out a pair of languages such that they print the correct results for the 4 programs.

When you find a solution post an answer of it here and leave a comment on the original post linking to your answer.

## Scoring

Robbers will be given 1 point for every *vulnerable* or *safe* they solve. The goal of the robbers' thread is to gain as many points as possible.

## Languages and Output

In the interest of fairness, we are going to require that languages are free and reasonably cross platform. Both languages you choose must be freely available on Linux and FreeBSD (the two largest foss operating systems). This includes languages which are free and open source.

Your selected languages must predate this challenge.

Since this challenge requires that **A** and **B** produce different outputs for the same program, there is no requirement for what "counts" as a different language, the fact that they produce different outputs is enough.

Programs do not have to compile, run without error or "work" in the cases where they do not need to output **S**. As long as **S** is not the output it is valid.

Programs here should be complete programs, not functions, expressions or snippets.

# Answer
> 6 votes
# A = Haskell, B = Ruby, AZTECCO

1. Try it online in Haskell and Ruby.
2. Try it online in Haskell and Ruby.
3. Try it online in Haskell and Ruby.
4. Try it online in Haskell and Ruby.

This would also work with A = Curry (PAKCS).

# Answer
> 5 votes
# A = Hexagony, B = Labyrinth, Bubbler

1. Both Hexagony and Labyrinth

```
"123_1234!@

```

Try it online in Hexagony and Labyrinth

2. Only Hexagony

```
123+1
234!@

```

Try it online in Hexagony and Labyrinth

3. Only Labyrinth

```
1234@
;!;!;

```

Try it online in Hexagony and Labyrinth

4. Neither Hexagony nor Labyrinth

```
;!;!;
1234@

```

Try it online in Hexagony and Labyrinth

# Answer
> 3 votes
# A = HQ9+, B = Python 3, thejonymaster

Not sure if this was the intended solution but it works!

Also, it seems that some implementations of HQ9+ are case insensitive which invalidates this crack, but I am specifically using the HQ9+ implementation on DSO, which is case sensitive.

1. Both HQ9+ and Python 3 work

```
#console.log("Hello, world!")/*
print("hello, world!".capitalize())
#*/

```

Try It Online in Python 3 and HQ9+

2. Only HQ9+ works

```
console.log("Hello, world!")/*
print("hello, world!")
*/

```

Try It Online in Python 3 and HQ9+

3. Only Python 3 works

```
#console.log("Hello, world!")/*
print("Hello, world!")
#*/

```

Try It Online in Python 3 and HQ9+

4. HQ9+ and Python 3 both don't work

```
console.log(String.fromCharCode(49-1)+"ello, world!")/*
print(String.fromCharCode(49-1)+"ello, world!")
*/

```

Try It Online in Python 3 and HQ9+

# Answer
> 2 votes
# A = Python, B = PARI/GP, alephalpha

1. Try it online in Python and PARI/GP.
2. Try it online in Python and PARI/GP.
3. Try it online in Python and PARI/GP.
4. Try it online in Python and PARI/GP.

Instead of Python, it could be Ruby, Perl, Raku, or a zillion other languages.

# Answer
> 2 votes
# A = Python 2.7, B = SunSip, Number Basher

Only STDOUT is considered output, all programs liberally print garbage to standard error.

1. Both SunSip and Python2.7

```
print('0')
out

```

Try it online in Python 2 and SunSip

2. Only Python2.7

```
print('0')
out#

```

The # stops the parsing of the keyword so it doesn't work.

3. Only SunSip

```
print('0',)
out #

```

Try it online in Python 2.7 and SunSip

Outputs `('0',)` in python

4. Neither SunSip not Python 2.7

Obviously does nothing in either program.

# Answer
> 2 votes
# A = \>\<\>, B = Adapt, mousetail

Although this outputs a trailing newline for **B**, mousetail has clarified this is acceptable.

1. `2` in \>\<\>, `2` in Adapt
2. `2` in \>\<\>, `[]` in Adapt
3. no output & errors in \>\<\>, `2` in Adapt
4. `1` in \>\<\>, `1` in Adapt

# Answer
> 1 votes
# Vyxal and Jelly, cracks Number Basher's answer

1. empty program, Vyxal, Jelly
2. `!`, Vyxal, Jelly
3. `r`, Vyxal, Jelly
4. `"`, Vyxal, Jelly

# Answer
> 1 votes
# A = Pyth, B = V (vim), Mukundan314

1. Try it online in Pyth and .
2. Try it online in Pyth and .
3. Try it online in Pyth and .
4. Try it online in Pyth and .

# Answer
> 1 votes
# 0SAB1LE and yup, Kevin Cruijssen

1. 0SAB1LE, yup
2. 0SAB1LE, yup
3. 0SAB1LE, yup
4. 0SAB1LE, yup

I just went through everything on TIO that looked like a stack based language until I found one that worked.

---
Tags: cops-and-robbers, polyglot
---