title: Cook me a hot dog!

text:
# Question
Title: Cook me a hot dog!
Sometimes I find myself wanting a hot dog (don't we all) and so I make one. Now to make a hot dog, it is very simple.

1) Put the hot dogs into boiling water

2) Wait for a certain amount of time (detailed below)

3) Eat the hot dog once the time has elapsed.

You may have noticed that I said

> certain time (detailed below)

and so I will detail.

Many different brands have many different recommendations for how long we should cook the hot dogs, but I have found it best to cook them for exactly 4 minutes and 27 seconds (don't ask). I have tried many different timers, but have found that a program that continuously outputs is the best way to attract my attention.

## YOUR TASK

You have to make a program that will output the message `Not ready yet` for exactly 4 minutes and 27 seconds. After this time has elasped, you should output `Eat your hot dog` until the end of time. Please don't take any input.

# HOW TO WIN

You must write the shortest code in *bytes* to win because this is a

# Answer
# Scratch, ~~93~~ 78 bytes

Code:

```
when gf clicked
say[Not ready yet
wait until<(timer)>[267
say[Eat your hot dog

```

Generated by https://scratchblocks.github.io/, which seems to be the standard for Scratch scoring.

Fairly self explanatory. When the program starts, say "Not ready yet" until the timer (which is counted in seconds) is greater than 267. Then starts an infinite loop where it says `Eat your hot dog`.

It *is* continuous output, because the `say` block runs forever unless you `say []` or `say` something else.
> 20 votes

# Answer
# Bash + coreutils, 50

```
timeout 267 yes Not ready yet
yes Eat your hot dog

```

### Explanation

Fairly self-explanatory I think, but just in case:

* The `yes` coreutil continuously repeatedly outputs any parameters passed to it on the command line
* The `timeout` coreutil takes a numeric timeout parameter followed by a command. The command is run, then killed after the specified timeout.
> 14 votes

# Answer
# Operation Flashpoint scripting language, 67 bytes

```
#l
s="Not ready yet"
?_time>267:s="Eat your hot dog"
hint s
goto"l"

```

Save as `"hotdog.sqs"` (or whatever) in the mission folder and call with `[] exec "hotdog.sqs"`.

**Explanation:**

```
#l                                  // Label for the "goto"
s="Not ready yet"
?_time>267:s="Eat your hot dog"     // "?:" means "if () then" in a script.
                                    // "_time" is a local variable that is automatically
                                    // created and updated in every script. Its value
                                    // is the time in seconds since the script started.

hint s                              // Outputs the text in a text box.

~.1                                 // Sleeps for a tenth of a second.
                                    // The script seems to work without sleeping too,
                                    // so I didn't include this in the golfed version.
                                    // Looping in a script without sleeping is always
                                    // a bad idea, though. It sometimes crashes the game.

goto"l"                             // Go back to the beginning of the loop.
                                    // This is the only way to create a loop if you don't
                                    // want to halt the game (and the time calculation)
                                    // until the loop finishes.

```

> I have tried many different timers, but have found that a program that continuously outputs is the best way to attract my attention.

This solution should be especially good with attracting your attention, since the `hint` command plays a clinging sound effect every time it's called, which sounds very annoying when the simultaneous sounds get clipped in a tight loop.
> 8 votes

# Answer
# JavaScript ES6, 76 bytes

```
$=>setInterval("console.log(--_>0?`Not ready yet`:`Eat your hot dog`)",_=517)

```

# Explanation

This prints something to the console every 517 milliseconds. At first, it prints `'Not ready yet'` and decreases the counter. After 517 iterations (`= 517 * 517 = 267289 ms`), it starts printing `'Eat your hot dog'`.

# Test

```
f=
  $=>setInterval("console.log(--_>0?`Not ready yet`:`Eat your hot dog`)",_=517);
(setInterval("console.log('DONE NOW')",267000)&&f())();
```
> 7 votes

# Answer
## Powershell, 85 71 59 bytes

```
1..276|%{Sleep 1;'Not ready yet'};for(){'Eat your hot dog'}

```

There's probably a much better way, so criticism welcome! This is my first golf attempt :)

**EDIT** Down a whole 14 bytes thanks to AdmBorkBork! And definitely a technique to remember!

**EDIT 2** Another 12 bytes gone thanks to Matt. Not calling write twice also removed 2 spaces, very helpful!
> 7 votes

# Answer
# GameMaker' scripting language variant used in Nuclear Throne Together mod, 68 bytes

```
t=0while 1{trace(t++<8010?"Not ready yet":"Eat your hot dog")wait 1}

```

### Explanation

* GML's parser is deliciously forgiving. Semicolons and parentheses are optional, and the compiler is not at all concerned about your spacing outside the basic rules (`0while` parses as `0`,`while` and thus is ok)
* Variables leak into the executing context unless declared via `var` (same as with JS).
* GML variant used in NTT introduces a `wait` operator, which pushes the executing "micro-thread" to a list for the specified number of frames, resuming afterwards. Coroutines, basically.

The game is clocked at 30fps, so 4m27s == 267s == 8010 frames.
* trace() outputs the given string into the chat.

If you have the videogame+mod installed, you can save that as some `test.mod.gml`, and do `/loadmod test` to execute it, flooding the chat with "status reports":
> 7 votes

# Answer
# Python 2, 92 bytes

```
from time import*
t=time()
while 1:print"Not ready yet"if time()-t<267else"Eat your hot dog"

```

Try it online!
> 3 votes

# Answer
# TI-Basic, 75 bytes

```
For(A,1,267
Disp "Not ready yet
Wait 1
End
While 1
Disp "Eat your hot dog
End

```

Explanation

```
For(A,1,267             # 9 bytes, for 267 times...
Disp "Not ready yet     # 26 bytes, display message
Wait 1                  # 3 bytes, and wait one second
End                     # 2 bytes, ...end
While 1                 # 3 bytes, after that, continuously...
Disp "Eat your hot dog  # 31 bytes, output second message
End                     # 1 byte, ...end

```
> 3 votes

# Answer
## Batch, ~~99~~ 97 bytes

```
@for /l %%t in (1,1,267)do @echo Not ready yet&timeout>nul 1
:l
@echo Eat your hot dog
@goto l

```

Batch has no date arithmetic so as a simple 267 second timeout isn't permitted the best I can do is 267 one-second timeouts. Edit: Removed unnecessary `/t`.
> 2 votes

# Answer
# 05AB1E, ~~43~~ ~~29~~ 28 bytes (Thanks to Adnan)

```
267F…€–Žä‡«ªw,}[“Eat€ž…ß‹·“,

```

Does not work online, since it times out. Offline it will work.

`267F`: Loop 267 times

`…€–Žä‡«ª`: First string with dictionary

`w,`: Wait one second and print

`}[`: End if loop and start infinite loop

`“Eat€ž…ß‹·“`: Second string with dictionary

`,`: Print
> 2 votes

# Answer
# C#, 174 172 147 bytes

*Saved 25 bytes by "borrowing" some ideas from raznagul's C# answer and merging them with the sum of first n numbers trick!*

*Saved 2 bytes by using the sum of first n numbers trick for a loss of precision of 185 milliseconds.*

```
class P{static void Main(){for(int i=1;;){System.Console.WriteLine(i++<731?"Not ready yet":"Eat your hot dog");System.Threading.Thread.Sleep(i);}}}

```

Ungolfed program:

```
class P
{
    static void Main()
    {
        for (int i=1;;)
        {
            System.Console.WriteLine( i++ < 731 ? "Not ready yet" : "Eat your hot dog");
            System.Threading.Thread.Sleep(i);
        }
    }
}

```

**Explanation:**

Since the total time to wait is hardcoded at 267 seconds, one can consider this number as a telescopic sum of the first n natural numbers, `n * (n + 1) / 2`, which must equal 267000 milliseconds.

This is equivalent to `n^2 + n - 534000 = 0`.

By solving this second order equation, `n1 = 730.2532073142067`, `n2 = -n1`. Of course, only the positive solution is accepted and can be approximated as **730**.

The total time can be calculated as `730 * (730 + 1) / 2 = 266815 milliseconds`. The imprecision is *185 milliseconds*, imperceptible to humans. The code will now make the main (and only) thread sleeps for 1 millisecond, 2 milliseconds and so on up to 730, so the total sleep period is ~267 seconds.

***Update:***

The program's logic can be simplified further - basically it needs to continuously display a message and wait a specified time until switching to the second message.

The message can be change by using a ternary operator to check the passing of the specified time (~267 seconds).

The timing aspect is controlled by using an increasing counter and pausing the execution thread.

However, since the counter variable continues increasing indefinitely without any conditions to check its value, one can expect an integer overflow at some point, when the message reverts to `Not ready yet`.

A condition can be added to detect and mitigate the issue by assigning a positive value greater than 730 when the overflow occurs - like `i=i<1?731:i` inside the `for` loop. Sadly, it comes at the cost of 11 additional bytes:

```
class P{static void Main(){for(int i=1;;i=i<1?731:i){System.Console.Write(i++<731?"\nNot ready yet":"\nEat your hot dog");System.Threading.Thread.Sleep(i);}}}

```

The key here is using the **counter value** in milliseconds to greatly delay the moment of overflow.

The time until overflow can be calculated according to the `sum(1..n)` formula, where n = the maximum 32-bit signed integer value in C# (and the .NET framework) or 2^31 - 1 = 2147483647:

`2 147 483 647 * 2 147 483 648 / 2 = 2,305843008 x 10^18 milliseconds = 2,305843008 x 10^15 seconds = 26 687 997 779 days = ~73 067 755 years`

After **73 million years**, it might not matter if a glitch in the system appears - the hot dog, the hungry OP and maybe the human race itself are long gone.

---

**Previous version (172 bytes):**

```
namespace System{class P{static void Main(){for(int i=1;i<731;){Console.Write("\nNot ready yet");Threading.Thread.Sleep(i++);}for(;;)Console.Write("\nEat your hot dog");}}}

```

Ungolfed program:

```
namespace System
{
    class P
    {
        static void Main()
        {
            for (int i = 1; i < 731; )
            {
                Console.Write("\nNot ready yet");
                Threading.Thread.Sleep(i++);
            }
            for ( ; ; )
                Console.Write("\nEat your hot dog");
        }
    }
}

```

---

**Previous version (174 bytes):**

```
namespace System{class P{static void Main(){for(int i=0;i++<267e3;){Console.Write("\nNot ready yet");Threading.Thread.Sleep(1);}for(;;)Console.Write("\nEat your hot dog");}}}

```

Ungolfed program:

```
namespace System
{
    class P
    {
        static void Main()
        {
            for (int i=0; i++ < 267e3; )
            {
                Console.Write("\nNot ready yet");
                Threading.Thread.Sleep(1);
            }
            for ( ; ; )
                Console.Write("\nEat your hot dog");
        }
    }
}

```

---

Alternatively, the program may display `Not ready yet` only once, wait until the specified time is over and then output `Eat your hot dog` by overwriting the previous message while being quite a few bytes shorter:

# C#, 145 bytes

```
namespace System{class P{static void Main(){Console.Write("Not ready yet");Threading.Thread.Sleep(267000);Console.Write("\rEat your hot dog");}}}

```

Ungolfed program:

```
namespace System
{
    class P
    {
        static void Main()
        {
            Console.Write("Not ready yet");
            Threading.Thread.Sleep(267000);
            Console.Write("\rEat your hot dog");
        }
    }
}

```
> 2 votes

# Answer
# C# 144 bytes

```
()=>{for(int i=0;;){var s="\nEat your hot dog";if(i<267e3){i++;s="\nNot ready yet";}System.Console.Write(s);System.Threading.Thread.Sleep(1);}};

```

Ungolfed full program:

```
class P
{
    static void Main()
    {
        System.Action a = () =>
            {
                for (int i = 0; ;)
                {
                    var s = "\nEat your hot dog";
                    if (i < 267e3)
                    {
                        i++;
                        s = "\nNot ready yet";
                    }
                    System.Console.Write(s);
                    System.Threading.Thread.Sleep(1);
                }
            };

        a();
    }
}

```

Unfortunately I could not use the `?:`-operator as I have not found a way to stop incrementing `i` without the `if`.
> 2 votes

# Answer
# Ruby, 80 71 67 Bytes

*Edit: Thanks to manatwork for shaving off 13 whole bytes*

```
267.times{puts"Not ready yet"
sleep 1}
loop{puts"Eat your hot dog"}

```
> 2 votes

# Answer
# Python, 115 bytes

My first time trying something like this. I am also a beginner so here it goes in Python 3 for 115 bytes:

```
import time
for i in range(267):
    time.sleep(1)
    print("Not ready yet")
while 1:
    print("Eat your hotdog")

```
> 1 votes

# Answer
On the basis that the OP wants hotdogs continuously, until the end of time - which I understand from the phrase:

> After this time has elasped, you should output Eat your hot dog until the end of time.

This is my answer:

# C++, 187 188 224 167 bytes

Whitespace removed (167 bytes):

```
#include<stdio.h>
#include<windows.h>
int main(){for(;;){for(int x=0;x<267;x++){Sleep(1000);printf("Not ready yet");}Sleep(1000);printf("Eat your hot dog");}return 0;}

```

readable form (224 bytes):

```
#include <stdio.h>
#include <windows.h>

int main() {
  for( ; ; ){
    for(int x=0; x < 267; x++){
      Sleep(1000);
      printf("Not ready yet");
    }
    Sleep(1000);
    printf("Eat your hot dog");
  }
  return 0;
}

```

If, on the other hand, OP enjoys his hot dogs in moderation, then this is my answer:

**Whitespace removed (158 bytes):**

```
#include<stdio.h>
#include<windows.h>
int main(){for(int x=0;x<267;x++){Sleep(1000);printf("Not ready yet");}Sleep(1000);printf("Eat your hot dog");return 0;}

```

**readable form (198 bytes):**

```
#include <stdio.h>
#include <windows.h>

int main() {
  for(int x=0; x < 267; x++){
    Sleep(1000);
    printf("Not ready yet");
  }
  Sleep(1000);
  printf("Eat your hot dog");
  return 0;
}

```
> 1 votes

# Answer
# JavaScript Blocks Editor for micro:bit, 90 Bytes

The code:

```
basic.showString("Not ready yet")
basic.pause(254000)
basic.showString("Eat your hot dog")

```

You can try it here.

Got inspired by the Scratch answer to solve the task with my micro:bit. The only Problem is that the pause-block starts after outputting the first string so i needed to reduce the pause by 13s.

Note: The old Microsoft Block Editor for micro:bit is shorter to create but produces more code so is in fact longer.
> 1 votes

# Answer
# Excel VBA ~~122~~ 94 bytes

```
Sub p()
e=Now+#0:4:27#
Do
[a1]=IIf(Now<e,"Not ready yet","Eat your hot dog")
Loop
End Sub

```

Thanks Taylor Scott
> 1 votes

# Answer
# Excel VBA, 82 Bytes

Anonymous VBE immediates window function that takes no input and outputs whether or not you should eat your hot dog to cell `[A1]`.

```
d=Now+#0:4:27#:Do:[A1]=IIf(Now<d,"Not ready yet","Eat your hot dog"):DoEvents:Loop

```
> 1 votes

# Answer
## Javascript, 83 Bytes

```
d=Date.now()
while(1)alert(Date.now()-d<267000?"Not ready yet":"Eat your hot dog"))

```

Alertz for everyone!
> 0 votes

# Answer
# PERL, 76 bytes

```
$|++;
for(1..247){print'Not ready yet';sleep 1};print "Eat your hot dog";for(;;){}

```
> 0 votes

# Answer
## **PHP** 88 bytes

```
<?$t=0;do{$t++;echo "Not ready yet";sleep(1);} while ($t<267);echo "Eat your hotdog";?>

```
> 0 votes

# Answer
## REXX, 82 bytes

```
do forever
if time(e)<267 then say 'Not ready yet'
else say 'Eat your hot dog'
end

```
> 0 votes

# Answer
# Java 7, 152 bytes

```
void c(){for(long s=System.nanoTime(),e=s+(long)267e9;s<e;s=System.nanoTime())System.out.println("Not ready yet");System.out.print("Eat your hot dog");}

```

**Explanation:**

```
void c(){                                 // Method
  for(                                    //  Loop
      long s=System.nanoTime(),           //    Current time in nanoseconds as start
      e=s+(long)267e9;                    //    End time (267 seconds later)
      s<e;                                //    Loop as long as we haven't reached the end time
      s=System.nanoTime())                //    After every iteration get the new current time in nanoseconds
    System.out.println("Not ready yet");  //   Print "Not ready yet" as long as we loop
                                          //  End of loop (implicit / single-line body)
  System.out.print("Eat your hot dog");   //  Print "Eat your hot dog"
}                                         // End of method

```
> 0 votes

# Answer
# PHP, 68 bytes

```
for($t=268;$t--;sleep(1))echo$t?"Not ready yet←":"Eat your hot dog";

```

continuous output;  is ASCII 10 = LF. Run with `-r`.

**one-time output, 50 bytes**

```
Not ready yet<?sleep(267);echo"←Eat your hot dog";

```

where  is ASCII 13 = CR. Save to file or use piping to run.
> 0 votes

# Answer
# RBX.Lua, 69 bytes

```
for i=1,267 do print"Not ready yet"Wait(1)end;print"Eat your hot dog"

```

RBX.Lua is the language used on ROBLOX.com. It is a modified version of Lua 5.1 that features a built-in 'Wait' function. The above code is pretty self-explanatory, below is a more readable version:

```
for i = 1, 267 do
    print("Not ready yet");
    Wait(1);
end

print("Eat your hot dog");

```

The code outputs "Not ready yet" continuously into **STDOUT**, for 267 seconds (4 minutes 27 seconds) before outputting "Eat your hot dog".
> 0 votes

# Answer
# C - 130 bytes

It could be slightly shorter (128bytes), but I thought it neater to overwrite "Not ready yet"

```
#include<stdio.h>
#include<unistd.h>
int main(){printf("Not ready yet");fflush(stdout);sleep(267);printf("\rEat your hot dog\n");}

```
> 0 votes

# Answer
# Python 2.7, ~~90~~ 88 bytes

```
import time;exec"print'Not ready yet';time.sleep(1);"*267;while 1:print"Eat your hotdog"

```
> -1 votes

# Answer
# VBA,126 Bytes

```
sub hd()
Debug.print "Not ready Yet"
application.wait(now+timevalue(00:04:27))
Debug.print "Eat your hot dog"
end sub

```
> -1 votes

---
Tags: code-golf, date
---


# Question
Title: Count number of hefty decimals between 2 numbers
Let's say we have a non-negative integer that is "hefty" (that is, "heavy") if its average digit value is greater than 7.

The number 6959 is "hefty" because:

(6 + 9 + 5 + 9) / 4 = 7.5

The number 1234 is not, because:

(1 + 2 + 3 + 4) / 4 = 2.5

Write a function, in any language,

`HeftyDecimalCount(a, b)`

which, when provided two positive integers a and b returns an integer indicating how many "hefty" integers are within the interval \[a..b\], inclusive.

For example, given a=9480 and b=9489:

```
9480   (9+4+8+0)/4 21/4 = 5.25
9481   (9+4+8+1)/4 22/4 = 5.5
9482   (9+4+8+2)/4 23/4 = 5.75
9483   (9+4+8+3)/4 24/4 = 6
9484   (9+4+8+4)/4 25/4 = 6.25
9485   (9+4+8+5)/4 26/4 = 6.5
9486   (9+4+8+6)/4 27/4 = 6.75
9487   (9+4+8+7)/4 28/4 = 7
9488   (9+4+8+8)/4 29/4 = 7.25   hefty
9489   (9+4+8+9)/4 30/4 = 7.5    hefty

```

Two of the numbers in this range are "hefty" and so the function should return 2.

Some guidelines:

* assume that neither a or b exceeds 200,000,000.
* an n-squared solution will work, but will be slow -- what's the fastest we can solve this?

# Answer
The problem can be solved in \\$O(\operatorname{polylog}(b))\\$.

We define \\$f(d, n)\\$ to be the number of integers of up to \\$d\\$ decimal digits with digit sum less than or equal to \\$n\\$. It can be seen that this function is given by the formula

$$f(d, n) = \sum\_{i=0}^d (-1)^i \binom d i \binom {n+d - 10i} d$$

> Let's derive this function, starting with something simpler.
>
> $$h(n,d) = \binom{n+d-1}{d-1} = \binom{(n+1)+(d-1)-1}{d-1}$$
>
> The function \\$h\\$ counts the number of ways to choose \\$d - 1\\$ elements from a multi-set containing \\$n + 1\\$ different elements. It's also the number of ways to partition \\$n\\$ into \\$d\\$ bins, which can be easily seen by building \\$d - 1\\$ fences around \\$n\\$ ones and summing up each separated section . Example for \\$n = 2, d = 3\\$:
>
> | 3-choose-2 | fences | number |
> | --- | --- | --- |
> | `11` | `||11` | `002` |
> | `12` | `|1|1` | `011` |
> | `13` | `|11|` | `020` |
> | `22` | `1||1` | `101` |
> | `23` | `1|1|` | `110` |
> | `33` | `11||` | `200` |
>
> So, \\$h\\$ counts all numbers having a digit-sum of \\$n\\$ and \\$d\\$ digits. Except it only works for \\$n \< 10\\$, since digits are limited to 0 to 9. In order to fix this for values 10 to 19, we need to subtract the number of partitions having one bin with a number greater than 9, which I'll call overflown bins from now on.
>
> This term can be computed by reusing \\$h\\$ in the following way. We count the number of ways to partition \\$n - 10\\$, and then choose one of the bins to put the 10 into, which results in the number of partitions having one overflown bin. The result is the following preliminary function.
>
> $$g(n,d) = \binom{n+d-1}{d-1} - \binom{d}{1} \binom{n+d-1-10}{d-1}$$
>
> We continue this way for n less or equal 29, by counting all the ways of partitioning \\$n - 20\\$, then choosing 2 bins where we put the 10's into, thereby counting the number of partitions containing 2 overflown bins.
>
> But at this point we have to be careful, because we already counted the partitions having 2 overflown bins in the previous term. Not only that, but actually we counted them twice. Let's use an example and look at the partition \\$(10,0,11)\\$ with sum 21. In the previous term, we subtracted 10, computed all partitions of the remaining 11 and put the 10 into one of the 3 bins. But this particular partition can be reached in one of two ways:
>
> $$(10, 0, 1) \to (10, 0, 11) \\ (0, 0, 11) \to (10, 0, 11)$$
>
> Since we also counted these partitions once in the first term, the total count of partitions with 2 overflown bins amounts to 1 - 2 = -1, so we need to count them once more by adding the next term.
>
> $$g(n,d) = \binom{n+d-1}{d-1} - \binom{d}{1} \binom{n+d-1-10}{d-1} + \binom{d}{2} \binom{n+d-1-20}{d-1}$$
>
> Thinking about this a bit more, we soon discover that the number of times a partition with a specific number of overflown bins is counted in a specific term can be expressed by the following table (column \\$i\\$ represents term \\$i\\$, row \\$j\\$ partitions with \\$j\\$ overflown bins).
>
> ```
> 1 0 0 0 0 0 . .
> 1 1 0 0 0 0 . .
> 1 2 1 0 0 0 . .
> 1 4 6 4 1 0 . .
> . . . . . .
> . . . . . .
>
> ```
>
> Yes, it's Pascals triangle. The only count we are interested in is the one in the first row/column, i.e. the number of partitions with zero overflown bins. And since the alternating sum of every row but the first equals 0 (e.g. \\$1 - 4 + 6 - 4 + 1 = 0\\$), that's how we get rid of them and arrive at the penultimate formula.
>
> $$g(n,d) = \sum\_{i=0}^{d} (-1)^i \binom{d}{i} \binom{n+d-1 - 10i}{d-1}$$
>
> This function counts all numbers with \\$d\\$ digits having a digit-sum of \\$n\\$.
>
> Now, what about the numbers with digit-sum less than \\$n\\$ ? We can use a standard recurrence for binomials plus an inductive argument, to show that
>
> $$\begin{align} \bar{h}(n,d) & = \binom{n+d}{d} \\ & = \binom{n+d-1}{d-1} + \binom{n+d-1}{d} \\ & = h(n,d) + \bar{h}(n-1,d)\end{align}$$
>
> counts the number of partitions with digit-sum at most \\$n\\$. And from this \\$f\\$ can be derived using the same arguments as for \\$g\\$.

Using this formula, we can for example find the number of heavy numbers in the interval from 8000 to 8999 as \\$1000 - f(3, 20)\\$, because there are thousand numbers in this interval, and we have to subtract the number of numbers with digit sum less than or equal to 28 while taking in to account that the first digit already contributes 8 to the digit sum.

As a more complex example let's look at the number of heavy numbers in the interval \\$\[1234, 5678\]\\$. We can first go from 1234 to 1240 in steps of 1. Then we go from 1240 to 1300 in steps of 10. The above formula gives us the number of heavy numbers in each such interval:

|  |  |
| --- | --- |
| \\$\[1240, 1249\]\\$ | \\$10 - f(1, 28 - (1+2+4))\\$ |
| \\$\[1250, 1259\]\\$ | \\$10 - f(1, 28 - (1+2+5))\\$ |
| \\$\[1260, 1269\]\\$ | \\$10 - f(1, 28 - (1+2+6))\\$ |
| \\$\[1270, 1279\]\\$ | \\$10 - f(1, 28 - (1+2+7))\\$ |
| \\$\[1280, 1289\]\\$ | \\$10 - f(1, 28 - (1+2+8))\\$ |
| \\$\[1290, 1299\]\\$ | \\$10 - f(1, 28 - (1+2+9))\\$ |

Now we go from 1300 to 2000 in steps of 100:

|  |  |
| --- | --- |
| \\$\[1300, 1399\]\\$ | \\$100 - f(2, 28 - (1+3))\\$ |
| \\$\[1400, 1499\]\\$ | \\$100 - f(2, 28 - (1+4))\\$ |
| \\$\[1500, 1599\]\\$ | \\$100 - f(2, 28 - (1+5))\\$ |
| \\$\[1600, 1699\]\\$ | \\$100 - f(2, 28 - (1+6))\\$ |
| \\$\[1700, 1799\]\\$ | \\$100 - f(2, 28 - (1+7))\\$ |
| \\$\[1800, 1899\]\\$ | \\$100 - f(2, 28 - (1+8))\\$ |
| \\$\[1900, 1999\]\\$ | \\$100 - f(2, 28 - (1+9))\\$ |

From 2000 to 5000 in steps of 1000:

|  |  |
| --- | --- |
| \\$\[2000, 2999\]\\$ | \\$1000 - f(3, 28 - 2)\\$ |
| \\$\[3000, 3999\]\\$ | \\$1000 - f(3, 28 - 3)\\$ |
| \\$\[4000, 4999\]\\$ | \\$1000 - f(3, 28 - 4)\\$ |

Now we have to reduce the step size again, going from 5000 to 5600 in steps of 100, from 5600 to 5670 in steps of 10 and finally from 5670 to 5678 in steps of 1.

An example Python implementation (which received slight optimisations and testing meanwhile):

```
def binomial(n, k):
    if k < 0 or k > n:
        return 0
    result = 1
    for i in range(k):
        result *= n - i
        result //= i + 1
    return result

binomial_lut = [
    [1],
    [1, -1],
    [1, -2, 1],
    [1, -3, 3, -1],
    [1, -4, 6, -4, 1],
    [1, -5, 10, -10, 5, -1],
    [1, -6, 15, -20, 15, -6, 1],
    [1, -7, 21, -35, 35, -21, 7, -1],
    [1, -8, 28, -56, 70, -56, 28, -8, 1],
    [1, -9, 36, -84, 126, -126, 84, -36, 9, -1]]

def f(d, n):
    return sum(binomial_lut[d][i] * binomial(n + d - 10*i, d)
               for i in range(d + 1))

def digits(i):
    d = map(int, str(i))
    d.reverse()
    return d

def heavy(a, b):
    b += 1
    a_digits = digits(a)
    b_digits = digits(b)
    a_digits = a_digits + [0] * (len(b_digits) - len(a_digits))
    max_digits = next(i for i in range(len(a_digits) - 1, -1, -1)
                      if a_digits[i] != b_digits[i])
    a_digits = digits(a)
    count = 0
    digit = 0
    while digit < max_digits:
        while a_digits[digit] == 0:
            digit += 1
        inc = 10 ** digit
        for i in range(10 - a_digits[digit]):
            if a + inc > b:
                break
            count += inc - f(digit, 7 * len(a_digits) - sum(a_digits))
            a += inc
            a_digits = digits(a)
    while a < b:
        while digit and a_digits[digit] == b_digits[digit]:
            digit -= 1
        inc = 10 ** digit
        for i in range(b_digits[digit] - a_digits[digit]):
            count += inc - f(digit, 7 * len(a_digits) - sum(a_digits))
            a += inc
            a_digits = digits(a)
    return count

```

**Edit**: Replaced the code by an optimised version (that looks even uglier than the original code). Also fixed a few corner cases while I was at it. `heavy(1234, 100000000)` takes about a millisecond on my machine.
> 12 votes

# Answer
Recurse, and use permutations.

Suppose we define a general function that finds the values between a and b with a heaviness more than x:

```
heavy_decimal_count(a,b,x)

```

With your example of a=8675 to b=8689, the first digit is 8, so throw it away - the answer will be the same as 675 to 689, and again from 75 to 89.

The average weight of the first two digits 86 is 7, so the remaining digits need an average weight of more than 7 to qualify. Thus, the call

```
heavy_decimal_count(8675,8689,7)

```

is equivalent to

```
heavy_decimal_count(75,89,7)

```

So our range for the (new) first digit is 7 to 8, with these possibilities:

```
7: 5-9
8: 0-9

```

For 7, we still need an average of more than 7, which can only come from a final digit of 8 or 9, giving us 2 possible values.

For 8, we need an average of more than 6, which can only come from a final digit of 7-9, giving us 3 possible values.

So, 2+3 yields 5 possible values.

What is happening is that the algorithm is starting with the 4-digit number and dividing it into smaller problems. The function would call itself repeatedly with easier versions of the problem until it has something it can handle.
> 5 votes

# Answer
Maybe you can skip many candidates in the interval from a to b by accumulating their "heaviness".

if you know the length of you number you know that every digit can change the heaviness by only 1/length.

So, if you start at one number which is not heavy you should be able to calculate the next number which will be heavy, if you increase them by one.

In your example above starting at 8680 avg=5.5, which is 7-5.5=1.5 point away from you heaviness border, you'd know that there are 1.5/(1/4)=6 numbers in between, which are NOT heavy.

That should to the trick!
> 3 votes

# Answer
How about a simple recursive function? To keep things simple, it calculates all heavy numbers with `digits` digits, and a minimal digit sum of `min_sum`.

```
int count_heavy(int digits,int min_sum) {
  if (digits * 9 < min_sum)//impossible (ie, 2 digits and min_sum=19)
    return 0; //this pruning is what makes it fast

  if (min_sum <= 0)
      return pow(10,digits);//any digit will do,
      // (ie, 2 digits gives 10*10 possibilities)

  if (digits == 1)
  //recursion base
    return 10-min_sum;//only the highest digits

  //recursion step
  int count = 0;
  for (i = 0; i <= 9; i++)
  {
     //let the first digit be i, then
     count += count_heavy(digits - 1, min_sum - i);
  }
  return count;
}

count_heavy(9,7*9+1); //average of 7,thus sum is 7*9, the +1 is 'exceeds'.

```

Implemented this in python and it found all 9-digit heavy numbers in ~2 seconds. A little bit of dynamic programming could improve this.
> 1 votes

# Answer
# C, for interval \[a,b\] it is O(b-a)

```
c(n,s,j){return n?c(n/10,s+n%10,j+1):s>7*j;}

HeftyDecimalCount(a,b){int r; for(r=0;a<=b;++a)r+=c(a,0,0); return r;}

```

//the exercise

```
main()
{
 printf("[9480,9489]=%d\n", HeftyDecimalCount(9480,9489));
 printf("[0,9489000]=%d\n", HeftyDecimalCount(9480,9489000));
 return 0;
}

```

//the results

```
//[9480,9489]=2
//[0,9489000]=66575

```
> 0 votes

---
Tags: math, fastest-algorithm
---


# Question
Title: Greedily partition the list of combinations with repetition
First, a few definitions:

* Given `n` and `k`, consider the sorted list of **multisets**, where for each multiset we choose `k` numbers from `{0, 1, ..., n-1}` with repetitions.

For example, for `n=5` and `k=3`, we have:

> \[(0, 0, 0), (0, 0, 1), (0, 0, 2), (0, 0, 3), (0, 0, 4), (0, 1, 1), (0, 1, 2), (0, 1, 3), (0, 1, 4), (0, 2, 2), (0, 2, 3), (0, 2, 4), (0, 3, 3), (0, 3, 4), (0, 4, 4), (1, 1, 1), (1, 1, 2), (1, 1, 3), (1, 1, 4), (1, 2, 2), (1, 2, 3), (1, 2, 4), (1, 3, 3), (1, 3, 4), (1, 4, 4), (2, 2, 2), (2, 2, 3), (2, 2, 4), (2, 3, 3), (2, 3, 4), (2, 4, 4), (3, 3, 3), (3, 3, 4), (3, 4, 4), (4, 4, 4)\]

* A **part** is a list of multisets with the property that the size of the intersection of all multisets in the part is at least `k-1`. That is we take all the multisets and intersect them (using multiset intersection) all at once. As examples, `[(1, 2, 2), (1, 2, 3), (1, 2, 4)]` is a part as its intersection is of size 2, but `[(1, 1, 3),(1, 2, 3),(1, 2, 4)]` is not, because its intersection is of size 1.

**Task**

Your code should take two arguments `n` and `k`. It should then greedily go through these multisets in sorted order and output the parts of the list. For the case `n=5, k=3`, the correct partitioning is:

```
(0, 0, 0), (0, 0, 1), (0, 0, 2), (0, 0, 3), (0, 0, 4)
(0, 1, 1), (0, 1, 2), (0, 1, 3), (0, 1, 4)
(0, 2, 2), (0, 2, 3), (0, 2, 4)
(0, 3, 3), (0, 3, 4)
(0, 4, 4)
(1, 1, 1), (1, 1, 2), (1, 1, 3), (1, 1, 4)
(1, 2, 2), (1, 2, 3), (1, 2, 4)
(1, 3, 3), (1, 3, 4)
(1, 4, 4)
(2, 2, 2), (2, 2, 3), (2, 2, 4)
(2, 3, 3), (2, 3, 4)
(2, 4, 4)
(3, 3, 3), (3, 3, 4)
(3, 4, 4), (4, 4, 4)

```

Here is another example for `n = 4, k = 4`.

```
(0, 0, 0, 0), (0, 0, 0, 1), (0, 0, 0, 2), (0, 0, 0, 3)
(0, 0, 1, 1), (0, 0, 1, 2), (0, 0, 1, 3)
(0, 0, 2, 2), (0, 0, 2, 3)
(0, 0, 3, 3)
(0, 1, 1, 1), (0, 1, 1, 2), (0, 1, 1, 3)
(0, 1, 2, 2), (0, 1, 2, 3)
(0, 1, 3, 3)
(0, 2, 2, 2), (0, 2, 2, 3)
(0, 2, 3, 3), (0, 3, 3, 3)
(1, 1, 1, 1), (1, 1, 1, 2), (1, 1, 1, 3)
(1, 1, 2, 2), (1, 1, 2, 3)
(1, 1, 3, 3)
(1, 2, 2, 2), (1, 2, 2, 3)
(1, 2, 3, 3), (1, 3, 3, 3)
(2, 2, 2, 2), (2, 2, 2, 3)
(2, 2, 3, 3), (2, 3, 3, 3)
(3, 3, 3, 3)

```

**Clarification of what greedy means:** For each multiset in turn we look to see if it can be added to the existing part. If it can we add it. If it can't we start a new part. We look at the multisets in sorted order as in the example given above.

**Output**

You can output the partitioning in any sensible format you like. However, multisets should be written horizontally on one line. That is an individual multiset should not be written vertically or spread over several lines. You can choose how you separate the representation of parts in the output.

**Assumptions**

We can assume that `n >= k > 0`.

# Answer
> 4 votes
# Jelly, ~~26~~ 25 bytes

```
œ&µL‘<⁴ȧ⁹ȯ
œċµç\L€=⁴œṗµḊ’

```

Full program which prints a representation of a list of lists, each list being a part, e.g. for n=5, k=3:

```
[[[0, 0, 0], [0, 0, 1], [0, 0, 2], [0, 0, 3], [0, 0, 4]], [[0, 1, 1], [0, 1, 2], [0, 1, 3], [0, 1, 4]], [[0, 2, 2], [0, 2, 3], [0, 2, 4]], [[0, 3, 3], [0, 3, 4]], [0, 4, 4], [[1, 1, 1], [1, 1, 2], [1, 1, 3], [1, 1, 4]], [[1, 2, 2], [1, 2, 3], [1, 2, 4]], [[1, 3, 3], [1, 3, 4]], [1, 4, 4], [[2, 2, 2], [2, 2, 3], [2, 2, 4]], [[2, 3, 3], [2, 3, 4]], [2, 4, 4], [[3, 3, 3], [3, 3, 4]], [[3, 4, 4], [4, 4, 4]]]

```

*Note: the representation used removes the redundant* `[` *and* `]` *around lists of length 1.*

**Try it online!** or see a pretty print version (cost 3 bytes)

### How?

```
œ&µL‘<⁴ȧ⁹ȯ - Link 1, conditional multi-set intersection: list x, list y
œ&         - multi-set intersection(x, y)
  µ        - monadic chain separation (call that i)
   L       - length(i)
    ‘      - increment
     <     - less than?:
      ⁴    -     2nd program input, k
       ȧ   - logical and with:
        ⁹  -     link's right argument, y (y if i is too short, else 0)
         ȯ - logical or (y if i is too short, else i)

œċµç\L€=⁴œṗµḊ’ - Main link: n, k
œċ             - combinations with replacement(n, k) (sorted since n implies [1,n])
  µ            - monadic chain separation (call that w)
         œṗ    - partition w at truthy indexes of:
   ç\          -     reduce w with last link (1) as a dyad
     L€        -     length of €ach
        ⁴      -     2nd program input, k
       =       -     equal (vectorises)
           µ   - monadic chain separation
            Ḋ  - dequeue (since the result will always start with an empty list)
             ’ - decrement (vectorises) (since the Natural numbers were used by œċ)

```

# Answer
> 3 votes
# MATLAB, 272 bytes

```
function g(n,k);l=unique(sort(nchoosek(repmat(0:n-1,1,k),k),2),'rows');p=zeros(0,k);for i=1:size(l,1)p=[p;l(i,:)];a=0;for j=1:size(p,1)for m=1:size(p,1)b=0;for h=1:k if(p(j,h)==p(m,h))b=b+1;end;end;if(b<k-1)a=1;end;end;end;if(a)fprintf('\n');p=l(i,:);end;disp(l(i,:));end;

```

**Output:**

```
>> g(5,3)
 0     0     0

 0     0     1

 0     0     2

 0     0     3

 0     0     4

 0     1     1

 0     1     2

 0     1     3

 0     1     4

 0     2     2

 0     2     3

 0     2     4

 0     3     3

 0     3     4

 0     4     4

 1     1     1

 1     1     2

 1     1     3

 1     1     4

 1     2     2

 1     2     3

 1     2     4

 1     3     3

 1     3     4

 1     4     4

 2     2     2

 2     2     3

 2     2     4

 2     3     3

 2     3     4

 2     4     4

 3     3     3

 3     3     4

 3     4     4

 4     4     4

>> g(4,4)
 0     0     0     0

 0     0     0     1

 0     0     0     2

 0     0     0     3

 0     0     1     1

 0     0     1     2

 0     0     1     3

 0     0     2     2

 0     0     2     3

 0     0     3     3

 0     1     1     1

 0     1     1     2

 0     1     1     3

 0     1     2     2

 0     1     2     3

 0     1     3     3

 0     2     2     2

 0     2     2     3

 0     2     3     3

 0     3     3     3

 1     1     1     1

 1     1     1     2

 1     1     1     3

 1     1     2     2

 1     1     2     3

 1     1     3     3

 1     2     2     2

 1     2     2     3

 1     2     3     3

 1     3     3     3

 2     2     2     2

 2     2     2     3

 2     2     3     3

 2     3     3     3

 3     3     3     3

```

Two empty lines between different parts.

**Ungolfed:**

```
function g(n,k);
l=unique(sort(nchoosek(repmat(0:n-1,1,k),k),2),'rows');
p=zeros(0,k);
for i=1:size(l,1)
    p=[p;l(i,:)];
    a=0;
    for j=1:size(p,1)
        for m=1:size(p,1)
            b=0;
            for h=1:k
                if(p(j,h)==p(m,h))
                    b=b+1;
                end;
            end;
                if(b<k-1)
                    a=1;
                end;
        end;
    end;
    if(a)
        fprintf('\n');
        p=l(i,:);
    end;
    disp(l(i,:));
end;

```

**Explanation:**

First we find all the multisets with brute force:

```
l=unique(sort(nchoosek(repmat(0:n-1,1,k),k),2),'rows');

```

`repmat(0:n-1, 1, k)` repeats the vector of values from `0` to `n-1` `k` times.

`nchoosek(x, k)` returns a matrix containing all k-combinations of the repeated vector.

`sort(x, 2)` sorts all the k-combinations, and then `unique(x, 'rows')` removes all duplicates.

`p=zeros(0,k);` creates an empty matrix with `k` columns. We'll use it as a stack. On each iteration of the outernmost `for` loop, we first add the current multiset to said stack: `p=[p;l(i,:)];`.

Then we check if the intersection of all multisets in the stack is at least `k-1` long with the following code (we can't use MATLAB's `intersect` command to check for the intersections, because it returns a set, but we need a multiset):

```
a=0;
for j=1:size(p,1)
    for m=1:size(p,1)
        b=0;
        for h=1:k
            if(p(j,h)==p(m,h))
                b=b+1;
            end;
        end;
        if(b<k-1)
            a=1;
        end;
    end;
end;

```

Now, if the intersection is long enough, `a == 0`, otherwise `a == 1`.

If the intersection isn't long enough, we print a newline and empty the stack:

```
if(a)
    fprintf('\n');
    p=l(i,:); % Only the current multiset will be left in the stack.
end;

```

Then we just print the current multiset:

```
disp(l(i,:));

```

# Answer
> 3 votes
# MATL, 34 bytes

```
vi:qiZ^!S!Xu!"@!&vt1&dXasq?0&Y)0cb

```

Parts are separated by a line containing whitespace.

Try it online!

### Explanation

*Disclaimer: this method seems to work (and it does in the test cases), but I don't have a proof that it always does*

Multisets are sorted, both internally (i.e. each multiset has non-decreasing entries) and externally (i.e. multiset *M* comes before multiset *N* if *M* precedes *N* lexicographically).

To compute the multiset intersection, the sorted multisets are arranged as rows of a matrix and consecutive differences are computed along each column. If all columns except at most one have all differences equal to zero, the multisets belong to the same part.

This test would give a false negative result for multisets like `(1,2,3)` and `(2,3,4)`: even if `2`, `3` are common entries, they would not be detected as such because they are in non-matching columns.

However, this doesn't seem to be a problem, at least in the test cases. It appears that a test between multisets like `1,2,3` and `2,3,4` never actually has to be done, because some intermediate multiset gave a negative result and so they already are in different parts. If this is indeed true, the reason no doubt has to do with the fact that the multisets are sorted.

I don't have a proof of this, though. It just seems to work.

```
v           % Concatenate stack vertically: gives an empty array. This will
            % grow into the first part
i:q         % Input n. Push [0 1 ... n-1]
i           % Input k
Z^          % Cartesian power. Each Cartesian tuple is on a row
!S!         % Sort each row
Xu          % Unique rows. This gives all multisets, sorted, each on a row
!           % Transpose
"           % For each column
  @!        %   Push current multiset as a row
  &v        %   Vertically concatenate with the part so far
  t         %   Duplicate
  1&d       %   Consecutive differences along each column
  Xas       %   Number of columns that contain at least one non-zero entry
  q?        %   If that number is not 1 (this means that the current
            %   multiset should begin a new part)
    0&Y)    %     Push last row, then the array with the remaining rows.
            %     Said array is a part, which we now know is complete
    0c      %     Push character 0. This will be shown as a line containing
            %     a space. This is used as a separator between parts.
    b       %     Bubble up. This moves the loose row to the top. This row
            %     is the beginning of a new part
            %   Implicitly end if
            % Implicitly end for
            % Implicitly display

```

# Answer
> 1 votes
# PHP, 245 Bytes

```
for(;$i<($n=$argv[1])**$m=$argv[2];$i++){for($a=[],$v=$i;$v|count($a)<$m;$v=$v/$n^0)array_unshift($a,$v%$n);sort($a);in_array($a,$r)?:$r[]=$a;}foreach($r as$k=>$v)$k&&count(array_diff_assoc($x[$c][0],$v))<2?$x[$c][]=$v:$x[++$c][]=$v;print_r($x);

```

Try it online!

Expanded

```
for(;$i<($n=$argv[1])**$m=$argv[2];$i++){ # loop till $argv[1]**$argv[2]
    for($a=[],$v=$i;$v|count($a)<$m;$v=$v/$n^0)
    array_unshift($a,$v%$n); # create base n array
    sort($a); #sort array
    in_array($a,$r)?:$r[]=$a; # if sorted array is not in result add it
}
foreach($r as$k=>$v)
    $k&& # > first item and
    count(array_diff_assoc($x[$c][0],$v))<2 # if difference is only 1 item between actual item and first item in last storage item
    ?$x[$c][]=$v # add item in last storage array
    :$x[++$c][]=$v; # make a new last storage array
print_r($x); # Output as array

```

Output as String

```
foreach($x as$y){$p=[];
foreach($y as$z){$p[]=$o="(".join(",",$z).")";}
    echo join(", ",$p)."\n";
}

```

## n\>15 for more precision

```
for($i=0;$i<bcpow($argv[1],$argv[2]);$i=bcadd($i,1)){
    for($a=[],$v=$i;$v|count($a)<$argv[2];$v=bcdiv($v,$argv[1]))
    array_unshift($a,bcmod($v,$argv[1]));
    sort($a);
    in_array($a,$r)?:$r[]=$a;
}

```

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


title: One Expression, Many Values

text:
# Question
Title: One Expression, Many Values
Using our familiar mathematical symbols: +, x, parenthesis, and any rational number, it's easy to create expressions that evaluates to some desired number. For example: `1+(2x3)=7`, `(1+2)+(3x6.5)=22.5` and so on. Boring enough.

In this challenge, we'll use a new operator: `±`. The use of `±` in an expression means you need to evaluate the expression by replacing the `±`'s by `+` or `-` in all possible ways, and return the set of all possible values. For example:

* `1±2±3 = {-4,0,2,6}` because `1±2±3` can be any of `1+2+3`, `1+2-3`, `1-2+3` and `1-2-3` and their values are `6,0,2,-4` respectively.
* `(±2)x(2±3) = {-10,-2,2,10}` for similar reasons.

Now, as it turns out, given any set of distinct real numbers, it's possible to create an expression with `+`,`x`,`(`,`)`,`±`, and real numbers that evaluates to the given set.

### Task

Your task is to write a program or function in a language of your choice, that takes a sequence (list/array/any convenient format) of *integers* and outputs an expression (as a string) consisting of `+`,`x`,`(`,`)`,`±`, and *rational numbers* that evaluates to the set of the given numbers.

* Note that the exact character `±` doesn't matter; you can use any other character of your choice as long as it's distinguishable from the other characters you're using. But you must mention which character you are using in your submission.
* The input is allowed to consist of decimal approximations (up to reasonable accuracy) of the rational numbers used.
* Input and output can be taken in any of the standard ways.
* Standard loopholes are forbidden.
* You can assume the given integers will be distinct, and provided in increasing order.
* Output may contain spaces and newlines.

### Winning Criterion

This is , so shortest code in bytes wins.

### Examples

```
Input        |  Possible output
-------------+-----------------------------
[1,2,3]      |  2±0.5±0.5
[-7,-3,1,21] |  (1±2)x(3±4)

```

Idea taken from a question in the Tournament of Towns, Fall 2015.

# Answer
> 11 votes
# Python 2, 56 bytes

```
f=lambda h,*t:t and"(.5?.5)*(%s+%%s)+"%f(*t)%-h+`h`or`h`

```

Try it online!

The `?` stands for `±`. Example usage:

```
f(-3,5,20) ->
(.5?.5)*((.5?.5)*(20+-5)+5+3)+-3

```

The idea is that we can take an expression `E` and adjoin a new value `h` to its set of values by doing `(.5±.5)*(E+-h)+h`.

# Answer
> 9 votes
# Haskell, 52 bytes

```
f(h:t)=shows h"+(.5?.5)*("++f[x-h|x<-t]++")"
f e="0"

```

Try it online!

Uses `?` for `±`. Example:

```
f [1,3,7] ->
1+(.5?.5)*(2+(.5?.5)*(4+(.5?.5)*(0)))

```

The function `shows` does `shows a b=(show a)++b`, a trick I learned from Lynn.

```
shows 12 "abc" ->
"12abc"

```

# Answer
> 5 votes
# Haskell, 58 bytes

Using `#` for `±`, as it's one less byte.

`f` takes a list of integers and returns a string.

```
f[x]=show x
f(x:r)=show x++"+(.5#.5)x("++f((-x+)<$>r)++")"

```

Result is of the form `n+(.5#.5)x(rest)`, where `n` is the first element of the list and `rest` is the representation of all the others with `n` subtracted from each.

Try it online!

# Answer
> 5 votes
# Jelly, 29 bytes

```
“(¤)”j.⁾+×j;”(
I;@Ḣj¢;”)ẋ⁸L¤¤

```

Prints **v+(0.5¤0.5)×(i1+(0.5¤0.5)×((i2+(0.5¤0.5)×(...(in)...)))** where **v** is the first number in the input array and **in** is the **nth** incremental difference between elements of the input array.

**Try it online!**

### How?

```
“(¤)”j.⁾+×j;”( - Link 1, adjoining list: no input
“(¤)”          - literal     ['(','¤',')']
      .        - literal     0.5
     j         - join        ['(',0.5,'¤',0.5,')']
       ⁾+×     - literal     ['+','×']
          j    - join        ['+',['(',0.5,'¤',0.5,')'],'×']
            ”( - literal     '('
           ;   - concatenate ['+',['(',0.5,'¤',0.5,')'],'×','(']

I;@Ḣj¢;”)ẋ⁸L¤¤ - Main link: list a               e.g. [-1,5,2]
I              - incremental differences(a)           [6,-3]
   Ḣ           - head(a)                              [-1]
 ;@            - concatenate (rev @rgs)               [-1,6,-3]
     ¢         - last link (1) as a nilad             ['+',['(',0.5,'¤',0.5,')'],'×','(']
    j          - join                                 [-1,['+',['(',0.5,'¤',0.5,')'],'×','('],6,['+',['(',0.5,'¤',0.5,')'],'×','('],-3]
             ¤ - nilad followed by link(s) as a nilad
            ¤  -     nilad followed by link(s) as a nilad
          ⁸    -         link's left argument, a
           L   -         length                       3
       ”)      -     literal ')'
         ẋ     -     repeat                           [')',')',')']
      ;        - concatenate                          [-1,['+',['(',0.5,'¤',0.5,')'],'×','('],6,['+',['(',0.5,'¤',0.5,')'],'×','('],-3,')',')',')']
               - implicit print                       -1+(0.5¤0.5)×(6+(0.5¤0.5)×(-3))

```

# Answer
> 4 votes
# 05AB1E, 25 bytes

```
0¸«¥X;D"+(ÿ±ÿ)*("ý¹g<')×J

```

Try it online!

**Explanation**

```
0¸«                        # prepend a 0 to input list
   ¥                       # calculate delta's
    X;D                    # push 0.5 twice
       "+(ÿ±ÿ)*("          # push this string and interpolate 0.5 where "ÿ" is
                 ý         # merge the list of delta's with this string as a separator
                  ¹g<')×J  # add the closing parenthesis

```

Building the expression from the right unfortunately ends up at that the same byte count with
`0¸«¥¤s¨RvX;Dy"ÿ+(ÿ±ÿ)*(ÿ)`. The 8 bytes used for the setup is the big waste here.

# Answer
> 3 votes
# Haskell, 54 bytes

```
f[]="0"
f(x:s)=show x++"+(.5?.5)*("++f(map(-x+)s)++")"

```

the +- sign is `'?'`. example:

```
f[1,2,3,4] = "1+(.5#.5)*(1+(.5#.5)*(1+(.5#.5)*(1+(.5#.5)*(0))))"

```

# Answer
> 2 votes
## JavaScript (ES6), ~~56~~ 51 bytes

```
f=([v,...a],x=v)=>x?x+`+(.5@.5)*(${f(a,a[0]-v)})`:0

```

Based on @JonathanAllan's formula. `@` stands for `±`.

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


title: Derive the Units

text:
# Question
Title: Derive the Units
## Challenge

Given a list of SI base units, a list of equations and a target, you must derive the units of the target using only the base units.

## Derived Units

*From Wikipedia:*

> The International System of Units (SI) specifies a set of seven base units from which all other SI units of measurement are derived. ***Each of these other units (SI derived units) is either dimensionless or can be expressed as a product of powers of one or more of the base units.***
>
> For example, the SI derived unit of area is the square metre (m2), and the SI derived unit of density is the kilogram per cubic metre (kg/m3 or kg m−3).

The seven SI base units are:

* Ampere, *A*
* Candela, *cd*
* Kelvin, *K*
* Kilogram, *kg*
* Metre, *m*
* Mole, *mol*
* Second, *s*

## Example

### Input

**Base units:**

```
d [m]
m [kg]
t [s]

```

**Equations:**

```
v = d/t
a = v/t
F = m*a
E = F*d

```

**Target:**

```
E

```

### Output

```
E [kg*m*m/s/s]

```

---

### Input

**Base units:**

```
G [cd]
L [m]
y [A]
a [K]

```

**Equations:**

```
T = y*y/L
A = T*G

```

**Target:**

```
A

```

### Output

```
A [cd*A*A/m]

```

## Rules

The units will be always be given in the form

```
a [b]

```

Where `a` will be a single uppercase or lowercase alphabetical letter and `b` will be a unit (one or more characters).

The equation will be in the form

```
a = c

```

Where `c` will be an expression which will only ever use previously defined units and the operators `*` and `/`.

Powers must be expanded. For example, the unit of area is officially `m^2`, but you should represent this as `m*m`. The same applies to negative powers such as speed (`m*s^-1`) which should be represented as a division: `m/s`. Similarly, the units for acceleration, `m/s^2` or `m*s^-2`, should be represented as `m/s/s`.

You do not have to do any cancelling out. For example, an output `C*s/kg/s` is valid even though it can be cancelled down to `C/kg`.

There is no specific order for the multiplication: `kg*s/m`, `s/m*kg`, `s*kg/m` are all valid (but `/m*s*kg` is invalid).

**Note: *You will never have to divide by a derived unit.***

## Winning

The shortest code in bytes wins

# Answer
> 12 votes
## Retina, ~~50~~ 48 bytes

```
 =

+`((.) (.+)\D*)\2(?!\w*])
$1$3
A-2`
](.).
$1

```

Try it online!

### Explanation

```
 =

```

Remove all equals signs together with the space in front of them. Who needs those anyway...

```
+`((.) (.+)\D*)\2(?!\w*])
$1$3

