21
\$\begingroup\$

A GCSE computer science student recently made this hilarious blunder on their exam and posted it online. Now, you must make it work:

day = "Monday"
x = day.length
print(x)

To which they said the output was: 24 hours. Now, we all know that this is incorrect, but to validate this random student, try to golf a program that can take the code above and return the output of 24 hours.

Details

The primary constraint is that the code above must be included, in its entirety, in your program, and it must output the string "24 hours"

This program takes no input, but it must provide its output (to stdout, the screen, or anything) by utilizing a function called print. If this is built in to your language, then use it. If not, then you will need to write your own. A trailing newline may or may not be included, that's up to you.

If your language of choice does not support a variable declaration (or assignment) syntax of the format name = value, then it will not be usable in this challenge. Whichever language you use should support running code of the syntax that is provided in the exam. This eliminates most esolangs, such as Brainfuck, Jelly, and others that don't have = assignment-based variables. Some usable languages could include Swift, Python, Go, and others. The same goes for printing, although as stated earlier, you can create your own print function if that's necessary.

Rules

  • The provided code segment must not be in a comment or an unreachable section; it must be executed.
  • The provided code segment must be used as-is and cannot be golfed in any way.
  • Semicolons (or the equivalent to the end of a line for your chosen language) are the only allowed modification to the provided code segment.

Pseudocode Example

modify class String {
    let length = "24 hours"
}

day = "Monday"
x = day.length
print(x)

This is a Code Golf challenge, so do still try to make the code with the fewest bytes possible!

\$\endgroup\$
14
  • 2
    \$\begingroup\$ As interesting as the question is, it's unclear what language is required in submissions, or if there's no particular language requirement, what to do it a language doesn't support the syntax of day = "Monday" x = day.length print(x). Therefore, I've voted to close as needing details/clarity. \$\endgroup\$
    – lyxal
    Commented Aug 8 at 0:58
  • 4
    \$\begingroup\$ that would allow more languages, but then that has the problem of determining whether something is considered equivalent. \$\endgroup\$
    – lyxal
    Commented Aug 8 at 1:17
  • 2
    \$\begingroup\$ I think that whether code is "a comment or an unreachable section" is not an observable requirement. \$\endgroup\$
    – Wheat Wizard
    Commented Aug 8 at 20:10
  • 2
    \$\begingroup\$ It's some tests that British folks take in school, but it is shockingly similar to Code Gold Stack Exchange. \$\endgroup\$
    – TKDKid1000
    Commented Aug 9 at 15:08
  • 1
    \$\begingroup\$ @noodleperson Not necessarily, no. \$\endgroup\$
    – TKDKid1000
    Commented Aug 9 at 15:09

27 Answers 27

26
\$\begingroup\$

Python, 68 bytes

class day:length="24 hours";\
day = "Monday"
x = day.length
print(x)

Attempt This Online!

Not sure the backslash is cheating or not.

\$\endgroup\$
5
  • 5
    \$\begingroup\$ I'm a Python programmer (effectively) but still have to ask: how the hell does this work? \$\endgroup\$
    – Neinstein
    Commented Aug 8 at 9:07
  • 3
    \$\begingroup\$ @Neinstein: the often-forgotten explicit line joining behavior triggered by backslash-escaping the "physical newline" character. That makes line 2 just another field in class day's __dict__. Very clever! (Practical note: most coding styleguides recommend using the implict line joining behavior offered by opened brackets/parentheses, as this is less subtle and fragile.) \$\endgroup\$
    – ojdo
    Commented Aug 8 at 9:14
  • 9
    \$\begingroup\$ Definitely a creative abuse of python features and not cheating \$\endgroup\$ Commented Aug 8 at 9:33
  • 1
    \$\begingroup\$ Very clever submission! I suppose you could remove both the backslash and the newline for -2 bytes while keeping the embedded code intact, albeit less visually appealing. \$\endgroup\$
    – Jitse
    Commented Aug 8 at 13:17
  • \$\begingroup\$ Definitely no cheating, you have the original code as it is in there. This is just the whackiest thing ever. \$\endgroup\$
    – TKDKid1000
    Commented Aug 8 at 18:27
