I am not sure I would use "just" in this context ;) This is the kind of trolling I can really appreciate. I can't stop laughing at the full script. So much dedication that went into this troll post (This monstrosity freaking runs and outputs something "meaningful").
... vs Esoteric Languages:
_"Hello World!
Yes, that's a complete program. Yes, it doesn't have a closing quotation. Pyth doesn't care. Pyth just keeps on trucking. Pyth just interprets _
as reversal. Pyth just implicitly prints the output. Pyth is also a very real programming language, although god help you if you write production code in it.
It also has online interpreters so you can verify that it works.
But we can do better. We can avoid writing "Hello World!"
entirely.
Enter...
“,ḷṅḳȦ»Ṛ
I swear, I didn't just smash the keyboard. I'll give you the online interpreter first, even.
Now do talk about why this works. Jelly is... Well, Jelly just is. It has strings. Strings aren't like most languages. There's a language construct (not even a function, it's built into the syntax) specifically made to compress strings, especially those that have English words (like, what do you know, "Hello World!"). “,ḷṅḳȦ»
is that string; »
marks it as a compressed string, ,ḷṅḳȦ
is the compressed content (that decompresses to Hello World!
... Don't ask me how, I don't exactly know)... And Ṛ
reverses it.
I'm pretty sure it's because the char*
being returned is allocated on the stack, so the memory gets freed instantly once the function returns.
Once free, it gets overwritten by garbage.
It works if you use new
to allocate it on the heap: Try it online!
Note that in practice this can cause memory leaks since you're not deleting the string.
I think this is the sim you're referring to. I had it in my history.
[Try it online](https://tio.run/##NYxRCoBACEQPtMycQOYiy35UEETQR9D5TTd7oD6Fcb2X49qf7XRvRdffU76yAENhgtS6jVxFAWDlmMI4GmjTMakREknGP/cX)
Even shorter and cleaner: <code>”yṄß</code>.
That's four bytes of Jelly and translates as "on the character y
(”y
), output that character and a newline (Ṅ
), then return to the start of the program (ß
).
It wouldn't surprise me if this could be beaten in some language, but you'd probably have to make some part of the program (most likely the newline, the output, or the infinite loop) implicit so that you don't have to waste bloated code writing it explicitly.
The c is fine. (TIO)
The rust is broken.
In IronPython python 2 only:
(locals().setitem("i",i+1) or i)
Thank me later. ^(never actually use this thanks)
If you're using globals()
it works in a lot more versions of python... I want to say it works in all or nearly all versions.
If you only need to do simple things with it tryitonline.net have a license to offer as part of their online interpreter service. Mathematica page
Simple implementation that also scans input for Letters (according to the Unicode Letter
property) so invalid chars in the input will be ignored.
sub score($s) { my @l = $s.comb(/<:Letter>/); @l».lc.unique.map(-> $k { $k => @l.grep($k) - @l.grep($k.uc) }).sort(-*.value) }
for < abcde dbbaCEDbdAacCEAadcB EbAAdbBEaBaaBBdAccbeebaec > -> $s { say score($s) }
OUTPUT:
(a => 1 b => 1 c => 1 d => 1 e => 1) (d => 2 b => 2 a => 1 c => 0 e => -2) (c => 3 d => 2 e => 1 a => 1 b => 0)
Python one-liner:
>![int(''.join(p)) for p in __import__('itertools').permutations('123456789') if all(int(''.join(p[:x]))%x==0 for x in range(1,10))][0]!<
My not-very-pretty Nat
version.
I'm having some trouble understanding the actual specification. Is there any reason why your "automated" tests require visual inspection to interpret? Like, wouldn't it be easier to include the expected output? I'm really struggling with the rules.
I probably don't understand the problem, but here's my best guess. https://tio.run/##nZNda8IwFIav7a84FC8quNDoHFMZbGwdE5xKdezGm9qGLqxfJKlziL/dpY1uona0XjU5PM85b5PW5VduzMg25TTyYfrNBQn72uEOzchKIJv4aeAwa5UwwjmNI97fuoHDOUxY7DMnhLVWS9JFQF3gwhH5g2VdbJIEjksmhNHY48au6jC/kSm13V52TQMBdxL3yQrtJENiTbjXjflTY44M1NCboNcx1Ft6oy/lA...
public static string ReplacePeriods(string arg) { string result = Regex.Replace(arg, @"(\D).(.)", "$1 $2"); result = Regex.Replace(result, @"(.).(\D)", "$1 $2"); return result; }
Try it online if you're lazy.
Aside from the fact that most of the languages they use on there look like gibberish without any syntax to them, I am genuinely confused how anyone learns those languages.
Edit: For anyone who's never been on this Stack Exchange or just doesn't know what I'm talking about, it's things like Jelly
J, both parts:
steps=. 4 2 $ 1 0 0 _1 _1 0 0 1 coords=. 0 0 , [: +/\ [: ; [: (] <@(# ,:)"0 1 steps $~ #) 2 # 1 + i.@>.@%: part1 =. [: +/ <: { coords
neighbors=. (0 0 -.~ > , { ;~ 1 0 1) +"1 ] next_neighbor_sum=. [: +/ ] ({~ ::0:)" 0 [ i. [: neighbors #@] { [ part2=. [: {: ] (] , coords@[ next_neighbor_sum ])^:([ > {:@])^:_ 1:
(part1 ; part2) 277678
We consider a coordinate system with 1 at location 0,0. Positive x goes rightward; positive y goes downward. We generate a flat list of the coordinates, in their correct spiral order. With this approach, part 1 becomes trivial (taking the correct element from the list) and part 2 becomes easier.
Zsh: Printable, non-space ANSI characers, 24 bytes
<<<${(F):-{~..!}w{~..!}}
All current unicode codepoints after !
, 30 bytes:
<<<${(F):-{..!}w{..!}}
I have some code that I wrote, but I don't know how it works. Modified to be slightly more readable (the original as included in the link was for a code golf competition),
type family a+b where Zero+b=b Succ a+b=a+Succ b type family a*b where Zero*b=Zero Succ a*b=a*b+b class(a#b)c|a b->c instance a*b~c=>(a#b)c
I understand how the type families work, but I don't understand how going from the multiplication type family (*)
to the multiplication type class (#)
works. Especially how the functional dependency is not violated. Do equality constraints have any special behaviour when it comes to functional dependencies?
Don't think parens are needed for ifs, but I tried with them like so and it still gives me as well. Would appreciate learning what I'm doing wrong (Am on mobile at the moment as well)
The value of &input
is not the same as the other two (which are indeed the same). Here’s a test program to show the addresses of each of those
&input
refers to the address in memory where the input
pointer is stored, whereas the other two do optimize to the same thing
Notably, it doesn't work in python3.9.
And if you black
it, it becomes more clear.
In a way, this should be a test case for code formatters; for example, black
doesn't remove unnecessary parentheses.
A functionally equivalent correctly-and-eagerly formatted version would look like this.
print("function isEven(number) {\n"+"\n".join(f"\t{'else 'if n!=1 else''}if number === {n}: return {str(n&1==0).lower()};"for n in range(1,int(1e10)))+"\n}")
Successfully made it even smaller! (also added missing semicolon).
Still trying to figure out how to bypass that .lower()
javascript - Try it online!
// warmup flipfront=(a,n)=>[...a.slice(0,n).reverse(),...a.slice(n)] // global flipfront=n=>[...a.slice(0,n).reverse(),...a.slice(n)] // global, in-place flipfront=n=>{for(i=0;i<n/2;)[a[i],a[n-++i]]=[a[n-i-1],a[i]]}
// challenge pancake==>a.map((,o,$,i=a.length-o)=>flipfront(a.indexOf(Math.max(...a.slice(0,i)))+1)||flipfront(i))
You can set the table dimnames right from within the table function by namimg the arguments. See example here: https://tio.run/##K/r/vyQxKSdVIzHRNrMoszhaxzBWRyEpSQHKM4rV/P8fAA
Also, table used in calculation is different from what you see in print. Check View(f) to see the actual layout.
I made a programming language that only accepts brackets and parentheses, here's "Hello, World!":
(((((((((((()()()()){}){}){}()))){}{}())[][][][])[][])[])[][][][][])([([][]{})]()()()([]))
A variable declared with declare -n name
I understand the logic you're trying to make with your -a
/-b
flags, but suppose I want to give one of those flags an element beginning with a -
? I much prefer -a
or -b
to take exactly one argument, which would then consume the following argument, whether it looks like a flag or not.
Also, _input=(`echo $@`)
prevents a user from specifying an --option 'with spaces'
. You can iterate over the command line arguments with just
for arg; do ... done
Anyway, check out zparseopts
, in the zsh/util
module. Here's a demo I just wrote.
See man zshmodules
for more information.
Here's a correct and efficient way to do it.
var listA = "aa,ab,ab,ac,bb,bb,bb,bbbd".Split(','); var listB = "aa,aa,ab,ab,bb,bb,de".Split(',');
var lookA = listA.ToLookup(l => l); var lookB = listB.ToLookup(l => l);
var result = new List<string>(); foreach (var el in lookA) { int count = Math.Min(el.Count(), lookB[el.Key].Count()); result.AddRange(Enumerable.Repeat(el.Key, count)); }
foreach (var el in result) Console.WriteLine(el);
Did you know that you can nest the $"" syntax?
$@"{($"{"@"}\"\{$"{"s"}"}{$"\""}")}" still produces @"\s".
See Try it Online.
I feel like >!APL!< could be used for this, but I couldn't wrap the ol' noodle around how and had to ask for a bit of help.
m←'GetType' b←⍉((≢m)⍴2)⊤⍳2*≢m g←(''@(⍸b))((⍴b)⍴m) g2←{⍵/⍨~2∧/0,''=⍵}¨↓g ⎕←↑g2
Let m
be one member name. It is 7 characters long, so we can take a 7-bit binary number and count up as many numbers as it can hold: 0000001, 0000010, 0000011, ..., 1111111 this can be interpreted as the 1 places representing every possible position of a wildcard asterisk in GetType
. Let b
be this boolean matrix, the ((member-length-in-characters)-number-of-bits)-base-2-encoding of (the first 2^(member-length)
numbers).
Let g
be the shape-of-b
-reshape-of-m
to repeat GetType
over and over again. And use @
to put asterisks replacing the letters at the positions indicated by the 1s
in the binary matrix, to give GetType, GetTyp*, GetTyp*e, GetTy**, ... *******
merger.
Let g2
be that, but with repeating asterisks GetT****
compressed down to one GetT*
. The (pairwise-logical-AND-reduction of the places where asterisks exist in a thing) compression of each word in the split of g
:
GetTyp* GetTy*e GetTy* GetT*pe GetT*p* GetT*e GetT* ... etc. for 127 of them
So then I just need to try all of those and stop at the shortest one which returns a unique value, and like heck can I do that in an online APL interpreter.
Goodness, for the amount of time I spend on Powershell codegolf, this was even longer. And it's not the entire problem either.
But now I know how to do it, gonna do this in Powershell, brb...
Yes, you do because you're only calling show
. If you want the UTF8 to be displayed properly, you must call print
/putStr . show
:
mov rdx, 13
should be 15
if you want the newline and exclamation mark printed.
Here is an online compiler/assembler where you can experiment
var s = 'InnS rloernixneoaLismiiafc stu ii seenDtacE'; console.log(s.split('').map(function(c,i){return s.charAt((i*13)%s.length)}).join('')); Try it online!
05AB1E with Bonus
For fun
'd¡`sFDL.Rs}U)DO„: +sðýJ
Explanation below
input is already in stack stack = ['3d6'] 'd¡ split input string on 'd' stack = [['3', '6']] ` put all items from list on stack stack = ['3', '6'] s swap top two items stack = ['6', '3'] F for N in range(0, a): stack = ['6'] D duplicate top item stack = ['6', '6'] L push [1..a] stack = ['6', [1, 2, 3, 4, 5, 6]] .R pick random item stack = ['6', 1] s swap top two items stack = [1, '6'] } end for loop body stack = [1, 5, 4, '6'] U get rid of top item stack = [1, 5, 4] )D duplicate stack stack = [[1, 5, 4], [1, 5, 4]] O sum of top item stack = [[1, 5, 4], 10] „: + concatenate ": " stack = [[1, 5, 4], '10: '] s swap top two items stack = ['10: ', [1, 5, 4]] ðý join list by space stack = ['10: ', '1 5 4'] J join everything together stack = ['10: 1 5 4'] top stack item gets printed stack = []
> Code golfers welcome.
w%n=(drop
w).(4).(mod
n)
main=mapM((putStrLn.)$max<$>show<>"Fizz"%3<>"Buzz"%5)[1..100]
90 bytes. Uses the Applicative instance for functions as well as the Semigroup instance for functions. Requires GHC 8.4 for Semigroup in the prelude.
I got this while messing around trying to (unsuccessfully) shorten this solution a few weeks ago. I believe this is the shortest publicly visible FizzBuzz.
The shortest known FizzBuzz is the 81 bytes by Henkma here.
Jelly's a newer language that was designed to beat the languages that beat GolfScript (possibly a few more generations than that). It's not the only one, but it's one of the two I'm most familiar with.
For what it's worth, it's fairly hard to do an infinite loop in GolfScript; you can do it but it's rather more verbose than the Jelly equivalent. The most natural way to write this code in GolfScript is 15 bytes:
{'y 'print 1}do
Pretty clear (if you know GolfScript), but rather verbose. (The basic problem is that you can't rely on implicit print because that requires the program to actually terminate.)
It wouldn't surprise me if there were a terser way to do the loop here (do
is a whole two characters!), but I can't see any way to get rid of having to write the print
.
I hate ranges of numbers and for
's dependency on it. For example take a look at this small exercise based on this code golf
You'll notice there's so many different ways to iterate over a range of ints incrementing, decrementing, inclusive of end and exclusive of end. And don't even try iterating over a range of int decrementing exclusive of end. I'd rather just write c-style for
loops
My SQLite solution
CREATE TABLE input(
data VARCHAR
);
INSERT INTO input(data)
VALUES('3,4,3,1,2');
WITH split_input(fish, data_str) AS (
SELECT
'',
data
FROM input
UNION ALL
SELECT
SUBSTR(data_str, 1, 1),
SUBSTR(data_str, 3)
FROM split_input
WHERE data_str != ''
),
school AS (
SELECT CAST(fish AS TINYINT) AS fish
FROM split_input
WHERE fish != ''
),
day_hist(d0, d1, d2, d3, d4, d5, d6, d7, d8, day) AS (
SELECT
SUM(CASE WHEN fish=0 THEN 1 ELSE 0 END),
SUM(CASE WHEN fish=1 THEN 1 ELSE 0 END),
SUM(CASE WHEN fish=2 THEN 1 ELSE 0 END),
SUM(CASE WHEN fish=3 THEN 1 ELSE 0 END),
SUM(CASE WHEN fish=4 THEN 1 ELSE 0 END),
SUM(CASE WHEN fish=5 THEN 1 ELSE 0 END),
SUM(CASE WHEN fish=6 THEN 1 ELSE 0 END),
0,
0,
0
FROM school
UNION ALL
SELECT
d1, d2, d3, d4, d5, d6, d7 + d0, d8, d0, day + 1
FROM day_hist
WHERE day < 256
)
SELECT
d0 + d1 + d2 + d3 + d4 + d5 + d6 + d7 + d8
FROM
day_hist
WHERE
day = 256
If saved as 6.sed
, and your input is in 6.txt
, you can run it like so: sed -f 6.sed 6.txt
.
Not really a script, but I tend to use this to test out stuff
> "int doesn't exist"
var_dump(int)
is still an error, as the article mentions. Try it online!
> "mysql_real_escape_string"
Alright, that is deprecated now, but…
>Alternatives to this function include:
>* mysqli_real_escape_string()
Sounds much better.
> Also who ever uses pure PHP for anything complex is out of their damn minds, there are many frameworks
So the correct way to use PHP is to not use PHP?
What if there was a turing complete DSL for arbitrary recursive descent parsers that looked BNFish? Say, something like this:
say .parse: '3+4*5*(1+2)', rule => <sub-expr>
given
grammar { rule sub-expr { <expr>* % <op('+')> } rule expr { [ <number> | '(' ~ ')' <sub-expr> ]* % <op('*')> } rule number { <.digit>+ } rule op ($op) { $op } }
where a rule is a function whose calling protocol took care of whitespace handling, backtracking bookkeeping if really necessary, etc., and displayed a parse tree like this:
「3+4*5*(1+2)」 expr => 「3」 number => 「3」 op => 「+」 expr => 「4*5*(1+2)」 number => 「4」 op => 「」 number => 「5」 op => 「」 sub-expr => 「1+2」 expr => 「1」 number => 「1」 op => 「+」 expr => 「2」 number => 「2」
(Imagine that it scaled up nicely to handling arbitrarily complex parsing, AST generation, and so forth.)
What if this all just worked? Thoughts?
Alternatively, this is POSIX sed and will remove multiple spaces after the headings as well.
sed '/^#/{s/#*/& /;s/# */# /}'
In R, the length of "hi there"
is also 1
, just try running it.
I think what's going on is that values in R are supposed to be vectors of values by default.
So length(list(1, 2, 3))
should be 3.
foo <- list(1, 2, 3) length(foo) # prints 3
Well, strings are scalar values iirc for R, meaning that operators will treat it like 1 value.
Thus, length
which expects a list of values needs to "cast it" to a list or like.
Thus, the example code is similar to
empty_str <- list("") # 1 value, the empty string empty_char <- list() # No scalar value, at all like a null value
So, I believe that the "casting function" would look like this in Python
def listize(x): # it's good if it is a list if isinstance(x, list): return x # None represents a missing value # so make an empty list elif x is None: return [] # A present value is like a collection of 1 datum. # place it by itself into a list. else: return [x]
And so I think the length(empty_char) == 0
statement is basically saying that the "empty_char" is like a None
/null
in mainstream languages.
For context, I think numpy broadcasting behavior is a good starting point when trying to understand R.
R is designed for working with collections of values (for statistics), so implicitly casting 1 value to a collection of 1 value and a missing value to a collection of 0 values makes sense. (Insert argument about whether it's good in practice).
FULL DISCLAIMER: I don't know R, I may be totally off base but this argument has given me enough closure to move on from thinking about this.
That hideous code is not the only way we can match.
getMass :: Body -> F64 getMass body = case body of Planet { mass = m } -> m Star { mass = m } -> m
You may like this 29 byte version:
(]=3+4=*)[:+/^:2(,"0/~i:1)&|.
Originally found here on Reddit, can't find the source link atm.
The difference between the two is what the value the expression evaluates to. I can do something like: int k = ++i;
At the end of the statement, i
's new values is one more than it was previously. But what is the value of k
(which was assigned the value the expression resulting from the evaluation of ++i
)
++i
is the pre-increment operator. Its value is the same as the value of i
AFTER i
has been incremented.
i++
is the post-increment operator. Its values is the same as the value of i
*BEFOREi` has been incremented.
See the below C++ code.
#include <iostream> using namespace std;
int main() {
int i = 0;
cout << "Original value of i: " << i << endl; cout << "Pre-increment evaluation: " << ++i << endl; cout << "i after evaulation: " << i << endl;
cout << "Post-increment evaluation: " << i++ << endl; cout << "i after evaulation: " << i << endl;
}
which prints:
Original value of i: 0 Pre-increment evaluation: 1 i after evaulation: 1 Post-increment evaluation: 1 i after evaulation: 2
(See on tio.run)
cell_values([H|T], S, Values) :- R = [V|Values],
cell_values(Coords, Matrix, Values).
Here, Values has to be the result and the tail of result with V in front of it. It can't be both [1,2,3]
and [2,3]
.
Your base case, I think it's too basic, it doesn't give any hint that the Values list ends, ever. I came up with a base case that is the last item in the Coords list and the Value list, and makes more use of Prolog's pattern matching to get the X and Y parts:
cell_values([[X,Y]|[]], Matrix, [Value|[]]) :- nth0(X, Matrix, Row), nth0(Y, Row, Value).
cell_values([[X,Y]|ItemTail], Matrix, [Value|ValueTail]) :- nth0(X, Matrix, Row), nth0(Y, Row, Value), cell_values(ItemTail, Matrix, ValueTail).
Queries:
?-cell_values([[0,0], [0,1]], [[2,1],[1,2]], Values), write(Values). ?-cell_values([[0,1]], [[1,2]], Values), write(Values).
Which seems to work for those cases, at least. Note that my "Values" deconstructs to "Value" for the head and "ValueTail" for the rest, and that "nth0(Y, Row, Value)" does the pattern maching to unify and connect the matrix row with the cell_values parameter.
Sounds like a perfect job for Group-Object.
Typed out a test (on mobile) Try It Online: https://tio.run/##fZLLbsIwEEX3/opRmkW7cFTDuhKUt9QiClFfqkQjGBq3Jo4SU4SAbw@Ok/BIo3o347nn@o4cyjVGsY9CJIm94AJjuIOGRZr3Lfr69k5f@k2389wZ01tW0atV9Oqm9zSeULc/mBS6U10r1ZfzrCxgZQUrJKmtq23Pn5bVtYualQdYxUSdWA2gcSi4AuszsAi5glaEnkJQGCuY8whnSkYbMsQ1HShcAh16SwQ3v...
Unable to insert link as reddit app says it’s invalid.
But actually
Use Map
if the lookup might result in a Nothing
and the domain is large(ish). How about the following?
statement = choice $ zipWith (\x c-> x <$ char c) [Inc ..] "+-><,."
To make the [Inc ..]
work you will need to pull apart your constructors into something like data Stmt = Atom Atom | Loop [Stmt]
and data Atom = Inc | ... | Out deriving Enum
: Try it online!
Of course, you could also just explicitly list the constructors yourself: Try it online!
Hm, what do you mean? That worked in Python 2 too.
See it in action: https://tio.run/##RYwxCoAwDAD3viKjblpwEfoYoYkGJCmhDn19bUHqjXdwqeRLxdcakYBUJ5l3Bw1SAwYWsENOHLrD1EoIsG6/6xjmx2SownhHYOfGqv/98p2SsWTgWl8
You try arguing that someone hasn't won a competition because their code wasn't "clean" enough :P
CodeGolf - as few characters as possible - has a clear way to measure a winner. Although it often devolves into arguing whether some code meets the conditions and it's hard to have challenges so perfectly specified that there's no room for misunderstanding.
Outside that, "fastest code" struggles because everyone has different computers and piles of different software installed.
And there isn't really an online PowerShell engine we can all agree to use as like other languages have. https://tio.run
does it, for very short scripts, but I think it's quite restricted.
And if you just want "write some code" without the competition bit, you can pick any code challenge you like - /r/dailyprogrammer, or /r/adventofcode for examples and write them in PowerShell.
Or do what some of us do, and trawl /r/powershell or https://StackOverflow.com/questions/tagged/powershell looking for questions we can answer by writing a few lines of "crunch this data" style code.
Not that I'm against it - feel free to post some, and I'll upvote and be interested.
This is top-notch J code, and deserves a TIO:
Note: After tangentstorm's and according to standard stackexchange code gold rules, this is 29 bytes.
For the record, it appears that all languages are available from all others, and Perl5 is already a shared library.
Just to clarify, the body of the post is an exchange between the folk who run TIO.run and me.
Bottom line is, given they prefer or may require fedora packages as the base of operations:
cache = {} def f(s): try: return cache[s] except: if not s: ans = 0 elif s[0] == s[-1]: ans = f(s[1:-1]) else: ans = min(f(s[1:]), f(s[:-1])) + 1 cache[s] = ans return ans
Recursion with memoization.
This is a small enough case you can just enumerate them.
Here's the online Mathematica code for your OP.
The result is 66 ways.
You can change the code to cover other small cases.
For larger cases, you'd need to avail yourself of mechanisms to count restricted partitions, see any good advanced combinatorics book for methods.
Simple recursive solution, returns a sequence, but can call .join
method on the function as required.
sub fold(UInt $n = 0) { return (1,) unless $n; flat .cache, 1, .reverse.map(* +^ 1) with samewith($n - 1) }
To get the same output as in description, with line breaks for readability
fold(8).batch(78)».join».say Try it online!
EDIT: Non-recursive version, essentially a translation of /u/TotalPerspective's one-liner
sub folds(UInt $n = 0) { my $s = 1; $s ~= 1 ~ $s.flip.trans('10' => '01') for ^$n; return $s; }
Returns a string, and obviously has better performance characteristics than my recursive solution.
The answer by /u/Kevoguy is a bit off - it overstates the probability by about 5%.
The correct probability is ~ 3.5553x10^-22
You can do this via a Markov Chain or use generating functions, among others.
On average, you'd need to roll 2,759,410,526,315,789,473,684,211 times to see one of the desired sequences.
Safe bet, no one has ever seen such a sequence in their D20 rolls.
J, both parts:
under_rot=. 2 :'(u@(] |. [) (-@] |. [) ]) v' NB. utility verb
f=. ([: +/ (}: , 0:) , -@# ]\ 1 $~ >./) under_rot (1 + ] i. >./) g=. (] , f@{:)^:({: . }:)^:_
part1=. [: <:@# g part2=. (<:@# - (i. {:))@g
Don't think the parens are required, still works for me without them: Try it online!
(I have basic knowledge of both versions, but I don't regularly use them so there are occasionally gaps in my understanding
Scanner let's you can extract the information you wan't from input, characters, lines numbers and so on.
You can make multiple new Scanners if you wish.
The input doesn't necessarily need to be keyboard input, it can also be a file or String.
Inside the parens you place what input you want to parse.
'in', in System.in the InputStream which reads byte data from keyboard input.
However you can not do;
InputStream keyboard = new InputStream(); // does not work
You have to use System.in
You can use System.in without a Scanner
When you put System.in inside the parens of new Scanner( )
Then Scanner takes 'in' as argument to a constructor, and then that scanner let's you deal with user input more conveniently.
J:
p1=. [: +/ (>./ - <./)"1 p2=. [: +/ (#~ >&1 * ]=<.)@,@(%/~)"1
(p1 ; p2) d
where d is your input.
map
applies the first argument, ord
, to each element of the second argument, data
. In Python 2 it results in a list identical to [ord(item) for item in data]
. As for what you get, couldn't you figure that out by running it?
That's not the best example. is
should never be used for comparing integers, as it fails for larger values:
a = 10 b = 10 print(a is b) #True y = 10*3 x = 10*3 print(x is y) #False Try it online here.
A better example would be membership:
valid_inputs = ['yes', 'no'] user_input = input("Please enter yes or no: ") while user_input not in valid_inputs: print("Please try again.") user_input = input("Please enter yes or no: ")
I'm sure there's a better solution than brute force, but in this case I think it's fine to simply permute over all options. Here's an example if the discounts for a product are a list of functions which apply their discount.
>So on value “15” it will print all three (if fizzbuzz were included) instead of the most relevant (fizzbuzz only).
If you are going to scold someone for joke code do it properly and at least understand what it does because it's clear you have no idea what is going on. Which I admit is biggest flaw of Chad's code. Right side doesn't need FizzBuzz and/or breaks because it builds answer instead of pulling it from dictionary. Chad is also more extensible if more divisor are needed while incel side grow exponentially. I've modified output of chad and added more divisors to illustrate the point you can check it here.
> scalable by “lines of code written” for larger amount of choices
Please tell me about scalability of incel code? It's non-existent.
Thanks! I appreciate the help. I threw a more realistic chunk of html at it. It did not match anything, though.
Very cool tool there. I'll use that.
I edited my original. You can see it in action here.
The %% is an alternation. Basically, we say that you can alternate between junk and stuff we want (e.g. junk, stuff, junk, stuff, junk, stuff). The %% allows us to finish on stuff, whereas % would require us to end on junk (which, I suppose, being zero width ends up the same, actually)
The given code seems to work (at least print something) (link, class name changed to Main
). The issue is probably either in any IDE you're using or in the way you're running the program.
Do you want to strip single quotes that occur both at the beginning and end?
var tests = ["'footloose'", "Godfather", "'Inception", "Frozen'"];
tests.forEach(function(s) { var title = s.replace(/^'(.*)'$/, "$1");
console.log(title); });
Output:
footloose Godfather 'Inception Frozen'
Not the OP obviously, but based on the percentages it'd have to be at least 3238.
would be nice to link a v (vim) tio link and/or a nice visual as a gif or something as i keep messing it up lol
I think this also works. Code
Retina (part 2)
[0-9]+
$0;$0
([0-9]+)¶([0-9]+)
$2¶$1
([0-9]+);([0-9]+)
$2;$1
^.*¶
¶.*$
[0-9]+
$0*a
(a+)¶\1
>
>a
Yeah, that's because your function is really taking a char*
parameter, and then taking the address of that gives the address of the copy of the pointer on the stack.
If you do it in the context where the array was created they're identical: https://tio.run/##S9ZNT07@/185My85pzQlVcGmuCQlM18vw44LRSgnMwkkxpWZV6KQm5iZp6GpUM2lAATJGYlFCpl5BaUl0UamZrHWYEEwUVAEVJymoaRaEJOnpANRo2mNTUpNA2KAQawmDgUwzWDJotSS0qI8BQNrrtr//wE
> value of an object type is the value of it's pointer
The "value of ~~an object type~~ reference type" is not the pointer. That's the value of the location the reference is stored. The actual value is accessed through that reference. Value equality doesn't make sense on reference types, because it's called identity if declared as you do. Primitives get plenty of special treatment, and the fact that they are value types with special equality overloads are a great example.
Even with your definition, accepting that it's value equality comparing the pointer, it breaks down for +0 == -0
and Double.NaN == Double.NaN
, which return true
, false
in that order, but if it really was value equality (and not special primitive-specific overloads) the result should be the opposite. Indeed, it is overloaded per-primitive as per IEEE-754 and not a naive, quick and dirty value equality. Runnable example with TIO
I don't know how ==
works in C because i've never needed to write C and it looks scary and i have to manage my own memory and shit, so i have no comment on what i have no experience with
I made a version using the 100 most common characters, because I was not able to find all Chinese characters. Anyway here is the link
Braces don't do change expansion at all. echo $foo
and echo ${foo}
have exactly the same behavior, regardless of what foo
is.
Now echo "$foo"
is different.
foo='* /*' echo $foo echo ${foo} echo "$foo"