```

This performs the substitutions of known quantities. It repeatedly matches a quantity definition (the quantity is any character in front of a space and the definition the string after it), as well as some place after the definition where that quantity is used, and insert the definition for the usage. We exclude units from those matches (by ensuring that there is no `]` after the match), so that we don't replace `[m]` with `[[kg]]` for example. This substitution is repeated until the regex no longer matches (which means that there are no usages of a quantity left, and all lines have been turned into expressions of units).

```
A-2`

```

Discard all but the last line.

```
](.).
$1

```

Finally, remove extraneous square brackets. Basically, we want to keep the first `[` and the last `]` but discard all others. Those others always appear with an operator in between, so either as `]*[` or as `]/[`. But more importantly, those are the only cases where a `]` is followed by two more characters. So we match all `]` with two characters after them, and replace that with the second of those three characters to retain the operator.

# Answer
> 1 votes
# JavaScript (ES6), ~~155~~ ~~153~~ 152 bytes

```
(U,E,T)=>(u={},U.map(x=>u[x[0]]=x.slice(3,-1)),e={},E.map(x=>e[x[0]]=x.slice(4)).map(_=>s=s.replace(r=/[A-z]/g,m=>e[m]||m),s=e[T]),s.replace(r,m=>u[m]))

```

Takes base units and equations as arrays of strings.