17
\$\begingroup\$

R, 60 bytes

day.length="24 hours"
day = "Monday"
x = day.length
print(x)

Attempt This Online!

. is just a part of variable name in R.

\$\endgroup\$
2
  • \$\begingroup\$ Well done, I really didn't expect anyone to beat my Uiua score! \$\endgroup\$ Commented Aug 8 at 15:56
  • \$\begingroup\$ Is there no language that would interpret day.length = "a" as day = { length : "a" } if day isn't defined? Seems like obvious syntactic sugar. \$\endgroup\$
    – JollyJoker
    Commented Aug 9 at 8:31
14
\$\begingroup\$

gnuplot, 58 bytes

length="\r24 hours"
day = "Monday"
x = day.length
print(x)

Try it online! (Note that due to a bug, the output from both TIO and gnuplot.io is different from the output produced on a local Windows machine, see the screenshot below.)

How this works:

The dot operator concatenates two strings. This way the string x contains "Monday\r24 hours". When printing x, first "Monday" appears, then the symbol \r (carriage return without linefeed) moves the cursor to the start of the same line and then printing "24 hours" over the string "Monday" overwrites it.

enter image description here

Edit: since this answer has received so many upvotes, I have decided to try and print the string "Monday\r24 hours" from the Linux OS. The result in Python can be checked online here.

\$\endgroup\$
4
  • 2
    \$\begingroup\$ It should work on Mac/Linux too, just TIO doesn't render \r properly in the browser since it just receives raw bytes. I don't have gnuplot installed to verify but I have used \r successfully in other languages on Mac. \$\endgroup\$ Commented Aug 8 at 16:57
  • 2
    \$\begingroup\$ And congrats on the shortest solution so far, this is a great idea! \$\endgroup\$ Commented Aug 8 at 16:58
  • \$\begingroup\$ @noodleperson thanks, good to know! Regarding the shortest one, we have a 51 byte Charcoal answer from Neil... \$\endgroup\$ Commented Aug 8 at 16:59
  • \$\begingroup\$ Neil's Charcoal solution is a bit shorter but it doesn't seem to be valid under current challenge rules \$\endgroup\$ Commented Aug 8 at 17:01
7
\$\begingroup\$

Wolfram Language (Mathematica), 65 bytes

print _^:=Print@"24 hours"
day = "Monday"
x = day.length
print(x)

Try it online!

I've taken the liberty of generalizing "This program... must provide its output... by utilizing a function called print" slightly. Strictly speaking, Mathematica doesn't exactly have functions; instead, it has a collection of definitions describing transformations on an expression. During evaluation, these are applied until no more such definitions are applicable.

print _^:=Print@"24 hours"

Add a definition to the symbol print: when it's multiplied with anything, print 24 hours.

day = "Monday"

Assign "Monday" to the symbol day.

x = day.length

Assign the dot product of day and length to the symbol x. There is no built-in rule for evaluating the dot product of a string and a symbol.

print(x)

Multiply print with x.


Probably against the spirit of the rules, but line 1 could simply be print:=Print@"24 hours" (-3 bytes): print 24 hours when print is encountered.

\$\endgroup\$
0
7
\$\begingroup\$

JavaScript, 63 bytes

print=_=>alert`24 hours`
day = "Monday"
x = day.length
print(x)

Now using alert rather than console.log, as suggested by Shaggy.

\$\endgroup\$
2
  • 1
    \$\begingroup\$ ahaha, i was excepting prototype change, but not print command l o l \$\endgroup\$ Commented Aug 8 at 6:28
  • 2
    \$\begingroup\$ 63 bytes. Or, if you prefer more vanilla JS, you could use alert instead of write. \$\endgroup\$
    – Shaggy
    Commented Aug 8 at 18:27
7
\$\begingroup\$

Python, 103 bytes

import gc
gc.get_referents(str.__dict__)[0]["length"]="24 hours"
day = "Monday"
x = day.length
print(x)

Attempt This Online!

Just for fun - a version with no syntax trickery. Uses implementation-specific behaviour, but works on CPython 3.12.2. str.__dict__ is an immutable proxy but it has a hidden reference to the underlying mutable dictionary, which we can access using the gc module.