```
f=
(U,E,T)=>(u={},U.map(x=>u[x[0]]=x.slice(3,-1)),e={},E.map(x=>e[x[0]]=x.slice(4)).map(_=>s=s.replace(r=/[A-z]/g,m=>e[m]||m),s=e[T]),s.replace(r,m=>u[m]))

console.log(
  f(
    ['d [m]', 'm [kg]', 't [s]'],
    ['v = d/t', 'a = v/t', 'F = m*a', 'E = F*d'],
    'E'
  )
)
console.log(
  f(
    ['G [cd]', 'L [m]', 'y [A]', 'a [K]'],
    ['T = y*y/L', 'A = T*G'],
    'A'
  )
)
```

## Explanation

```
// Base Units, Equations, Target
(U,E,T)=>(
    // Map variable names to SI units
    u={},
    U.map(x=>u[x[0]]=x.slice(3,-1)), // x[0] is the variable name,
                                     // x.slice(3,-1) is the unit

    // Map variable names to equations
    e={},
    E.map(x=>e[x[0]]=x.slice(4)) // x[0] is the variable name,
                                 // x.slice(4) is the unit

    // (Initialize return string to the target variable's equation
    // using the (useless) second argument to .map() below)
    // s=e[T]

    // For as many times as there are equations (chained from above),
    .map(_=>
        // Substitute each variable with its equivalent expression
        // if there is one.
        s=s.replace(
            r=/[A-z]/g, // Save this regex for final step.
            m=>e[m]||m
        ),

        // The working string variable is initialized here.
        s=e[T]
    ),

    // Substitute remaining variables with SI units and return.
    s.replace(r,m=>u[m])
)

```

---
Tags: code-golf, physics
---


title: You had me at hello

text:
# Question
Title: You had me at hello
**Task**

Read in a possibly infinite text stream or file, outputting its contents until the word `hello` has been output, abiding to the following rules.

* Once `hello` has been output, your code should quit immediately. It should not wait for a newline for example.
* Your code should output as it goes. That is it shouldn't read in a huge amount of input and then start outputting.
* If the stream/file doesn't contain `hello`, your code should just carry on outputting the input forever or until the end of the stream/file is reached.
* This is a case sensitive challenge, so `hello` is not equal to `Hello`.
* You may assume that the input consists solely of printable ASCII characters and newlines.
* Your code can't expect that the text will be terminated by a newline or that there will be any newlines at all in the input. Also, you code cannot assume that it will run on a machine with an infinite amount of memory.
* You may assume that your code will be called from an empty directory.

**Example input stream**

```
I once had a horse called hellopina.

```

**Output**

```
I once had a horse called hello

```

**Tip**

Run `yes | tr -d \\n | <your program>` to check if it works with infinite streams. If it doesn't print anything and/or leaks memory, the program doesn't comply with the spec. It should print `yyyyyyyyyyyyyyyyyyyyyy...` forever with no newlines.

# Answer
> 2 votes
# Jelly, 24 bytes