\$\endgroup\$
3
  • \$\begingroup\$ This is great! How did you work it out? \$\endgroup\$
    – Simd
    Commented Aug 10 at 9:13
  • 1
    \$\begingroup\$ A bunch of ways to mutate builtin classes' __dict__s are listed here: github.com/python/cpython/issues/88004 \$\endgroup\$
    – pxeger
    Commented Aug 10 at 9:16
  • \$\begingroup\$ When I was testing whether this challenge was possible, I initially tried to modify the __dict__ but wasn't able to. This is impressive! \$\endgroup\$
    – TKDKid1000
    Commented Aug 10 at 12:13
5
\$\begingroup\$

Haskell, 91 bytes

main=print"24 hours"where{_._=0;length=0;day = "Monday";
x = day.length;
print(x)=putStr x}

Attempt This Online!

Thanks to WheatWizard

\$\endgroup\$
1
  • \$\begingroup\$ 85 bytes, or 91 if you consider that to be unreachable, which I still don't think is a clear requirement. \$\endgroup\$
    – Wheat Wizard
    Commented Aug 11 at 21:35
4
\$\begingroup\$

Uiua, 61 bytes

print=ggg&p
day = "Monday"
x = day.length
print(x)."24 hours"

Try it!

First, let's look at what the given program says in Uiua:

day = "Monday"    # Assign 'day' to the string.
x = day.length    # Assign 'x' to a function which pushes the value
                  # of 'day' and pushes twice the length of an array.
print(x)          # Call a function 'print' after calling the function 'x'.

x has to take an array as input, so we put it on the stack. x has three outputs, all of which are useless, so print has to three values and print "24 hours". We kill two birds with one stone by using "24 hours" as the array x takes. print is defined to pop three stack values and print a string.

If you prefer, the ."24 hours" section can be moved to its own line at the start of the program, but this way is a byte shorter and as far as I can tell is perfectly allowed.

\$\endgroup\$
2
  • \$\begingroup\$ Doesn't this alter the student's original code? I think you have to add that extra byte, as annoying as it might be. \$\endgroup\$
    – ouflak
    Commented Aug 9 at 9:41
  • 1
    \$\begingroup\$ @ouflak The original code never specified that it had a trailing or leading newline, although that is what most answers have been assuming, so I'll ask the challenger for clarification \$\endgroup\$ Commented Aug 9 at 13:12
4
\$\begingroup\$

C++ (GCC), 168 135 134 bytes

Thanks to G B for −33 bytes.