```
“Ṣẉ»ẇ⁸Ṇȧ®
ṫ-3;ƈ©Ȯ¤µ⁺Ç¿ṛ“

```

Try it online!

Explanation:

```
ṫ-3;ƈ©Ȯ¤µ⁺Ç¿ṛ“ Main link. Arguments: 0
ṫ-3            Truncate the list to its 4 last elements.
   ;ƈ©Ȯ¤       Store a character from STDIN in the register, print it, and append it to the list (list is initially [0]).
        µ      Start a new monadic chain, everything to the left is a link.
          Ç    Execute the helper link with the existing list as its argument.
         ⁺ ¿   Do-while loop, left link is body, right link is condition.
            ṛ“ When the loop ends, replace the return value with [] (invisible on output).

“Ṣẉ»ẇ⁸Ṇȧ® Helper link. Arguments: string
“Ṣẉ»ẉ⁸Ṇ   Check if "hello" isn't in the string.
        ® Return the character we stored in the register.
       ȧ  Check if both of the above are truthy.

```

# Answer
> 26 votes
# C (gcc), ~~81~~ ~~80~~ ~~76~~ ~~75~~ ~~72~~ ~~71~~ ~~70~~ 69 bytes

```
main(n,c){while(~(c=getchar())&n-0xb33def<<7)n=n<<5^putchar(c)/96*c;}

```

Try it online!

### How it works

This is a full program. We define a function **f** for our purposes. To save bytes, it is declared with two argument that default to *int*. This is undefined behavior, but in practice, **n** will be initialized as **1** when running the program without additional arguments, **c** will hold the lower 32 bits of the pointer to the argument vector

While the condition

```
~(c=getchar())&n-0xb33def<<7

```

holds, we'll execute the *while* loop's body:

```
n=n<<5^putchar(c)/96*c

```

To fully understand the condition, we must first examine the body. For now, all we observe is that `c=getchar()` reads a single byte from STDIN (if possible) and stores it in the variable **c**.

The byte sequence **hello** looks as follows in different representations.

```
char     decimal     binary (8 bits)
'h'      104         0 1 1 0 1 0 0 0
'e'      101         0 1 1 0 0 1 0 1
'l'      108         0 1 1 0 1 1 0 0
'l'      108         0 1 1 0 1 1 0 0
'o'      111         0 1 1 0 1 1 1 1

```

All of these fall in the range **\[96, 192)**, so `c/96` will evaluate to **1** for each of these bytes, and to **0** for all remaining ASCII characters. This way, `putchar(c)/96*c` (*putchar* prints and returns its argument) will evaluate to **c** if **c** is ```, a lowercase letter, one of `{|}~`, or the DEL character; for all other ASCII characters, it will evaluate to **0**.

**n** is updated by shifting it five bits to the left, then XORing the result with the result from the previous paragraph. Since an *int* is 32 bits wide (or so we assume in this answer), some of the shifted bits might "fall off the left" (signed integer overflow is undefined behavior, but gcc behaves as the x64 instruction it generates here). Starting with an unknown value of **n**, after updating it for all characters of **hello**, we get the following result.

```
 n  ?????????????????????????|???????
'h'                          |    01101000
'e'                          |         01100101
'l'                          |              01101100
'l'                          |                   01101100
'o'                          |                        01101111
-----------------------------+--------------------------------
    <------ discarded ------>|???????0101100110011110111101111