#include<cstdio>
#define print(Z)puts("24 hours");}
struct A{A*length;A(char*){}};main(){A*x,
day = "Monday";
x = day.length;
print(x)

Attempt This Online!

\$\endgroup\$
3
  • 2
    \$\begingroup\$ 135 bytes \$\endgroup\$
    – G B
    Commented Aug 8 at 9:31
  • 2
    \$\begingroup\$ Suggest #import<ios> instead of #include<cstdio> \$\endgroup\$
    – ceilingcat
    Commented Aug 9 at 1:22
  • \$\begingroup\$ 129 bytes \$\endgroup\$
    – Maya
    Commented Sep 6 at 12:47
4
\$\begingroup\$

PARI/GP, 58 bytes

a.length="24 hours"
day = "Monday"
x = day.length
print(x)

Attempt This Online!

PARI/GP's member function syntax is a bit weird. When we define a member function a.length="24 hours", we actually define a new function _.length = (a) -> "24 hours". This function is associated with _.length instead of a, so we can call it from any object, not just a.

\$\endgroup\$
3
\$\begingroup\$

Ruby, 68 bytes

def print a;puts"24 hours"end
day = "Monday"
x = day.length
print(x)

Try it online!

For reference, previous solution:

Ruby, 82 bytes

String.class_eval{def length;"24 hours"end}
day = "Monday"
x = day.length
print(x)

Try it online!

\$\endgroup\$
3
\$\begingroup\$

VBScript, 263 249 bytes

class o
public length
property let day(x)
end property
property get day
me.length="24 hours"
set day=me
end property
function print(x)
end function
function x
day = "Monday"
x = day.length
print(x)
end function
end class
set x=new o
wscript.echo x.x

day is a date function in VBScript. print is apparently also a function, but I don't know what it does. Wrapping everything in a class allows me to declare local properties to override them, so the only statement that actually achieves anything is x = day.length, which reads the me.length set earlier and returns it as the result of x.x, which we echo at the end of the script.

\$\endgroup\$
0
3
\$\begingroup\$

Perl 5, 85 bytes

sub day:lvalue{$x="24 hours"}sub x:lvalue{$x}
day = "Monday";
x = day.length
print(x)

Try it online!

Explanation

Works by defining two lvalue subroutines which can be assigned to, day and x, with the desired value hardcoded to "24 hours" for day. day.length actually concatenates the output of day and length but since $_ is undefined, length outputs undef which is coerced to the empty string.

\$\endgroup\$
2
  • \$\begingroup\$ Is there no way to be rid of that semi-colon? Even if it adds a byte for two? \$\endgroup\$
    – ouflak
    Commented Aug 9 at 9:51
  • 1
    \$\begingroup\$ @ouflak I was hopeful, since x= is string repetition, but because "Monday" is a constant, it can't be repeated. I'd be interested to know if there is a way though! Trivial solution to this challenge would be s//24 hours/;q;<original code unchanged> but then the assignment would just be avoided in a big string. \$\endgroup\$ Commented Aug 9 at 10:04
3
\$\begingroup\$

PowerShell, 67 bytes

filter print{'24 hours'}
$day = "Monday"
$x = $day.length
print($x)

Try it online!

This requires a modification to the original code by adding $ in front of the variables; functionally, I don't see any difference to the allowed adding of semicolons at the line ends, or replacing the "=" assignment operator with a different one.

Straightforward: 'filter' is basically the same as 'function' (but with automatic pipeline processing, which is not the point here), but has only 6 instead of 8 characters. It will ignore any arguments and just return the static string '24 hours'.

PowerShell, 167 165 185 171 bytes

165 Found two spaces that could be removed
185 print now generates the output
171 thanks to @julian who golfed the C#

Add-Type 'public class c{static void print(int x){System.Console.Write("24 hours");}public static void d(){int x;var
day = "Monday";
x = day.Length;
print(x);
}}'
[c]::d()

Try it online!

This takes the original code as C# and compiles it into a class c that can be used by PowerShell. Some further golfing of the C# might be possible ...