```

Note that the lower 25 bits form the integer **0xb33def**, which is the magic constant in the condition. While there is some overlap between the bits of two adjacent bytes, mapping bytes below **96** to **0** makes sure that there aren't any false positives.

The condition consists of two parts:

* `~(getchar())` takes the bitwise NOT of the result of reading (or attempting to read) a byte from STDIN.

If *getchar* succeeds, it will return the value of the read byte as an *int*. Since the input consists entirely of ASCII characters, the read byte can only have its lower 7 bits set, so the bitwise NOT will have its highest 25 bits set in this case.

If *getchar* fails (no more input), it will return **-1** and the bitwise NOT will be **0**.
* `n-0xb33def<<7` subtracts the magic constant from before from **n**, then shifts the result 7 units to the left.

If the last 5 read bytes were **hello**, the lowest 25 bits of **n** will be equal to **0xb33def** and the subtraction will zero them out. Shifting the difference will yield **0** as the 7 highest bits will "fall off the left".

On the other hand, if the last 5 read bytes were *not* **hello**, one of the lowest 25 bits of the difference will be set; after shifting, one of the *highest* 25 bits will be.

Finally, if *getchar* was successful and we didn't print **hello** yet, the bitwise AND, all of the highest 25 bits of the left operand and at least one of the highest 25 bits of the right one will be set. This way, `&` will yield a non-zero integer and the loop continues.

On the other hand, if the input is exhausted or we have printed **hello** already, one of the bitwise AND's operand will be zero, and so will the result. In this case, we break out of the loop and the program terminates.

# Answer
> 19 votes
# Bash, ~~74~~ ~~75~~ ~~103~~ ~~99~~ ~~88~~ ~~82~~ 76 bytes

*-10 bytes thanks to @DigitalTrauma!*
*-11 bytes thanks to @manatwork!*
*-6 bytes thanks to @Dennis!*

```
IFS=
b=ppcg
while [ ${b/hello} ];do
read -rN1 a
b=${b: -4}$a
echo -n $a
done

```

Explanation:

```
IFS=    # making sure we can read whitespace properly
b=ppcg  # set the variable b to some arbitrary 4 letter string

while [ ${b/hello} ]; do  # while the variable b doesn't contain "hello", do the following
    read -rN1 a           # get input
    b=${b: -4}$a          # set b to its last 4 chars + the inputted char
    echo -n $a            # output the inputted char
done

```

Try it online!

# Answer
> 13 votes
## Labyrinth, ~~43~~ 41 bytes

*Thanks to Sp3000 for saving 2 bytes.*

```
<_%-742302873844_::%*:*:420#+.:%):,*652_>

```

Try it online!

### Explanation

The basic idea is to encode the last five characters in base 256 in a single integer. When a new character comes in, we can "append" it by multiplying the integer by 256 and adding the new code point. If we want to look only at the last 5 characters, we take the value modulo 256<sup>5</sup> = 2<sup>40</sup> = 1099511627776. Then we can simply check whether this value is equal to 448378203247, which is what we get when we treat the code points of `hello` as base-256 digits.

As for the code... `<...>` is a bit of a Labyrinth idiom. It allows you to write an infinite loop without any conditional control flow on a single line, saving a lot of bytes on spaces and linefeeds. The main condition for this to work is that there are two disposable values on top of the stack when we reach the `<` (we normally use `0`s for that, but the actual value is arbitrary).

Of course, the program does need some conditional logic to figure out when to terminate. But conditionally ending the program is possible by dividing by a value which is zero when we want the program to end. The `<...>` construct works by shifting the entire row left (cyclically) when the IP is at the left end, and then immediately shifting it back into position. This means that the code is actually executed right to left. Let's reverse it:

```
_256*,:)%:.+#024:*:*%::_448378203247-%_

```

This is one iteration of the loop which reads a character, terminates if we've reached EOF, prints the character, adds it to our encoding, truncates that to 5 characters, checks for equality with `hello` and repeats. Here is how that works in detail (remember that Labyrinth is stack-based):

```
_256*            Multiply the encoding by 256 in preparation for the next iteration.
,                Read one byte from STDIN.
:)%              Duplicate, increment, modulo. If we hit EOF, then , returns
                 -1, so incrementing and modulo terminates the program due to
                 the attempted division by zero. However, if we did read a
                 character, we've just compute n % (n+1), which is always n itself.
:.               Print a copy of the character we just read.
+                Add it to our encoding (we'll make sure to multiply the
                 encoding by 256 at the end of the iteration, so there's room
                 for our new character).
#024             Push 1024, using the stack depth to push the initial 1.
:*:*             Square it twice. That gives 2^40.
%                Take the encoding modulo 2^40 to truncate it to the last 5
                 characters.
::               Make two copies of the encoding.
_448378203247    Push the value that corresponds to "hello".
-                Subtract it from the encoding, giving zero iff the last 5
                 characters were "hello".
%                Take the other copy of the encoding modulo this value, again
                 terminating if we've reached "hello".
                 The actual value of this modulo - if it didn't terminate the
                 the program - is junk, but we don't really care, we just need
                 any disposable value here for the <...>
_                We push a zero as the second disposable value.

```

# Answer
> 8 votes
# Bash, ~~73~~ ~~68~~ 66 bytes

```
IFS=
[[ $1 != olleh ]]&&read -rN1 c&&echo -n $c&&exec $0 $c${1::4}

```

Assumes a directory with no or only hidden files. Must be run as `<path/to/script>`.

Try it online!

### How it works (outdated)

At the beginning of the *while* loop, we first test if the string in the variable **s** (initially empty) equals **olleh** (**hello** backwards, olé), and return **0** (match) or **1** (not a match) accordingly. While formally part of the loop's condition, the outcome won't affect it on its own, as only the last command before `do` determines if the condition holds.

Next, we set the internal field separator to the empty string (so `read` won't choke on whitespace), read raw bytes (`-r`) from STDIN and store them in `c`. `$?` is the exit code of the previous command, so this reads exactly one (`-N1`) byte for a non-match and zero bytes (`-N0`). Reading zero bytes, whether its due to hitting EOF or because `-N0` was specified, causes `read` to exit with status code **1**, so the while loop will end; otherwise, the body is executed and we start over.

In the body, we first print the byte we read, then update **s** with `s=$c${s::4}`. This prepends the read byte to (up to) the first four bytes in **s**, so **s** will equal **olleh** once **hello** has been printed.

# Answer
> 8 votes
## Brainfuck, 658 bytes

```
+[>,.>++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++[-<->]+<[>-<[-]]>[-<,.>++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++[-<->]+<[>-<[-]]>[-<,.>+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++[-<->]+<[>-<[-]]>[-<,.>+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++[-<->]+<[>-<[-]]>[-<,.>++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++[-<->]+<[>-<[-]]>[-<<->>]]]]]<<]

```

Over 500 bytes are in the constants which I need to golf a bit.

It essentially is a state machine, so infinite input is not a problem.

This is the slightly commented version

```
+
[
  >,.
  >h
  [-<->]
  +<
  [
    >-<[-][in input spot, not h]
  ]
  >
  [
    -
    <
    [in input spot, h has been read]
    ,.
    >e
    [-<->]
    +<
    [
      >-<[-][in input spot, not e]
    ]
    >
    [
      -
      <
      [in input spot, e has been read]
      ,.
      >l
      [-<->]
      +<
      [
        >-<[-][in input spot, not l]
      ]
      >
      [
        -
        <
        [in input spot, l has been read]
        ,.
        >l
        [-<->]
        +<
        [
          >-<[-][in input spot, not l]
        ]
        >
        [
          -
          <
          [in input spot, l has been read]
          ,.
          >o
          [-<->]
          +<
          [
            >-<[-][in input spot, not o]
          ]
          >
          [
            -
            <
            [in input spot, o has been read]
            <->>
          ]
        ]
      ]
    ]
  ]
  <<
]

```

# Answer
> 8 votes
## brainfuck, 117 bytes

```
--->>>------>>>+>>>+>>>++++<,[.-----<-[>--<-----]<[<<<]>>>[<[<<<+>>>>->+<<-]>[>>
+>]<[+[-<<<]]>>[<+>-]>>]<[[-]<<<,<]>]

```

Formatted:

```
--->>>------>>>+>>>+>>>++++
<,
[
  .-----<-[>--<-----]<[<<<]
  >>>
  [
    <[<<<+>>> >->+<<-]
    >[>>+>]
    <[+[-<<<]]
    >>[<+>-]
    >>
  ]
  <[[-]<<<,<]
  >
]

```

Try it online.

This initializes the tape with the characters in `hello` offset by `107`, spaced out with one value every three cells, then keeps track of the last five characters seen and checks for a match with every new character processed, using a flag to the right of the string to keep track of whether there has been a match.

# Answer
> 7 votes
# Ruby, ~~46~~ 60 bytes

```
a="";loop{q=$<.getc;~p if a[-5..-1]=="hello"||!q;a+=q;$><<q}

```

Try it online!

Reads characters from stdin until the last 5 are `hello`, then outputs the string (or until no characters are left in stdin). Terminates with error.

Equivalent to:

```
a = ""
loop {
    q = $<.getc
    ~p if a[-5..-1] == "hello" || !q
    a += q
    $><< q
}

```

Or, more ungolfed:

```
a = ""
loop do
    q = STDIN.getc
    break if a[-5..-1] == "hello" or not q
    a += q
    print q
end

```

# Answer
> 7 votes
# Python 3, 120 116 104 Bytes

Works with infinite streams, first time golfing, any tips are appreciated.

```
import sys
a=1
c=''
while(a):
    a=sys.stdin.read(1)
    if a:print(end=a)
    c=(c+a)[-5:]
    if c=='hello':break

```

Thanks @DJMcMayhem for saving some bytes :)

# Answer
> 7 votes
# Cubix, ~~94 83 82 79 63~~ 56 bytes

```
p>q'-?w.uh'e@U7.'hqi?oqB-!ul.-..$WWu_q<o'\;>....6t?.../!@

```

Expanded:

```
        p > q '
        - ? w .
        u h ' e
        @ U 7 .
' h q i ? o q B - ! u l . - . .
$ W W u _ q < o ' \ ; > . . . .
6 t ? . . . / ! @ . . . . . . .
. . . . . . . . . . . . . . . .
        . . . .
        . . . .
        . . . .
        . . . .

```

# Notes

* The interpreter disables the input field when the program starts. As such, an infinite stream of input is impossible. This program takes the input character-by-character, so if it weren't for this limitation, it would work properly.
* This program doesn't clear up the stack, and it gets messy very quickly. Since the machine this will be used on apparently can give infinite input streams, it seems reasonable to assume that it also has infinite memory.
* Any and all golfing help is much appreciated.

# Try it online

You can try the program here.

# Explanation

## General idea

The general idea is that we want to read a character, and then check it against varying characters (first `h`, then `e`, then `l` etc.). To keep track of the character we have missed, we keep it at the very bottom of the stack. When we need it, we can easily bring it to the top again.

## Read/Write loop

The read-write loop is simply the 5<sup>th</sup> line. All characters that are not used are replaced by no-ops (`.`):

```
        . . . .
        . . . .
        . . . .
        @ . . .
' h q i ? o q B - ! u l . - . .
. . . . _ . . . . . . . . . . .
. . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . .
        . . . .
        . . . .
        . . . .
        . . . .

```

This can be split up in two parts: Reading and (writing and checking). The first part contains the instructions up to and including the question mark. The second part up is the rest of the line. Because this loops around, we assume we start with a stack of `[...]`

```
    @
'hqi?
    _

Explanation
'h          Push the character code of the h
            Stack: [..., 104]
  q         Send it to the bottom
            Stack: [104, ...]
   i        Read one character of the input (-1 for EOF)
            Stack: [104, ..., input]
    ?       Start of condition:
              if (input < 0):
    @           execute '@', ending the program
              if (input = 0):
                continue going right
              if (input > 0):
    _           turn to the right, reflect back ('_') and
                turn right again, effectively not changing
                the direction at all

```

The second part (writing and checking) is linear again. The stack starts as `[next-char, ..., input]`. We abstracted the next character, because that changes later in the program.

```
oqB-!ul.-  Explanation
o          Output the character at the top of the stack
 q         Send the input to the bottom of the stack
           Stack: [input, next-char, ...]
  B        Reverse the stack
           Stack: [..., next-char, input]
   -       Push the difference of the top two characters, which
           is 0 if both are equal, something else otherwise
           Stack: [..., next-char, input, diff]
    !      if (diff = 0):
     u       make a u-turn to the right
           else:
      l.     execute two no-ops
        -    push [input - next-char - input], which is disregarded
             later, so it effectively is a no-op as well.