\$\endgroup\$
6
  • 4
    \$\begingroup\$ As much as I like PowerShell, I don't believe that this qualifies under the stated rules, as you are not using the student's code unaltered (you're adding the $ to the variable references. \$\endgroup\$ Commented Aug 8 at 11:08
  • 3
    \$\begingroup\$ I'd file that in the same category as the different assignment characters and semicolon as line ends. The original code is not altered in any relevant way. And it's certainly not golfed, as it adds 4 characters to the count ... \$\endgroup\$
    – user314159
    Commented Aug 8 at 14:04
  • 2
    \$\begingroup\$ Unfortunately, the comments on the question direct appear to state that it is, in fact, disallowed. \$\endgroup\$ Commented Aug 8 at 18:36
  • \$\begingroup\$ Maybe Try it online! would be an acceptable solution? \$\endgroup\$
    – Julian
    Commented Aug 9 at 5:39
  • \$\begingroup\$ @julian I thought about something like that, too, but it doesn't execute the original code, but runs the same script as above. I've added a C# based solution, though, where you might have some golfing ideas; I'm not really versed in C# ... \$\endgroup\$
    – user314159
    Commented Aug 9 at 14:31
3
\$\begingroup\$

Swift, 101 96 bytes

Assuming I am allowed to answer my own question...

extension String{var length:String{"24 hours"}}
var x="",
day = "Monday"
x = day.length
print(x)

The Swift compiler on tio.run doesn't support Swift v6.0 implicit returning, but a different one does. Try it here.

\$\endgroup\$
1
2
\$\begingroup\$

Raku (Perl 6) (rakudo), 126 124 bytes

use MONKEY-TYPING;augment class Str {method length {"24 hours"}};my \day:=my \x:=$;
day = "Monday";
x = day.length;
print(x)

Attempt This Online!

\$\endgroup\$
2
\$\begingroup\$

Google Sheets, 77 bytes

=let(print,lambda(_,"24 hours"),_,
day = "Monday"&
x = day.length,
print(x)
)
\$\endgroup\$
2
  • \$\begingroup\$ Clever, and I upvoted it, but I don't think this quite adheres to the rules (though I wonder if you posted this before the more stringent original-unaltered-code requirement?). \$\endgroup\$
    – ouflak
    Commented Aug 9 at 9:14
  • \$\begingroup\$ @ouflak yeah... spreadsheet formula languages are first-level functional languages and do not have assignable variables. They have constants only. The code given in the question is executed by the formula above, but = stands for comparison instead of assignment. \$\endgroup\$ Commented Aug 9 at 19:43
2
\$\begingroup\$

Lua, 84 65 bytes

day={length="24 hours"}os.
day = "Monday"
x = day.length
print(x)

Try it online!

-19 thanks to Daniel Schepler

\$\endgroup\$
4
  • \$\begingroup\$ Why not simply replace the first line with: day={length="24 hours"}os. ? \$\endgroup\$ Commented Aug 8 at 23:30
  • \$\begingroup\$ @DanielSchepler Clever, thanks! \$\endgroup\$
    – chunes
    Commented Aug 8 at 23:53
  • \$\begingroup\$ Or a bit more in the spirit of the original code you posted: p=print print=load"p('24 hours')" \$\endgroup\$ Commented Aug 8 at 23:55
  • \$\begingroup\$ Think I might have got a shorter solution by just a few bytes, assuming it's ok that mine ends with an error after executing the last line. \$\endgroup\$
    – ouflak
    Commented Aug 9 at 9:12
2
\$\begingroup\$

Haskell, 270 bytes

{-# LANGUAGE CPP #-}
{-# LANGUAGE OverloadedRecordDot #-}
{-# LANGUAGE DataKinds #-}
#define print(x) in putStrLn x
import GHC.Records
instance GHC.Records.HasField "length" String String where getField=const"24 hours"
main=let 
 day = "Monday"
 x = day.length
 print(x)

Try it

\$\endgroup\$
1
  • \$\begingroup\$ You don't need the first and last spaces in your language pragmata. But also here's a 156 bytes solution. \$\endgroup\$
    – Wheat Wizard
    Commented Aug 9 at 14:06
2
\$\begingroup\$

Fortran (GFortran) -cpp, 102 bytes

#define print(x)print*,"24 hours"
#define x !
#define day !
day = "Monday"
x = day.length
print(x)
end

Try it online!

Zsh attempt failed - Fortran works though! The -cpp flag allows me to #define away the problematic code. print(x) is a (poorly named) macro that prints the text in a way the compiler understands. The assignments for x = and day = just become comments (!).

\$\endgroup\$
1
  • \$\begingroup\$ Perhaps I'm bending the rules but this does comply. The = assignment exists. The variable assignment lines are reached by the compiler, and 'executed' as comments :P \$\endgroup\$
    – roblogic
    Commented Aug 16 at 4:38
1
\$\begingroup\$

Progress Openedge ABL, 198 bytes

def var day as char.
def var x as char.
def temp-table day
FIELD length as char init "24 Hours".
function print char(x as char):
message x.
end.
create day.
day = "Monday".
x = day.length.
print(x).

Works by defining each component of the code. First instance of day is read as a normal variable. day.length is read as the field 'length' in the table 'day'.

Try It
You may need to switch the dojo to run on v12.2.12 to avoid an error with the site

\$\endgroup\$
1
\$\begingroup\$

Lua, 62 bytes

print=print("24 hours")
day = "Monday"
x = day.length
print(x)

Try it online!

\$\endgroup\$
3
  • \$\begingroup\$ Takes advantage of the fact that you can redefine any function in Lua to do pretty much anything that's possible in the language - including built-ins. This does end with an error as it tries to execute the last line, but I assume that is ok since that's still within the spirit of the rules. \$\endgroup\$
    – ouflak
    Commented Aug 9 at 9:08
  • 1
    \$\begingroup\$ As far as I can tell, the output happens on the first line, which to me violates the spirit of the rule that the program "must provide its output (to stdout, the screen, or anything) by utilizing a function called print". \$\endgroup\$ Commented Aug 9 at 18:43
  • \$\begingroup\$ @DanielSchepler, It does utilize a function called 'print' to print correct ouput. Indeed, it's utilizing the Lua built-in print function. If it didn't do that, this code wouldn't work! (You'd error out on the first line.) The rules state that all of the lines of code must execute - which they do. The rules don't state that all, or any, of those executing line must contribute to the output. Only that the code itself produces the desired output, which this code does. \$\endgroup\$
    – ouflak
    Commented Aug 10 at 13:40
1
\$\begingroup\$

Rust, 145 bytes

macro_rules!x{($a:stmt;$b:tt=$c:expr;$e:stmt)=>{$a;$b=();print!("24 hours")}}fn main(){let(day,x);x!{
day = "Monday";
x = day.length;
print(x)
}}

Try it online!

the macro x! rewrites the code to:

day = "Monday";
x = ();
print!("24 hours")
\$\endgroup\$
1
  • \$\begingroup\$ Ah, using a macro, nice idea \$\endgroup\$ Commented Aug 9 at 21:08
1
\$\begingroup\$

Japt, 47 bytes

$day = "Monday"
x = day.length
print(x)$`24 ÊÀs

Test it

\$\endgroup\$
3
  • 2
    \$\begingroup\$ This is invalid because the whole snippet has to actually run. The = signs must be doing assignment. I think this might be possible in Japt but this way is not it. \$\endgroup\$ Commented Aug 8 at 19:31
  • \$\begingroup\$ Also, the original code segment is supposed to be used un-golfed. \$\endgroup\$
    – ouflak
    Commented Aug 9 at 8:59
  • \$\begingroup\$ Nice edit, very clever to just let it print() and ignore it! \$\endgroup\$ Commented Aug 12 at 17:54
1
\$\begingroup\$

Rexx (Regina), 63 bytes

Here are two solutions in Rexx. Thanks to its flexible syntax the solutions are quite compact.

Since Rexx does not have print function/statement, it is defined in both cases within the program.

In the first and shorter solution (below) the user-defined print function takes no argument (x is ignored), prints the hardcoded string 24 hours and stops the execution. No need to care about return statement, which is normally required. Although print is formally a function, the way it is defined it could only run once, which is enough for the task.

day = "Monday"
x = day.length
print(x)
print:say"24 hours"
exit

Try it online!

Rexx (Regina), 71 bytes

This longer solution is actually more exciting. This time the print function prints the content of the global variable x. The content of x comes from day., which is a separate from day variable. My guess is that since length is not defined it is simply ignored and, so, day.length evaluates to day..

day.="24 hours"
day = "Monday"
x = day.length
print(x)
print:say x
exit

Try it online!

\$\endgroup\$
1
\$\begingroup\$

Java 22, 210 159 bytes

Modified after @noodle person comment

class C{String day,length="24 hours";void print(String s){System.out.print(s);}void main(){String x;C day=new C();day.
day = "Monday";
x = day.length;
print(x);
}}

Un-golfed

class C {
  String day, length = "24 hours";
  void print(String s) { System.out.print(s); }
  void main() {
    String x;
    C day = new C();
    day.
    day = "Monday";
    x = day.length;
    print(x);
  }
}

Must be compiled and run with --release 22 and --enable-preview

javac --release 22 --enable-preview C.java
java --enable-preview C
\$\endgroup\$
1
  • 3
    \$\begingroup\$ Hey, in the rules it says "Semicolons (or the equivalent to the end of a line for your chosen language) are the only allowed modification to the provided code segment." so you shouldn't need reflection for that. Also, this currently is breaking the rule that "The provided code segment must not be in a comment or an unreachable section; it must be executed." because only the last line is currently running. \$\endgroup\$ Commented Aug 8 at 15:58
1
\$\begingroup\$

C (MSVC), 118 bytes

#define day /##/
#define x /##/
#define print(x)puts("24 hours");}
int main() {
day = "Monday"
x = day.length
print(x)

Try in GodBolt

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.