```

Now, the IP will start again at the beginning of this loop, resetting the next character to check to `h`.

# Matching the next character

If the IP made a u-turn (i.e. the character we read and printed matched the next character in `'hello'`), we need to check what character the input was and depending on that, push the next character to the bottom of the stack. After that, we need to return to the read/write loop, without pushing `h` to the stack, so we need another way to get there.

First things first: determine what character the input was. The stack looks like this: `[..., prev-char, input, 0]`.

```
        . . . .
        - ? . .
        u h ' e
        . . . .
. . . . . . . . . ! u . . . . .
. . . . . . . . . \ ; . . . . .
. . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . .
        . . . .
        . . . .
        . . . .
        . . . .

```

To compare the input, we use the character code of `h` again. Initially, this was because I didn't really know how I was going to handle this and `h` is the first character in the string to check for, but it ended up being quite convenient. If we subtract the character code of h from the input, we get `-3` if the input is `e`, `0` if the input is `h`, `4` if the input is `l` and `7` if the input is `o`.

This is useful, because the `?` command lets us easily separate negative values from positive values and zero. As such, if the IP turns left, the difference was negative, so the input was `e`, so the next character should be an `l`. If the IP continues going straight, the difference was `0`, so the input was `h`, so the next character should be an `e`. If the input is an `l` or an `o`, the IP turns right.

All instructions executed before the aforementioned question mark are:

```
;!e'h-     Explanation
;          Delete the top of the stack
           Stack: [..., prev-char, input]
 !         if (input = 0):
  e          execute 'e' (no-op)
   'h      Push the character code of h
           Stack: [..., prev-char, input, 104]
     -     Push the difference of the input and 104
           Stack: [..., prev-char, input, 104, diff]

```

Now the IP changes its direction as detailed above. Let's go over the different possibilities.

# Input `'e'`

First we'll consider the input `e`, which causes the IP to move upwards from the `?`, since the difference is 3. All irrelevant characters have been removed from the cube.

```
        . > q '
        . ? . .
        . . . .
        . . . .
. . q . . . . . . . . l . . . .
$ W W . . . . . . . . > . . . .
. . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . .
        . . . .
        . . . .
        . . . .
        . . . .

```

The characters are executed in this order (excluding some control-flow characters):

```
q'l$WWq
q           Save the difference (-3) to the bottom of the stack so
            we can tell whether the l on the bottom of the stack is
            the first or the second l in hello
            Stack: [-3, ...]
 'l         Push the character code of l to the stack
            Stack: [-3, ..., 108]
   $W       no-op
     W      Sidestep into the loop
      q     Send the character code to the bottom
            Stack: [108, -3, ...]

```

Now the IP has reached the read/write loop again.

# Input `'h'`

If the input was `'h'`, the difference is 0, so the IP doesn't change its direction. Here's the cube again, with all irrelevant characters removed. Since this path includes quite a few no-ops, all the no-ops it passes have been replaced by `&`. The IP starts at the question mark.

```
        . . . .
        . ? w .
        . . ' e
        . . . .
. . . . . . . . . ! . . . . . .
. . . u _ q < . . \ . . . . . .
. . ? & & & / . . & . . . . . .
. . & . . . . . . & . . . . . .
        . . . .
        & & & &
        . . . .
        . . . .

```

The instructions executed are:

```
'e!\?q_
'e          Push the character code of the e
            Stack: [..., 101]
  !         if (101 = 0):
   \          reflect away (effectively a no-op)
    ?       if (101 > 0):
              turn right (always happens)
     q      Move 101 to the bottom of the stack
            Stack: [101, ...]
      _     No-op

```

And now we're entering the read/write loop again, so we're done.

# Other inputs

All other inputs result in a positive difference, so the IP turns right at the question mark. We still need to separate the `l` and the `o`, so that's what we'll do next.

## Separating the `'l'` and `'o'`

Keep in mind that the difference is 7 for `o` and 4 for `l` and that we have to end the program if the input was an `o`. Here's the cube again with the irrelevant parts replaced by a `.` and the no-ops the IP crosses have been replaced by ampersands.

```
        . . q .
        . ? w .
        . h ' .
        . U 7 .
. . . . . . . . . . . . . - . .
. . . . . . . . . . . . . & . .
. . . . . . / ! @ . . . . & . .
. . . . . . & . . . . . . & . .
        . . & .
        . . & .
        . . & .
        . . & .

h7'wq-!@
h           no-op
 7          Push 7 to the stack
            Stack: [..., diff, 7]
  'wq       Push w to the stack and send it to
            the bottom. We don't care about it,
            so it's now part of the ellipsis.
            Stack: [..., diff, 7]
     -!     if (diff = 7):
       @        End the program

```

# Discerning between the two `'l'`s

So, now we've we know that the input was an `l`, but we don't know which `l`. If it's the first, we need to push another `l` to the bottom of the stack, but if it's the second, we need to push an `o`. Remember we saved `-3` to the bottom of the stack just before we pushed the first `l`? We can use that to separate the two branches.

```
        . . . .
        . . . .
        . . . .
        . . . .
. . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . .
6 t ? . . . . . . . . . . . . .
. . . . . . . . . . . . . . . .
        . . . .
        . . . .
        . . . .
        . . . .

```

The stack starts as `[..., -3 or 140, ...]`

```
Explanation
6t?
6t          Take the 6th item from the top and move
            it to the top (which is either -3 or 140)
  ?         If that's positive, turn right, otherwise,
            turn left

```

## First `'l'`

If this was the first `'l'`, we need to push another `'l'`. To save bytes, we use the same characters as for the first `'l'`. We can simplify the stack to `[...]`. Here's the relevant part of the cube, with no-ops replaced by ampersands.

```
        p > q '
        . . . .
        . . . .
        . . . .
' . q . . . . . . . . l . . . .
$ W W . . . . . . . . > & & & &
. . ? . . . . . . . . . . . . .
. . . . . . . . . . . . . . . .
        . . . .
        . . . .
        . . . .
        . . . .

```

The following instructions are executed:

```
$'pq'lq
$'          no-op
  pq        no-op
    'l      Push the character code of l
            Stack: [..., 108]
      q     Send it to the bottom
            Stack: [108, ...]

```

We're about to enter the read/write loop, so we're done with this branch.

## Second `'l'`

If the input was the second `'l'` in `'hello'`, the IP turned right at the question mark. Once again, we can simplify the stack to `[...]` and the IP starts at `?`, pointing south this time.

```
        . . . .
        . . . .
        . . . .
        . . . .
. . . . . . . . . . . . . . . .
. . . u _ q < o ' \ . . . . . .
. . ? . . . . . . & . . . . . .
. . & . . . . . . & . . . . . .
        . . . .
        & & & &
        . . . .
        . . . .

```

The instructions executed are:

```
'oq_
'o          Push the character code of 'o'
            Stack: [..., 111]
  q         Move the top item to the bottom
            Stack: [111, ...]
   _        No-op

```

And the IP is about to enter the read/write loop again, so we're done with this branch as well.

# Answer
> 6 votes
## Haskell, ~~41~~ ~~47~~ 43 bytes

```
f l|w@"hello"<-take 5l=w|a:b<-l=a:f b|1<2=l

```

Haskell's laziness handles the infinite input/output quit well.

Try it online!

Edit: didn't handle finite input - fixed. Thanks @Leo for pointing out.

Edit II: @Ørjan Johansen saved 4 bytes. Thanks!

# Answer
> 5 votes
# C++, ~~142~~ 141 bytes

```
#import<iostream>
void f(std::istream&i){i>>std::noskipws;char c;for(std::string s="     ";s!="hello"&&i>>c;)s.erase(0,1),s+=c,std::cout<<c;}

```

Try it online!

# Answer
> 3 votes
## Node, 124 bytes

```
with(process)with(stdin)on('data',d=>[...d].map(c=>(s=(stdout.write(c),s+c).slice(-5))=='hello'&&exit()),setEncoding(),s='')

```

Not assuming that the stream will fit in available memory.

# Answer
> 3 votes
# PHP, ~~57 55~~ 53 bytes

```
while(hello!=$s=substr($s.$c,-5))echo$c=fgetc(STDIN);

```

as there are no infinite files, I take input from STDIN. Run with `-nr`.

Loop through input, print the current character, append it to `$s`, cut `$s` to the last 5 characters. Break loop when `$s` is `hello`.

# Answer
> 3 votes
# C#, 134 bytes

```
using C=System.Console;class P{static void Main(){var s="";for(int c;(c=C.Read())>=0&!s.Contains("olleh");C.Write(s[0]))s=(char)c+s;}}

```

Try It Online

Reads a character, checks it isn't -1 (EOS) and that we havn't seen "hello" yet, then prepends it to a string, and writes the character out. We prepend because `s[0]` is a lot shorter than `(char)s`. This has a quadratic cost in the length of the string, as it has to allocate and scan the entire input each time it reads a character (this will crash after 2GB of input due to constraints in the CLR, is that allowed?)

```
using C=System.Console;

class P
{
    static void Main()
    {
        var s="";
        for(int c;(c=C.Read())>=0&!s.Contains("olleh");C.Write(s[0]))
            s=(char)c+s;
    }
}

```

For a (longer: 142 bytes) version which *won't* run out of memory, and which has constant per-character cost, see below:

```
using C=System.Console;class P{static void Main(){var s="     ";for(int c;(c=C.Read())>=0&s!="hello";C.Write(s[4]))s=s.Substring(1)+(char)c;}}

```

This one keeps the last 5 characters in a 5-length string, which means short comparisons, and cheap last-char lookup, but is considerably more expensive to update.

```
using C=System.Console;

class P
{
    static void Main()
    {
        var s="     ";
        for(int c;(c=C.Read())>=0&s!="hello";C.Write(s[4]))
            s=s.Substring(1)+(char)c;
    }
}

```

# Answer
> 3 votes
# Vim, 39 bytes

```
:im hello hello:se noma
:map : i

i

```

Try it online!

```
:im hello                        "Remap 'hello' in insert mode to
          hello                "write hello, then hit escape
                 :se noma       "then set the buffer to not-modifiable
:map : i                        "THEN remap ':' to 'i' so that can't be changed

i                                "enter insert mode and await an infinite stream of input

```

# Answer
> 3 votes
# Ruby, ~~59~~ ~~49~~ ~~48~~ 43 bytes

Now rant-free, shorter, *and* without memory leak.

```
s=''
s=$>.putc$<.getc+s[0,4]until'olleh'==s

```

Saved 5 bytes by getting rid of some parentheses and a space thanks to Dennis

# Answer
> 3 votes
# PowerShell, 111 bytes

There is probably a better way to do this, but I can't see it at the moment.

```
while(($x=($x+$host.UI.RawUI.ReadKey("IncludeKeyDown").character+"     ").substring(1,5)).CompareTo("hello")){}

```

This reads the key strokes without supressing the echo. The character is added to $x which is trimmed to the last 5 characters and compared to "hello". This carries on until the comparison is true.

Note: this does not work in the PowerShell ISE. ReadKey is disabled in that environment.

# Answer
> 3 votes
# Python 3 (Linux), ~~73~~ 72 bytes

```
s=c='_';I=open(0)
while'olleh'!=s>''<c:c=I.read(1);s=c+s[print(end=c):4]

```

*Thanks to @MitchSchwartz for golfing off 1 byte!*

Try it online!

# Answer
> 3 votes
# Scheme 115 bytes

```
(do((c(read-char)(read-char))(i 0(if(eqv? c(string-ref"hello"i))(+ i 1)0)))((or(eof-object? c)(= i 5)))(display c))

```

Readable version:

```
(do ((c (read-char) (read-char))                            ; read stdin
     (i 0 (if (eqv? c (string-ref "hello" i)) (+ i 1) 0)))  ; check target
    ((or (eof-object? c) (= i 5))) ; finish if end of stdin, or word found
  (display c))                     ; display each character

```

This takes an individual char from stdin each time around the loop, and marks off its position on the target word as it meets the characters of "hello".

Stops when the input runs out or "hello" has been seen. No memory used on infinite stream.

# Answer
> 3 votes
# AWK, 95 bytes

```
BEGIN{RS="(.)"
split("hello",h,"")}{for(j=0;++j<6;){c=RT
printf c
if(c!=h[j])next
getline}exit}

```

There are 2 things I learned here:
1) To split records between characters use `RS="(.)"` and then `RT` must be used instead of `$1`
2) `ORS` is used by `print` and is defaulted to `"\n"`
3) I can't count to 2 and using `printf` is "cheaper" than assigning `ORS` and using `print`

Example usage: Place code in FILE

```
awk -f FILE some_data_file

```

or

```
some process | awk -f FILE

```

Code was tested using Dennis's `yes | ...` suggestion and I saw lots and lots of `y`s.

FYI, you can do the RS assignment as an option and pull it out of the `BEGIN` block via:

```
awk -v RS='(.)'

```

# Answer
> 3 votes
# 8086 machine code, 22 bytes

```
00000000  bf 11 01 b4 01 cd 21 ae  75 f6 81 ff 16 01 72 f3  |......!.u.....r.|
00000010  c3 68 65 6c 6c 6f                                 |.hello|
00000016

```

Equivalent assembly code:

```
org 0x100
use16
a:  mov di, msg
b:  mov ah, 1       ; read one byte from stdin with echo
    int 0x21        ; dos syscall -> result in AL
    scasb           ; if (DI++ == AL)
    jne a
    cmp di, msg+5
    jb b
    ret
msg db "hello"

```

# Answer
> 2 votes
# Pyth, ~~49~~ 47 bytes

```
Wn"hello"=>5+kp$__import__("sys").stdin.read(1)

```

Pyth's not very good at taking a single character of input. Everything in `$__import__("sys").stdin.read(1)` is simply doing that. Also, it means that this only runs offline.

Everything else is short...

The program is a bodyless while loop. Inside the condition, the program reads a character, prints it back, appends that character to `k` (which is initially the empty string), trims off all but the last 5 characters of `k`, and then checks that the result is not `"hello"`.

32 characters are getting one byte of input, 15 characters does the rest.

Tested on Linux, works even with no newline, infinite input, etc.

# Answer
> 2 votes
# Lua, ~~68~~ 64 bytes

```
l=""while l~="hello"do c=io.read(1)io.write(c)l=l:sub(-4)..c end

```

# Answer
> 1 votes
# Röda, ~~49~~ 47 bytes

```
{a=[0]*5{|x|[x];a=a[1:]+x;z if[a&""="hello"]}_}

```

Try it online!

This is an anonymous function that reads characters from its input stream and outputs them until "hello" is found. It uses the array `a` to track the last characters.

It outputs some junk to STDERR, but I understood that is allowed.

Explanation:

```
{
    a=[0]*5                /* Initialize the array with 5 zeroes. */
    {|x|                   /* For each x in the input stream: */
        [x];               /* Print x */
        a=a[1:]+x;         /* Add x and remove the sixth last character. */
        z if[a&""="hello"] /* If "hello" is found, crash the program */
                           /* with an undefined variable. */
    }_                     /* End for loop. */
}

```

# Answer
> 1 votes
## Python + msvcrt (Windows), ~~114~~ 105 bytes

Both of these solutions use information provided by this SO answer.

```
import sys,msvcrt
x=""
o=sys.stdout
while"hello"!=x[-5:]:c=msvcrt.getch();o.write(c);o.flush();x=x[-4:]+c

```

## Python (Unix terminal), ~~145~~ ~~136~~ 135 bytes

Same as above, but for Unix terminal. This version can be partially tested online if you comment out the second line (to avoid an error), except that the input has to be user-entered and newline terminated (only to test online). For the full functionality, you have to run in a terminal.

```
import sys as s,tty
tty.setraw(s.stdin.fileno())
x=""
o=s.stdout
while"hello"!=x[-5:]:c=s.stdin.read(1);o.write(c);o.flush();x=x[-4:]+c

```

**Partial test online**

This requires a terminal to run, otherwise you'll get this error:

```
termios.error: (25, 'Inappropriate ioctl for device')

```

**Ungolfed**

```
import sys,tty
tty.setraw(sys.stdin.fileno())
x=0
while 1:
 c=sys.stdin.read(1)
 sys.stdout.write(c)
 sys.stdout.flush()
 if"hello"[x]==c:
    x+=1
    if x>5:break
 else:x=0

```

# Answer
> 1 votes
# Java 7, ~~122~~ ~~118~~ ~~124~~ ~~123~~ ~~150~~ 141 bytes

```
void c()throws Exception{String a="aaaaa";for(int b;!a.equals("hello")&(b=System.in.read())>=0;a=a.substring(1)+(char)b)System.out.write(b);}

```

Now stops when the end of the stream is reached. Now handles infinite input without running out of memory.

# Answer
> 1 votes
# C (gcc), ~~73~~ ~~72~~ ~~65~~ ~~63~~ ~~69~~ ~~77~~ ~~72~~ 71 bytes

It now terminates on the end of the input as well as handling input like this;

```
I once had a horse called hellhellopina.

```

```
i;main(c){for(;~(c=getchar())&i-5;i=putchar(c)^"hello"[i]?c=='h':i+1);}

```

Try it online!

# Answer
> 1 votes
# Ruby, 51 bytes

```
x="";$><<x[-1]while/hello./!~x=x[/.{0,5}$/]+$<.getc

```
* Does not expect newlines
* Works with infinite input

# Answer
> 1 votes
# AHK, 116 bytes

```
Loop,Read,%1%
{a=%A_LoopReadLine%`n
Loop,Parse,a
{Send % c:=A_LoopField
If((f:=c SubStr(f,1,4))=="olleh")
ExitApp
}}

```

There's nothing clever or magical in there, really. The variable `%1%` is the first passed argument and should be a file path with the stream. The file must be saved as it is updated but the code will read to the end even if it expands after the reading starts.

# Answer
> 1 votes
# Mathematica, 107 bytes

```
i="";EventHandler[Dynamic@i,"KeyDown":>(i=i<>CurrentValue@"EventKey";If[StringTake[i,-5]=="hello",Exit[]])]

```

The output becomes a field where the user can infinitely type text (including newlines) until the last 5 characters are equal to `"hello"`; at that point, it exits.

# Answer
> 1 votes
# brainfuck, 281 bytes

```
>++++++++[<+++++++++++++>-]>++++++++++[<++++++++++>-]<+>>+++++++++[<++++++++++++>-]>++++++++++[<+++++++++++>-]<+>+[[[[[,.<<<<[->>>>->+<<<<<]>>>>>[-<<<<<+>>>>>]<],.<<<[->>>->+<<<<]>>>>[-<<<<+>>>>]<],.<<[->>->+<<<]>>>[-<<<+>>>]<],.<<[->>->+<<<]>>>[-<<<+>>>]<],.<[->->+<<]>>[-<<+>>]<]

```

I'm not sure why, but I just felt like brainfuck was the right thing to do this. Doesn't require infinite memory, and can output forever.

## Explained

```
Set up the buffers with helo
This is done Naively; sue me
>++++++++[<+++++++++++++>-]     h
>++++++++++[<++++++++++>-]<+>   e
>+++++++++[<++++++++++++>-]     l
>++++++++++[<+++++++++++>-]<+>  o

THE MAIN LOOP
+
[ matches o
    [ matches l
        [ matches l
            [ matches e
                [ matches h
                    ,. Read a character and immediently write it
                    <<<<[->>>>->+<<<<<] Subtract it from h
                    >>>>>[-<<<<<+>>>>>] Correct the h
                    < Terminate this part of the loop if it matches h
                ]
                ,. Same as above
                <<<[->>>->+<<<<] Subtract it from e
                >>>>[-<<<<+>>>>] Correct the e
                < Terminate this part of the loop if it matches e
            ]
            ,. Same as above
            <<[->>->+<<<] Subtract it from l
            >>>[-<<<+>>>] Correct the l
            < Terminate this part of the loop if it matches l
        ]
        ,. Same as above
        <<[->>->+<<<] Subtract it from l
        >>>[-<<<+>>>] Correct the l
        < Terminate this part of the loop if it matches l
    ]
    ,. Same as above
    <[->->+<<] Subtract it from o
    >>[-<<+>>] Correct the o
    < Terminate this part of the loop if it matches o
]

```

Try it online!

# Answer
> 1 votes
# AWK, 72 bytes

```
BEGIN{RS="(.)"
h="olleh"}{printf RT
if("hello"==h=substr(h RT,2,6))exit}

```

I know, I have another `AWK` solution, but this is using a different approach with no loop, inspired by some of the other solutions.

As per @manatwork this one appears more `AWK`ish :)

# Answer
> 1 votes
# Chip, 154 bytes

```
H.G~.F~.E.D~.C~.B~.A~.AabB
Z<Z~<Z~<Z<Z~<Z~<Z-<Z-<CcdD
Z<Z~<Z~<Z<Z~<Z~<Z-<Z-<EefF
Z<Z~<Z~<Z<Z-<Z~<Z-<Z~<GghH
Z<Z~<Z~<Z<Z~<Z-<Z-<Zv'
 `--^--^-^--^--^--^-^~t

```

Try it online!

Chip is a language inspired by integrated circuits, and designed to operate on the individual bits of a byte stream.

### How it works

The rightmost 4x4 block of characters is the simple Chip cat program. We already need linebreaks for the other stuff, so we suffer no penalty spreading this across multiple lines. It simply copies input to output, one byte at a time.

The remaining elements are dedicated to detecting 'hello' and terminating once it is found.

The algorithm I use is to locate differences between the string `'hello'` and the five most recent bytes. If no differences are found, then we have seen `'hello'` and the program will terminate itself with element `t`.

In the actual implementation, there are eight sets of columns, one for each bit of the input. Let's look at the `0x8` bit, accessed by element `D`:

```
D~.
Z~<
Z~<
Z-<
Z~<
 -^-

```

The top row is looking at the current byte. In this case, its value, `D` is inverted by `~` and propagated into the wire along the right. So, if this bit is not set in the input, we know it can't be the `'o'` at the end of `'hello'`, and we can't yet terminate. We then look to the previous value in row 2, then the one before that in row 3, and so on. In the fourth row, we see a `-` instead of a `~`, meaning that we don't invert it. This is because the `'e'` of the keyword does not have this bit set, unlike all the other letters.

All this means that the wire along the right is activated if there is a discrepancy in the `0x8` bit of the last few bytes. The results for all bits are then collected along the bottom row, and if any of them show a discrepancy, we know to not yet terminate.

If the termination keyword were longer, we would simply need to add one row per additional byte.

# Answer
> 0 votes
# Python 105

Hopefully this count is fair, I've included what you need to set it up. Not the characters for the usage:

```
def c():
 b=yield
 while b!='hello':
  b+=yield b[-1]
  if len(b)==6:
   b=b[1:]
i=c()
i.next()

```

Usage would be something like this:

```
import string
import random

consumer = c()
consumer.next()
while True:
    try:
        char = random.choice( string.ascii_letters )
        print consumer.send( char )
    except GeneratorExit:
        print 'stopped'

```

# Answer
> 0 votes
# C(bcc gcc), 66 bytes

```
main(b,c){for(;~(c=getchar())&&b-'hell'|putchar(c)-'o';b=b<<8|c);}

```

the trick it is easy: We can consider the variable b as one buffer of 4 characters so, each char it read, it push it in the b buffer in this way b=b\<\<8|c. In b-'hell' it checks in b buffer there is "hell", if there is, and there is c=='o' too =\> it end the loop. It seems even in gcc in http://ideone.com/uPSMo6 it compile run and stop well. For to be ok the C language compiler I believe has to translate in the way:

1) the first argument 'b' it is argc so initialized with number of arguments one give to program

2) int is 4 characters of 8 bit

3) the 4 characters in quote 'abcd' are translated in one int/unsigned as in '1234' the number 0x31323334

Other above it assume

4) putchar() can not fail in write its character in stdout

i proposed this 67 bytes solution too but they said it is not ok.

```
z(c,b){for(;putchar(c=getchar()),~c&&b-0x68656c6c|c-'o';b=b<<8|c);}

```

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


# Question
Title: Shortest python A + B program with input and output
Some of you may say that I am wasting my time, but this task does not give me peace for more than 500 days. It is required to write a program in **Python 3.x** that takes two numbers as input and displays their sum. The numbers are given in the following format:

```
a b

```

Some example test cases:

```
100 500 -> 600
3 4     -> 7

```

The length of the code is calculated with the formula **max(code length without spaces or tabs or newlines, code length / 4)**. I know only 2 solutions, each of them has a length of 36 characters:

```
print(sum(map(int, input().split())))

```

and:

```
print(eval(input().replace(' ', '+')))

```

Also I know, that the exists solution with length of 34 symbols. You can check it on this website.

# Answer
Given the right hint toward the solution in the comment to the same question asked on stackoverflow ( see here ), I have got it right down to 34 and without any limitations on the input number or other tricks necessary:

`print(eval(input().replace(*' +')))`

Here a short summary of currently known different solutions:

> `print(eval(input().replace(' ','+'))) #` **36**
>
> `print(sum(map(int,input().split()))) #` **36**
>
> `print(eval(input().replace(*' +'))) #` **34**
>
> `print(sum(map(int,input()[::2]))) #` **33 (limited to numbers between 0 and 9)**

Maybe it could be considered cheating, but maybe not. At least there is no rule for this defined yet so let's include it into the collection of possible solutions:

> `import f;f.f() #` **13**

Required for this solution to work is a script f.py available in a search directory for modules of Python with following content:

```
def f():
    print(sum(map(int,input().split())))

```
> 6 votes

---
Tags: code-golf, tips, python
---