text
stringlengths
180
608k
[Question] [ ## Challenge You have been assigned a task to write a program which takes a multigraph as its input and if it contains an Eularian circuit to return one. Otherwise, the program's behavior is undefined, according to the specifications you're handed by your boss. However, you recently caught your new coworker Steven several times treating undefined behavior in C carelessly and urged him be more careful because undefined behavior can also mean that all files on the system get deleted. He now dared you to write your program in a way such that it deletes itself when the aforementioned case of (previously) undefined behavior occurs. You don't want to lose your honor and accept. ## Description An [Eulerian circuit](https://en.wikipedia.org/wiki/Eulerian_path) is a circuit in an undirected multigraph which visits every edge exactly once. You may choose the formats of your program's input and output yourself. They don't need to be the same formats. For example, you may take a description of the edges like ``` ({1,2},{1,4},{2,4},{2,3},{2,3}) ``` as your input for this graph ![](https://i.stack.imgur.com/PNz08.png) , but return a sequence of vertices as your output: ``` (1,2,3,2,4,1) ``` ## Details You don't need to be able to accept multigraphs which contain vertices without edges. Holding your program only in RAM and terminating it afterwards doesn't count as deleting it. It needs to be in a file. The file must only be deleted if no Eulerian circuit exists in the input multigraph. The vertices have to be identifiable (it needs to be possible to tell the Euler circuit in the input provided the output of your program), the edges don't. However, you may restrict the means of identification (e.g. only positive integers or only strings consisting of a `#` followed by a positive integer) as long as large graphs are representable (only 1 letter of the English alphabet isn't sufficient). Identifiers don't have to be explicit. For example, you may let the order of the input determine the number a vertex is identified with in the output. The means of output (saved to a file, printed at stdout, return value of a function) don't matter. You can't rely on the name of your program on the disk not changing. If you only write a function, you still have to delete the file on the disk. ## Victory Condition This is code golf, shortest code wins. --- **Spoiler warning for this link:** [Simple algorithms](http://www.ctl.ua.edu/math103/euler/ifagraph.htm) to solve this problem can be found on the internet. [Answer] # Mathematica, 48 bytes ``` FindEulerianCycle@#/.{}->DeleteFile@FileNames[]& ``` Yep, there's a builtin for that. It returns `{}` if there's no Eulerian cycle, so we manually redirect that to a command deleting all files in the current working directory. ]
[Question] [ **Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/59482/edit). Closed 8 years ago. [Improve this question](/posts/59482/edit) I have read: [Tips for golfing in Python](https://codegolf.stackexchange.com/questions/54/tips-for-golfing-in-python) I would like to golf this code further. Any more tips? ``` x,y,q,w=[int(i) for i in raw_input().split()] while 1: a=int(input()) s=d="" if q>x: s="W" q-=1 elif q<x: s="E" q+=1 if w>y: d="N" w-=1 elif w<y: d="S" w+=1 print d+s ``` The program: You move on a map which is 40 wide by 18 high. Thor is initially placed on a random spot on the map and must reach the light of power as quickly as possible. You need to have the shortest code possible. During each turn, you must specify in which direction to move, from one of the following: N (North) NE (North-East) E (East) SE (South-East) S (South) SW (South-West) W (West) NW (North-West) YOU WIN WHEN THOR REACHES THE LIGHT OF POWER. YOU LOSE: if Thor moves off the map. if Thor doesn't have enough energy left to reach the light of power. EXAMPLE: THOR STARTS ON THE MAP ON THE SQUARE (3, 6). THE LIGHT OF POWER IS ON SQUARE (3, 8). TURN 1 THOR MOVES SOUTHWARDS. NEW POSITION = (3, 7). THOR HAS ENOUGH ENERGY LEFT FOR 10 MOVES TURN 2 THOR MOVES SOUTHWARDS. NEW POSITION = (3, 8). THOR HAS ENOUGH ENERGY LEFT FOR 9 MOVES The program must first read the initialization data from standard input. Then, within an infinite loop, read the data from the standard input related to Thor's current state and provide to the standard output Thor's movement instructions. INITIALIZATION INPUT: Line 1: 4 integers indicate the position of the light of power. 2 indicate Thor’s starting position. INPUT FOR ONE GAME TURN: Line 1: The level of Thor’s remaining energy. This represents the number of moves he can still make. OUTPUT FOR ONE GAME TURN: A single line providing the move to be made: N NE E SE S SW W or NW Edit : it's a code golf on codingame.com [Answer] ### N.B.: This may not be entirely correct as I don't know what your code is supposed to do The first thing to do is remove unnecessary whitespace, especially that after the if statements: ``` x,y,q,w=[int(i) for i in raw_input().split()] while 1: a=int(input()) s=d="" if q>x:s="W";q-=1 elif q<x:s="E";q+=1 if w>y:d="N";w-=1 elif w<y:d="S";w+=1 print d+s ``` This golfs your code down by 4 bytes. What would be ideal for this challenge is a switch case which, unfortunaley, does not exist in Python. Instead we can be clever with an array's index: ``` x,y,q,w=[int(i) for i in raw_input().split()] while 1: a=int(input()) s=d="" exec(['s="W";q-=1','s="E";q+=1'][q<x]) exec(['d="N";w-=1','d="S";w+=1'][w<y]) print d+s ``` Saving you *x* bytes. Finally you can get rid of all whitespace now: ``` x,y,q,w=[int(i) for i in raw_input().split()] while 1:a=int(input());s=d="";exec(['s="W";q-=1','s="E";q+=1'][q<x]);exec(['d="N";w-=1','d="S";w+=1'][w<y]);print d+s ``` ]
[Question] [ **Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/44882/edit). Closed 9 years ago. [Improve this question](/posts/44882/edit) This a code challenge. **The winner will be the person to provide the most efficient implementation of the solution in terms of algorithmic complexity.** Using the dictionary found in '/usr/share/dict' (on OS X and Linux), your task is to find the word with the most anagrams of itself in the dictionary, and print all of the words that are the anagrams. [Answer] # C++ 14 - 0.077 seconds for 52875 words --- Code: ``` #include <thread> #include <mutex> #include <string> #include <map> #include <vector> #include <iostream> #include <fstream> #include <algorithm> using namespace std; void thread_func(mutex& file_lock, mutex& map_lock, map<string, vector<string>>& anagrams, ifstream& file) { string word; string sorted_word; while (true) { { lock_guard<mutex> locker(file_lock); if (file.eof()) { return; } file >> word; } sorted_word = word; sort(sorted_word.begin(), sorted_word.end()); { lock_guard<mutex> locker(map_lock); anagrams[sorted_word].push_back(word); } } } void nothread_func(map<string, vector<string>>& anagrams, ifstream& file) { string word; string sorted_word; while (true) { if (file.eof()) { return; } file >> word; sorted_word = word; sort(sorted_word.begin(), sorted_word.end()); anagrams[sorted_word].push_back(word); } } int main(int argc, char *argv[]) { string fname = "/usr/share/dict/words"; int number_of_threads = 1; if (argc > 1) { fname = argv[1]; } if (argc > 2) { number_of_threads = atoi(argv[2]); } mutex file_lock; mutex map_lock; map<string, vector<string>> anagrams; cout << "Opening file '" << fname << "'" << endl; ifstream file(fname); if (!file) { cerr << "Could not open file" << endl; return 1; } if (number_of_threads == 1) { nothread_func(anagrams, file); } else { cout << "Starting " << number_of_threads << " threads" << endl; vector<thread> threads; for (int i = 0; i < number_of_threads; ++i) { thread th(thread_func, ref(file_lock), ref(map_lock), ref(anagrams), ref(file)); threads.push_back(move(th)); } for (auto& thread : threads) { thread.join(); } cout << "Threads done" << endl; } int largest_size = max_element(anagrams.begin(), anagrams.end(), [](const auto& a, const auto& b){return a.second.size() < b.second.size();})->second.size(); for (auto p : anagrams) { if (p.second.size() == largest_size) { for (auto word : p.second) { cout << word << " "; } cout << endl; } } } ``` Compile: `g++ anagrams.cpp -o anagrams --std=c++14 -pthread -ggdb -O3` CLI: `./anagrams <wordfile, defaults to /usr/share/dict/words> <number of threads, defaults to 1>` Example: ``` $ wc -l /usr/share/dict/cracklib-small 52875 /usr/share/dict/cracklib-small $ time ./anagrams /usr/share/dict/cracklib-small Opening file '/usr/share/dict/cracklib-small' caret carte cater crate react recta trace pares parse pears rapes reaps spare spear real 0m0.077s user 0m0.073s sys 0m0.000s ``` The code does have multithreaded built in, but it slows things down on my system. Might be useful on slower systems / bigger files. If the number of threads is `1`, it disables threads and does everything normally. Algorithm is essentially the same as CarpetPython's, but my code is slightly longer (well, 81 lines). [Answer] # Python 2 Efficient to write, and reasonably efficient to run. ``` groups = {} for word in open('/usr/share/dict/words'): word = word.strip() signature = ''.join(sorted(list(word))) if signature not in groups: groups[signature]=[] groups[signature].append(word) anagrams = groups.values() maxlen = max(len(x) for x in anagrams) for group in (x for x in anagrams if len(x) == maxlen): print ' '.join(sorted(group)) ``` produces: ``` carets caster caters crates reacts recast traces pares parse pears rapes reaps spare spear ``` in about 0.4 seconds. The algorithm has O(n) complexity. The full word list is processed in 0.42 seconds. A half-size word list is processed in the expected 0.21 seconds. ]
[Question] [ **Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers. --- Questions without an **objective primary winning criterion** are off-topic, as they make it impossible to indisputably decide which entry should win. Closed 9 years ago. [Improve this question](/posts/34898/edit) # The Golf (re)Sort ![Our favourite place](https://i.stack.imgur.com/TpPyb.jpg) *Everyone is sorting arrays these days, and so do we at our day jobs. But we like to go out golfing. When we do, we sure like to take our time. It is important to have a stress free experience.* *Since we like golfing so much, we have decided to make a sorting algorithm that will let us stay away from the desk as much as possible. We decided to make **Golf (re)Sort**, a sorting algorithm that takes as time long as possible to complete. This way we can spend more time doing what we like the most, golfing.* --- The task is easy: **Sort an array of integers using an algorithm that takes as long time, and has as high O-notation, as possible.** ## The rules: * The algorithm must be deterministic. Thus you may not use randomness in the algorithm (so no bogosort) * You may not use any un-productive operations or loops. Eg.: `sleep 2`, `for i<n; i++ {/*no-op*/}`, `Open("www.the_internet.com").download`. Every operation needs to bring you closer to the goal of a sorted list. An example would be to simply reverse the array for no other reason than reversing the array to increase the Ω-notation. ## Provide: * Name of the language * The code * An explanation to the approach + Ω(Big-Omega)-notation (lower bound). ## Scoring: Scoring will be done by looking at the Ω-runtime. The higher the better. --- # Example: Language: **Ruby** Code: ``` a = [6,9,7,5,7,90,9,6,4,32,9,7,4,223] sorted = [] while a.count > 0 min = [Float::INFINITY, -1] a.each_with_index do |e,i| min = [e,i] if e < min[0] end sorted << min[0] a.delete_at(min[1]) end puts sorted.to_s ``` This is a variation on selection sort which have runtime of **Ω(n^2)**. It is slow because it scans the array for the lowest value, then pushes that to the result array. It then deletes the value from the original array and starts over. [Answer] # Python ``` def ackermann(m, n): if m == 0: return n + 1 if n == 0: return ackermann(m - 1, 1) return ackermann(m - 1, ackermann(m, n - 1)) def sort(lst): newlst = [] while len(lst) > 0: a, i = min([(ackermann(n, n), i) for i, n in enumerate(lst)]) newlst.append(lst[i]) del lst[i] return newlst ``` Uses Ackermann function to slow things down. That may qualify as unproductive... Use example: ``` print sort([3, 1, 2, 3, 0]) # --> [0, 1, 2, 3, 3] ``` It actually works quite well for numbers between 0 and 3. (Note that it's destructive and only works for non-negative integers.) Runtime - I'm not quite sure. [Answer] ## k4 (100) ``` {{if[y<z;.z.s[x]'[y,m+1;(m:_(y+z)%2),z];if[(x m)>x z;@[x;z,m;:;x m,z]];.z.s[x;y;z-1]]}[x;0](#. x)-1} ``` This is a fairly straightforward (i.e. not particularly golfed) implementation of [slowsort](http://www.cs.uiuc.edu/class/fa05/cs473ug/resources/pessimal-algorithms.pdf). Here's a sample run, with timing information in milliseconds (the `\t` instruction): ``` s:{{if[y<z;.z.s[x]'[y,m+1;(m:_(y+z)%2),z];if[(x m)>x z;@[x;z,m;:;x m,z]];.z.s[x;y;z-1]]}[x;0](#. x)-1} l:100?1000 \t s`l 4270 ``` The paper (*v.s.*) claims that the last few paragraphs of section 5 contain a proof of the running time of the algo, but I can't make heads or tails of it; all I know is that 4.2 seconds to sort 100 ints is *pretty slow*. (I should also note that this implementation is an in-place sort, as given in the paper, which is why the list to sort is passed by name, rather than by value. This is rather strongly contrary to the functional programming principles of k4/q, but it was easier than figuring out a proper functional version.) [Answer] ## Python This one isn't golfed, because I'm not much of a code golfer yet. ``` def sorted(l): for i in range(1, len(l)): if l[i] < l[i-1]: return False return True class T: def __init__(self,l1,l2): self.l1 = l1 self.l2 = l2 self.children = [] def build(self): if len(self.l2) == 0: return else: for i in range(0, len(self.l2)): nl1 = self.l1[:] nl2 = self.l2[:] nl1.append(self.l2[i]) nl2.pop(i) child = T(nl1, nl2) child.build() self.children.append(child) def find_sorted(self): if len(self.l2) == 0: if sorted(self.l1): return self.l1 return None result = None for child in self.children: if child.find_sorted() is not None: result = child.find_sorted() return result def sort(l): tree = T([],l) tree.build() return tree.find_sorted() ``` Been a while since I took any classes so I'm trying to think of how to word the complexity. I know the number of nodes in the tree can be calculated with: ``` def numberOfNodes(n): if n==0: return 1 return 1 + n * numberOfNodes(n - 1) ``` It builds this entire tree and searches through every node. So for a list size grows very fast: ``` 0 1 1 2 2 5 3 16 4 65 5 326 6 1957 7 13700 8 109601 9 986410 10 9864101 ``` If searching every node is cheating I can change that. A list of 9 elements took about 6 seconds, and a list of 10 elements ran out of memory (used at least 1.9 GB of ram before it chickened out 25 seconds in). [Answer] ## Python, Omega(n^(n+2)) ``` def sort(a): for i in xrange(len(a)**len(a)): b = list(a) for j in range(len(a)): k = i / len(a)**j % len(a) b[0], b[k] = b[k], b[0] if all(b[x] <= b[y] for x in range(len(a)) for y in range(x, len(a))): return b ``` Tries all possible orderings (and then some), returning only if the array is sorted. Uses Omega(n^2) to test if it's sorted, just to add insult to injury. ]
[Question] [ **This question already has answers here**: [Fibonacci function or sequence](/questions/85/fibonacci-function-or-sequence) (334 answers) Closed 9 years ago. Your goal is to calculate the sum of Fibonacci series from **n** th term to **m** th term (including both terms). * No use of `/ * %` or mathematically what they are in your language of choice. * No use of special **functions** or **code language** specialized in doing so ! * You have to produce the series yourself and not by any special function or code language. ## OUTPUT ``` #1 0 5 series : 1 1 2 3 5 8 sum : 20 #2 2 5 series : 2 3 5 8 sum : 18 ``` Best of luck **:]** [Answer] # Julia ``` fib(n)=n<2?1:fib(n-1)+fib(n-2) sumfib(n,m)=sum([fib(i) for i=n:m]) ``` Output examples: ``` julia> sumfib(0,5) # 1 1 2 3 5 8 20 julia> sumfib(2,4) # 2 3 5 10 julia> sumfib(2,5) # 2 3 5 8 18 ``` **EDIT:** Changed to fit question's fibonacci convention. [Answer] # J (35 characters) A solution in J *with Fibonacci sequence starting at index 0 and value 0 according to most current conventions*. The slash `/` has absolutely nothing to do with mathematical operation in J. ``` (;+/)@:(+/@(!|.)@i."0)@([+i.@>:@-~) ``` For instance: ``` 3 (;+/)@:(+/@(!|.)@i."0)@([+i.@>:@-~) 6 ┌───────┬──┐ │2 3 5 8│18│ └───────┴──┘ ``` [Answer] # Delphi ``` uses System.SysUtils,idglobal; var i,n,m,ires:integer; a:TArray<integer>; res:string; begin ires:=0; readln(n,m); SetLength(a,m+1); for i:=0to m+1 do a[i]:=iif(i<2,1,a[i-1]+a[i-2]); for i:=n to m do begin write(Format('%d ',[a[i]])); inc(ires,a[i]); end; WriteLn('|'+IntToStr(ires)); end. ``` Input: `0 5` Output: `1 1 2 3 5 8 | 20` Input: `1 20` Output: `1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 | 28655` [Answer] # C ``` int fsum (int start, int end) { int a[2]={1,0}; int p=1,b=1,d=0; for (;p<=end+2;b=!b) { a[b]+=a[!b]; d=p++==start+1?a[b]:d; } return a[!b]-d; } ``` To make it more interesting, I've decided to see if I could a) use a static amount of memory, and b) produce the requested sum without actually adding up the [n..m] elements. So my code doesn't print out all the elements (since it wasn't required), but produces the correct result nevertheless. ]
[Question] [ **Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/20145/edit). Closed 10 years ago. [Improve this question](/posts/20145/edit) # Challenge Given an email in plain text format, including headers, decide if the email is either spam or ham, and output SPAM or HAM respectively. The emails will be given below. Your code **must** be able to correctly identify all of the samples, but should be general enough to work on any email. # Scoring This is a code golf, so shortest code wins. # Restrictions Do not: * Rely on message length * Rely on particular senders, recipients, dates, or subjects # Data ### Spam ``` Subject: favorable offer From: "Simon Nicolas" [[email protected]](/cdn-cgi/l/email-protection) Date: Sun, August 28, 2005 0:00 To: "UK resident" Hello! I am Simon Nicolas, a general manager of international company IFSD Inc. ( http://www.ifsd-company.com ) and I have a favorable offer for you. Now it is a little about our company. We are engaged the organization of plans of reception of payments for private persons and the companies. Our services are demanded by those who has requirement to accept remittances from clients in other countries. Our company conducts wide international activity; we work with the organizations and private persons from the various countries worldwide. Our activity constantly extends, we enter new services, we expand staff of employees we open representations of the company in the territory of the various countries. In connection with constant expansion of our international activity we feel necessity of new employees in the territories of the various countries. Now we have announced a set of employees on a post "the Regional Financial Manager". Working on this post, our colleagues produce work with the bank transfers and the checks. Our clients are private persons and the companies of the different countries and for simplification of remittances we use our Regional Financial managers. The functions of the Regional Financial Manager: -reception of bank payments on a bank account The scheme of work is those: the Regional Financial Manager receives money resources and informs us on this. We in turn at once enroll the necessary sum on the account of our client. It allows you to save a lot of time - now the client does not need to wait for reception of money from abroad. As such scheme allows you to save money. From the sum of each transaction lead through you our company pays 5 %. The basic requirements: -age of 21-60 years -access to the Internet, e-mail -opportunity to work not less than 3 hours per day It is your really favorably chance to earn! Start to work right now! For the beginning with us you need to fill works only labour agreement --- Best regards, Simon Nicolas. http://www.ifsd-company.com ``` ### Spam ``` From: "Met Investment Fund" [[email protected]](/cdn-cgi/l/email-protection) To: "UK competitor" Subject: Job offer from http://www.metinvf.com Date: Sat, 19 Mar 2005 00:10:07 +0000 Vacancies We have some vacancies right now, here they are: Financial manager: JOB DESCRIPTION Requirements: Resident of the United Kingdom Knowledge of Microsoft Word and Microsoft Excel; Home Computer with e-mail account and ability to check your e-mail box at least twice a day; 1-3 hours free during the week; Be fast in decisions; To manage MIF financial affairs through the provision of efficient and effective financial systems and support; To ensure that the financial affairs are conducted in compliance with current legislative requirements and in line with requirements set by DCAL, DFP and DCMS; To ensure adherence to all internal and external audit requirements; To recieve MIF payments and our sub-companies payments and send them directly to our investors; To co-ordinate and control the completion of all necessary payments to our clients (through our site's member zone); Have a university degree; UK Bank account (for wire transfers from our company and our clients); All offers here: http://www.metinvf.com/careers.html ``` ### Ham ``` From: "Tony McAdams" <[[email protected]](/cdn-cgi/l/email-protection)> To: "Bobby" <[[email protected]](/cdn-cgi/l/email-protection)> Subject: Bobby, check out this job posting Date: Sun, 30 May 2005 03:50:02 +0000 Hey Bob, I heard you were looking for work, so I figured I'd pass along this job offer. A friend of mine works for Webdings Inc., and he mentioned they are hiring. Their site is: http://www.webdings.com Anyways, how's the new apartment? Get everything moved in alright? We should be by Tuesday with some food and a house warming present. If Tuesday doesn't work, we can drop by any time during the week. Unfortunately Sparky won't be able to make it, she's not really feeling all that well. The vet called and said they'd have to keep her for observation for at least a week. Bummer. Anyways, I hope to hear back from you soon Bob, everyone here misses you a lot! Talk to you soon, Tony ``` ### Ham ``` Subject: Quote Selection From: "Simon Nicolas" [[email protected]](/cdn-cgi/l/email-protection) Date: Mon, January 2, 2005 20:01 To: "undisclosed-recipients" Hello class, Before next week's lecture, I need you all to read "His Last Bow" by Doyle. Pay particular attention to the following paragraphs: From that day they were seen no more in England. Some six months afterwards the Marquess of Montalva and Signor Rulli, his secretary, were both murdered in their rooms at the Hotel Escurial at Madrid. The crime was ascribed to Nihilism, and the murderers were never arrested. Inspector Baynes visited us at Baker Street with a printed description of the dark face of the secretary, and of the masterful features, the magnetic black eyes, and the tufted brows of his master. We could not doubt that justice, if belated, had come at last. "A chaotic case, my dear Watson," said Holmes over an evening pipe. "It will not be possible for you to present in that compact form which is dear to your heart. It covers two continents, concerns two groups of mysterious persons, and is further complicated by the highly respectable presence of our friend, Scott Eccles, whose inclusion shows me that the deceased Garcia had a scheming mind and a well-developed instinct of self preservation. It is remarkable only for the fact that amid a perfect jungle of possibilities we, with our worthy collaborator, the inspector, have kept our close hold on the essentials and so been guided along the crooked and winding path. Is there any point which is not quite clear to you?" Thank you, Simon ``` [Answer] ## J (40) This program has a 100% success rate on the given samples. ``` echo>(+./(3#1)E.LF=1!:1[3){'HAM';'SPAM' ``` How does it work? It checks if the mail contains three or more newlines in a row, and if so, classifies it as spam. For the test set, this holds. (Interestingly enough, from a cursory glance at my spam folder, this also holds for quite a lot of real spam.) [Answer] # Befunge 98 - 34 ``` ~a-!2*1-+:2`98+*j"SP"8j@,k3"MA"<H' ``` This is a translation of marinus's answer; it checks for 3 or more newlines in a row. ]
[Question] [ Choose a language and write a program in the language that: * Take a valid program of the language as input, * Output a string(bytearray, etc.). It needn't be a valid program. * Only finite valid inputs result in longer/same-length(in bytes) output. * Different valid input, even if behave same, lead to different output. Let length of your code as \$L\$ and number of inputs with longer/equal-length output as \$n\$. To win, you should be lowest on at least one of: * \$L\$, * \$N\$, * \$L+N\$, * \$L+\log\_2(N+1)\$. # Notes * Solution exist so long as [illegal substring](https://codegolf.stackexchange.com/questions/133486/) exist. [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), \$L=79\$, \$N\approx255^{1500}\$ -3 bytes thanks to @Jonathan Allan ``` f=lambda b,s=0,l=0:b and f(b[1:],255*s+b[0],l+1)or s.to_bytes(l-(l>1500),"big") ``` [Try it online!](https://tio.run/##dYxBDoIwFET3nqLWBS1UQzEkhgTX3sAFIYZK0SaflrR1wemxagwx6l/Nnzczw@ivRm93g506a3rkRodUPxjrkZPeyvPNOmU0qF75xZdDeBqOTl0JTS/aBgnmypRBmRYCNbpFHREVL2qW5XnsElGlNYOEU2OR23hzEqOXjsCawJ7nYYhhoS6YToNV2pNQxpjSxfy9VHSQAAYdjYV2GdFHZDVnGhw/t949kPrT/w34P5AFMN0B "Python 3.8 (pre-release) – Try It Online") Python source code can't contain null bytes. This converts the input (bytestring) to base 255 and then back to bytes. After 1500 removes a redundant byte. ]
[Question] [ **Closed**. This question needs to be more [focused](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Update the question so it focuses on one problem only by [editing this post](/posts/176039/edit). Closed 5 years ago. [Improve this question](/posts/176039/edit) # Introduction [Busy Beavers](https://en.wikipedia.org/wiki/Busy_beaver) are programs (specifically Turing Machine programs) that aim to output the **most ones as possible**, while having the least states as possible and halting. --- # Challenge Your challenge is to make a busy beaver, which outputs as many ones as possible, but also outputs **a second busy beaver**. That second busy beaver must be executable in the same language as the original program, and can be **no more bytes than the program that produced it** So, for example, say my program was `a`. That program should aim to print as many `1`s as possible, and also output another program, say `b`, which also aims to print as many `1`s as possible and outputs another program etc etc etc. `b` must be no more bytes than `a` The program should be printed after the `1`s, separated by any reasonable delimiter. The outputted programs must also not be the same as any of the previous programs. When no more programs are generated, the scores are calculated from there. For example, program `a` can print `b` can print `c` can print `d`, but `d` doesn't print any other program. The scores would be calculated as `(a_ones + b_ones + c_ones + d_ones) / (a_bytes + b_bytes + c_bytes + d_bytes)` (see below) The programs must also never error. The "programs" can also be functions, as long as they execute with no arguments --- # Scoring Your submission's score is the sum of the number of ones outputted by your programs, all divided by the sum of the bytes of the programs. The higher the score, the better. [Answer] # [C (gcc)](https://gcc.gnu.org/), 71 bytes I've not done one of these before but here's a shot at it; Each program should print 4,294,967,295 ones, divided by the sum of bytes 71+30 scores 85,048,857 ``` main(c){puts("main(c){while(~c++)puts(\"1\");}");for(;~c++;)puts("1");} ``` [Try it online!](https://tio.run/##S9ZNT07@/z83MTNPI1mzuqC0pFhDCcYrz8jMSdWoS9bW1gRLxCgZxihpWtcCcVp@kYY1SMYaIqVkCJL4/x8A "C (gcc) – Try It Online") [Answer] # [JavaScript (Node.js)](https://nodejs.org), 50 bytes ``` (f=_=>_?'1'.repeat(_)+`&&(f=${f})(${_-1})`:1)(1e3) ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z@cn1ecn5Oql5OfrvFfI8023tYu3l7dUF2vKLUgNbFEI15TO0FNDSihUp1Wq6mhUh2va1irmWBlqKlhmGqs@V/zPwA "JavaScript (Node.js) – Try It Online") [Answer] # brainfuck, 99 bytes, \$f\_{255}(255^2)\$ ``` -[>-[[>]-[<]>>-]<-]-[-[[>]+[<]<+>>-]-[<+>-----]<--.,<[>>>[[-<+>]<[<]<[->+<<+>]>[>]>]<+[<]>,<<-]>>>] ``` Assumes a wrapping implementation with an infinite tape in both directions. This is modified from my [Largest Number Printable](https://codegolf.stackexchange.com/a/156702/76162) to print `1`s instead of `3`s. ]
[Question] [ **Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/145971/edit). Closed 6 years ago. [Improve this question](/posts/145971/edit) Task: * Make a program that draws the following figure line by line. * Your program should wait for one-second after drawing each line(it can be longer, just has to be a noticeable difference) . * Your program can **only** draw line by line (you cannot jump to another point or re-draw over a line) * Given a positive integer n, produce an art image of the below drawing * The angle measures should always be the same (regardless of n's value) * However, each line's length should be 150\*n pixels * You only need to account for when n = 1, n = 2, n = 3 The picture below shows when `n` = 1 (You don't have to include the angles and side lengths in your drawing - they are just guides) [![dfwm](https://i.stack.imgur.com/aDPEJ.png)](https://i.stack.imgur.com/aDPEJ.png) **Answering** - Name the language you used followed by its bytes Example: > > **Java (swing), 500 bytes** > > > **Scoring** * This is code golf. Lowest score (bytes) wins. * [standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are **forbidden**. Good luck! [Answer] # [Python 2](https://docs.python.org/2/), ~~150~~ ~~140~~ ~~132~~ 120 bytes *-5 bytes thanks to @Mr.Xcoder* ``` from turtle import* n=150*input() for a,b in zip([0,90,30,120,30]+[135]*3+[-75,240],[n]*5+[2**.5*n,n]*2+[n]):rt(a);fd(b) ``` [Try it on Trinket](https://trinket.io/python/8f175e11f3) modified slightly to run with Python 3 ]
[Question] [ **This question already has answers here**: [Find the prime factors](/questions/1979/find-the-prime-factors) (26 answers) Closed 8 years ago. Yes, this is old and probably very simple, but I really want to be mindblown by things that I thought were obvious, so here's the **challenge**: You're given a positive integer as the input and you need to output the **exponents** of all of the prime factors **up to the highest factor** in base 36 ( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, a, b, c ... z ). If there are some primes in between that are no factors, they have exponent 0. The output must be ordered can be either an array or a string separated by `\n`, (space) or just outputs from different calls. The program should calculate correctly the output for exponents bigger than 36, but it's not required Say you're given `42` as the input, its prime factorization is `2*3*7`, all of which have `1` as the exponent, but there is also `5` with an exponent of `0`, so your output would be `[ 1, 1, 0, 1 ]` because `2` is the first prime and has an exponent of `1`, `3` is the second and has an exponent of `1`, `5` is the third and has an exponent of `0` and so on. Here are the correct input/outputs for the first 30 numbers ``` 2 1 3 0 1 4 2 5 0 0 1 6 1 1 7 0 0 0 1 8 3 9 0 2 10 1 0 1 11 0 0 0 0 1 12 2 1 13 0 0 0 0 0 1 14 1 0 0 1 15 0 1 1 16 4 17 0 0 0 0 0 0 1 18 1 2 19 0 0 0 0 0 0 0 1 20 2 0 1 21 0 1 0 1 22 1 0 0 0 1 23 0 0 0 0 0 0 0 0 1 24 3 1 25 0 0 2 26 1 0 0 0 0 1 27 0 3 28 2 0 0 1 29 0 0 0 0 0 0 0 0 0 1 30 1 1 1 ``` and you can find a working expanded version of this [on codepen](http://codepen.io/towc/pen/Qjjzmx) The solution with the lowest number of bytes wins. Feel free to send in languages who have built-in prime factorization functions, but I won't accept them as answers for pretty obvious reasons. If you send in a solution that doesn't use such functions I'll consider it. It's kind of a grey area, but we'll figure it out. ### Edit: If it's unclear what do I mean by "base", consider the number `3072`. Its prime factors are `2` and `3`. `2` has an exponent of `10`, so in base 36 that's `a`. That means that the output would look like this: ``` a 1 ``` or the number `732421875000` whose factorization is `2^3 * 3^1 * 5^15`, whose output would be ``` 3 1 f ``` [Answer] # Octave, 51 bytes ``` @(n)dec2base(histc(factor(n),unique(factor(n))),36) ``` This defines an anonymous function that takes a number and returns a char array. Explanation to come. [Answer] # Pyth, 15 bytes ``` VheSPQIP_NC/PQN ``` [Try it here](http://pyth.herokuapp.com/?code=VheSPQIP_NC%2FPQN&input=1583817601203918457031250000000000&debug=0) Outputs in base 256. (Base36 version, 33 bytes) ``` VheSPQIP_NjjkmC++48d*>hdT7j/PQN36 ``` [Try it here](http://pyth.herokuapp.com/?code=VheSPQIP_NjjkmC%2B%2B48d*%3CdT7j%2FPQN36&input=1583817601203918457031250000000000&debug=0) (Base 10 version, 14 bytes) ``` VheSPQIP_N/PQN ``` [Try it here](http://pyth.herokuapp.com/?code=VheSPQIP_NC%2FPQN&input=1583817601203918457031250000000000&debug=0) All versions are separated by newlines. There is some unclearness over whether not base 36 outputs are allowed so I included many versions. Uses factorisation functions and is\_prime functions. [Answer] ## Mathematica, 80 bytes ``` #~IntegerExponent~Prime@Range@PrimePi@FactorInteger[#][[-1,1]]~IntegerString~36& ``` I tried. Without factorization: ## Mathematica, 90 bytes ``` #~IntegerExponent~Prime@Range@PrimePi@Select[Divisors@#,PrimeQ][[-1,1]]~IntegerString~36& ``` ]
[Question] [ **This question already has answers here**: [math with bitwise operators](/questions/12706/math-with-bitwise-operators) (2 answers) Closed 10 years ago. * You cannot use `if`,`while`,`for`, `?:`, `||`, `&&` etc., or recursion! * Assume it is Int.32 * Shortest answer wins [Answer] ## C - 91 Based on Kogge-Stone, there is probably ways to cut parts of this off, but it seems good enough to start the race. ``` g,p;t(h){g|=p&g<<h;p&=p<<h;}d(a,b){g=a&b,p=a^b;t(1);t(2);t(4);t(8);t(16);return a^b^g<<1;} ``` An ungolfed version and possibly some explanation can be found from <http://chessprogramming.wikispaces.com/Parallel+Prefix+Algorithms> [Answer] # Python 3 (66 chars) ``` def a(i,j):v=locals();exec("i,j=i^j,(i&j)<<1;"*32,v);return v['i'] ``` [Answer] # Golfscript, 3 (or 7, if it needs to be assigned to a function) Since you never said `+` was forbidden ``` 0|+ ``` `0|` basically does nothing (if the top of the stack is a number), because `n [bitwise or] 0` is `n`. `+` adds them. If it needs to be a function: ``` {0|+}:s ``` Assigned to function `s`. [Answer] ## J - 814 A better version ``` +&.(1&(32 b.)) ``` Which does: sum under rotate bits which means (for people who don't speak J): do rotate on both arguments, sum them, inverse the rotation. This way the bit operation is really used in the result. ]
[Question] [ **Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** [Update the question](/posts/3969/edit) so it's [on-topic](/help/on-topic) for Code Golf Stack Exchange. Closed 12 years ago. [Improve this question](/posts/3969/edit) The students in my high school computer science class were asked to write the game of nim for a simple project. Most of them found it very easy and finished quickly. However, one student came up with this solution. I'll probably make them redo it anyway, but I'm wondering if anyone can understand what's going on. ``` enum $ { $$; static int _, $_$, $_, _0_; { { { { _$ $_ = _$.__; } } } } enum _$ { __(new byte[][]{ "\nNumber of stones: \0\nPlayer one move: \0Computer takes \0\nComputer wins!\n\0\nPlayer wins!\n".getBytes(), new byte[]{(byte) (_ = (int) (Math.random() * (_ = ((_ = -~_) * (_ << -~-~_) + -~-~-~_ + -~ ~ ~-~_)) + _))}}, null); java.io.Console ___ = System.console(); _$(byte[] _$_[], String $[]) { for ($ = new String(_$_[$_$]).split(Character.toString((char) $_$)); _ > 0;) { ___.printf($[$_$] + _); do _0_ = ___.readLine($[-~$_$]).getBytes()[$_$] - 060; while (_0_ > -~-~-~$_$ || _0_ > _); _ -= $_$ + _0_ >> $_$; if (((!(!(((!((!((_) < -~($_ = $_$))))))))))) break; _ -= $_ = Math.min((int) (Math.random() * -~-~-~$_$ + -~$_$), _); ___.printf($[-~-~$_$] + $_); } ___.printf(($_$ = -~-~-~$_$) > _ ? $[$_ > 0 ? -~$_$ : $_$] : $[2]);}}}; ``` ` [Answer] just cause I have way too much time on my hands: ``` import java.io.*; import java.util.*; enum MyEnum { $$; { EnumCalc $_ = EnumCalc.CONSTR; } enum EnumCalc { static int total, $_$, comp, player; CONSTR( ); PrintStream out = System.out; Scanner scan = new Scanner(System.in); EnumCalc() { total = (int) (Math.random() * 20 + 20); strings = new String[] { "\nNumber of stones: ", "\nPlayer one move: ", "Computer takes ", "\nComputer wins!\n","\nPlayer wins!\n" }; while(total > 0) { out.printf("\nNumber of stones: " + total); do { out.printf("\nPlayer one move: "); player = scan.nextLine().charAt(0) - '0'; } while (player > 3 || player > total);//input loop total -= player; comp = 0; if (total < 1) break; comp = Math.min((int) (Math.random() * 4), total); total -= comp; out.printf("Computer takes " + comp); } String string; if (3 > total) string = comp > 0 ?"\nPlayer wins!\n":"\nComputer wins!\n"; else string = "Computer takes "; out.printf(string); } } }; ``` note that `-~i` is the same as `1+i` and I replaced the console calls with System.out and Scanner cause eclipse doesn't give me a Console ]
[Question] [ # Is it a good chord? ### Definition of a `chord`: We define a `chord` as three notes together. ### Definition of a `note`: We define a `note` as a number between `1` and `7`, inclusive. As in music, we define `1` as `do`, `2` as `re`, `3` as `fa`, etc. However, the note names are not important. They will not be included in the question and likely not in a golfed solution. `1` is a note. `0` and `8` are not a note. As we will mention later, the input is a list of three notes, and invalid notes will **not appear** as an input. So even if you print the entire Never Gonna Give You Up lyrics when you encounter invalid inputs, I don't care. (However, I don't see how that's more golf-y.) ### Definition of a `good chord`: We define a `good chord` as follows: * If there are any two notes that are the same, disregard one of them. * Sort the notes. * Space the result on a piano. For instance, `135` will look like `X X X` and so will `246`, `357`, for instance. * If any of the notes are adjacent, it is considered a `bad chord` and thus not a `good chord`. That is, a chord containing `1` and `2` is `bad`, so is a chord containing `1` and `7`. * The only possibilities that are left are: With three digits, * 135 * 136 * 137 * 146 * 147 * 157 * 246 * 247 * 257 * 357 And with two digits, * 13 which could have been 113 or 133 * 14 which could have been 114 or 144 * 15 which could have been 115 or 155 * 16 which could have been 116 or 166 * 24 which could have been 224 or 244 * 25 which could have been 225 or 255 * 26 which could have been 226 or 266 * 27 which could have been 227 or 277 * 35 which could have been 335 or 355 * 36 which could have been 336 or 366 * 37 which could have been 337 or 377 * 46 which could have been 446 or 466 * 47 which could have been 447 or 477 * 57 which could have been 557 or 577 And with one digit, * 1 which means 111 * 2 which means 222 * 3 which means 333 * 4 which means 444 * 5 which means 555 * 6 which means 666 * 7 which means 777 Note that the above possibilities are already sorted, **while you should not expect your input to be sorted**. Also, the above possibilities are represented as a three digit number, **while your input will be a list of three numbers from `1` to `7` inclusive**. I would not expect an answer that hard-codes the values above, but if you intend to, or for some reason it is more golf-y, you are **permitted** to do it. ### Your challenge: Given an input, decide whether it is `good` or not. Return a true-y or false-y value, a true-y value such as `1` means that it is `good`, while a false-y value such as `0` means that it is `not good`. Do not use ambiguous values like or `\n` (indicating a newline) or `[[]]` et cetera. ### Scoring: This is `code-golf`. [Answer] # x86-64 machine code, 19 bytes ``` 31 D2 AD 0F AB C2 FF CF 75 F8 8D 04 12 85 D0 0F 94 C0 C3 ``` [Try it online!](https://tio.run/##RVLBbqMwED17vmJKFQmKGyUhTaWw6WXPe9nTSikHxzaJK2Iq7GhJEb@@7LiU9ID9Zt6b5/Fg@XiUchiEO2OMv6MY5seqPogKSyi3rK0b1KrlYYFmy6paOQXs4N1XWrTAlJYUGWBv9gMbYJUWgeC4b1Sb0lcA89r5MRmcmNP@A0UFrNEekgiTHORJNFjGxnq0HMP2ICgN98bK6qI0/nBemXp@egFwXngj0fnmIj0Gbymcxi5UiX1W5D1MSbcvcIcddEue8aeeB7DmzwFQPIIVZTYTeB41y1G8nqiMyrORWo2AiMnnVv40gRtFZACbKROcVz30OYRmz8LYOIEOWEmT/ry8oXYXOW13O1xuCKRpAowU7L0hvoyjmXm1EadZZRy/r2mKuUhoYKyHm/LV/hLyZKxGWSu9jQIdzmjDGRyvFKoau0mOs8XqDzlfd3F8sc4crVYY/stDUib7Nk2LJO/x78lUGuNraHDR/syC6c0hnhk8XKmr5LPHlsh@GP7JshJHNzyeN2ta6LHtSK@r/w "C (gcc) – Try It Online") Following the standard calling convention for Unix-like systems (from the System V AMD64 ABI), this takes the length and address of an array of 32-bit integers in EDI and RSI, respectively, and returns a value in AL. In assembly: ``` .global f f: xor edx, edx # Set EDX to 0. r: lodsd # Load a number from the array into EAX, advancing the pointer. bts edx, eax # Set the bit in that position in EDX to 1. dec edi # Subtract 1 from EDI, counting down from the length. jnz r # Jump back if that is not zero. lea eax, [rdx+rdx] # Set EAX to 2 times EDX -- the bits move up by 1. test eax, edx # Set flags based on the bitwise AND of EAX and EDX. # This checks for adjacent bits being 1. setz al # Set AL based on whether the result was zero. ret # Return. ``` [Answer] # [Python 3](https://docs.python.org/3/), 32 bytes ``` lambda l:not{*l}&{x+1for x in l} ``` [Try it online!](https://tio.run/##PYzLCoMwEEX3fsWsirbZJPEBQr9Es1BKqDBNRLJQxG9PMwxxd@aee2c9wtc7He17jDj95s8E2Dsfzidej3N/Ses32GFxgFckRuKhGKTQojGCoBYdQboZVEraDB13JJfrrHSaa1aKIYn85543GW6VJEGbE/qsTGF6WLfFhdKWWFXxDw "Python 3 – Try It Online") ]
[Question] [ **Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/211326/edit). Closed 3 years ago. [Improve this question](/posts/211326/edit) The coefficients of a perfect square polynomial can be calculated by the formula \$(ax)^2 + 2abx + b^2\$, where both a and b are integers. The objective of this challenge is to create a program that not only can find if an input trinomial is a perfect square, but also find its square root binomial. The input trinomial will be written in this format: ``` 1 2 1 ``` which symbolizes the perfect square number \$x^2 + 2x+ 1\$, since all 3 input numbers represent coefficients of the trinomial. The outputs must be readable and understandable. To count as a perfect square in this challenge, a trinomial must have \$a\$ and \$b\$ as real integer numbers. No fractions, decimals, irrational numbers or imaginary/complex numbers allowed in the final binomial. Make a program that accomplishes this, and since this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest code in bytes wins. [Answer] # [JavaScript (Node.js)](https://nodejs.org), 42 bytes **I would delete this, but I can't because it's been accepted.** ``` (a,b,c)=>[A=Math.sqrt(a),b/A/2,b*b==c*a*4] ``` [Try it online!](https://tio.run/##bck7DoQgFAXQflYC5KqB2EzxJnEBrsBYPPAzGiMzQtw@2hptz5l55@C26Rez1Xd9GigJhoWT9Gkqqjl@8/DfomAJW1SFgVWWyClWZZucX4Nf@nzxoxiEhoGW8nVVgxLmpm/oM545Oz0d "JavaScript (Node.js) – Try It Online") Can be called as `f(a,b,c)`. Output is in the form `[<factor of x>, <constant>, True/False]` (if it's False, then the first 2 values are meaningless). ]
[Question] [ **Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/205392/edit). Closed 3 years ago. [Improve this question](/posts/205392/edit) You are the first engineer in a hot new startup, Lexographical. Our company is making waves by digitizing and indexing all words, real or not. The core of our product... Our secret sauce... Well, that's why we hired you :) Because we're bleeding edge, we're enforcing the latest standards. Even the latest ones aren't good enough. We need the ones that haven't been made yet. No language in existence is good enough for us, so you need to use Lexo to write your code (funnily enough, it looks identical to your favorite programming language). **Your mission...** Given 2 strings of arbitrary length and composition, return a string that is lexicographically between the 2 strings (i.e. `input_a` < `output` < `input_b`). Please use standard lexicographical comparisons. We want ALL THE STRINGS, so the output doesn't have to resemble either of the inputs (though it might, and that's fine). Because of legal hot water we're in, we can't actually process inputs longer than 10 characters. The output can be as long as we need it to be. Inputs will always be printable ASCII characters and may not be in lexicographical order. They are gUaranteed to not be identical strings. Sample inputs and outputs (using Python string comparison): `Lexo`, `Rules` => `M` `qwerty`, `qwertyuiop` => `qwertyu` `"123"`, `"124"` => `"1230"` Oh yeah, we're running this on very *very* small computers... we're on a tight budget. So the smaller you can make the program, the better! [Answer] # JavaScript, 8 bytes Appends a space to the first string. ``` a=>a+' ' ``` [Answer] # [Keg](https://github.com/JonoCode9374/Keg), `-pn`, 5 bytes ``` ᠀᠀⑭^, ``` Probably the only valid answer. Same as the 0 byter but it sorts the stack lexically. # [Keg](https://github.com/JonoCode9374/Keg) and [05AB1E](https://github.com/Adriandmen/05AB1E/wiki), 0 bytes This is a port of the Javascript answer, but instead of appending a space to the string, it appends a newline. A `0`-byte Keg program is simply a cat program on the first input, meaning that it takes the first word and prints it, followed by a newline. [Try it online!](https://tio.run/##y05N/w8EPqkV@VxBpTmpxQA "Keg – Try It Online") ]
[Question] [ **Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers. --- This site is for programming contests and challenges. **General programming questions** are off-topic here. You may be able to get help on [Stack Overflow](http://stackoverflow.com/about). Closed 3 years ago. [Improve this question](/posts/204318/edit) This might be a very basic question in terms of math, ``` x % constant = x_modulus (x + some_number) % constant = y_modulus ``` Given the value of `x_modulus`, `y_modulus`, `(x + some_number)` and `constant`(common in both), output the value of x itself based on these values. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 1 byte Finds the smallest possible value of all values of `x`, takes input as `some_number, constant, x_modulus, y_modulus` ``` α ``` [Try it online!](https://tio.run/##yy9OTMpM/f//3Mb//425TLmMuQwB "05AB1E – Try It Online") ## Explanation Here are my observations: * The value of `some_number` is the absolute difference between `x_modulus` and `y_modulus` * The above value is in turn x's distance with the closest multiple of constant larger than x. Therefore it's impossible to find what exactly is the value of x. That greatly trivializes the question into a simple absolute difference between `some_number` and `constant`. The code itself is just absolute difference, I don't feel like explaining it. :D ]
[Question] [ Your task is to remove smallest amount elements from a list, so the most elements are on their corresponding place. The element is on it's corresponding place, when it's value is equal to it's position. Let's look at this example list: ``` 1 5 3 2 5 ``` This list has three elements on their corresponding place (1 on position 1, 5 on position 5, 3 on position 3). ## Input The input is a sequence of decimals in any reasonable format. For example: ``` 1 3 2 3 6 ``` ## Output The output is a sequence of decimals in any reasonable format which contains, as its first element, the amount of elements removed from the input then the corresponding, 1-based element positions removed. For example, for input given above, the (correct) output: ``` 1 2 ``` instructs us to remove one element, the one at index two (the first `3`), which will leave us with `1 2 3 6` which has three elements at their index positions. This output would be incorrect: ``` 2 2 5 ``` Since although removing the two elements at indexes two and five would leave us with `1 2 3` which *also* has three elements at their index positions, we've removed more than the minimal necessary. ## More complicated example ``` 1 2 3 3 4 5 6 ``` In this case you can remove **either** of 3's, but not both (so `1 3` and `1 4` are both acceptable outputs). ``` 1 3 2 3 4 5 6 7 8 ``` In this case, if you would remove 3 on position 2, it would pass more elements, than if you would remove 3 on position 4 (so `1 4` is incorrect while `1 2` is correct). ``` 1 3 2 3 5 6 7 8 9 ``` Here removing 3 on position 2 is a mistake, because this actually makes the situation worse in obvious way (there are now less correctly placed elements than before). (the correct output is `0` since removing no elements is the best thing to do) ``` 1 7 2 8 1 3 9 ``` In this case we want to remove the three elements at positions 2, 4, and 5 (leaving us `1 2 3 9` for three in the correct location) so the correct output would be `3 2 4 5`) ## Rules * This is code golf, so the shortest code wins! * Loopholes are forbidden. * Assume that input is valid, contains nothing more than digits and spaces, and the input numbers inside the string are decimals in range of 0 <= n <= 99. * Please include a link to an online interpreter for your code. * If anything is unclear, please let me down in the comments. [Answer] # [Pyth](https://github.com/isaacg1/pyth), 20 bytes ``` lBhMh.Ms.eqktb.DQZyU ``` [Try it online!](https://tio.run/##K6gsyfj/P8cpwzdDz7dYL7UwuyRJzyUwqjL0//9oQx0FIx0FYzAy0VEw1VEwiwUA "Pyth – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 18 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` JŒPṚœPF=J$SʋÞ⁸ṪL;$ ``` **[Try it online!](https://tio.run/##AUIAvf9qZWxsef//SsWSUOG5msWTUEY9SiRTyovDnuKBuOG5qkw7JP/Dh8WS4bmY//9bMSwgNywgMiwgOCwgMSwgMywgOV0 "Jelly – Try It Online")** ### How? ``` JŒPṚœPF=J$SʋÞ⁸ṪL;$ - Link: list of numbers, A J - range of length (A) [1,2,3,...,len(A)] ŒP - all partitions [[1],[2],...,[1,2],[1,3],...,[2,3],...] Ṛ - reversed (so longest to shortest) Þ - sort (the p's in all partitions) by: ⁸ - (using the chain's left argument, A, as the right argument) ʋ - last four links as a dyad, i.e. f(p, A): œP - partition A at the indices in p F - flatten (to give result of dropping the values at indices in p) $ - last two links as a monad: J - range of length (of the flatten result) = - equals? (vectorises) S - sum Ṫ - tail (i.e. the shortest p which yields the maximal sum) $ - last two links as a monad: L - length (of that result) ; - concatenate ``` --- An alternative for `=J$` is `ĖE€` ]
[Question] [ **Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers. --- Questions without an **objective primary winning criterion** are off-topic, as they make it impossible to indisputably decide which entry should win. Closed 5 years ago. [Improve this question](/posts/177421/edit) Ex :- Input: n = 12, k = 5 Output: ans = 2 Sorted list S: ["1", "10", "11", "12", "2", "3", "4", "5", ...., "9"] ans = 2 [Answer] # [R](https://www.r-project.org/), 32 bytes ``` function(n,k)sort(c(1:n,"x"))[k] ``` [Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP08jTydbszi/qEQjWcPQKk9HqUJJUzM6O/Z/moahkY6p5n8A "R – Try It Online") [Answer] # Javascript (ES6), 55 bytes ``` (n,i)=>+[...Array(n).keys()].map(x=>x+1+"").sort()[i-1] ``` [Try it online!](https://tio.run/##bcxBCsMgEIXhfY@R1QyaAQNdFQMlxwhZTKwptiaKhpKc3rpvt9/Pey/@cDbJxb3dwsOWsmjYpEPdi5GI7inxCapDetszA060coRD94dQommQckg7AMu5Lph8MOztENbIycKMOLpWTcWELQdva37CUt/kFfF2@VH1X7vK5Qs) Unfortunately I can't comment yet, so I'll include it in my answer: Welcome to PPCG! To make this a challenge you have to clarify some requirements of the challenge. Add a proper description, define the expected output and the winning criteria and also add some example tests. ]
[Question] [ **The Challenge** Given a number, find the sum of the non-composite numbers in the Fibonacci sequence up to that number, and find the prime factors of the sum. For example, if you were given 8, the non-composite numbers would be 1, 1, 2, 3, and 5. Adding these up would get 12. The prime factors of 12 are 2, 2 and 3, so your program should return something along the lines of `2, 2, 3` when given 12. **The Objective** This is Code Golf, so the answer with the least amount of bytes wins. [Answer] # [Neim](https://github.com/okx-code/Neim), 8 bytes ``` 𝐈f𝕌Σ𝐭}𝐬𝐏 ``` Doesn't work on TIO, but works locally. Explanation: ``` 𝐈 Inclusive range [1 .. input] f Fibonacci numbers 𝕌 Get elements that are only in both lists Σ Keep each element where running the following is falsy 𝐭 Check if composite } Close loop 𝐬 Sum 𝐏 Prime factors ``` ]
[Question] [ **This question already has answers here**: [Reversible hex dump utility (aka `xxd`)](/questions/11985/reversible-hex-dump-utility-aka-xxd) (4 answers) Closed 8 years ago. In this task, your goal is to write a program for generating hexdumps of files of arbitrary types. # Input The input consists of a (relative or absolute) path to the file to be processed. It may be taken from STDIN, a function argument, or a command line argument. # Output The output (which may be written to a separate plaintext file or to STDOUT) should contain a hexdump of the file, formatted as follows: * A-F may be uppercase or lowercase, but should be consistent throughout the output * Spaces between bytes on the same line * 16 bytes per line (the last line may be shorter, depending on the input file) * A trailing newline at the end of the output is permissible * A single trailing space at the beginning or end of each line is permissible, but should be consistent throughout the output. # Some test cases: **Input text file:** ``` Hello, World! ``` **Output (STDOUT or separate text file):** ``` 48 65 6C 6C 6F 2C 20 57 6F 72 6C 64 21 ``` **Input text file:** ``` "Look behind you! It's a three-headed monkey!" ``` **Output (STDOUT or separate text file):** ``` 22 4C 6F 6F 6B 20 62 65 68 69 6E 64 20 79 6F 75 21 20 49 74 27 73 20 61 20 74 68 72 65 65 2D 68 65 61 64 65 64 20 6D 6F 6E 6B 65 79 21 22 ``` **Input JVM class file:** <https://googledrive.com/host/0B66Q2_YrkhNnQkYzY0hyck04NWc/HelloWorld.class> **Output (STDOUT or separate text file):** ``` CA FE BA BE 00 00 00 34 00 1D 0A 00 06 00 0F 09 00 10 00 11 08 00 12 0A 00 13 00 14 07 00 15 07 00 16 01 00 06 3C 69 6E 69 74 3E 01 00 03 28 29 56 01 00 04 43 6F 64 65 01 00 0F 4C 69 6E 65 4E 75 6D 62 65 72 54 61 62 6C 65 01 00 04 6D 61 69 6E 01 00 16 28 5B 4C 6A 61 76 61 2F 6C 61 6E 67 2F 53 74 72 69 6E 67 3B 29 56 01 00 0A 53 6F 75 72 63 65 46 69 6C 65 01 00 0F 48 65 6C 6C 6F 57 6F 72 6C 64 2E 6A 61 76 61 0C 00 07 00 08 07 00 17 0C 00 18 00 19 01 00 0D 48 65 6C 6C 6F 2C 20 57 6F 72 6C 64 21 07 00 1A 0C 00 1B 00 1C 01 00 0A 48 65 6C 6C 6F 57 6F 72 6C 64 01 00 10 6A 61 76 61 2F 6C 61 6E 67 2F 4F 62 6A 65 63 74 01 00 10 6A 61 76 61 2F 6C 61 6E 67 2F 53 79 73 74 65 6D 01 00 03 6F 75 74 01 00 15 4C 6A 61 76 61 2F 69 6F 2F 50 72 69 6E 74 53 74 72 65 61 6D 3B 01 00 13 6A 61 76 61 2F 69 6F 2F 50 72 69 6E 74 53 74 72 65 61 6D 01 00 07 70 72 69 6E 74 6C 6E 01 00 15 28 4C 6A 61 76 61 2F 6C 61 6E 67 2F 53 74 72 69 6E 67 3B 29 56 00 21 00 05 00 06 00 00 00 00 00 02 00 01 00 07 00 08 00 01 00 09 00 00 00 1D 00 01 00 01 00 00 00 05 2A B7 00 01 B1 00 00 00 01 00 0A 00 00 00 06 00 01 00 00 00 01 00 09 00 0B 00 0C 00 01 00 09 00 00 00 25 00 02 00 01 00 00 00 09 B2 00 02 12 03 B6 00 04 B1 00 00 00 01 00 0A 00 00 00 0A 00 02 00 00 00 03 00 08 00 04 00 01 00 0D 00 00 00 02 00 0E ``` **Input ICO image file:** <http://cdn.sstatic.net/codegolf/img/favicon.ico> **Output (STDOUT or separate text file):** 340 lines starting with `00 00 01 00 02 00 10 10 00 00 01 00 20 00 68 04` **Input PNG image file:** <https://i.stack.imgur.com/xPAwA.png> **Output (STDOUT or separate text file):** 7982 lines starting with `89 50 4E 47 0D 0A 1A 0A 00 00 00 0D 49 48 44 52` **Input MP3 Audio file:** <http://www.newgrounds.com/audio/download/142057> (CC BY-NC-SA NemesisTheory 2008) **Output (STDOUT or separate text file):** 300769 lines starting with `49 44 33 03 00 00 00 00 1F 76 54 49 54 32 00 00` [Answer] # Bash/sed, 35 bytes `xxd -p -c16 $1|sed 's/\(..\)/\1 /g'` Basically. ]
[Question] [ Here goes a quick proof by Alan Turing that there is no program `H` that can solve the [halting problem](https://en.wikipedia.org/wiki/Halting_problem). If there was, you could make a program `X` such that `X(n) = if H(n,n) == Halt then output X(n) else output ":-)"`. What is the value of `H(X,X)`? Your job is to make a partial halting solver, such that when some `X` of your choice is inputted, your program will output "Curse you Turing!!!" repeatedly. Specifically, you will make two programs in the same programming language. One will be `H`, the partial halting solver. Given a program `P` (in the same programming language) and an input, H will: * output "halts" if `P` halts * output "no halts" if `P` doesn't halt * If `P` is program `X` (with input `X`), output "Curse you Turing!!!" infinitely, on different lines. * If `H` isn't `X`, and `H` can't figure out if `P` halts, go into an infinite loop without output. Program `X`, will be given an input `n`, and then it will check `H(n,n)`. If it outputs "not halts", it will terminate at some point. For any other result of `H(n,n)`, it will go into an infinite loop. The output of `X` is unimportant. `H` and `X` will not have access to external resources. Specifically, that means that there is a mutual-quine-aspect to this problem. As to how hard `H` has to try to figure out whether a program halts: * Once it determines that its input isn't `X` and `X`, it will run the program with the input for 10 seconds. If it terminates (either correctly or with error) it will output "halts". * You must identify an infinite number of "no halts" programs. Oh, and this may be go without saying, but the programming language needs to be Turing complete (I knew you were thinking of an esoteric language without infinite loops. Sorry.) (That said, Turing complete subsets of languages are also okay.) Your score is the number of bytes in `H`. Least number of bytes wins! Bonuses: * -50 bytes: If `H` captures output from its input program, and reoutputs it but with "PROGRAM OUTPUT: " in front of every line. (This is only done when `H` runs the program to test it.) * -20 bytes: If `H` outputs "halts" based on criteria other than time as well. Try and find a fun combination of `H` and `X` calls to put together to make it interesting (like `H(H,(X,X))` or even more crazy stuff.) [Answer] # Mathematica, ~~140~~ ~~138~~ 127 bytes ``` H=(While[#==#2[[1]]=="While[#~H~{#}==\"halts\"]&",Print@"Curse you Turing!!!"];TimeConstrained[#=="#&"||ToExpression@#@@#2;"halts",10,"no halts"])& ``` Defines a function `H` that takes a function string and argument list as arguments. This also receives the -20 bonus, with the extra criteria being that if the program is `#&`, then it halts. This is to show that it is flawed. Here is the `X`: ``` While[#~H~{#}=="halts"]& ``` ]
[Question] [ **Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/45042/edit). Closed 9 years ago. [Improve this question](/posts/45042/edit) Rules/Objectives: 1. The program must be executed using `./program-name` without shell parameter/arguments. 2. the `program-name` may not contain any of characters in `/etc/passwd`, that is `acdepstw` 3. You may not open any other file, including own's source code, only `/etc/passwd` that should be read. 4. The program must print the content the `/etc/passwd` file. 5. Total score of the code equal to number of characters in the code added with constant literal declaration point. Each byte of constant declaration literal equal to `+100` to the score, after `3` declaration, each byte adds `+200` to the score. So the program should not contain too many constant declaration, but you may use predeclared constants (`M_PI` for example) or exploit the reflection of the function/variable/class name (function, variable or class names in this case are not considered as constant). Counting example: ``` int x = 12; // counted as 1 byte (12 can fit to 8-bit) x += 345; // counted as 2 bytes (345 can fit to 16-bit) #define Y 'e' // counted as 1 byte ('e') #define X Y // counted as 0 (not considered as constant) string s = "abc"; // counted as 3 bytes ("abc") :foo // counted as 3 bytes (:foo) // ^ EACH characters in atom (Elixir, etc) // or characters in symbol (Ruby, etc) // are counted as 1 byte constant '' // counted as 0 (not considered as constant) [0xAC, 12, 114] // counted as 3 bytes (0xAC, 12, 114) ``` **Clarification**: things that counted as constant literal: * numbers, each byte, depends on size * strings/symbols, each character = 1 byte * chars, one byte things that not counted as constant literal: * class declaration * function declaration * variable declaration * operators, brackets * predefined symbols * predefined constants [Answer] # CJam, 49 characters + 0 bytes constant = 49 ``` W[JCJFJIJBEIDHDHDHJBKGIJDHKCIHKFKFKJJA]Y/f+Afb:cg ``` It doesn't work in the online interpreter for obvious reasons. [Answer] # NodeJS - 179 characters + 1 byte constant declaration = 279 ``` #!/usr/bin/env node fs=function fs(){};fs=require(fs.name);x=function etc(){};y=function passwd(){};z='/';fs.readFile(z+x.name+z+y.name,function(err,data){console.log(''+data);}); ``` Readable version: ``` #!/usr/bin/env node fs = function fs(){}; fs = require(fs.name); x = function etc(){}; y = function passwd(){}; z = '/'; // 1 declaration fs.readFile(z+x.name+z+y.name,function(err,data){ console.log(''+data); }); ``` ]
[Question] [ **Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers. --- Questions without an **objective primary winning criterion** are off-topic, as they make it impossible to indisputably decide which entry should win. Closed 9 years ago. [Improve this question](/posts/41731/edit) I just discovered this website and was amazed. Somehow this challenge popped into my mind: Provided a very long list of words; Write or describe an algorithm which finds a regex to match them all. Ex.: A very long list of Dates, model-numbers, CD-Codes, ISBNs et cetera. I hope it's not too big or does not belong here. Please refer to downvote in that case but write a comment and I will delete this. Edit: Sorry at my clumsy attempt. I fear there is not a very sharp goal. Of course .\* is not what I look for :) Here are some specifications: * It has to match all *words* * It has to group characters and find out what kind of characters are in that group, e.g. identify that an american date always consits of one to four numbers, then a slash etc. * It does not need to be able to identify transverses etc * There is a huge list of not-to-match-examples available as well Winner is the one who can write a code which does what I described for one of my examples (or a similar one). In case that no code is committed, the winner is the one who can convince me, that the described algorithm *could* work. [Answer] In Java 8: ``` public class Reg{ public static void main(String... args){ System.out.println(args[0].replaceAll(",", "|")); } } ``` Matches only the strings inputed. Expects input to be of form: goodWord1,goodWord2,goodWord3...(space)badWord1,badWord2,badWord3... **Edit:** Edited for new requirements. Now accepts a list of bad words also. It also now works in Java 7. ]
[Question] [ **This question already has answers here**: [Valid Through The Ages](/questions/25913/valid-through-the-ages) (27 answers) Closed 9 years ago. **Header:** this question has a very close duplicate, but the other question requires a difference between versions of the languages, instead of a difference between different implementation. this means that ***all*** answers from the almost-duplicate are invlid here. this is also my first question, so please don't be harsh. # the question: in this challenge you will be writing code that runs differently on at least two different implementations of your language, such as jython / ironPython for python. different versions of the same implementation don't count. your code should be runnable on all existing implementations (code that doesn't compile on one implementation or halts with an error isn't valid). your code should be well-defined in the scope of each one of the implementations you chose (your code should always do the same thing when run on the same implementation, even on different computers/OS's etc.) also, code isn't allowed to check the implementation directly. this is a popularity contest so try to be creative, most upvoted answer wins. [Answer] # C++ This should print `6.28319` on all *compliant* compilers of C++..and `3.14159` for the Visual C++ compiler. ``` #include <iostream> #if compl-1 #define oddNewPi =6.28318530718,compl #else #define twoPlusTwoIsFive #endif int main(int twoPlusTwoIsFive, char **warIsPeace){ double goodOlPi = -3.14159265359, bitand oddNewPi = goodOlPi; int J = 42; float k = (compl+J)/-40.0f; goodOlPi *= -1; if(k > 1.0f){ twoPlusTwoIsFive oddNewPi *= compl-3; } std::cout << goodOlPi << std::endl; } ``` How this works: `compl` is equivalent to the operator `~`, thus, `compl-1` is `0`. However, for the Visual C++ compiler, `compl` is not treated as an operator (if you include `<ciso686>`, then it is a macro that expands to `~`), therefore, `#if compl-1` is treated as `#if 0-1`, or `#if -1`. `bitand` is equivalent to `&`, but in the code here, the Visual C++ compiler treats it as a variable name instead. When `compl-1` evaluates as false, the code expands to ``` #include <iostream> int main(int, char **warIsPeace){ double goodOlPi = -3.14159265359, &oddNewPi = goodOlPi; int J = 42; // equal to 43/40.0f float k = (~ +J)/-40.0f; goodOlPi *= -1; if(k > 1.0f){ // always true oddNewPi *= ~ -3; // equal to two } // prints 6.28319 std::cout << goodOlPi << std::endl; } ``` whereas if `compl-1` evaluates as true, the code expands to ``` #include <iostream> int main(int twoPlusTwoIsFive, char **warIsPeace){ double goodOlPi = -3.14159265359, bitand = 6.28318530718, compl = goodOlPi; int J = 42; // equal to (-3.1415.. + 42)/-40.0f: about -1 float k = (compl + J)/-40.0f; goodOlPi *= -1; if(k > 1.0f){ // always false twoPlusTwoIsFive = 6.28318530718, compl *= compl - 3; } // prints 3.14159 std::cout << goodOlPi << std::endl; } ``` [Answer] # JavaScript (ES6) In ES5 and possibly older versions, prefixing a number with `0x` would cause the number to be treated as hexadecimal. In ES6, prefixing a number with `0b` causes the number to treated as binary. The `Number` constructor attempts to evaluate the argument as a number and if it is unable to do so, returns `NaN`. For strings, the [evaluation syntax](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-tonumber-applied-to-the-string-type) describes a positive/negative sign with decimal digits OR `0x` followed by hexadecimal digits (optionally surrounded by whitespace). The JavaScript engine in Firefox and Chrome appear to have different implementations when a string is passed beginning with `0b`: ### Firefox 32 ``` Number('11'); // 11 Number('011'); // 11 Number('0b11'); // NaN Number('0x11'); // 17 Number(11); // 11 Number(011); // 9 Number(0b11); // 3 Number(0x11); // 17 ``` ### Chrome 37 ``` Number('11'); // 11 Number('011'); // 11 Number('0b11'); // 3 Number('0x11'); // 17 Number(11); // 11 Number(011); // 9 Number(0b11); // 3 Number(0x11); // 17 ``` I'm assuming that the Chromium dev team will fix the bug sooner or later, but these are the latest stable versions of the browsers at this point in time. Neither Node.js nor Internet Explorer's JavaScript implementation supports this feature of ES6, so it would not be fair to test on those platforms. I should also note that the ES6 specification is still a draft, so perhaps strings beginning with "0b" may be allowed in the evaluation syntax some time in the future. [Answer] ## C++ I'm not sure this is exactly what the question asked for, but this came up as a side-question in an interview once: ``` #include <iostream> #define f(a, b) a * b int main(int argc, char **argv) { int i = 3; std::cout << f(i++, i++) << std::endl; std::cin.ignore(); return 0; } ``` VC++ returns the answer as `3 * 3 = 9`. [compileonline.com](http://www.compileonline.com/compile_cpp_online.php) (which uses g++) returns the answer as `3 * 4 = 12` (those are all the compilers I have access to right now). I can't imagine that there's any more possible answers than those two. Try it out for yourself and see what you get! ]
[Question] [ Some built-in functions in PHP return mixed types, like `file_get_contents` that returns both `string` or `false`. Union structs in C can be used to simulate this, but is there a way to make it polyglot, that is, can be run in both PHP *and* C without (major) modification? Macros is often one way. ``` $result === false ``` can be replaced with ``` CHECK_RESULT($result, false) ``` where ``` #define CHECK_RESULT(res, b) res.success == b ``` and in PHP ``` function CHECK_RESULT($res, $b) { return $res === $b; } ``` Maybe C11 generics can help in a macro too? To switch on second argument. Thankful for any suggestions regarding this. :) [Answer] This behaves the same in C and PHP (assuming there's a file named moo.txt with content "hej" in it). ``` //<?php echo "\x08\x08"; ob_start(); ?> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdbool.h> enum type { STRING = 0, BOOL = 1 }; struct Result { enum type t; union { char* str; bool b; }; }; struct Result file_get_contents(char* filename) { //struct Result r = {.t = BOOL, .b = false}; char* s = malloc(4); strcpy(s, "hej\n"); struct Result r = {.t = STRING, .str = s}; return r; } bool compare_string(struct Result r, char* val) { printf("compare_string\n"); return false; } #define DO_OP(a, op) a op a #define COMPARE_MIXED(res, val, op) _Generic(val, int: (res.t == BOOL && res.b op val),\ char*: (res.t == STRING && strcmp(res.str, val) == 0)\ ) #define OP_EQUALS == #define OP_PLUS + #if __PHP__//<?php define("OP_EQUALS", "=="); define("OP_PLUS", "+"); function COMPARE_MIXED($res, $val, $op) { switch ($op) { case OP_EQUALS: return $res == $val; break; default: assert(false, 'Unkown operation'); } } #endif //<?php /** * Compile with * cat mixed.c | sed -e "s/#__C__//g" | gcc -g -I. -Wno-incompatible-pointer-types -xc - -lgc */ #define function int function main() #undef function { #__C__ struct Result $r = file_get_contents("moo.txt"); if (COMPARE_MIXED($r, false, OP_EQUALS)) { printf("Is false\n"); } else if (COMPARE_MIXED($r, "hej\n", OP_EQUALS)) { printf("Is hej\n"); } return 0; } //?> //<?php ob_end_clean(); main(); ``` ]
[Question] [ **Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/197589/edit). Closed 4 years ago. [Improve this question](/posts/197589/edit) # Introduction In a list of strings, there is a certain length you can shorten strings to before they become indistinguishable. This is a pretty bad explanation, so here is an example. 1. `['hello', 'help', 'helmet']` 2. `['hell', 'help', 'helme']` 3. `['hell', 'help', 'helm']` 4. `['hel', 'hel', 'hel'] <- At this point the strings are indistinguishable` # Challenge Given a list of strings, you program must shorten them until just before any of them become indistinguishable. Shorting is defined as removing one character from the end of a string. To shorten a list of strings by one remove the last character from all of the longest strings in the list, or, if all strings are the same length, every string in the list. For example, given the above input, your program would output `['hell', 'help', 'helm']`. If the strings cannot be shortened, or are already indistinguishable, your program should just output the list unchanged. If, at any point, shortening the strings in the list would make some, but not all, of the strings indistinguishable, you program should still output the list as is, instead of shortening it more. *Note for those who are wondering: If multiple strings can be shortened in the list, they should all be shortened.* * Your program may take input in any format you like, as long as it is one of the [default I/O methods](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods). Input can be of any encoding, but must be a valid UTF-8 string, or your language's equivalent, as can the list of strings. The strings will never be empty, but they might be of different lengths. They will always have at least one common character or be all the same length. There are no restrictions on string content, other than this. The list can also be of any length. * The same goes for output: you may use any of the [default I/O methods](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods). Output can be of any encoding and type, just like the input. All strings in the output should be the same length. # Example I/O * `['hello', 'help', 'helmet']` `['hell', 'help', 'helm']` * `['like', 'likable', 'lick']` `['like', 'lika', 'lick']` * `['hello', 'hello', 'hello']` `['hello', 'hello', 'hello']` * `['a1', 'a2', 'bb']` `['a1', 'a2', 'bb']` * `['farm', 'farms', 'farmer']` `['farm', 'farms', 'farmer']` * `['ape', 'bison', 'caterpillar']` `['a', 'b', 'c']` * `['😀😁😂', '😀🤨😐😑', '😀😛😜😝']` `['😀', '😀', '😀']` # Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins! [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 54 bytes ``` ≔⌊EθLιζ≔⌈EθLιδ≔EδEθ…λ⎇‹ιζι⌈⟦ζ⁻⁺ιLλδ⟧η≔Φη⬤ι⁼№ιλ¹η⎇η§η⁰θ ``` [Try it online!](https://tio.run/##dY4/C8IwEMV3P0W2XiCCzk5SFAQFB7fSIbbBHF7TNmmk9cvHRuufxeneHb/33hVa2qKWFMLaObwYOKDByldwkA20gu2VuXQakHMu2J2vZm9M9n@x8hdroBRsotKhIJXqugES7KSskXaAvXIOMIYLhhF9BWf3UaPxDo7kn8DUQa@KnPNnmf6WbZE6ZUELtiaKjk3rJTlIa2@6uNPILz@uo8Xx/H4jurqdKVUf5WJkWs5XIWRZQnhViWBxyjNNsrgmeR7mN3oA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ≔⌊EθLιζ≔⌈EθLιδ≔Eδ ``` Get the length of the shortest and longest strings, and loop over the latter. ``` Eθ…λ⎇‹ιζι⌈⟦ζ⁻⁺ιLλδ⟧η ``` Trim each string appropriately; the longest string simply trims a character each time but shorter strings stop when they reach the length of the shortest string, until finally the longest string joins them and all the strings can be trimmed again. ``` ≔Φη⬤ι⁼№ιλ¹η ``` Filter out the results with indistinguishable prefixes. ``` ⎇η§η⁰θ ``` Print the shortest distinguishable prefixes, or failing that, the original strings. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), (11?) 18 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) This follows the example given in the question rather than "To shorten a list of strings by one remove the last character from all of *the longest strings* in the list, or, if all strings are the same length, every string in the list." ``` Ṗ€µẈnṂ$TȯJµ¦ƬQƑƇṪȯ ``` **[Try it online!](https://tio.run/##y0rNyan8///hzmmPmtYc2vpwV0few51NKiEn1nsd2npo2bE1gccmHmt/uHPVifX/D7dr6wNVHZ30cOeM//@j1TOAevPVdRRAjAIonZtaoh4LAA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8///hzmmPmtYc2vpwV0few51NKiEn1nsd2npo2bE1gccmHmt/uHPVifX/D7dr6wNVHZ30cOcMzcj//6Oj1TOA2vPVdRRAjAIonZtaoh7LpROtnpOZnQoSA9KJSTlQZnI2RBJZJzIDLJloCBJINAKRSUlQsQKwCUmZxfl5IEZyYklJalFBZk5OahFERVpiUS5IBkQXwxgwyQ/zZzQAcSMQN4HkIPwlK4D0BCCeiBCbMRuI5wDxXKDOWAA "Jelly – Try It Online"). (Both use the footer to format the resulting list of strings). ### How? ``` Ṗ€µẈnṂ$TȯJµ¦ƬQƑƇṪȯ - Link: list, S Ƭ - collect up until a fixed point applying: ¦ - sparse application... µ µ - ...to indices: this monadic chain: Ẉ - length of each $ - last two links as a monad: Ṃ - minimum n - not equal (vectorises) T - truthy indices J - range of length (of current list) - i.e. all indices ȯ - logical OR Ṗ€ - ...action: pop each Ƈ - filter keep those for which: Ƒ - is invariant under: Q - deduplicate Ṫ - tail (0 if none remain) ȯ - logical OR with S (for the 0 case) ``` --- If the text is correct rather than the example then this works for **11 bytes**: ``` ḣ€ⱮẈṀ$QƑƇḢȯ ``` A monadic Link accepting a list which yields a list. [Try it online!](https://tio.run/##y0rNyan8///hjsWPmtY82rju4a6OhzsbVAKPTTzW/nDHohPr/x9u19YHyh2d9HDnjP//o9UzgDry1XUUQIwCKJ2bWqIeCwA "Jelly – Try It Online") Or see the [test-suite](https://tio.run/##y0rNyan8///hjsWPmtY82rju4a6OhzsbVAKPTTzW/nDHohPr/x9u19YHyh2d9HDnDM3I//@jo9UzgJry1XUUQIwCKJ2bWqIey6UTrZ6TmZ0KEgPSiUk5UGZyNkQSWScyAyyZaAgSSDQCkUlJULECsAlJmcX5eSBGcmJJSWpRQWZOTmoRREVaYlEuSAZEF8MYMMkP82c0AHEjEDeB5CD8JSuA9AQgnogQmzEbiOcA8VygzlgA "Jelly – Try It Online"). (Both use the footer to format the resulting list of strings). ### How? ``` ḣ€ⱮẈṀ$QƑƇḢȯ - Link: list, S $ - last two links as a monad - f(S): Ẉ - length of each Ṁ - maximum Ɱ - map across (implicit range [1..m]) applying: ḣ€ - head each to index Ƈ - filter keep those for which: Ƒ - is invariant under: Q - deduplicate Ḣ - head (0 if none remain) ȯ - logical OR with S (for the 0 case) ``` ]
[Question] [ **Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/193564/edit). Closed 4 years ago. [Improve this question](/posts/193564/edit) Challenge: Add two numbers. In O(n^m) time, where n and m are the two numbers given. Sleeping, or your language equivalent, is not allowed. Input: Two integers, separated by a space. Output: The sum of the two integers. Additional notes: The exact timing doesn't matter, as long as the input `1000 2` takes roughly 1/1000th the time as the input `1000 3` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 4 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set") Anonymous tacit infix function: ``` ⊃*⍴+ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT////1FXs9aj3i3a/9MetU141Nv3qG@qpz9Q8NB640dtE4G84CBnIBni4Rn8XzM5v6BSISUtr1ghObegggtEKKgbGhgopCkYqaNwjdUB "APL (Dyalog Unicode) – Try It Online") However, if it really needs to take the two arguments together, separated by a space, we need the following anonymous tacit prefix function: # [APL (Dyalog Unicode)](https://www.dyalog.com/), 6 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set") ``` ⊃*/⍴+/ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT////1FXs5b@o94t2vr/0x61TXjU2/eob6qnP1D40HrjR20TgbzgIGcgGeLhGfxfMzm/oFIhJS2vWCE5t6CCC0QoqKcpGBoYKBipo3CN1QE "APL (Dyalog Unicode) – Try It Online") `+` or `+/` sum the numbers `⍴` cyclically **r**eshape that to the following length: `*` or `*/` one number raised to the power of the other `⊃` pick the first element of that [Answer] # [Python 3](https://docs.python.org/3/), 34 bytes ``` lambda n,m:sum(range(n**m))and m+n ``` [Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSFPJ9equDRXoygxLz1VI09LK1dTMzEvRSFXO@9/QVFmXolGmoahgYGBjrGm5n8A "Python 3 – Try It Online") Alternatively, as suggested by [user202729](https://codegolf.stackexchange.com/users/69850/user202729): # [Python 2](https://docs.python.org/2/), 26 bytes ``` lambda n,m:n**m*[1]and n+m ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSFPJ9cqT0srVyvaMDYxL0UhTzv3f0FRZl6JQpqGoYGBjpEmFzLXWPM/AA "Python 2 – Try It Online") which also works with Python 3. ]
[Question] [ **Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/175703/edit). Closed 5 years ago. [Improve this question](/posts/175703/edit) # Challenge Take an input string \$s\$, and split it into words \$w\_1, w\_2, ..., w\_n\$. If the amount of words is odd, then return \$s\$. Otherwise, for each word: Take the *second last* letter, and swap it with the first letter keeping capitalization positions. So `GolF` becomes `LogF`. Now check if the amount of words is a multiple of 2, if they are, then take the new words and make another set of words \$q\_1, q\_2, ..., q\_{n/2}\$, where \$q\_n\$ is a concatenation of \$w\_n\$ and \$w\_{2n}\$ before applying the whole thing again to the \$q\$ words. If the amount of words isn't a multiple of 2, then return \$w\$ separated by spaces. --- # Example String: `Hello bye hey world woo doo`. * Split it: `[Hello, bye, hey, world, woo, doo]` * Is the length an even number? Yes, proceed * Swap the first and second-last letters: `[Lelho, ybe, ehy, lorwd, owo, odo]` * Is the length an even number? Yes, make new groups of 2: `[Lelho ybe, ehy lorwd, owo odo]` * Swap again: `[Belho yle, why lored, dwo ooo]` * Is the length an even number? No, return `Belho yle why lored dwo ooo` --- # Notes * Input words will always have more than 2 characters * Input will always be letters from a-z, capital or lowercase, and separated by a single space * Standard loopholes and Default I/O rules apply * You may not take input in the form of a word list/array * You don't need to handle edge cases --- # Test Cases ``` Hello bye hey world woo doo --> Belho yle why lored dwo ooo Code golf awesome stuff --> Goce lodf swesoae ftumf Very hard code golf challenge --> Very hard code golf challenge (odd length) Very hard coding stuff --> Hevy rard sodicg ftunf ``` --- # Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code (in bytes) wins. [Answer] # [Node.js v10.9.0](https://nodejs.org), 171 bytes ``` s=>(h=a=>a.map(w=>Buffer(w).map((c,i,a)=>(i?i-p?c:x:a[x=c,p=w.length-2])&31|c&96)+''),g=n=>n&1?a.join` `:g(n/2,a=h(h(a).join` `.match(/\S+ \S+/g))))((a=s.split` `).length) ``` [Try it online!](https://tio.run/##fZBRa8IwEMff9ykOHzTB2qKDwYRUcA/zfbCXbWCWXpJKzJWmWgv77l063WA@eJA8HD9@97/byaMMqi6rZuapwF6LPoicWSFFLtO9rFgr8vVBa6xZy38aTCVlInmkylU5q1ZqeVrKt5NQSSXa1KE3jZ0tPvj4fv6lxo8PfDqZ8MQIL3I/nq9kuqPSb2G7NMxni0QKyyyT/LcdZzTKsuz9ZQrxZYbHYkyKkIbKlU1E@GUK7xX5QA5TR4ZpNtqgcwSfHYLFDlqqXRF/goJoBMA5ZBms0VmCziG0tgNHNRZQtAREdHele4oXAUNOg2wx0B4hNPEUUTXUWfdMCqOl0BAGRiLo5rDX16pXrDuwsi5A/UmVlW5YBEdn1U3mprD05l@0S7YNHjuoByZERpkhmtf9Nw "JavaScript (Node.js) – Try It Online") ### Commented The helper function \$h\$ takes an array of words \$a\$ and apply the letter transformation to each of them. ``` h = a => // a[] = input array a.map(w => // for each word w in a[]: Buffer(w) // convert w to a Buffer .map((c, i, a) => // for each ASCII code c at position i in this array a[]: ( i ? // if this is not the first letter: i - p ? // if this is not the second last letter: c // just use c : // else: x // use the backup x of the first letter : // else: a[ // use the second last letter x = c, // save the first letter in x p = w.length - 2 // p = index of the second last letter ] // ) & 31 // use the lower bits of the above character | c & 96 // use the upper bits of the current character (case) ) + '' // end of inner map(); coerce the Buffer back to a string ) // end of outer map() ``` Main part: ``` s => ( // s = input string g = n => // g = recursive function taking the number of words n n & 1 ? // if n is odd: a.join` ` // stop recursion and return a[] joined with spaces : // else: g( // do a recursive call to g: n / 2, // with n / 2 a = h( // update a[]: h(a) // apply the letter transformation .join` ` // join with spaces .match(/\S+ \S+/g) // make groups of 2 words ) // apply the letter transformation again on the result ) // end of recursive call )((a = s.split` `).length) // initial call to g with a[] = list of words, n = length ``` [Answer] # [Python 3](https://docs.python.org/3/), 189 bytes ``` J=' '.join s=input().split() f=lambda w,i:(w[~i].lower(),w[~i].upper())[w[i-1].isupper()] while~len(s)&1:s=[f(w,1)+w[1:-2]+f(w,-1)+w[-1]for w in s];s=[*map(J,zip(s,s[1:]))][::2] print(J(s)) ``` [Try it online!](https://tio.run/##LYxNDoMgFIT3noJVhYomtjsaL@ABuiEsbJX6GgTC0xC78OqW/qwm32S@8es8Onve97bJSV49HdgMG7B@mSmr0BtImenGdNOt70jkIGiUG6jKuDgEyviPFu8/xGSUUNaqAvw3KosjmGEzg6XIDrXARmoaec2KKGtRnlTxwfLLydQukEjAElSXND1Onactf4GnyDEJijElhTipzAewM23TK9v36xBWMnahJ3fXg30QnBet3w "Python 3 – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 68 bytes ``` ≔⪪S θF¬﹪L貫≔¹ηW¬﹪Lθη«≔EE⪪θη⪫λ ⭆⭆Eλ⁻⁻Lλλ⎇∧νξξν⎇№α§λξ↥ν↧νθ≔²η»»⪫θ ``` [Try it online!](https://tio.run/##dZDBasMwDIbPzVOInmTIDuu1p7DLOpox6PYAXuLVBiMljrMkjD57ZsdpYIcdJCz0/fIvVVq6iqWd56LrzJXw0ljj8URN7y/eGbqiyGEP@5Bbccy@2AG@sseS694ynhVdvcY2tA9CCPjJduugxxx0EOwGbaz6T6NXzV1UymaJ5KKNQA4vbAhtchHKZGuhtleMQJSG@g5TXn@xQTEmdzkU/kS1GiP6rhxJN2FBNVJCxhxIROzee@KePMo/ujECH02jXCU7hRSqMw9btejjobaVDusdbtktewt@PS77tOs@x3l@VtYyfE4KtJpgYGfrkBlq5mx@@La/ "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ≔⪪S θ ``` Split the input on spaces. ``` F¬﹪L貫 ``` Do nothing if the number of words is odd. ``` ≔¹η ``` Don't pair the words up on the first pass. ``` W¬﹪Lθη« ``` Repeat while the number of words is even. ``` ≔EE⪪θη⪫λ ...θ ``` Pair the words up, map over the paired words, and save the result. ``` Eλ⁻⁻Lλξ² ``` Map each character index to the length of the word minus the index minus 2. ``` ⭆...§λ⎇∧νξξν ``` Map each character to itself unless its index or the above calulation is zero in which case use the character at the index given by the above calculation. ``` ⭆...⎇№α§λξ↥ν↧ν ``` Map each character to upper or lower case depending on whether the original character of that word was upper or lower case. ``` ≔²η»» ``` Pair the words up on successive passes. ``` ⪫θ ``` Join the (remaining) words on spaces and implicitly print. ]
[Question] [ **This question already has answers here**: [Find the prime factors](/questions/1979/find-the-prime-factors) (26 answers) Closed 5 years ago. It's been a while since I posted here, so here we go another day another challenge. # Challenge : Given a number(*`n`*) split it into it's prime factors. --- # Input : A positive non-zero integer greater than 2. --- # Output : Decompose the number into it's prime factors and return the number of occurances of each prime in it. --- ## Ouput format : You can choose Any valid output format. --- # Example : ``` n = 86240 v------------------------------- number of times it occurs in n output : [[2, 5], [5, 1], [7, 2], [11, 1]] ^-------------------------------- prime number n = 7775460 v--------------- 5 only occurs once in 7775460 so we don't need to write any power output : [[2, 2], [3, 3], [5], [7], [11, 2], [17]] ^--------------------------------- same as first example ``` # Note : * Prime factors have to be in either ascending order or descending order. * You may choose to either write 1 as power or note # Winning criterion : This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest code in bytes for each programming language wins [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 2 bytes Built in command =) ``` ÆF ``` [Try it online!](https://tio.run/##y0rNyan8//9wm9v///8tzIxMDAA "Jelly – Try It Online") --- # [Brachylog](https://github.com/JCumin/Brachylog), 10 bytes ``` ḋ≡ᵍ⟨h≡l⟩ᵐ ``` -1 bytes thanks to Erik the Outgolfer [Try it online!](https://tio.run/##SypKTM6ozMlPN/r//@GO7kedCx9u7X00f0UGkJXzaP7Kh1sn/P9vYWZkYvA/CgA "Brachylog – Try It Online") ]
[Question] [ **Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/163445/edit). Closed 5 years ago. [Improve this question](/posts/163445/edit) **Challenge** Create a function that takes an string as a parameter. (Easy as far) This string will contain * Single digit numbers * Letters from the alphabet * Question marks (Of course) Your function will check if there are exactly `3 question marks` between every pair of two numbers that add up to 10 or more. If so, then your function should return `truthy`, otherwise it should return `falsey`. If there are not any two numbers that add up to 10 or more in the string, your function should return false. **Rules** * Input must be a string * Output must be `truthy` or `falsey` value * If string contains only one number or none return `falsey` * If string contains odd amount of single digits, ignore the last one (left to right) **Example** Given: `"arrb6???4xxbl5???eee5"` Your function must output `true` because there are exactly `3 question marks` between `6` and `4`, and `3 question marks` between `5` and `5` at the end of the string --- Given: `"a4sd???9dst8?3r"` Your function must output `false` because there is just a `single question mark` between `8` and `3` **Test Cases** **Input:** `"aa6?9"` **Output:** `false` --- **Input:** `"acc?7??sss?3rr1??????5"` **Output:** `true` --- **Input:** `"sdty5???xcd8s3"` **Output:** `true` --- **Input:** `"sthfer5dfs"` **Output:** `false` --- ## Update (Some clarification points) * Once you use a number to pair with other, you can not use it again. * You only can pair consecutive numbers (left to right). Example `"as4f???6sda3?3d"` the pairs are `4-6` and `3-3` --- This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes win. [Answer] # [Python 3](https://docs.python.org/3/), 148 bytes ``` def f(a):q=[a.group(1).count("?")==3for a in re.finditer("(?=((\d+)\D+(\d+)))",a)if 10==sum(map(int,a.groups()[1:]))];return any(q)*all(q) import re ``` [Try it online!](https://tio.run/##LY2xDoIwFEV3v6Jhek8JkSAOmKaLfwEMRVptAm15tAl8PTbG6dzlnOv38HG2Oo5RaaZBYrPwVhZvctFDicXLRRsgExlyXmlHTDJjGalCGzuaoAgyEBygGy/YPS8/Ima5RKNZeeV8jTPM0oOxIf93V8C2bHrE/kEqRLJM2h0WPMtpSjiZ2TsK6eTwlDTQSfYxQAofkmi4CyFu2zZMdRpKqfoL "Python 3 – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 126 bytes `all*any` idea is by @HyperNeutrino, checkout [his answer](https://codegolf.stackexchange.com/a/163449/66855) ``` def f(n):r=[sum(map(int,g[0::2]))>9for g in re.findall('(\d)(.*?)(\d)',n)if 3==g[1].count('?')];return all(r)*any(r) import re ``` [Try it online!](https://tio.run/##LVDBboMwDD3DV0RcklQZWkvpVibqD2EcKEloJAjICRJ8PQsdvvjZz@9Z9rT612gv2yaVJppZXmBZuXlgQzMxY73oqs@iuNScP@56RNIRYwmqVBsrm75nlP1KztIT8B1QYbnRJCvLrjrXaTvO1jMKlNc/qPyMluwa5KfGriHFZphG9MFv272NnWa/@1eJ8y@tMJfaJSKOoqRpbnA/IOLzBgDXZXn2eQBKqfyg2ha@AJxzkCGe4R0H56Rf9@mlld8uS0KrLuJownDj/2JB6MeDivCEd8m3Pw "Python 2 – Try It Online") --- # [Python 2](https://docs.python.org/2/), 125 bytes Ouputs `[]` for false and `[True]` for true ``` def f(n):r=[sum(map(int,g[0::2]))>9for g in re.findall('(\d)(.*?)(\d)',n)if 3==g[1].count('?')];return r[:1]*all(r) import re ``` [Try it online!](https://tio.run/##NVBBboMwEDzDKywutiMHFQhpQ0T8EMqBYJtYAoPWRiKvp3ZL9zSzszPa3eXtXrPJ911IhRQxtIK6setEpm4h2jg2NB9VlbeUPm5qBjQgbRDIVGkjunEkmHwLStITpwFgZqhWqKjrocnatJ9X4wjmmLZ3kG4Fb22qrD0FJ9BYT8sMzsftIVqbZXUhvkmseykJpVA2YXEUJV135bd/mHHO84MAPK@eXrbtOZYeSCnLQ@p7/sm5tZYXAMHj69CscO8wvfXiyxaJb7VVHC3g7/3bgiF8fmDmH/JL6f4D "Python 2 – Try It Online") ]
[Question] [ Suppose I have a linear inequality like > > x0A0 + x1A1 + ... + xnAn <= C > > > with xi a non-zero positive integer and Ai and C a positive non-zero multiple of `0.01`. Find all the positive integer n-tuples {x1,...,xn} such that: > > D <= x0A0 + x1A1 + ... + xnAn <= C > > > where D is also a positive non-zero multiple of `0.01`. --- **Challenge:** Find the shortest code to produce the n-tuple solution(s) for any Ai, C, D. --- Example: Let A0,A1=1, C = 2.5, and D=1.5. This gives > > 1.5 <= x01+x11 <= 2.5 > > > Here, the (only) 2-tuple solution is {1,1}: [![enter image description here](https://i.stack.imgur.com/KVNnH.png)](https://i.stack.imgur.com/KVNnH.png) [Answer] # [Haskell](https://www.haskell.org/), 64 bytes ``` (d#c)a=[x|x<-mapM(\_->[1..c])a,y<-[sum$zipWith(*)x a],y>=d,y<=c] ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/XyNFOVkz0Ta6oqbCRjc3scBXIyZe1y7aUE8vOVYzUafSRje6uDRXpSqzIDyzJENDS7NCITFWp9LONgUoZ5sc@z83MTNPwVYhJV@BS6GgKDOvREFFQUNZU8FQz1TBGIijDXUMY/8DAA "Haskell – Try It Online") Defines a funktion `(#)` which takes D as first argument, C as second argument and A as a list as last argument and returns a list of possible X as lists. E.g. `(#) 1.5 3.5 [1,1]` yields the three solutions `[[1.0,1.0],[1.0,2.0],[2.0,1.0]]`. --- ### 61 bytes with D and C integers: ``` (d#c)a=[x|x<-mapM(\_->[1..c])a,elem(sum$zipWith(*)x a)[d..c]] ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/XyNFOVkz0Ta6oqbCRjc3scBXIyZe1y7aUE8vOVYzUSc1JzVXo7g0V6UqsyA8syRDQ0uzQiFRMzoFJB/7PzcxM0/BVqGgKDOvREFFQUNZU8FIwVQh2lDHUMco9j8A "Haskell – Try It Online") E.g. `(#) 2 5 [1,1,2]` yields `[[1,1,1],[1,2,1],[2,1,1]]`. ]
[Question] [ **This question already has answers here**: [Shortest program that continuously allocates memory](/questions/101709/shortest-program-that-continuously-allocates-memory) (71 answers) Closed 7 years ago. Your task is to write a program that: * Runs indefinitely * Produces no output * Consumes an unbounded amount of memory ## Specifications * You must list the implementation used for your program. This is relevant because some implementations might preform optimizations while others do not. For example, the LISP code `(defun f () (f)) (f)` may or may not consume infinite memory depending on whether the implementation optimizes tail recursion. * Obviously, your program may terminate from running out of memory. ## Examples BF: ``` +[>+] ``` Python: ``` l = [] while True: l.append(1) ``` JavaScript: ``` l = []; while (true) l.push(1); ``` C (I'm not sure if this works): ``` #include <stdio.h> int main() { while (1) malloc(1); } ``` --- This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest valid solution (in bytes) wins. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 2 bytes ``` ‘ß ``` Increments and calls itself recursively. As the integer gets bigger, more memory is required to store it. You can [Try it online!](https://tio.run/nexus/jelly#@/@oYcbh@f//AwA "Jelly – TIO Nexus"), but it's not much to look at. [Answer] # Python 3, 16 bytes ``` i=9 while i:i*=9 ``` As `int`s in Python3 are only limited by the memory, this will run until there is no more memory available. [Answer] # Befunge-98, 1 byte ``` ' ``` Fills the stack with strings containing `'` [Answer] # [Java (OpenJDK 9)](http://openjdk.java.net/projects/jdk9/), 75 bytes ``` interface G{static void main(String[]a){a=new String[1];for(;;)a[0]+=' ';}} ``` [Try it online!](https://tio.run/nexus/java-openjdk9#@5@ZV5JalJaYnKrgXl1ckliSmaxQlp@ZopCbmJmnEVxSlJmXHh2bqFmdaJuXWq4AFTCMtU7LL9KwttZMjDaI1bZVV1C3rq39/x8A "Java (OpenJDK 9) – TIO Nexus") [Answer] # [Bash](https://www.gnu.org/software/bash/), 17 bytes ``` for((;;)){ a+=a;} ``` [Try it online!](https://tio.run/nexus/bash#@5@WX6ShYW2tqVmtkKhtm2hd@/8/AA "Bash – TIO Nexus") [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 8 bytes ``` (()){()} ``` [Try it online!](https://tio.run/nexus/brain-flak#@6@hoalZraFZ@/8/AA "Brain-Flak – TIO Nexus") [Answer] # Vim, 13 bytes ``` qqaa<esc>"Ax@qq@q ``` This defines a macro, `q` that appends the letter `a` to the register `A` and then calls itself. This results in an infinite loop of making register `A` bigger and bigger, only limited by memory. [Answer] ## Ruby, 15 bytes ``` i=[];loop{i<<0} ``` ]
[Question] [ Develop a program which takes two arrays of decimal numbers, and compare the sum of whole numbers only and the decimal part. If the sums of the whole numbers are the same, and the decimal parts of Array a are a subset of the decimal parts of Array b, return True. Otherwise, return False. Example-1 :- Array a ={2.5,3.0,1.3} Array b = {5.0,1.0,0.5,0.3} Sum of whole numbers: Array a = 2+3+1 = 6 and Array b = 5+1 =6 --Matched Individual fraction part: Array a = 2.5 = 0.5 and Array b = 0.5--Matched Individual fraction part: Array a = 1.3 = 0.3 and Array b = 0.3--Matched All the above are matched, so it returns true. Example-2 :- Array a ={1.7,2.3} Array b = {1.2,0.5,2.3} Sum of the whole numbers: Array a = 2+1 = 3 and Array b = 2+1 =3 --Matched Individual fraction part: Array a = 1.7 = 0.7 and Array b = 0.2 or .5 or .3 --No Exact match Individual fraction part: Array a = 2.3 = 0.3 and Array b = 2.3 = 0.3 -Matched One of the conditions is not matched, so it returns false. [Answer] # JavaScript, 63 bytes ``` (a,b)=>a.reduce((s,n)=>s+~~(n),0)===b.reduce((s,n)=>s+~~(n),0); ``` ## Test it ``` const x=(a,b)=>a.reduce((s,n)=>s+~~(n),0)===b.reduce((s,n)=>s+~~(n),0); const A = [2.5, 3.0, 1.3]; const B = [5.0, 1.0, 0.5, 0.3]; console.log(x(A,B)); // true ``` [Answer] # Mathematica ~~88~~ 81 This should be easy to beat. I was surprised that `Rationalize` was needed. ``` r=Rationalize;f=Floor; (Tr[f@#]==Tr[f@#2] && Complement[r@Mod[#2,1],r@Mod[#, 1]]=={})& ``` --- ``` (Tr[f@#]==Tr[f@#2] && Complement[r@Mod[#2,1],r@Mod[#, 1]]=={})& @@ {{2.5, 3.0, 1.3}, {5.0, 1.0,0.5, 0.3}} ``` > > True > > > --- ``` (Tr[f@#]==Tr[f@#2] && Complement[r@Mod[#2,1],r@Mod[#, 1]]=={})& @@ {{1.7, 2.3}, {1.2, 0.5, 2.3}} ``` > > False > > > [Answer] # Python, 45 bytes ``` x=lambda a,b:sum(map(int,a))==sum(map(int,b)) ``` [Try it online!](https://tio.run/##K6gsycjPM/7/v8I2JzE3KSVRIVEnyaq4NFcjN7FAIzOvRCdRU9PWFlkgSVPz/38A) ]
[Question] [ **Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/38470/edit). Closed 6 years ago. [Improve this question](/posts/38470/edit) ***Goal:*** Write a piece of code that produces a array containing *all* integer values in a set range in random order (upper and lower bounds included). Use any language you like, but use as little built-in functions as possible (ie PHP's `array_shuffle` should be avoided) ***Rules:*** * All ints in the range must be used once, and only once * The range can be negative, or positive * When using JavaScript: ECMAScript6 features are to be avoided * If you choose to write a function the `function(params){` and closing `}` needn't be counted. Bonus points for clever argument validation/normalization if you do write a function * Aliases like `m = Math;` or `Array.prototype.p = [].push;` will be counted, using closures/functions, passing `Math` as an argument will be counted as `<argName>=Math;` ***Benchmark:*** As a starting point or target: here's a snippet that meets all of the criteria apart from the randomness. It's approx. 50 bytes long (depending on `v`'s value). That would be a nice target to hit: ``` for(l=3,a=[v=12],i=v>0?-1:1;(v+=i)!=l+i;)a.push(v) ``` Caveats: if `l` is bigger than `v`, the code fails. [Answer] ## APL, 18 ``` {(⍺⌊⍵)-1-?⍨1+|⍺-⍵} ``` Takes upper/lower bounds as left/right argument. Works for any bounds, also reversed bounds. Can be shortened to 13 characters if the assumption l<=u can be made: ``` {⍺-1-?⍨⍵-⍺-1} ``` [Try](http://tryapl.org/) [Answer] ## GolfScript (26 bytes) ``` ~)1$-:x,\{+}+%{;x.*rand}$` ``` [Online demo](http://golfscript.apphb.com/?c=OyctNyAtNCcKCn4pMSQtOngsXHsrfSslezt4LipyYW5kfSRg) Could be slightly shorter but at the cost of worse randomisation. By picking random numbers up to the square of the size of the range I come close enough IMO to avoiding collisions. [Answer] ## JavaScript, 73 bytes ``` for(i=l,s=[];i<=u;)s[i-l]=i++;s.sort(function(){return Math.random()<.5}) ``` Assumes `l` and `u` have the lower and upper bounds resp. and `l<=u` [Answer] ## PYTHON, 21 `list(set(range(l,u+1)))` * assumes `l <= u` I believe `set` uses the hash value of the arguments for the order of this list it generates. This generates kind-of random ordering, for example with `l, u = 30, 50`, I get `[32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 30, 31]`. I'd say this still counts though. [Answer] ## J (11 (or 9)) ``` f=:>.-?~@>:@|@- ``` This defines a dyadic function, the arguments of which define the start and end of the range. The order of the arguments doesn't matter. (Does this give me bonus points?) As per the rules, I'm not counting `f=:` as this is part of the function definition (i.e., what would be `function f(params){`...`}`. An anonymous function would be `(>.-?~@>:@|@-)`, where the `()` can be disregarded according to that rule. If I can assume the *left* argument to be the *upper* bound, and the *right* argument to be the *lower* bound, it can be shortened to **9**: ``` g=:[-?~@>:@- ``` Or, as an anonymous function, `([-?~@>:@-)`. Test: ``` f=:>.-?~@>:@|@- g=:[-?~@>:@- _5 f 10 _1 2 0 _2 _5 3 _4 _3 1 9 4 10 5 7 6 8 2 f 10 2 10 5 3 8 4 9 7 6 10 f 2 2 9 4 5 6 10 3 7 8 10 f _5 _3 9 4 3 2 6 _2 1 5 8 7 _1 _4 10 _5 0 10 g 2 2 3 4 7 9 5 6 10 8 10 g _5 1 2 7 4 3 _4 5 8 6 9 _1 10 0 _5 _2 _3 ``` [Answer] ## CJam, 12 (or 10) bytes Aannnd, if other languages are allowed, here is an answer in CJam ``` {$~1$-),f+mr`}:F; ``` This creates a function `F` , thus not counting the `{` and `}:F;`. Example Usage: ``` {$~1$-),f+mr`}:F; [7 -2]F ``` Output: ``` [1 -2 6 2 -1 5 7 0 3 4] ``` If I assume that first integer is always less than the second integer, then the code comes down to **10 bytes**: ``` {1$-),f+mr`}:F; ``` Example usage: ``` {1$-),f+mr`}:F; -2 7F ``` Output: ``` [1 -2 6 2 -1 5 7 0 3 4] ``` [Try it online here](http://cjam.aditsu.net/) [Answer] ## Perl - 19 ``` sort{rand>.5}$l..$v ``` Assuming `$l` and `$v` are already defined. If you wanted to make it a function: ``` sub random_array { sort{rand>.5}$_[0].._$[1] } ``` You can try it with: ``` perl -E'$,=",";$l=1; $v=15; say sort{rand>.5}$l..$v' ``` or ``` perl -E'say random_array(0,5);sub random_array{sort{rand>.5}$_[0]..$_[1]}' ``` ]
[Question] [ **Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** [Update the question](/posts/10937/edit) so it's [on-topic](/help/on-topic) for Code Golf Stack Exchange. Closed 10 years ago. [Improve this question](/posts/10937/edit) Implement the following JavaScript method as short as possible: ``` function same_subnet(ip_a,ip_b,sn_mask) { } ``` It should get 2 IP addresses and a subnet mask. It should return `true` if `ip_a` and `ip_b` are in the same subnet. Example calls: 1. `same_subnet("192.168.0.1","192.168.0.15","255.255.255.0")` → `true` 2. `same_subnet("192.168.0.1","192.168.1.15","255.255.0.0")` → `true` 3. `same_subnet("192.168.0.1","192.168.1.15","255.255.255.0")` → `false` [Answer] # 126 Fits into a tweet and doesn't even leak globals. ``` function same_subnet(a,b,c){function x(n){return n=n.split("."),n[0]<<24|n[1]<<16|n[2]<<8|n[3]}return(x(a)&x(c))==(x(b)&x(c))} ``` ]
[Question] [ **Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers. --- Questions without an **objective primary winning criterion** are off-topic, as they make it impossible to indisputably decide which entry should win. Closed 9 years ago. [Improve this question](/posts/8586/edit) Given * the number of goods N * positive weight of each good weight[N] * positive profit of each good profit[N] * and a positive number W which is the knapsack capacity. This problem is called “the zero-one knapsack” for choosing the most beneficial goods for the knapsack of limited capacity. ## Example: * The number of goods (items) : 5 * Weight of each item (kg) : {2, 3, 5, 7, 8} which apply to item 1, item 2, ...... item 5 in that order * Value of each item (10,000 yen) : {2, 4, 8, 9, 10} which apply to item 1, item 2, .... item 5 in that order * Capacity of the knapsack : 10 kg Among the five goods: ``` Goods chosen Total weight Total value Goods 1, 2 and 3 2 + 3 + 5 = 10 2 + 4 + 8 = 14 <- Maximum ``` [Answer] # Python, 236 Charaters Okay, I guess I'll bite. ``` from itertools import * def k(w,p,c): n=len(w) r=range(n) return max(filter(lambda y:y[1]<=c,[(s,sum(map(lambda y:w[y],s)),sum(map(lambda y:p[y],s))) for s in chain.from_iterable(combinations(r,u) for u in r+[n])]),key=lambda y:y[2])[0] ``` ### Usage The `k` function takes three arguments: a list containing the weights, a list containing the profits, and the capacity of the knapsack. Here is how to call it given the example above: ``` > print k([2,3,5,7,8], [2,4,8,9,10], 10) (0, 1, 2) ``` Meaning that items 0, 1, and 2 are the optimal solution. ]
[Question] [ **Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers. --- Questions without an **objective primary winning criterion** are off-topic, as they make it impossible to indisputably decide which entry should win. Closed 5 months ago. [Improve this question](/posts/265365/edit) Need to write a JS function compare(a,b) for numbers which return 1 when a > b, 0 when a == b, -1 when a < b. Also following properties should hold: 1. compare(NaN, NaN) = 0 2. NaN is bigger than any other number, so compare(NaN, any) = 1 and compare(any, NaN) = -1. 3. compare(-0.0, 0.0) = -1 and compare(0.0, -0.0) = 1. Other numbers are ordered by default. Other way to define: function should behave as Double.compare method in Java. [Answer] # [JavaScript (Node.js)](https://nodejs.org), 61 bytes *-5 bytes, thanks to l4m2* ``` compare=(a,b)=>(a>b)-(b>a)||(1/a>1/b)-(1/b>1/a)+(b==b)-(a==a) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70kLz8ldcGCpaUlaboWN22T83MLEotSbTUSdZI0be00Eu2SNHU1kuwSNWtqNAz1E-0M9UECQBLIStTU1kiytQUJJNraJmpCDLnF-DI5P684PydVLyc_XQNqooahjoGmJhc2GQM8MoZoMkq6cKCEXY-RjjEO03SNdUxJNk7XMy8tMy-zpFIHxsBlujkhFYRMIuwYv0Q_HSDGYT5IFndIYuojbJ-Bji4uA3XBsQaJcVjyAQA) ## Explanation ``` compare=(a,b)=> (a>b)-(b>a)|| // compare values, return if non-zero (1/a>1/b)-(1/b>1/a) // compare inverse values to check for -0<0 +(b==b)-(a==a) // compare equalities to check for NaN ``` ]
[Question] [ **This question already has answers here**: [Build a polyglot for Hello World](/questions/10695/build-a-polyglot-for-hello-world) (9 answers) Closed 4 years ago. Rules: 1. Your program must print "hello world" when executed 2. Your program must be interpretable or compilable into 2 or more languages 3. Your program must require no input or arguments 4. Languages with identical syntax are too easy, and will be shunned. We all know you can write `echo hello world` in Bash and Batch, so let's make it more interesting. I'll add my example as an answer. [Answer] ## Ruby and Foo, 17 bytes ``` puts"hello world" ``` Foo prints everything in the quotes, and Ruby uses a built-in function to output to stdout. [Answer] **Python 2.7 and Bash, 45 bytes** ``` x="hello world" ''''echo $x;exit #''' print x ``` Adding 1 byte can make it Python 3 compatible as well -- `print(x)` Explanation by line: 1. Variable assignment valid in both languages 2. Python comment `'''` with an extra `'` will be interpreted as 0-length string concatenation in bash, followed by echo and exit. The `#'''` closes the python comment block, but is preceded by a bash comment, so it will be ignored 3. Python print (bash will exit before getting here, so it won't complain) ]
[Question] [ **This question already has answers here**: [I copied my password to the clipboard! Can you delete it?](/questions/111380/i-copied-my-password-to-the-clipboard-can-you-delete-it) (54 answers) Closed 6 years ago. Make a program (or a function) that copies the exact text "Hello, World!" to the clipboard, and terminates. [Answer] # JavaScript (ES6), 19 bytes Run in your browser's console. ``` copy`Hello, World!` ``` [Answer] ## Mathematica, 31 bytes ``` CopyToClipboard@"Hello, World!" ``` [Answer] # Notepad++, 15 keystrokes ``` Hello, World!<C-a><C-c> ``` [Answer] # Windows command shell, 23 characters ``` echo Hello, World!|clip ``` ]
[Question] [ **This question already has answers here**: [Random Password Generator](/questions/17662/random-password-generator) (37 answers) Closed 10 years ago. Task: Make a program that generate a 24-digit password. Rule: * None of the character can be repeated more than once * Must include at least one upcase, one locase, one number, five special character. * The answer which got most votes win. SPECIAL CHARACTER LIST: `~!@#$%^&\*()\_+-={}|[]\:";'<>?,./ or other [Answer] # bash You might need to tune `A-M` by increasing or decreasing the range to meet specs. ``` ls -al ~ | grep -o . | tr -d A-M | sort | uniq | head -n 24 | xargs | sed 's/ //g' ``` E.g: ``` $ ls -al ~ | grep -o . | tr -d A-M | sort | uniq | head -n 24 | xargs | sed 's/ //g' +-.0123456789:@OPSTU_a ``` ]
[Question] [ **This question already has an answer here**: [Bingo Cards PDF](/questions/266879/bingo-cards-pdf) (1 answer) Closed 3 months ago. Generate the contents of an SVG file containing 6 bingo cards. Winner is the one that uses the shortest code. A qualifying answer has an output that can be directly pasted in a blank to get the required image. Rules are as follows. * The generated SVG code should comply with SVG version 1.1 described [here](https://www.w3.org/TR/SVG11/). * The size of the image should be equal to either Letter or A4 page sizes. * Cards should be arranged in 3 rows and 2 columns. * Each card should be 3 inches in width and height. * Each card should contain numbers 1 to 25 in random order, arranged in 5x5 squares. The numbers in all 6 cards should be generated independently. * Text size should be 20 points and text color should be black. * Text font should be Helvetica, Arial, Calibri or Open Sans. Text should be centered in each cell. * The line in the cards should have thickness either 0.5 or 1 points, and black color. * The cards should be arranged evenly around the image: The vertical distances between cards and the vertical distances between the cards and image boundaries should all be the same. Similar for horizontal distances. * There is a margin of 5% allowed in each dimension, but all cards should be strictly equal in size. The following image shows the intended layout of the image, although sizes and spacing may not be accurate. Can someone please close my [older question](https://codegolf.stackexchange.com/questions/266879/bingo-cards-pdf) and open up this one? This question is more realistic for because it doesn't need file-write operations or libraries. I could update the older question to remove the PDF requirement, but it was already getting allegations of a chameleon question so I didn't want to risk it. I can delete the older question if there is no other option but I would prefer to keep it (even if closed). [![sample bingo cards](https://i.stack.imgur.com/rpPLw.png)](https://i.stack.imgur.com/rpPLw.png) [Answer] # Python 3.10 ~~1954~~ 943 bytes Thanks to the suggestion by lyxal, the code is almost half the original length. ``` from random import shuffle def m(h,j,k,l): print('<line x1="'+str(h)+'pt" y1="'+str(j)+'pt" x2=\"'+str(k)+'pt" y2="'+str(l)+'pt" stroke="black" stroke-width="1pt" />') print('<svg version="1.1" width="612pt" height="792pt" xmlns="http://www.w3.org/2000/svg">') a=[i for i in range(1,26)] for b in range(0,3): for c in range (0,2): shuffle(a) e=252*b d=276*c m(60+d,36+e,276+d,36+e) m(276+d,36+e,276+d,246+e) m(60+d,36+e,60+d,246+e) m(60+d,246+e,276+d,246+e) for g in range(0,5): f=g*43.2 m(60+d,36+e+f,276+d,36+e+f) m(60+d+f,36+e,60+d+f,246+e) for i in range(0,5): print('<text x="'+str(81.6+d+f)+'pt" y="'+str(57.6+e+i*43.2)+'pt" dominant-baseline="middle" text-anchor="middle" font-size="20pt" font-family="Arial, Helvetica, sans-serif">'+str(a[i+5*g])+'</text>') print("</svg>") ``` ]
[Question] [ **This question already has answers here**: [Who has a comma for a middle name?](/questions/122322/who-has-a-comma-for-a-middle-name) (46 answers) Closed 6 years ago. ### The Challenge Convert a phrase of two words to reverse style: `candy bar -> bar le candy`. ### Specifications * There will be one word (only `a-zA-Z0-9` + `-`), a space (), and then another word. * For equal length, score is used to determine winner. ### Test cases: ``` candy bar -> bar le candy code golf -> golf le code programming puzzles -> puzzles le programming ``` [Answer] # Reng v.3.3, 55 bytes [Try it here!](https://jsfiddle.net/Conor_OBrien/avnLdwtq/) ``` 1#zaií1ø ):Weq!vz1+#z br[zÀz/]; !o le"Wro/ !ob" ~;/ ``` I can probably golf it by taking input until a space is found, as this approach takes all input at once. ## Explanation ### Input & init ``` 1#zaií1ø ``` `1#z` stores `1` to `z`. `a` is a one-sided mirror from the left side, meaning you can pass through it from left-to-right, but not otherwise. `i` takes a char of input, and `í` mirrors iff there is input on the input stack. Otherwise, it proceeds. `1ø` goes to the next line. ### Print first word ``` ):Weq!vz1+#z ``` `)` rotates the stack left one, `:` duplicates it, `We` checks for the equality with a space, and `!v` goes down iff it is a space and goes to the next phase. `z1+#z` increments `z` otherwise. (more to come) --- Here's a GIF: [![explanation](https://i.stack.imgur.com/0LBfE.gif)](https://i.stack.imgur.com/0LBfE.gif) [Answer] # Vim 9 keystrokes ``` dwA le <esc>p ``` I'm so close to beating pyth and Cjam! Unfortunately, I can't figure out how to take any more off, so I'll have to be satisfied with tying. =) Explanation: ``` dw 'Delete a word A le <esc> 'Enter " le " at the end of the current line p 'Paste the previously deleted text ``` [Answer] # CJam, 9 bytes ``` rr" le "@ ``` [Try it online!](http://cjam.aditsu.net/#code=rr%22%20le%20%22%40&input=candy%20bar) Pushes first 2 tokens and then the " le " literal to stack, and then rotates the stack, moving the first word to the end of the stack. Output of the resulting stack is implied. [Answer] # Pyth - 9 bytes ``` j" le "_c ``` [Test Suite](http://pyth.herokuapp.com/?code=j%22+le+%22_c&test_suite=1&test_suite_input=%22candy+bar%22%0A%22code+golf%22%0A%22programming+puzzles%22&debug=0). [Answer] # [MATL](https://github.com/lmendo/MATL), 12 bytes ``` Yb'le'h7L)Zc ``` [**Try it online!**](http://matl.tryitonline.net/#code=WWInbGUnaDdMKVpj&input=J2NvZGUgZ29sZic) ``` Yb % Take input implicitly. Split by spaces. Gives a cell array 'le' % Push this string h % Concatenate horizontally into cell array 7L % Push [2 3 1] ) % Apply as index, to change order Zc % Join with spaces. Gives a string. Display implicitly ``` [Answer] ## Python 3, 41 bytes ``` print(' le '.join(input().split()[::-1])) ``` [Answer] # R, 30 bytes ``` cat(rev(scan(,"")),sep=" le ") ``` This is a full program that accepts reads a string from STDIN and prints to STDOUT. The `scan` function implicitly separates space-delimited input into elements of an array. We then just `rev`erse the array and print it, using `le` as a separator between elements in the output. [Answer] # [GS2](https://github.com/nooodl/gs2), 9 [bytes](https://en.wikipedia.org/wiki/Code_page_437#Characters) ``` , ♦ le ♣2 ``` [Try it online!](http://gs2.tryitonline.net/#code=LCDimaYgbGUg4pmjMg&input=Y2FuZHkgYmFy) [Answer] # Jelly, 9 bytes ``` ṣ⁶Ṛj“ le ``` [Try it online!](http://jelly.tryitonline.net/#code=4bmj4oG24bmaauKAnCBsZSA&input=&args=Y2FuZHkgYmFy) [Answer] # [><>](https://esolangs.org/wiki/Fish), 35 bytes ``` i:" "=?v ov?(0:i< "\~~r" el o>l?!; ``` The first line reads a character of the first word and put it on the stack, then goes to the second line if it encounters " " or otherwise loops. The second line reads a character of the second word and prints it right away, then goes to the third line when if encounters EOF or otherwise loops. The third line removes the space and the EOF from the stack, reverts it and pushes " le " backward, then goes to the fourth line. The fourth line stops execution if the stack is empty, otherwise it prints a character of the stack (poping it) and loops. [Answer] # [IPOS](https://github.com/DenkerAffe/IPOS), 13 bytes ``` rS!r%S" le "R ``` Could < 10 bytes if I had implemented all the builtins that I have planned... ### Explanation ``` r # Reverse the input S!r% # Reverse every word -> Word order is now swapped S" le "R # insert a " le " between the two words by replacing the space ``` ### Non-competing 9-byte version This only works with the version I pushed just now (implemented `C`). ``` SC"le"@Sj ``` This works by splitting the input on spaces to obtain the two words (`SC`), pushing the literal `le`, rotating the stack (`@`) so the words are swapped and the `le` is between them and finally joining the stack on spaces (`SJ`). Again, could be shorter since I also plan to add commands for joining and splitting on spaces which would make this 7 bytes. But since those are probably gonna be non-ASCII characters and I haven't fully figured out the codepage I am gonna use, those have to wait a bit. [Answer] # JavaScript (ES6), ~~34~~ 32 bytes ``` s=>(a=s.split` `)[1]+" le "+a[0] ``` *Saved 2 bytes thanks to @jrich!* [Answer] ## Pyke, 10 bytes ``` dcX"le"RdJ ``` [Try it here!](http://pyke.catbus.co.uk/?code=dcX%22le%22RdJ&input=candy+bar) Or 9 bytes (noncompeting, add insert) ``` Dd@" le": ``` [Try it here!](http://pyke.catbus.co.uk/?code=Dd%40%22+le%22%3A&input=%22candy+bar%22) [Answer] # Python, 37 bytes ``` lambda s:" le ".join(s.split()[::-1]) ``` [Answer] ## Python 2, 34 bytes ``` a,b=input().split();print b,"le",a ``` Expects input in quotes. ``` >> "code golf" golf le code ``` [Answer] # Jolf, 10 bytes [Try it here!](http://conorobrien-foxx.github.io/Jolf/#code=Ul9wdGkiIGxlIA&input=Y29kZSBnb2xmCgpwcm9ncmFtbWluZyBwdXp6bGVz) ``` R_pti" le pti input split by spaces _ reversed R " le joined by that string ``` [Answer] # BATCH file, 14 bytes ``` @ECHO %2 le %1 ``` Save to a file and invoke as `notFrench word1 word2`. ``` C:\Users\Conor O'Brien\Documents\Programming\PPCG>notFrench code golf golf le code C:\Users\Conor O'Brien\Documents\Programming\PPCG> ``` [Answer] # Go, 81 bytes ``` import."strings" func f(s string)string{h:=Split(s," ") return h[1]+" le "+h[0]} ``` [Answer] # Perl, 18 bytes ``` / /;$_="$' le $`" ``` This program is **17 bytes** long and requires the `-p` switch (**+1 byte**). [Answer] ## Lua, 46 Bytes ``` a=(...):gsub("(%w+) (%w+)","%2 le %1")print(a) ``` I save the result of `gsub` to a variable because it returns 2 values, and would therefore print a `1` which is the number of changes made to the string. The other work around is about disallowing `gsub`'s return to unpack. Also, it is actually longer by 1 byte: ``` print((...):gsub("(%w+) (%w+)","%2 le %1")..'') ``` [Answer] ## [Retina](https://github.com/mbuettner/retina), 14 bytes Byte count assumes ISO 8859-1 encoding. ``` M!r`\S+ ¶ le ``` [Try it online!](http://retina.tryitonline.net/#code=JShHYApNIXJgXFMrCsK2CiBsZSAKKUdg&input=Y2FuZHkgYmFyCmNvZGUgZ29sZgpwcm9ncmFtbWluZyBwdXp6bGVz) (Slightly modified to process all test cases at once.) The first stage reverses the two words and separates them by a linefeed (this is done by matching them with `r`ight-to-left mode and printing all matches). The second stage replaces the linefeed (`¶`) with `le` . [Answer] # Mathematica, 30 bytes ``` #2<>" le "<>#&@@StringSplit@#& ``` Not very complicated... [Answer] ## Seriously, 13 bytes ``` "le"' ,so/' j ``` [Try it online](http://seriously.tryitonline.net/#code=ImxlIicgLHNvLycgag&input=ImNhbmR5IGJhciI) Explanation: ``` "le"' ,so/' j ' ,s split input on space "le" o/ stick "le" between words ' j join on space ``` [Answer] # Gawk, ~~17~~ 16 bytes *1 byte off thanks to muru* ``` {$0=$2" le "$1}1 ``` ### Old ``` {print$2" le "$1} ``` [Answer] # Java 8, ~~41~~ 39 bytes A simple lambda, for a simple challenge ``` s->s.replaceAll("(.+) (.+)","$2 le $1") ``` --- **Update** * **-3** [17-02-23] Thanks to *[@Kevin](https://codegolf.stackexchange.com/questions/77609/convert-phrases-to-reverse-style/110959?noredirect=1#comment270303_110959)* [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~9~~ 8 bytes Note the trailing space. ``` ¸w q` ¤ ``` * Saved a byte thanks to a reminder from obarakon. [Try it online](http://ethproductions.github.io/japt/?v=1.4.4&code=uHcgcWAgpCA=&input=ImNhbmR5IGJhciI=) --- ## Explanation ``` :Implicit input of string U ¸ :Split to array on space w :Reverse q. :Join to string... ` ¤ : with the compressed string " le " ``` [Answer] # **C# - 43 bytes** ``` string.Join(" le ",x.Split(' ').Reverse()); ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 24 bytes ``` ->s{s=~/ /;"#$' le #$`"} ``` [Try it online!](https://tio.run/nexus/ruby#S7P9r2tXXF1sW6evoG@tpKyirpCTqqCskqBU@7@gtKRYIS1aKTkxL6VSISmxSCmWCy6Wn5KqkJ6fk6YU@x8A "Ruby – TIO Nexus") [Answer] # PHP, 47 Bytes ``` <?=preg_filter("#(.+) (.+)#","$2 le $1",$argn); ``` [Try it online!](https://tio.run/nexus/php#s7EvyCjgUkksSs@zVSooyk8vSszNzcxLVygorarKSS1Wsuayt/tvY29bUJSaHp@WmVOSWqShpKyhp62pACKUlXSUVIwUclIVVAyVdMDmaFr//w8A "PHP – TIO Nexus") ]
[Question] [ **Question** Write a program to accept one string on the console only and print back its letters arranged in alphabetical order. The string must only have the following characters: > > 0123456789abcdefghijklmnopqrstuvwxyz > > > **Rules** The ascending alphabetical order is defined in the given string. All repeated characters must be printed. If the string contains characters other than the ones mentioned above, it must display "Invalid input". This is code-golf, so shortest answer in bytes wins. Standard loopholes are forbidden. A null string "" will output "Invalid input". Your program must be executable and not a function or snippet. Boilerplate is not required. **Examples** ``` "dragon"--> adgnor "skoda3ferrari"--> 3aadefikorrrs "ferret"--> eefrrt "werewolf92"--> 29eeflorww "@hog"--> Invalid input "gTa5"--> Invalid input " l "--> Invalid input ""--> Invalid input ``` Edit: The double quotes are given for clarification. May the force be with you. Good luck! [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~16~~ 15 bytes *-1 byte thanks to Kevin Cruijssen* ``` žKlsSåßi{ë”Í¼î® ``` [Try it online!](https://tio.run/##yy9OTMpM/V9Waa@kYGunoGRf6fL/6D7vnOLgw0sPz8@sPrz6UcPcw72H9hxed2jdfyD70IpaHc2Y/9FKKUWJ6fl5SjoKSsXZ@SmJxmmpRUWJRZkgARAztQTEKk8tSi3Pz0mzNALxHDLy00F0ekiiKYhWUMgBUUqxAA "05AB1E – Try It Online") [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 37 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set") ``` {0∊(≢⍵),⍵∊⎕D,⌊⎕A:'Invalid input'⋄∧⍵}⍞ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qKO94H@1waOOLo1HnYse9W7V1AESQO6jvqkuOo96QLSjlbpnXlliTmaKQmZeQWmJ@qPulkcdy4Hqah/1zgMZ8V8BDAq4UooS0/PzuGDc4uz8lETjtNSiosSiTLgoiJ9aAueWpxallufnpFkawYUcMvLT4Zz0kERTOEdBIUcBzgEA "APL (Dyalog Extended) – Try It Online") `⍞` prompt for text input from the console `{`…`}` apply the following anonymous lambda to that:  `⎕A` the uppercase **A**lphabet  `⌊` **L**owercase that  `⎕D,` prepend the digits  `⍵∊` for each character of the argument, indicate if it is a member thereof  `(`…`),` prepend the following:   `≢⍵` the tally of characters in the argument  `0∊`…`:` if zero is a member thereof:   `'Invalid input'` return (and implicitly print) this message  `⋄` else:   `∧⍵` sort the argument ascending [Answer] # [Burlesque](https://github.com/FMNSSun/Burlesque), 37 bytes ``` ><JJann!/^zz!=||{vv"Invalid Input"}if ``` [Try it online!](https://tio.run/##SyotykktLixN/f/fzsbLKzEvT1E/rqpK0bamprqsTMkzrywxJzNFwTOvoLREqTYz7f9/JQA "Burlesque – Try It Online") ``` >< # Sort input string JJ # Duplicate twice ann! # Not alphanumeric /^ # Swap and duplicate (sorted string) zz!= # Lowercased not equal to original (i.e. contains uppercase) || # Or {vv"Invalid Input"}if # If not alphanumeric or lowercase drop sorted list and output invalid input ``` [Answer] # x86-16 machine code, IBM PC-DOS, ~~81~~ 80 bytes **Binary:** ``` 00000000: b40a ba4f 01cd 218b f2ad 8bd6 8acc 8be9 ...O..!......... 00000010: 938b f28b fe51 ad3c 307c 0c3c 397e 0e3c .....Q.<0|.<9~.< 00000020: 617c 043c 7a7e 06ba 4201 59eb 103a c47c a|.<z~..B.Y..:.| 00000030: 0286 c4ab 4e4f e2de 59e2 d688 1bb4 09cd ....NO..Y....... 00000040: 21c3 496e 7661 6c69 6420 696e 7075 7424 !.Invalid input$ ``` Build and test `DISSECT.COM` using `xxd -r` **Unassembled listing:** ``` B4 0A MOV AH, 0AH ; DOS read buffered input from STDIN BA 014F R MOV DX, OFFSET BUF ; load buffer pointer CD 21 INT 21H ; get STDIN input 8B F2 MOV SI, DX ; buffer pointer into SI AD LODSW ; load char count into AH 8B D6 MOV DX, SI ; save start of string 8A CC MOV CL, AH ; string length into CX 8B E9 MOV BP, CX ; save string length for later display OUTER_LOOP: 8B F2 MOV SI, DX ; reset SI to beginning of buffer 8B FE MOV DI, SI ; reset DI to beginning of buffer 51 PUSH CX ; save outer loop counter INNER_LOOP: AD LODSW ; load next two chars into AH/AL 3C 30 CMP AL, '0' ; is char < '0' ? 7C 0C JL INVALID ; if so, not valid 3C 39 CMP AL, '9' ; is char <= '9'? 7E 0E JLE VALID ; if so, valid 3C 61 CMP AL, 'a' ; is char < 'a'? 7C 04 JL INVALID ; if so, not valid 3C 7A CMP AL, 'z' ; is char <= 'z'? 7E 06 JLE VALID ; if so, valid INVALID: BA 0142 R MOV DX, OFFSET INV ; load address of "invalid" string 59 POP CX ; discard saved counter EB 11 JMP OUTPUT ; display "invalid" string VALID: 3A C4 CMP AL, AH ; compare chars 7C 02 JL NO_SWAP ; if AL < AH, do not swap 86 C4 XCHG AL, AH ; otherwise, swap chars NO_SWAP: AB STOSW ; store chars back to buffer 4E DEC SI ; adjust SI to previous char 4F DEC DI ; adjust DI to previous char E2 DE LOOP INNER_LOOP ; loop inner iterations 59 POP CX ; restore outer loop counter E2 D6 LOOP OUTER_LOOP ; loop outer C6 03 24 MOV BYTE PTR[BP+DI],'$'; add string terminator OUTPUT: B4 09 MOV AH, 09H ; DOS display string function CD 21 INT 21H ; write output to console C3 RET ; exit to DOS INV DB "Invalid input" ; "invalid" message string BUF DB '$' ; buffer size is 36 bytes, also string terminator ``` Standalone PC DOS executable. Implements a simple bubble sort algorithm. Input via console/`STDIN`, output to console/`STDOUT`. [![enter image description here](https://i.stack.imgur.com/RjNey.png)](https://i.stack.imgur.com/RjNey.png) [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), ~~77~~ ~~75~~ ~~74~~ 88 bytes ``` import re print(*re.match('[0-9a-z]+$',i:=input())and sorted(i)or'Invalid input',sep='') ``` [Try it online!](https://tio.run/##HY29CsIwFEb3@xShCEm0irUIKhQEdXBycROH0Ny2wTYJt/H30Vx9sGqdvuFwzuefoXI2XXjqNoftLouiqDONdxQYIXgyNogh4aRRIa8EP03HSzV@nUcDHptVZqy/BiGlspq1Pwe1MNIR39ubqo1mf87jFn3Guex@cQB8YC76r2EylZ0mVToL7cVplRZIpMhAvxjgjoR3VxfLGawrV0J5VHNgrAZIZil83vAF "Python 3.8 (pre-release) – Try It Online") [Answer] # [Red](http://www.red-lang.org), 86 bytes ``` func[s][a: charset[#"0"-#"9"#"a"-#"z"]either parse sort s[some a][s]["Invalid input"]] ``` [Try it online!](https://tio.run/##TcsxC8IwEIbhvb/iuMyCWBzaydVV3EKGo7m0wZqUS2rBPx/JItnuffhO2JYHW206Nxa3h0kno2mEaSFJnLXCM54UDqiQ6vFFwz4vLLDVAaQoGZJO8c1Apj7jPXxo9RZ82PaMxpRNfMjgAK3QHAN2f0ivaKl3LELiG6/CuYGDhY@4uuHS4G2Jc5Pzk65NAqzQJJYf "Red – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 18 bytes ``` ɠfƑØBŒl¤ȧṢȯ“4{ẉṄi» ``` [Try it online!](https://tio.run/##ATgAx/9qZWxsef//yaBmxpHDmELFkmzCpMin4bmiyK/igJw0e@G6ieG5hGnCu///c2tvZGEzZmVycmFyaQ "Jelly – Try It Online") A full program that reads its input from STDIN and outputs to STDOUT. If the input validation and requirement to use STDIN were removed, this would be a single byte: `Ṣ` [Answer] # [Perl 5](https://www.perl.org/) `-pF//`, 45 bytes ``` $_=/^[a-z\d]+$/?join"",sort@F:"Invalid Input" ``` [Try it online!](https://tio.run/##FcW9CsIwEADg/Z4ihG5aAkoHBbFTobubfxwkjanhLlyiBR/eiN/yJSexq7W5H8ztjO3nYq@rxhxnDqT1OrOUftjrkd4Yg1UjpVfRtVpBzwT5yRa3kxNBCfDfFVicuIXjtNtA/2AP/oQdKBUVwJdTCUy5tjENxvwA "Perl 5 – Try It Online") [Answer] # [Keg](https://github.com/JonoCode9374/Keg), 35 bytes ``` ₳0a&᠀:(⑴|⑻-)⒃᠀⒃¬+[Invalid input|¿÷⑭ ``` Nice to see Keg still "up to par" with Golfscript! *No regrets about the bad pun* [Answer] # [GolfScript](http://www.golfscript.com/golfscript/), 37 bytes ``` .$\58,48>123,97>+-!*"Invalid input"or ``` [Try it online!](https://tio.run/##S8/PSStOLsosKPn/X08lxtRCx8TCztDIWMfS3E5bV1FLyTOvLDEnM0UhM6@gtEQpv@j/fwA "GolfScript – Try It Online") ## Explanation Whoa. Maybe I shouldn't have done this.. ``` . # Make 2 copies of the input, $ # One is the sorted copy of the input, \58,48>123,97>+-! # Another is whether all of input is in the # lowercase alphanumeric range * # Multiply them: # If the input contains invalid characters, # e.g. @hog, this multiplies the sorted copy by 0. # ----If the input is a null string, # The input multiplies 0 by the null string, # which is still the null string. # ----If the input is a valid string, # e.g. dragon, the input multiplies the # sorted copy by 1 (because everything is # inside the range) "Invalid input"or # Do a "logical magic": # If the input is 0 or the null string, # returns "Invalid input" # Otherwise, this returns the # sorted copy of the input. # Further explanation of the code snippet # \ # Swap the stack so that an unused copy of the input emerges # 58, # Generate a range and drop the last: 0 to ASCII ':' # (The previous character is '9') # 48> # Select everything that is larger than 48 (ASCII '0') # 123,97> # Same thing with generating 'a' to 'z' # + # Join the inputs together # - # Set subtraction: subtract this string from the fresh unused input # # This results in everything that isn't alphanumeric # ! # Negate the string. If the string has something, # # it turns to 0. Otherwise it turns to 1. ``` ``` [Answer] # [PHP](https://php.net/), 92 bytes ``` $a=str_split($s=$argn);sort($a);echo preg_match('/^[a-z\d]+$/',$s)?join($a):'Invalid input'; ``` [Try it online!](https://tio.run/##FcpNCsIwEEDhq3QRSIOW7o2lrgTP4E8Z2pJE2pkhM7rw8Ma6efDB48jl2PNWA51oHoSXpLWRzkAO6LxQ3gjOz2OkivMchhV0jLVtH1doPrfpvjOt3Rtx/ZMS/t@DveAbljRVCfml1pdyihS@xJoIpTTnHw "PHP – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 37 bytes ``` ≔⁺⭆χιβη¿∨¬θ⊙θ¬№ηιInvalid inputFηF№θιι ``` [Try it online!](https://tio.run/##LYzLCsIwEEX3fsXQ1QQiqDvpqrhyUS34BbGmzUBImleLXx8T6cAw3MucMyrhRyt0zl0INBscdAr4ip7M3IsFzycOxDi8yyrWHmgCfHp82IiuVJ35ouNQ480mE1HV9zowFEXE5m5WoekDZJYUm2KQOkiYrEfF6oEddH9wp4i1OW/Sy83q6XrJx1X/AA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ≔⁺⭆χιβη ``` Concatenate the digits with the lowercase letters. ``` ¿∨¬θ⊙θ¬№ηι ``` If the input is empty or contains a character not in the digit letter string, ... ``` Invalid input ``` ... then output the required error message, ... ``` Fη ``` ... else for each digit and lowercase letter... ``` F№θιι ``` ... output each time it appears in the input. [Answer] # [C++ (clang)](http://clang.llvm.org/), ~~223~~ \$\cdots\$ ~~182~~ 170 bytes Saved ~~8~~ a whopping 20 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!! ``` #import<bits/stdc++.h> int main(){std::string s,i="Invalid input";getline(std::cin,s);sort(begin(s),end(s));for(int c:s)s=c<48|c>122|c>57&c<97?i:s;std::cout<<(s[0]?s:i);} ``` [Try it online!](https://tio.run/##JczNDoIwEATgu09BMDFtwN9o0LbA2WcwHqBg3QS2DVu8qM@OVS8zyWTyaeeWuqvQTNMcemcHr2rwtCbf6CRZ3YsZoI/6CpDxZxiFID8AmohSyOMzPqoOmgjQjT6WpvUdYMt@Pw2YEpcUSFa3JgDE0xabUFze7MC@sBbEKddqf3zpYrvbhTxkC61OWQmC5B@yo1eK0WVzLUkAl@9paobKWPwA "C++ (clang) – Try It Online") A program that reads a single string from `stdin` (handling all invalid cases) and outputs to `stdout`. ]
[Question] [ **Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/220340/edit). Closed 2 years ago. [Improve this question](/posts/220340/edit) # Challenge The main objective of the challenge is pretty simple, this is an answer chaining contest, where you have to serially print numbers from 1. That means User 1's answer will print `1`, then User 2's answer will print `2` and so on. But there are some rules to make the contest tougher. # Rules * **You can't use the characters of the source code used in the previous answer.** * Use of comments in your code is disallowed. * You cannot post 2 answers in a row, let me explain, suppose you have written answer no. 5, now you cannot write answer no. 6, you have to wait someone to post a valid answer no. 6 (That prints `6` without using characters in answer no. 5), and after that you can write a valid answer no. 7 following the rules. * Program cannot take input or access internet. * Standard loopholes apply. * You can have leading/trailing newlines but not whitespaces (except newline) in the output. # Scoring criterion **This is not [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge, so there is a custom objective scoring criteria. Try to make your score higher.** * Each answer's initial score is 1. (Only chain beginning answer has score 0). * For each distinct byte you use, your score is increased by the number of distinct bytes. That means if your number of distinct bytes is `6`, then your score increases by `1+2+3+4+5+6`, and if your number of distinct bytes is `7`, then your score increases by `1+2+3+4+5+6+7` and so on. * You have to calculate distinct byte difference with the previous answer, and add/subtract score using the 2nd rule. So if byte difference is `3` then you will get a `+1+2+3` score, or if `-3` (Previous answer has 3 more distinct bytes than yours), then `-1-2-3`. * For each 1 to 9th byte `-1`, from 10th to 19th byte `-2` for each byte, from 20th to 29th byte `-3` for each byte and so on. A total example: # Answer format ``` # Answer Number. Language Name, x Bytes, y Distinct bytes, Score: Z source code (TIO/Any other interpreter link) -> Not required, but preferred ``` **example** ``` 1. Powershell, x Bytes, y Distinct Bytes, Score: Z ...... ``` # Winning criterion **Winner will be determined after 30 days, winner is determined by total score. But users are welcome to continue the chain after that!** Suppose you have three answers with score `33,16,78` then your total score will be `33+16+78=127`. And there is two special prizes from me after 30 days: * +150 bounty for the winner. * +50 bounty for the single answer with highest score! (Such as man of the match in Cricket) [Answer] # 2. [Python 3](https://docs.python.org/3/), 102 bytes, 66 distinct bytes, Score: 3710, My Total Score: 3710 ``` print(int(str(2+3+4+5+6+7+8+90-25*5+2)+"abcdefghijklmnopqrstuvwxyz`-=:{}][;'_+()*&^%$#@!~`/.,?>< "*0)) ``` [Try it online!](https://tio.run/##K6gsycjPM/7/v6AoM69EA4SLS4o0jLSNtU20TbXNtM21LbQtDXSNTLVMtY00tZUSk5JTUtPSMzKzsnNy8/ILCouKS0rLyisqqxJ0ba2qa2OjrdXjtTU0tdTiVFWUHRTrEvT1dOztbBSUtAw0Nf//BwA "Python 3 – Try It Online") [Answer] # 3. [Vyxal](https://github.com/Lyxal/Vyxal), 162 bytes, 162 distinct bytes, Score: 16467, My total score: 16467 ``` γ₥⌊₴λƛ¬∧⟑∨⟇÷«»°•․⍎Ṛ½∆øÏÔÇæʀʁɾɽÞƈ∞⫙ß⎝⎠⎡⎣⨥⨪∺❝ð→←ÐřŠč√⳹ẊȦȮḊĖẸṙ∑Ĥ⟨⟩ı⁌\tΤĴ²‿⁂ĸ¶⁋⁑Ńń‼⨊≈µʗ◁⊐∫⍋⍒∈ₛ£Œœ≕≠¥ⁱ‹›⍲⍱‸¡⊑≀℅≤≥↜≗⋯⧢ũ⁰¹ªₑϊ≎⇿⊛ׯ±⊂⍞፣⍉ΐ₁⊘ᶢ₌↭ſƀƁ⁚⌈⊓⊣Ḟḟ∪∩⊍⁜⌑Ḇ₂⁾₦¼ƒɖꝒ′α″βΠ" ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%CE%B3%E2%82%A5%E2%8C%8A%E2%82%B4%CE%BB%C6%9B%C2%AC%E2%88%A7%E2%9F%91%E2%88%A8%E2%9F%87%C3%B7%C2%AB%C2%BB%C2%B0%E2%80%A2%E2%80%A4%E2%8D%8E%E1%B9%9A%C2%BD%E2%88%86%C3%B8%C3%8F%C3%94%C3%87%C3%A6%CA%80%CA%81%C9%BE%C9%BD%C3%9E%C6%88%E2%88%9E%E2%AB%99%C3%9F%E2%8E%9D%E2%8E%A0%E2%8E%A1%E2%8E%A3%E2%A8%A5%E2%A8%AA%E2%88%BA%E2%9D%9D%C3%B0%E2%86%92%E2%86%90%C3%90%C5%99%C5%A0%C4%8D%E2%88%9A%E2%B3%B9%E1%BA%8A%C8%A6%C8%AE%E1%B8%8A%C4%96%E1%BA%B8%E1%B9%99%E2%88%91%C4%A4%E2%9F%A8%E2%9F%A9%C4%B1%E2%81%8C%5Ct%CE%A4%C4%B4%C2%B2%E2%80%BF%E2%81%82%C4%B8%C2%B6%E2%81%8B%E2%81%91%C5%83%C5%84%E2%80%BC%E2%A8%8A%E2%89%88%C2%B5%CA%97%E2%97%81%E2%8A%90%E2%88%AB%E2%8D%8B%E2%8D%92%E2%88%88%E2%82%9B%C2%A3%C5%92%C5%93%E2%89%95%E2%89%A0%C2%A5%E2%81%B1%E2%80%B9%E2%80%BA%E2%8D%B2%E2%8D%B1%E2%80%B8%C2%A1%E2%8A%91%E2%89%80%E2%84%85%E2%89%A4%E2%89%A5%E2%86%9C%E2%89%97%E2%8B%AF%E2%A7%A2%C5%A9%E2%81%B0%C2%B9%C2%AA%E2%82%91%CF%8A%E2%89%8E%E2%87%BF%E2%8A%9B%C3%97%C2%AF%C2%B1%E2%8A%82%E2%8D%9E%E1%8D%A3%E2%8D%89%CE%90%E2%82%81%E2%8A%98%E1%B6%A2%E2%82%8C%E2%86%AD%C5%BF%C6%80%C6%81%E2%81%9A%E2%8C%88%E2%8A%93%E2%8A%A3%E1%B8%9E%E1%B8%9F%E2%88%AA%E2%88%A9%E2%8A%8D%E2%81%9C%E2%8C%91%E1%B8%86%E2%82%82%E2%81%BE%E2%82%A6%C2%BC%C6%92%C9%96%EA%9D%92%E2%80%B2%CE%B1%E2%80%B3%CE%B2%CE%A0%22&inputs=&header=&footer=) The power of Unicode. I'm not sure about the score, but this takes the average of [1, 2, 8] (`3.66666...`) and takes the floor of that number. Feel free to correct my score if needed. I calculated it as \$(1+2+3+...+162)\$ [part 1 of scoring] \$+ (1+2+3+...+96)\$ [part 2 of scoring: 162 my answer - 66 previous answer = 96 difference distinct bytes) * (`sum(map(lambda x: x*10, range(1, 17)))`)\$ - 16\*2\$ [part 3] ~~[My scoring utility. Takes number of distinct bytes in your answer, the number of distinct bytes in the previous answer and the length of your answer](http://lyxal.pythonanywhere.com?flags=&code=%3A%CA%80%E2%88%91%24%3F%C4%B8%CA%80%E2%88%91%2B%3F%3A%C2%A310%E2%B3%B9%3A%E2%86%92x%CA%8010*%E2%88%91-%E2%86%90x%C2%A510%25*-&inputs=162%0A66%0A162&header=&footer=)~~ [Try this one instead. It should work a bit more accurately and work for higher byte counts. Inputs are: a) your distinct bytes, b) last answers distinct bytes, c) program length](http://lyxal.pythonanywhere.com?flags=&code=%3F%20%E2%86%92your_bytes%0A%3F%20%E2%86%92their_bytes%0A%3F%20%E2%86%92program_length%0A%0A%E2%86%90your_bytes%20%3A%E2%A8%A5*%C2%BD%20%23%20The%20sum%20of%201%20%2B%202%20%2B%203%20%2B...%2B%20n%0A%0A%E2%86%90your_bytes%20%E2%86%90their_bytes%20-%20%23%20Distinct%20byte%20difference%0A%0A%3A%C2%A3%20%23%20Put%20that%20into%20the%20register%20for%20later.%20%0A%0A%3A%E2%A8%A5*%C2%BD%20%23%20Sum%20of%20the%20byte%20difference%0A%0A%C2%A50%3Cu%24e*%20%23%20If%20the%20original%20difference%20is%20negative%2C%20negate%20the%20sum%2C%20which%20will%20be%20positive%0A%0A%C2%A50%E2%89%A0*%2B%20%23%20If%20the%20difference%20is%200%2C%20make%20the%20sum%200.%20Then%20add%0A%0A%E2%86%90program_length%2010%E2%B3%B9%3A%C2%A3%3A%E2%A8%A5*%C2%BD-%20%23%20Subtract%20part%201%20of%20the%20byte%20penalty%0A%0A%E2%86%90program_length%2010%25%20%C2%A5*-%2C%0A%0A%0A&inputs=66%0A1%0A102&header=&footer=) [Answer] # 1. [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 1 byte, 1 distinct byte, Score: 0, My Total score: 0 ``` 1 ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/3/D/fwA "PowerShell – Try It Online") [Answer] # 6. [Mornington Crescent](https://esolangs.org/wiki/Mornington_Crescent), ~~425~~ ~~423~~ 396 bytes, ~~30~~ 32 distinct bytes, score ~~-8475~~ ~~-8391~~ -7155 To break the monotony of using all of the ASCII characters, let's rule out only *some* ASCII characters for the next answer. This is the shortest program in this language that outputs 6. I'm pretty sure making it any longer to include more distinct bytes would make the score even lower, as adding any more extraneous instructions would necessarily reuse some bytes. ``` Take Northern Line to Euston Take Victoria Line to Seven Sisters Take Victoria Line to Victoria Take Circle Line to Victoria Take District Line to Upminster Take District Line to Parsons Green Take District Line to Notting Hill Gate Take Circle Line to Notting Hill Gate Take District Line to Upminster Take District Line to Bank Take Circle Line to Bank Take Northern Line to Mornington Crescent ``` [Try it online!](https://tio.run/##lZFBDsJACEX3noILeAmrqQttTKruJxOipC0YoF6/jhrHhZ2FW97P58MfRJn44sLLqGgR2afpGDqERtSvqAw7YgQX2IyWZIsXPFN0UQoZtnhHhpbMUa2g@QzeuCKNPRbgOhlpmmR8ug3ET/MCPwQ1YYNaEbmgacQ93Qpb6nuog@NskILq70SrwN3sgi/4efE@twFVbuMB) Distinct bytes used: `BCDEGHLMNPSTUVaceghiklmnoprstuv` [Answer] # 4. [C (gcc)](https://gcc.gnu.org/), 106 bytes, 91 distinct bytes, Score: 6132, My Total score: 6132 ``` main(){printf("%d",strlen(" !#$&'*+./0123\4789:<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_`bcghjkoquvwxyz~")-65);} ``` [Try it online!](https://tio.run/##S9ZNT07@/z83MTNPQ7O6oCgzryRNQ0k1RUmnuKQoJzVPQ0lBUVlFTV1LW0/fwNDIOMbE3MLSysbWzt7B0cnZxdXN3cPTy9vH188/IDAoOCQ0LDwiMio6Ni4@ISk5PSMrO7@wtKy8orKqTklT18xU07r2//9/yWk5ienF/3XLAQ "C (gcc) – Try It Online") [Answer] # 7. [Keg](https://github.com/Lyxal/Keg), 4,376,598 bytes, 2,157,610 distinct bytes, Score: 3697321176253, My total score: 3697321192720 You can find the source code [here](https://github.com/Lyxal/Special/blob/main/seven.keg) Don't even bother trying it online. This uses everything in unicode except the bytes `\n BCDEGHLMNPSTUVaceghiklmnoprstuv`, so the next person to answer is going to have an extremely low score. Here's how I generated it: ``` file = open("seven.keg", mode="w", encoding="utf-8") file.write(chr(127240)) file.write("¶") bad = " BCDEGHLMNPSTUVaceghiklmnoprstuv" bad += "\n¶" + chr(127240) for i in range(4294967294): letter = chr(i) if letter in bad: continue try: file.write(letter) except: continue file.close() ``` Which turns into: ``` 🄈\";_`<massive string of unicode>`_ ``` Which prints `7` and then pushes (`"` - 1), discards that, pushes a massive string and then discards it. Don't bother putting the score into my utility. It's calculated via: $$ \frac{2,157,610 \times 2,157,611}{2} + \frac{(2,157,577 \times 2,157,578}{2} - rule3 $$ * it uses the triangle number formula to speed up computing. `2,157,577 = 2,157,610 - 33`. The total score is calculated by: ``` score = 4655211869108 for i in range(437696): score -= 10 * i score -= 9 * 437695 print(score) print(score + 16467) ``` [Answer] # [5. [Vyxal](http://lyxal.pythonanywhere.com/), 12 bytes, 9 distinct bytes, score 3436] ``` ⨥⨥²⨥⨥⨪½Ç◁ṙȦ₴ ``` [Try it online](http://lyxal.pythonanywhere.com?flags=&code=%E2%A8%A5%E2%A8%A5%C2%B2%E2%A8%A5%E2%A8%A5%E2%A8%AA%C2%BD%C3%87%E2%97%81%E1%B9%99%C8%A6%E2%82%B4&inputs=&header=&footer=) Well I really just wanted to get this challenge moving again, after @Noodle9 basically ruled out the entire ASCII character set! So I learnt a little Vyxal just for this... after writing a Deadfish interpreter here Vyxal actually made some sense... I'm sure I could do more useless operations to the register, but basically its just increment twice, square it, increment twice then decrement for 5, half it for 2.5, subtract from 1 for 1.5, reverse for 5.1, round it for 5, take the absolute value, and output it. (As far as the scoring, I'm totally confused, I just put what Lyxal's utility gave me. From the text, it sounds like my small answer should have a negative score for being smaller than #4...) [Answer] # [Deadfish~](https://github.com/TryItOnline/deadfish-), 8 bytes, 3 distinct bytes, Score:2,327,635,062,034 according to Lyxal's utility? ``` iisiiiio ``` [Try it online!](https://tio.run/##S0lNTEnLLM7Q/f8/M7M4Ewjy//8HAA "Deadfish~ – Try It Online") Well with not many options left from Lyxal's answer for #7, I had to resort to Deadfish... ]
[Question] [ **Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/59164/edit). Closed 5 years ago. [Improve this question](/posts/59164/edit) Your task is to create a program which takes a string, and if it contains **any** numbers, symbols or other non-letter characters, it throws an error. Else, it returns the original string. (The string may include whitespace) ("Letters" are a-z and A-Z) Examples: **Input:** `My name is Joe` **Output** `My name is Joe` --- **Input:** `My username is Joe32` **Output:** `(insert an error)` (FYI this question has nothing to do with Don't Google google. It was identified as a possible copy.) [Answer] # Julia, 53 bytes ``` s=readline();ismatch(r"[^a-z\s]"i,s)?error():print(s) ``` Read a string from STDIN using `readline()`. If any of its characters are not letters or whitespace (`ismatch(r"[^a-z\s]"i, s)`) then we `error()`, otherwise we `print(s)`. [Answer] # Gema, 14 characters ``` \W<-L>=@div{;} ``` Sample run: ``` bash-4.3$ gema '\W<-L>=@div{;}' <<< 'My name is Joe' My name is Joe bash-4.3$ gema '\W<-L>=@div{;}' <<< 'My username is Joe32' Floating point exception (core dumped) ``` [Answer] ### PowerShell, 24 bytes Filter the pipeline input based on whether it matches the regex: ``` |?{$_-match'^[a-z\s]+$'} ``` e.g. try it by piping the string in: ``` PS C:\> "Test Test"|?{$_-match'^[a-z\s]+$'} Test Test PS C:\> "Test ! Test"|?{$_-match'^[a-z\s]+$'} ``` The error message is silence/empty result. It matches case-insensitively by default. [Answer] # C++14, 132 126 121 117 121 bytes ``` #include<iostream> main(){std::string s;getline(std::cin,s);for(char c:s)if(!isalpha(c)&!isspace(c))throw;std::cout<<s;} ``` We read a line from `stdin`, check if each character is a letter or space - if it's not, we throw an error. Finally outputs the input. *Thanks to Alex A for golfing off two bytes* [Answer] ## STATA, 57 bytes ``` di _r(a) gl b=1/regexm("$a","^[a-zA-Z ]*$") di _d($b)"$a" ``` Uses a regex to match letters and space (STATA's regex doesn't include character classes). Set a variable to 1/match exists. Then it prints a that many times, if match exists=0, it says it's invalid syntax. Otherwise, it prints it 1/1 = 1 time. [Answer] # CJam, 18 bytes ``` q_" "'[,_el^|-!/ ``` The multi-line string contains a tabulator, a space and a linefeed. Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=q_%22%09%20%0A%22'%5B%2C_el%5E%7C-!%2F&input=My%20username%20is%20Joe32). ### How it works ``` q_ Read all input from STDIN and push a copy. "\t \n" Push that string. '[,_el^ Push all letters. See: codegolf.stackexchange.com/a/54348 | Concatenate both strings. - Remove their characters from the copy of the input. ! Logical NOT. Pushes 0 if there are other characters. / Split. Doesn't affect output if successful. Errors on 0. ``` [Answer] # Python 3, 56 characters ``` import re;print(re.match(r'[a-z\s]+$',input(),2).string) ``` Usefully, match objects have this attribute [`string`](https://docs.python.org/2/library/re.html#re.MatchObject.string) which is > > The string passed to match() or search(). > > > while `None` does not. ``` In [10]: import re;print(re.match(r'[a-z\s]+$',input(),2).string) 54 --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-10-0851dec671d1> in <module>() ----> 1 import re;print(re.match(r'[a-z\s]+$',input(),2).string) AttributeError: 'NoneType' object has no attribute 'string' In [11]: import re;print(re.match(r'[a-z\s]+$',input(),2).string) rffef rffef ``` [Answer] # Haskell, 56 bytes ``` q x|all(`elem`(['a'..'z']++['A'..'Z']++['\t'..'\r']))x=x ``` Throws the `Non-exhaustive patterns in function q` error if the string contains forbidden characters. [Answer] # JavaScript, ~~48~~ ~~46~~ ~~45~~ ~~46~~ *31* Bytes ``` /[^a-z\s]/i.exec(a=prompt())?q:a ``` Accepts input, searches for invalid characters, if it finds any, returns a truthy value and thus evaluates the undefined character `q`. Otherwise, returns null and thus returns the string. ## Old version, 44 bytes ``` ~(a=prompt()).search(/[^a-z\s]/i)?eval("@"):a ``` Tries to evaluate the invalid character `@` upon finding a numeric. --- ~~Edit 1: -2 bytes, thanks to @Alex A.~~ Edit 2: -1 byte, reworked. BONUS: Accounts for ALL whitespace! ^\_^ Edit 3: +1 byte, added underscore testing. Edit 4: Back to 46, unreworked. Edit 5: -2 extra bytes to @edc65 (for old version; -1 for new). [Answer] # Python 2, 60 bytes ``` import re;n=input();print[n][re.sub('[^a-zA-Z\s]+','',n)!=n] ``` Usage: ``` $ python -c "import re;n=input();print[n][re.sub('[^a-zA-Z\s]+','',n)!=n]" "abcdefg" abcdefg ``` [Answer] # [Hassium](http://HassiumLang.com), 166 Bytes ``` func main(){r="";foreach(c in input()){c=c.toString();if(!("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ \t\n\r".contains(c)))throw(c);else r+=c;}println(r);} ``` Run and see expanded [here](http://HassiumLang.com/Hassium/index.php?code=339a688e71a7624371c83b1cbf61ec56) [Answer] # PHP, ~~51~~ 48 bytes ``` <?=preg_match('/[^a-z\s]/i',$a=$argv[1])?e():$a; ``` Runs from command line, like: ``` php test.php "Test me" ``` --- Using `preg_match` is shorter than using `ctype_alpha` as the latter needs whitespaces to be stripped. --- As the error wasn't defined in the challenge, calling an undefined function seems the shortest way to generate an error. So this: ``` php test.php "Test me, 2" ``` leads to: > > PHP Fatal error: Call to undefined function e() > > > ## Edit Saved **3 bytes** by inverting the statement an by using the [`i`-modifier](http://php.net/manual/en/reference.pcre.pattern.modifiers.php). Thanks to [fschmengler](https://codegolf.stackexchange.com/users/43220/fschmengler). [Answer] # [Stax](https://github.com/tomtheisen/stax), 8 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` êF┼Aµ╧û┤ ``` [Run and debug online!](https://staxlang.xyz/#p=8846c541e6cf96b4&i=My+name+is+Joe%0AMy+username+is+Joe32&a=1&m=2) Shortest solution so far but expect to be defeated soon. ## Explanation Uses the unpacked version to explain. ``` ' Vl+-!uy ' Vl+ Alphabet plus space - Remove from input !u If result is not empty raise division by zero error y Else print input ``` [Answer] # Python 2, ~~68~~ ~~71~~ ~~70~~ 69 bytes ``` import re;s=raw_input();print s if re.match(r'[a-z\s]+$',s,2)else 0/0 ``` Thanks to [Alex A.](https://codegolf.stackexchange.com/users/20469/alex-a) and [Martin Büttner](https://codegolf.stackexchange.com/users/8478/martin-b%C3%BCttner) for saving a byte and [NightShadeQueen](https://codegolf.stackexchange.com/users/45325/nightshadequeen) for another byte! [Answer] # Java 127 Bytes ``` class A{public static void main(String[]a){String s=System.console().readLine();System.out.print(s.matches("[A-z ]+")?s:0/0);}} ``` In Java from the command line you can have input and with the help of regular expression `[A-z ]+` which matches alphabets and space in the line, you can have this kind of trick.Moreover, `0/0` will throw `ArithmeticException`. [Answer] ## **C#** - **174 157 148 bytes** ``` using System.Linq;namespace System{class A{static void Main(string[]s){if(!s[0].All(char.IsLetter))throw new Exception();Console.WriteLine(s[0]);}}} ``` usage: Console application that takes a parameter in the form of a string and checks via LINQ if all the characters in that string are letters. If so, writes it to console. Otherwise throws exception. Not particularly short. Will keep tinkering! Edit: Think I'm pretty much done. Can't get it much shorter don't think. [Answer] # Ruby, ~~26~~ 25 bytes "undefined method `+@' for nil:NilClass (NoMethodError)": ``` +(gets=~/^[A-z]*$/);print ``` Previous 26 bytes, "in `/': divided by 0 (ZeroDivisionError)": ``` puts gets[/^[A-z]*$/]||1/0 ``` ]
[Question] [ **This question already has answers here**: ["99 Bottles of Beer"](/questions/64198/99-bottles-of-beer) (168 answers) Closed 2 years ago. This code golf challenge is about making a rocket liftoff sequence. Your output (STDOUT) should be equal to this: ``` Liftoff in T-10 Liftoff in T-9 Liftoff in T-8 Liftoff in T-7 Liftoff in T-6 Liftoff in T-5 Liftoff in T-4 Liftoff in T-3 Liftoff in T-2 Liftoff in T-1 LIFTOFF! ``` Rules: * Your output must print to STDOUT. * Your program must not raise any errors. * This is code golf, shortest code in bytes wins. [Answer] # [Java (JDK)](http://jdk.java.net/), ~~92~~ ~~79~~ 78 bytes ``` v->{for(int i=11;i-->0;)System.out.println(i>0?"Liftoff in T-"+i:"LIFTOFF!");} ``` [Try it online!](https://tio.run/##LY6xCsIwFEV3v@LZqUUS6mq0DkJBqDgoLuIQYyOvpklpXgoi/fYaxPXeyz2nkYNkzeM1deFuUIEy0ns4SLTwmQF4khTTJq54IDRcB6sIneU7Z31o6359cfgoQMNmGljx0a5P0RLgZrkUyFiRi@z09lS33AXiXR9LY1Ms8m1SoSanNUTWmSULXCXVvjwfy3KeZGKcAMRf6m8xRBK0US09Ufx5Xm8g@6fPfqYAmkul6o5SG4zJRMzG2Th9AQ "Java (JDK) – Try It Online") Edit: Thanks to @KevinCruijssen for -1 byte [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 36 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?") ([SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set")) Full program. ``` ↑'Liftoff in T-'∘,∘⍕¨⌽⍳10 'LIFTOFF!' ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKO94P@jtonqPplpJflpaQqZeQohuuqPOmboAPGj3qmHVjzq2fuod7OhAZe6j6dbiL@bm6I6SNt/BTAoAAA "APL (Dyalog Unicode) – Try It Online") `⍳` **ɩ**ndices 1 through 10 `⌽` reverse them `'LIFTOFF!'` this string (implicitly output it to stdout) [Answer] # [Python 2](https://docs.python.org/2/), 56 bytes ``` d=11 exec"'Liftoff in T-%d'%d;d-=1;print"*d+"'LIFTOFF!'" ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P8XW0JArtSI1WUndJzOtJD8tTSEzTyFEVzVFXTXFOkXX1tC6oCgzr0RJK0UbqMTTLcTfzU1RXen/fwA "Python 2 – Try It Online") Wonderful application of [Using exec to remove repeated print](https://codegolf.stackexchange.com/a/204550/48931). -1 thanks to dingledooper who realised we can reuse the `d` variable in the exec multiplier. ## [Python 2](https://docs.python.org/2/), 57 bytes ``` d=~9 while d:print"Liftoff in T%d"%d;d+=1 print"LIFTOFF!" ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P8W2zpKrPCMzJ1UhxaqgKDOvRMknM60kPy1NITNPIUQ1RUk1xTpF29aQCyrp6Rbi7@amqPT/PwA "Python 2 – Try It Online") ## [Python 2](https://docs.python.org/2/), 59 bytes ``` d=10 while d:print"Liftoff in T-%d"%d+1/d*"\nLIFTOFF!";d-=1 ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P8XW0ICrPCMzJ1UhxaqgKDOvRMknM60kPy1NITNPIURXNUVJNUXbUD9FSykmz8fTLcTfzU1RyTpF19bw/38A "Python 2 – Try It Online") [Answer] # [Ruby 2.7](https://www.ruby-lang.org/), 51 50 bytes *Saved a byte using* `~9` *for* `-10`*, thanks to [Sisyphus](https://codegolf.stackexchange.com/users/48931/sisyphus)!* ``` puts (~9..-1).map{"Liftoff in T#{_1}"}<<"LIFTOFF!" ``` [Try it online!](https://tio.run/##KypNqvz/v6C0pFhBo85ST0/XUFMvN7GguiazRsknM60kPy1NITNPIUS5OrNWqdbGRsnH0y3E381NUen/fwA "Ruby – Try It Online") TIO uses an older version of Ruby, whereas in Ruby 2.7, we've numbered parameters, which saves two bytes. --- # [Ruby](https://www.ruby-lang.org/), 57 bytes ``` puts"Liftoff in T-#{11-($.+=1)}"while$.<10 puts"LIFTOFF!" ``` [Try it online!](https://tio.run/##KypNqvz/v6C0pFjJJzOtJD8tTSEzTyFEV7na0FBXQ0VP29ZQs1apPCMzJ1VFz8bQgAui1NMtxN/NTVHp/38A "Ruby – Try It Online") [Answer] # Bash, 67 bytes ``` for i in `seq 10`;do echo Liftoff in T-$((11-i));done;echo LIFTOFF! ``` [Try it online!](https://tio.run/##S0oszvj/Py2/SCFTITNPIaE4tVDB0DDBOiVfITU5I1/BJzOtJD8tDSQXoquioWFoqJupqQmUzku1hijwdAvxd3NT/P8fAA) # Bash, 43 bytes thanks to @Sisyphus for this suggestion. ``` seq -f'Liftoff in T%g' -10 -1;echo LIFTOFF! ``` [Try it online](https://tio.run/##S0oszvj/vzi1UEE3Td0nM60kPy1NITNPIUQ1XV1B19AAiK1TkzPyFXw83UL83dwU//8HAA) [Answer] # [Perl 5](https://www.perl.org/), 43 bytes ``` say"Liftoff in T$_"for-10..-1;say'LIFTOFF!' ``` [Try it online!](https://tio.run/##K0gtyjH9/784sVLJJzOtJD8tTSEzTyFEJV4pLb9I19BAT0/X0Booq@7j6Rbi7@amqP7//7/8gpLM/Lzi/7q@pnoGhgYA "Perl 5 – Try It Online") [Answer] # [PowerShell Core](https://github.com/PowerShell/PowerShell), 37 bytes ``` 10..1|%{"Liftoff in T-$_"} "LIFTOFF!" ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNydFNzi9K/f/f0EBPz7BGtVrJJzOtJD8tTSEzTyFEVyVeqZZLycfTLcTfzU1R6f9/AA "PowerShell Core – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 25 24 bytes ``` “ÞÆdḂbMG:ȯ»;Ɱ⁵ṚY⁷“KçÞ»Œu ``` [Try it online!](https://tio.run/##ATcAyP9qZWxsef//4oCcw57DhmThuIJiTUc6yK/Cuzvisa7igbXhuZpZ4oG34oCcS8Onw57Cu8WSdf// "Jelly – Try It Online") *-1 byte thanks to caird* ## Explanation ``` “ÞÆdḂbMG:ȯ»;Ɱ⁵ṚY⁷“KçÞ»Œu Main niladic link “ÞÆdḂbMG:ȯ» "Liftoff in T-" ; Join with Ɱ each of ⁵ [1 to] 10 Ṛ Reverse Y Join with newlines Print and discard ⁷ Newline Print and discard “KçÞ» "liftoff!" Œu Uppercase ``` [Answer] # [Nim](http://nim-lang.org/), 54 53 bytes ``` for i in -10..<0:echo "Liftoff in T",i echo"LIFTOFF!" ``` [Try it online!](https://tio.run/##y8vM/f8/Lb9IIVMhM09B19BAT8/GwCo1OSNfQcknM60kPy0NJBGipJPJBRJV8vF0C/F3c1NU@v8fAA "Nim – Try It Online") *-1 byte by using the negative numbers trick from other answers* [Answer] # 05AB1E, 30 bytes ``` TFNT-“ƒŸ€† Tÿ“'µë™ì,}’µëƒŸ!’u, ``` [Try it online!](https://tio.run/##yy9OTMpM/f8/xM0vRPdRw5xjk47ueNS05lHDAoWQw/uBAuqHth5e/ahl0eE1OrWPGmaCeCA1ikB2qc7//wA "05AB1E – Try It Online") ``` TFNT-“ƒŸ€† Tÿ“'µë™ì,}’µëƒŸ!’u, # full program F # for N in [0, 1, 2, ..., T # ..., 10... F # minus 1]... , # print... “ƒŸ€† Tÿ“ # "off in Tÿ"... # (implicit) with ÿ replaced by... N # variable... - # minus... T # 10... ì # prepended with... 'µë # "lift"... ™ # in title case... , # with trailing newline } # end loop , # print... ’µëƒŸ!’ # "liftoff!"... u # in uppercase... , # with trailing newline ``` [Answer] # [Deadfish~](https://github.com/TryItOnline/deadfish-), 1402 bytes ``` {{i}ddd}iiiiiic{i}{i}{i}dcdddc{i}iiiicdddddc{d}icc{{d}iii}c{{i}ddd}iiiciiiiic{{d}ii}iic{{i}ddddd}iic{{d}iiiiii}iciiiicdc{{d}iiiiii}iic{{i}dddd}iiiiiic{i}{i}{i}dcdddc{i}iiiicdddddc{d}icc{{d}iii}c{{i}ddd}iiiciiiiic{{d}ii}iic{{i}ddddd}iic{{d}iiiiii}ic{i}iic{{d}iiiii}iiic{{i}dddd}iiiiiic{i}{i}{i}dcdddc{i}iiiicdddddc{d}icc{{d}iii}c{{i}ddd}iiiciiiiic{{d}ii}iic{{i}ddddd}iic{{d}iiiiii}ic{i}ic{{d}iiiiii}ddddddc{{i}dddd}iiiiiic{i}{i}{i}dcdddc{i}iiiicdddddc{d}icc{{d}iii}c{{i}ddd}iiiciiiiic{{d}ii}iic{{i}ddddd}iic{{d}iiiiii}ic{i}c{{d}iiiiii}dddddc{{i}dddd}iiiiiic{i}{i}{i}dcdddc{i}iiiicdddddc{d}icc{{d}iii}c{{i}ddd}iiiciiiiic{{d}ii}iic{{i}ddddd}iic{{d}iiiiii}ic{i}dc{{d}iiiiii}ddddc{{i}dddd}iiiiiic{i}{i}{i}dcdddc{i}iiiicdddddc{d}icc{{d}iii}c{{i}ddd}iiiciiiiic{{d}ii}iic{{i}ddddd}iic{{d}iiiiii}ic{i}ddc{{d}iiiiii}dddc{{i}dddd}iiiiiic{i}{i}{i}dcdddc{i}iiiicdddddc{d}icc{{d}iii}c{{i}ddd}iiiciiiiic{{d}ii}iic{{i}ddddd}iic{{d}iiiiii}ic{i}dddc{{d}iiiiii}ddc{{i}dddd}iiiiiic{i}{i}{i}dcdddc{i}iiiicdddddc{d}icc{{d}iii}c{{i}ddd}iiiciiiiic{{d}ii}iic{{i}ddddd}iic{{d}iiiiii}iciiiiiic{{d}iiiiii}dc{{i}dddd}iiiiiic{i}{i}{i}dcdddc{i}iiiicdddddc{d}icc{{d}iii}c{{i}ddd}iiiciiiiic{{d}ii}iic{{i}ddddd}iic{{d}iiiiii}iciiiiic{{d}iiiiii}c{{i}dddd}iiiiiic{i}{i}{i}dcdddc{i}iiiicdddddc{d}icc{{d}iii}c{{i}ddd}iiiciiiiic{{d}ii}iic{{i}ddddd}iic{{d}iiiiii}iciiiic{{d}iiiiii}ic{{i}dddd}iiiiiicdddcdddc{i}iiiicdddddc{d}icc{{d}iiiiii}iiic ``` [Try it online!](https://tio.run/##xZSxDoAgDES/yI8yPY2dHZt@O0KBWOvgZgkDvd7Rl5CAbcXO57GUIsIKQNkW1apvUFVbaTJgVbURiZhbyUVppK2ldrKedWeihbqT8NBu@38Ywg9JOY3CKxh3Z4C8OHIwEDmSMCJHFkbgSMBgb@0YWRReSmIITxQY2qiP4fO3KeUC "Deadfish~ – Try It Online") [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal) `j`, 32 bytes ``` ₀ɾṘƛ«ƛ⟇⋏∨e«¡:£` in T-`+n+;¥⇧\!+J ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=j&code=%E2%82%80%C9%BE%E1%B9%98%C6%9B%C2%AB%C6%9B%E2%9F%87%E2%8B%8F%E2%88%A8e%C2%AB%C2%A1%3A%C2%A3%60%20in%20T-%60%2Bn%2B%3B%C2%A5%E2%87%A7%5C!%2BJ&inputs=&header=&footer=) ]
[Question] [ > > *A perfect square is an integer that is the square of an integer; in* > *other words, it is the product of some integer with itself.* > > > **Calculate the number of perfect squares below a number \$n\$ where \$n\$ will be taken as an input** --- **Examples:** There are 9 perfect squares below 100: 1, 4, 9, 16, 25, 36, 49, 64, 81 **Constraints:** \$0<n<10^6\$ --- Since this is a golfing challenge, the entry with least amount of bytes will win. Best of Luck! [Answer] # [brainfuck](https://github.com/TryItOnline/brainfuck), ~~161~~ 160 bytes ``` ,>>>>>>+[-<<<<<+[>+>+>+<<<-]>[-<+>]>[>[>+<<<+>>-]>[<+>-]<<-]>[-]<<<<[>>>+>+<<<<-]>>>>[<<<<+>>>>-]<[>+<<[>>[-]>+<<<-]>>>[<<<+>>>-]<[>>+<<-]<<->-]<[-]>>>>]<<<<<-. ``` [Try it online!](https://tio.run/##RU/LCoNADLz3K4JYVLZb9b4E@h1bDz6pFFyxK3jov2@TqHRyyOxkMmya@vMKbe3BGEh6NySA0LquDzcUKKsNQ1lUXER1hSQqpEbFikJkkbqujnnFS5YDxMEiwZrdzX4ju2Qh85m7O9Q5Z1kS5blHSLDR90CfvczLOPkBoucWpwe/bhCndFCWRfCF3M0@b5Z6nIa1ff@Z3Ehz14F@TKD9WoayKH4 "Bash ‚Äì Try It Online") Finally, a challenge simple enough that I could attempt some brainfuckery. Credits to <https://esolangs.org/wiki/Brainfuck_algorithms> for the squaring algorithm and the comparison algorithm ideas, [Fatih Erikli's brainfuck visualizer](http://fatiherikli.github.io/brainfuck-visualizer/), and to [El Brainfuck](https://copy.sh/brainfuck/?c=CiwgbiBpbnB1dAo-IGkgPSAwCj4gaXNxci90ZW1wMAo-IGljb3B5MS9uY29weS90ZW1wMQo-IGljb3B5Mi90ZW1wMgo-IHRlbXAzCj4gZXhpdGZsYWcgKGlzIGlzcXIgbHQgbikKK1stICAgICAgICAgICAgICAgICB3aGlsZSBleGl0ZmxhZyBub3QgMAogIDw8PDw8CiAgKyAgICAgICAgICAgICAgICAgaW5jcmVtZW50IGkKICBbPis-Kz4rPDw8LV0gICAgICBtYWtlIDMgY29waWVzIG9mIGkgKGRlc3RydWN0aXZlbHkpCiAgPlstPCs-XSAgICAgICAgICAgdXNlIG9uZSBvZiB0aGVtICh0ZW1wMCkgdG8gcmVzdG9yZSBpCgogIFNxdWFyaW5nIGJ5IG11bHRpcGx5aW5nIGljb3B5MSB3aXRoIGljb3B5MjoKICA-WyAgICAgICAgICAgICAgICB3aGlsZSBpY29weTEgbm90IDAKICAgID5bPis8PDwrPj4tXSAgICBjb3B5IGljb3B5MiB0byB0ZW1wMyBhbmQgYWRkIGl0IHRvIGlzcXIKICAgID5bPCs-LV0gICAgICAgICByZXN0b3JlIGljb3B5MiBmcm9tIHRlbXAzCiAgICA8PC0gICAgICAgICAgICAgZGVjcmVtZW50IGljb3B5MQogIF0KICA-Wy1dICAgICAgICAgICAgICByZXNldCB0ZW1wMiAoaWNvcHkyKSB0byAwCgogIENvbXBhcmluZyBuIGFuZCBpc3FyOgogIDw8PDxbPj4-Kz4rPDw8PC1dIGNvcHkgbiB0byBuY29weSBhbmQgdGVtcDIKICA-Pj4-Wzw8PDwrPj4-Pi1dICByZXN0b3JlIG4gZnJvbSB0ZW1wMgogIDxbICAgICAgICAgICAgICAgIHdoaWxlIG5jb3B5CiAgICA-KyAgICAgICAgICAgICAgaW5jcmVtZW50IHRlbXAyIGFzIGZsYWcKICAgIDw8Wz4-Wy1dPis8PDwtXSBpZiBpc3FyIGd0IDAgcmVzZXQgdGVtcDIgKGRlc3Ryb3lzIGlzcXIgJiBjb3BpZXMgdG8gdGVtcDMpCiAgICA-Pj5bPDw8Kz4-Pi1dICAgcmVzdG9yZSBpc3FyIGZyb20gdGVtcDMKICAgIDxbPj4rPDwtXSAgICAgICBzZXQgZXhpdGZsYWcgdG8gMSBpZiB0ZW1wMiB3YXMgbm90IHJlc2V0CiAgICA8PC0-LSAgICAgICAgICAgZGVjcmVtZW50IGlzcXIgJiBkZWNyZW1lbnQgbmNvcHkgCiAgICBdCiAgPFstXSAgICAgICAgICAgICAgcmVzZXQgaXNxciAod291bGQgaGF2ZSBiZWVuIHNldCB0byBuZWdhdGl2ZSBvZiBuIG1pbnVzIGlzcXIpCiAgPj4-PiAgICAgICAgICAgICAgY2hlY2sgdGhlIGZsYWcgYW5kIGV4aXQgaWYgaXNxciBndCBuCl0KPDw8PDwtLiAgICAgICAgICAgICAgZGVjcmVtZW50IGkgYnkgMSBhbmQgb3V0cHV0CgohCgo$) for quick runs. *(Also to user202729 for noticing an unnecessary space in the code and for a link with a bash I/O wrapper.)* Calculates \$ i^2 \$ for each \$ i \$ starting from 1, and checks if \$ i^2 < n \$. Returns the last \$ i \$ for which that's true. ~~Input and output are usually ASCII characters representing numbers. For eg., in the TIO link, input `d` (ASCII 100) returns character tab `\t` (ASCII 9).~~ Now links to a version that takes and returns numeric I/O directly. Assumes a wrapping implementation (for the comparison algorithm). ``` , n input > i = 0 > isqr/temp0 > icopy1/ncopy/temp1 > icopy2/temp2 > temp3 > exitflag (is isqr lt n) +[- while exitflag not 0 <<<<< + increment i [>+>+>+<<<-] make 3 copies of i (destructively) >[-<+>] use one of them (temp0) to restore i Squaring by multiplying icopy1 with icopy2: >[ while icopy1 not 0 >[>+<<<+>>-] copy icopy2 to temp3 and add it to isqr >[<+>-] restore icopy2 from temp3 <<- decrement icopy1 ] >[-] reset temp2 (icopy2) to 0 Comparing n and isqr: <<<<[>>>+>+<<<<-] copy n to ncopy and temp2 >>>>[<<<<+>>>>-] restore n from temp2 <[ while ncopy >+ increment temp2 as flag <<[>>[-]>+<<<-] if isqr gt 0 reset temp2 (destroys isqr & copies to temp3) >>>[<<<+>>>-] restore isqr from temp3 <[>>+<<-] set exitflag to 1 if temp2 was not reset <<->- decrement isqr & decrement ncopy ] <[-] reset isqr (would have been set to negative of n minus isqr) >>>> check the flag and exit if isqr gt n ] <<<<<-. decrement i by 1 and output ! ``` [Answer] # brainfuck, 49 bytes Use byte-value input/output. Can only process numbers up to maximum cell value. Requires a tape that has at least 3 cells to the left and 2 cells to the right of the initial memory pointer. ``` +>>,[<[<<]<[[<+>>+<-]++<[>+<-]<<+>]>>>->-]<<<<<-. ``` [Try it online!](https://tio.run/##bY7BCoMwDIbvPkUQR5UuU@8hsOeoHmpVlIGVroKHvXvXiWyXfYfwJfwh6fRzCtOge0CDNRCBGOwogMHYfgiS@apIEbWkFMVOErZSkjqE4qRlZuSPR/AW4nayunnxI6TNnuWnX3bIcqN9UaRw0CSxvKC0qy87p@dl3MzjZ8f5b8rG9@4LoN9q@MOZ8g6wBwEi1FX1Bg "Bash ‚Äì Try It Online") (with nice Bash wrapper that converts decimal input/output to byte input/output) --- Based on the identity \$1 + 3 + 5 + \dots + (2n-1) = n^2\$     (so it subtracts 1, then 3, then 5, then 7, ... from the input \$n\$ until it is \$\le 0\$, then count number of subtraction) Explanation: ``` # Mem layout: {r t A a c x}. Ptr initially at {a}. # {t} == 0. r == result. a == 1, then increase to 3, 5, ... # {c} counts from {a} to 0. # {x} is the input, gradually decremented. + # a=1 >>, # read x [ # while x: < # goto c [<<]< # if c, goto {t}, else goto {a} [ # if not c: [<+>>+<-] # A=c=a; a=0 ++<[>+<-] # a=2+A; A=0 <<+> # r+=1 ] # now mem pointer is at {t} regardless of initial # value of {c}, and c!=0 >>>- # c-=1 >- # x-=1 ] <<<<<-. # print r-1 ``` [Compilable Python code works the same way -- explanation in reverse](https://tio.run/##TY/NCsIwEITP3adY8NISI6ne7CbQ5wg9hKI0IGkJEevTx6Q/6t72m5lldnqHYXSXGL3spQAwsi4KxAMig1laF0rrpmcoq2qlSh3hNdjHDefrSjQg2ju6MWC/IUTSRB1lCbFNl02DRoq8LbImphQj3i0GI8@sbZJP7HHGSP90z1Kp/XBKwtYwqz3/FlZK8UTmP8Jh8vkHz@utP@XhpxhrIT4 "Python 3 ‚Äì Try It Online"). [Answer] # [Brain-Flak](https://github.com/Flakheads/BrainHack), 58 bytes ``` ({()<([]){({}{(<({}[()])>)}{}[()])}{}({}((<><>)))>}<>[()]) ``` [Try it online!](https://tio.run/##LYgxDoAwDMS@c7eVPbqPVB0KCwiJoWuUt4cIsdiW9zWv55zHnQkHDX3Q4eGwYgcHxfirXBMwmUgqTN/PzK21Fw "Brain-Flak ‚Äì Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes ``` ‚Äô√Ü¬Ω ``` [Try it online!](https://tio.run/##y0rNyan8//9Rw8zDbYf2/jcy1TncrvKoaY37fwA "Jelly ‚Äì Try It Online") Simply takes the floor of the square root of \$n-1\$. Assumes \$0\$ should be counted and assumes that we ought to find the number of perfect squares strictly lower than \$n\$. (This is just an illustration of why such trivial challenges are discouraged) [Answer] # [Panacea](https://github.com/okx-code/Panacea), 3 bytes ``` <qc ``` Explanation: ``` < decrement q square root c floor ``` [Answer] # JavaScript, 25 bytes ``` f=n=>--n&&!(n**.5%1)+f(n) ``` [Try it online](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/zTbP1k5XN09NTVEjT0tLz1TVUFM7TSNP839yfl5xfk6qXk5@ukaahqGBgabmfwA) [Answer] # [Japt](https://github.com/ETHproductions/japt), 4 bytes *Port of [Mr. XCoder Jelly Implementation](https://codegolf.stackexchange.com/a/168518/78039)* ``` ¬¥U¬¨f ``` [Try it online!](https://tio.run/##y0osKPn//9CW0ENr0v7/NzQwAAA "Japt ‚Äì Try It Online") [Answer] # [Brain-Flak](https://github.com/Flakheads/BrainHack), 76 bytes ``` {({}[()]<(({})){(<{}({}[({})({}[()])])>)}{}({}({})({}())[()])>)}{}{}({}[()]) ``` [Try it online!](https://tio.run/##SypKzMzLSEzO/v@/WqO6NlpDM9ZGA8jQ1KzWsKmuBQsBeVApILTTrAULQ0U1NDXBEmBhqHog9////4YGBgA "Brain-Flak (BrainHack) ‚Äì Try It Online") ## Explanation Uses a simple counting method. It has 3 counters, the number, the slice and the result. We decrement the number until it reaches zero, each time we do we also decrement the slice if it is non-zero. If the slice is zero we increment the result and set the slice to one less than twice the result. This computes the square root via the sum of consecutive odds. [Answer] # [Dodos](https://github.com/DennisMitchell/dodos), ~~121~~ 120 bytes Also based on the identity \$1 + 3 + 5 + \dots + (2n-1) = n^2\$    . Thanks to H.PWiz for saving some bytes. ``` dip f 1 f + 1 > - A f F F > - i r + 1 1 > i i I I > > r > > - A A + > + - - dip 1 dip + _ _ + dot > dab ``` [Try it online!](https://tio.run/##JYxBCoAwDATP2VfsvfQQHyD0IvgKUUohp4r6/5gqBMJkNlt77be7VDvZqGiQROXMzBKHBQtkgPH6TTgYxLhiDTXm@vd4QRmpoIQMyYxaKARff@KGDSmgP4hM3Q9310lf "Dodos ‚Äì Try It Online") Fortunately there are no scroll bar in the code... --- ``` _ Returns an empty list. 1 Append 1. - Assume x<y, given (x, y) return (0, y-x). > - A Get the first element of a list (return 0 for empty list). r Reverse a list of 2 elements. i Incremential: Given (x, y) return (x, y) if x<y else (y, y). f Main function. ``` Writing Dodos code is similar to Haskell that all functions are (effectively) pure. [Bonus Haskell code](https://tio.run/##FYsxDoAgEAR7X7GFBYRIwB7/QnGEi0CMUPD7E7uZZCbHflMpIgkTjABecDFGpgZvEtQ8WEOxOTWodILb6koD/sFLjdyWPC@3AYuKHd45@QA) (ungolfed) which this solution bases on. [Answer] # [MATL](https://esolangs.org/wiki/MATL) - 4 bytes Using the same approach as others ``` qX^k ``` Try it at [MATL Online](https://matl.io/?code=qX%5Ek&inputs=100&version=20.9.1) **Explanation** ``` Implicitly grab input q Subtract 1 X^ Compute the square root k Round down Implicitly display the result ``` [Answer] # [Neim](https://github.com/okx-code/Neim), 7 bytes ``` ùêàŒõqùïö)ùê•< ``` [Try it online!](https://tio.run/##y0vNzP3//8PcCR3nZhd@mDt1liaQvdTm/39DAwMA "Neim ‚Äì Try It Online") [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~14~~ 12 bytes *-2 bytes by @Shaggy* ``` _=>--_**.5|0 ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/e1k5XN15LS8@0xuB/cn5ecX5Oql5OfrpGmoahgYGm5n8A "JavaScript (Node.js) ‚Äì Try It Online") [Answer] # Noether, 9 bytes ``` I1-0.5^_P ``` [**Try it in the interpreter!**](https://beta-decay.github.io/noether?code=STEtMC41Xl9Q&input=NQ) ## Explanation: This is just an implementation of the formula \$\left\lfloor{\sqrt{n-1}}\right\rfloor\$: ``` I - Push the user input onto the stack 1 - Push 1 onto the stack - - Pop two numbers a and b off the stack and push the result of a-b 0.5 - Push 0.5 onto the stack ^ - Pop two numbers a and b off the stack and push the result of a^b _ - Pop the number on the top of stack, floor it and push the result P - Print the item on the top of the stack ``` [Answer] # Java 8, 22 bytes ``` n->(int)Math.sqrt(n-1) ``` Lambda using the formula \$\left\lfloor{\sqrt{n-1}}\right\rfloor\$. Trivial implementation. Try it online [here](https://tio.run/##Nc0xDoMwDAXQOZzCYzIQwYzaGzB1rDq4kNJQCBAbpKri7CkpZbL9Zb3f4oLpMBrX1q8wzvfOVlB1SAQlWgefRFjHxj@wMnCZZvSGYhhToP2WcXeqSMSaiD9BjLyNZbA19BskL@yta643QN@Q@hEHR3CC4NJzdFSJ/NQ0eZYuzVUQooifb2LT62FmPW4Md06SPtrzLFN7@Rq@). [Answer] # C (gcc), 18 bytes ``` f(n){n=sqrt(n-1);} ``` Trivial implementation of the formula \$\left\lfloor{\sqrt{n-1}}\right\rfloor\$. Try it online [here](https://tio.run/##DcdBCoAgEADAs75CgmAXEvQsPUYsRdClzE7S19ua2wSdQmCOQDhovc7WgbRF93CmrqrPBKiGFEf7H2Gat2lREawxiE6Ktve7kTJOPvyGWHy6WJf6AQ). ]
[Question] [ **Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/162015/edit). Closed 5 years ago. [Improve this question](/posts/162015/edit) Given an arbitrary sequence consisting of 1 and A split this sequence up so that A is at the beginning of each sub sequence. Sequences without a leading A and Sequences without 1 before the next A will be self contained. Example Input ``` 111A11A1111111A1A1AA ``` should result in ``` 111 A11 A1111111 A1 A1 A A ``` Above already contains the edge cases \* sequence of 1 without prior A \* subsequent A's without 1 between *Update* Open to all programming languages (functional / non-functional) [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 12 bytes Anonymous tacit function. Returns a list of strings. ``` ⊢⊂⍨1⊣@1=∘'A' ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24RHXYsedTU96l1h@KhrsYOh7aOOGeqO6v//P2qbmKagbmho6AhGYOAIgo7qAA "APL (Dyalog Unicode) – Try It Online") (`↑` is just to display the list of strings as separate lines.) `=∘'A'` Boolean list (1s and 0s) indicating As `1⊣@1` replace with a 1 at the first position `⊢⊂⍨` begin partitions of the argument at each 1 in that [Answer] ## [Retina](https://github.com/m-ender/retina/wiki/The-Language), 6 bytes ``` \BA ¶A ``` [Try it online!](https://tio.run/##K0otycxLNPz/P8bJkevQNsf//w0NDR3BCAwcQdARAA "Retina – Try It Online") An alternative to Luis's solution. Finds all `A` which are preceded by another character and inserts a linefeed in front of them. [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~6~~ 5 bytes *1 byte saved thanks to [@Neil](https://codegolf.stackexchange.com/users/17602/neil)!* ``` L`.1* ``` [Try it online!](https://tio.run/##K0otycxLNPz/3ydBz1Dr/39DQ0NHMAIDRxB0BAA "Retina – Try It Online") ### Explanation ``` L` Configure the stage as "list", so that it outputs all matchings .1* Regex to be matched: any character followed by zero or more "1" ``` [Answer] # [Haskell](https://www.haskell.org/), ~~54~~ 37 bytes ``` import Data.List groupBy(\_ x->x<'A') ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/PzO3IL@oRMElsSRRzyezuIQrzTa9KL@0wKlSIyZeoULXrsJG3VFd839uYmaegq1CQWlJcEmRXnFGfrmCikKagpKhoaEjGIGBIwg6Kv0HAA "Haskell – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) 1 The slooooow but shorter method which gets all ways\* to partition the list and then finds the maximal as measured by its transpose: ``` ŒṖZÞṪ ``` **[Try it online!](https://tio.run/##y0rNyan8///opIc7p0Udnvdw56r/h9sj//9XMjQ0dAQjMHAEQUclAA "Jelly – Try It Online")** \* that is all **2length(input)-1** ways! 2 The speedy method using the "partition at truthy indices" atom (the five byte `=”Aœṗ` fails for inputs starting with `A`): ``` Ḋ=”A0;œṗ ``` **[Try the speedy one!](https://tio.run/##y0rNyan8///hji7bRw1zHQ2sj05@uHP6/8Ptkf//KxkaGjqCERg4gqCjEgA "Jelly – Try It Online")** [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~10~~ 8 bytes ``` 'A" A".: ``` [Try it online!](https://tio.run/##MzBNTDJM/f9f3VGJy1FJz@r/f0NDQ0cwAgNHEHQEAA) Can probably be golfed further, but first submission and attempt at this. **Explanation** ``` 'A" Push A character, Push string "(new line) A" A" close string .: Replace all. Replace "A" with "(new line) A" in input ``` ~~If you want code to match output like in original post then 11 bytes~~ ``` I'A" A".:#» ``` -2 bytes thanks to Soaku! [Answer] # [Befunge-98 (FBBI)](https://github.com/catseye/FBBI), ~~14~~ 12 bytes -2 bytes thanks to [Jo King](https://codegolf.stackexchange.com/users/76162/jo-king) ``` #@~:d%5/ja,, ``` [Try it online!](https://tio.run/##S0pNK81LT9W1tPj/X9mhzipF1VQ/K1FH5/9/Q0NDRzACA0cQdAQA "Befunge-98 (FBBI) – Try It Online") ``` #@ # skips @ ~ push a byte of input : duplicate it d% modulo 13, 'A':0, '1':10 5/ divided by 5, 'A':0, '1':2 j jump this number of blocks, skips the next two instructions for '1' a, push 10 to the stack and output as a byte (\n) , output the byte of input ``` If there is no input left, `~` reflects the pointer and `@` terminates the program [Answer] # [Standard ML (MLton)](http://www.mlton.org/), 40 bytes ``` String.translate(fn#"A"=>"\nA"|x=>str x) ``` [Try it online!](https://tio.run/##HYq7CoAwDAB/JcTFDgqdpYV8g6tLBytCTKUN0sF/r4@7G68cPBysSdoVGCI4aLPmXbZRc5DCQdc@SoeEzuMihHd1vmiGatoE/fmuCgmiAbTW0t8PfRJO7QE "Standard ML (MLton) – Try It Online") Unfortunate that `String.translate` is so long... [Answer] # [Japt](https://github.com/ETHproductions/japt), 6 bytes ``` d'A_iR ``` [Try it online!](https://tio.run/##y0osKPn/P0XdMT4z6P9/JUNDQ0cwAgNHEHRUAgA "Japt – Try It Online") ### Explanation: ``` d'A_iR d // Replace: 'A // "A" with _iR // newline + "A" ``` Alternative 6-byte solution ``` r'A" A ``` [Try it online!](https://tio.run/##y0osKPn/v0jdUYnL8f9/JUNDQ0cwAgNHEHRUAgA) These would be 5-byte solutions if we could take `a` instead of `A`. [Answer] # [Perl 5](https://www.perl.org/) `-p`, 8 bytes ``` s/A/ A/g ``` [Try it online!](https://tio.run/##K0gtyjH9/79Y31Gfy1E//f9/Q0NDRzACA0cQdPyXX1CSmZ9X/F@3AAA "Perl 5 – Try It Online") [Answer] # [JavaScript (Node.js)](https://nodejs.org), 27 bytes ``` z=>z.split(/(?=A)/).join` ` ``` [Try it online!](https://tio.run/##HcJBDsAQEEDRfS/CLEocQBs3IUpDxEhJFy4/Tf33s3td909qY694BYqapj6m6K2kwSU/tQEJImOqdrPksXYsQRS8eeRMKWXWK/MzDIA@ "JavaScript (Node.js) – Try It Online") --- # Explanation : ``` z => // lambda function taking z as input z.split( // convert z to an array by splitting at /(?=A)/ // all `A's` ). // end split join`\n` // join all via new line ``` --- # Alternate : If printing an array is okay, then : # [JavaScript (Node.js)](https://nodejs.org), 19 bytes ``` z=>z.split(/(?=A)/) ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@7/K1q5Kr7ggJ7NEQ1/D3tZRU1/zf3J@XnF@TqpeTn66RpqGuqGhoSMYgYEjCDqqa2r@BwA "JavaScript (Node.js) – Try It Online") [Answer] # [JavaScript (Node.js)](https://nodejs.org), 22 bytes ``` s=>s.match(/A1*|^1+/g) ``` [Try it online!](https://tio.run/##VU5RCoMwDP33FJkMbDen9AAVeg5x6DS6irOydmPgPHtXdYyZhJeXPB5JWzwLXd7lYE69qtDW3Gqe6OhWmPJKYsEO7zM7xg21BrXhRPZDiK@B8mT0AGRN6nlFo1bJPs933GlfTp0OUKpeqw6jTjUkb5SBdD@ulimDy8OAM2BpsJoFx6dsMWKncePdnOGbM5M3v0Z8xphYagkxp/DDFAI3BSEE4teWWPkfrgAZ9ewH "JavaScript (Node.js) – Try It Online") [Answer] # [Scala](http://www.scala-lang.org/), 20 bytes ``` _.replace("A","\nA") ``` [Try it online!](https://tio.run/##K05OzEn8n5@UlZpcouCbmJmnkFpRkpqXUqzgWFCgUK1QlpijkGalEFxSlJmXrmBrB2f9j9crSi3ISUxO1VByVNJRislzVNL8XwCULMnJ00jTUDI0NHQEIzBwBEGgCk0urtr/AA "Scala – Try It Online") (Not sure if putting the types in the header is allowed, I'll change it if not.) [Answer] # [JavaScript](https://nodejs.org), ~~26~~ 23 bytes *-3 bytes thanks to caird coinheringaahing* ``` s=>s.replace(/A/g,` A`) ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@7/Y1q5Yryi1ICcxOVVD31E/XSeByzFB839yfl5xfk6qXk5@ukaahpKhoaEjGIGBIwg6Kmlqcv0HAA "JavaScript (Node.js) – Try It Online") [Answer] # Pyth, ~~8~~ 7 bytes ``` :Q\A" A ``` [Try it here](http://pyth.herokuapp.com/?code=%3AQ%5CA%22%0AA&input=%22111A11A1111111A1A1AA%22&debug=0) ### Explanation ``` :Q\A"\nA :Q Replace in the input... \A ... every instance of "A"... "\nA ... with a newline followed by "A". ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~20~~ 19 bytes ``` s=>s.split(/(?=A)/) ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@7/Y1q5Yr7ggJ7NEQ1/D3tZRU1/zf3J@XnF@TqpeTn66RpqGkqGhoSMYgYEjCDoqaWoq6OtHK6gDRdR1FNQd4RQYQNhIJIRQiOX6DwA "JavaScript (Node.js) – Try It Online") Thanks Pandacoder for 1 byte [Answer] # [Python 2](https://docs.python.org/2/), 29 bytes ``` lambda I:I.replace('A','\nA') ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUcHTylOvKLUgJzE5VUPdUV1HPSbPUV3zf0FRZl6JQpqGuqGhoSMYgYEjCILkAQ "Python 2 – Try It Online") [Answer] ## Batch, 44 bytes ``` @set/pa= @for %%a in (%a:A= A%)do @echo %%a ``` Takes input on STDIN. [Answer] # [Java (JDK 10)](http://jdk.java.net/), 19 bytes ``` s->s.split("(?=A)") ``` [Try it online!](https://tio.run/##RYzBCoMwDIbvPkXw1MIseN509LLbTh7HDp1Oqau1mCjI8Nk7rRtLAn8g@b5WTSppq5cvjUKEq9IW3hGAGx9Gl4CkaI2p1xV0640VNGjb3O6ghgZ5eAVoV4kYSRtRj7Yk3Vtx@S6nHTj8uBzqzGOSo0BnNLGYnTPJY@6PwVTMSM9O9CMJtwJkLPvL5TCoGQX1u4zVQjlnZhanaSrDhJJby5hzvjmXaPEf "Java (JDK 10) – Try It Online") [Answer] # [Pepe](https://github.com/Soaku/Pepe), 59 bytes ``` rEEeREeEeeeeeEREeeeeeeeeREEreeEREEeeREEreEeREEeEReEREEeeRee ``` [Try it online!](https://soaku.github.io/Pepe/#zeZnsZlxZ7z9ZsZ7zaZtZ5ZsZ4) That was hard... Outputs with leading newline. ``` rEEe # r - Get input Take the string REeEeeeeeE # R - Push A A - splitter REeeeeeeee # R - Push \0 \0 - end REE # R - Create label A label A: Next + newline reeE # Output newline Output newline REEee # R - Forward REE # R - Create label \0 label \0: Next without newline reEe # r - Output Output the current letter and pop it REEeE # R - Rewind ReE # r pointer == A, goto A Output newline, next letter REEee # R - Forward Else Ree # r pointer != \0, goto \0 If stack isn't empty, next letter ``` [Answer] # [Haskell](https://www.haskell.org/), 29 bytes ``` f s=do c<-s;['\n'|c>'1']++[c] ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P02h2DYlXyHZRrfYOlo9Jk@9JtlO3VA9Vls7Ojn2f25iZp6CrUJmXklqUWJyiULaf0NDQ0cwAgNHEHQEAA "Haskell – Try It Online") [Answer] # R, 26 bytes Not a whole lot to explain with this one. ``` cat(gsub("A","\nA",scan())) ``` [Answer] # sed, 9 bytes ``` s/A/\nA/g ``` [Try it online!](https://tio.run/##K05N0U3PK/3/v1jfUT8mz1E//f9/Q0NDRzACA0cQdAQA "sed – Try It Online") ]
[Question] [ **Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers. --- This question does not appear to be about code golf or coding challenges within the scope defined in the [help center](https://codegolf.stackexchange.com/help/on-topic). Closed 7 years ago. [Improve this question](/posts/60152/edit) So, you're browsing Programming Puzzles & Code Golf, and you see a new challenge. The author (*gasp*) forgot to say "No standard Loopholes". You decide to take advantage of this situation, and you read the answer from a file/network. However, you need to make sure that your answer is actually shorter than the legitimate answers, so you golf it, too. # The Challenge Write a complete program that prints out the contents of the file `definitelynottheanswer.txt` to STDOUT. This text file only contains valid ASCII characters. Alternatively, the program can get the file location from STDIN or command line args. The only input allowed is the file location if you choose to get the location from the user; otherwise, no input is allowed. There is no reward for getting the file location from the user, but the user input of the file location does not count against the byte total (in other words, `definitelynottheanswer.txt` wouldn't be included in the byte score). The program must not write to STDERR. ## Bonus Retrieve the file from the internet *instead* of a file (the URL must be user-supplied). **Reward: multiply source length by 0.85** # Scoring * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the lowest score,`program length (bytes) * bonus`, wins. * No (other) standard loopholes. * If the language does not support reading files from disk, it cannot be used (sorry). [Answer] # GNU sed, 0 bytes Even better.. [Answer] # Bash, 7 bytes \* .85 = 5.9 bytes ``` curl $1 ``` zzz [Answer] # Pyth - 2 bytes \* .85 = 1.7 ``` 'z ``` Does not work online. [Answer] ## Bash, 6 bytes ``` cat $1 ``` Provide filename as a command line argument. Probably breaks if the argument contains spaces or newlines or weird chars or whatever. [Answer] # CJam, 1.7 bytes ``` qg ``` For security reasons, this does not work in the online interpreter. ]
[Question] [ Your goal is to write a program that, given a number *N* and a string as input, will return a string containing every *N*th word of the original string, starting from the first word. Sample inputs/outputs: ``` N = 2, str = "This is a sentence" "This a" -- N = 2, str = "The quick brown fox jumped over the lazy dog." "The brown jumped the dog." -- N = 7, str = "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa." "Lorem elit. massa." ``` You're allowed to assume that the input will always contain at least *N+1* words, and that words will always be delimited by the space character `&#32;`. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins. [Answer] # Pyth, 6 ``` jd%Qcz ``` Splits on spaces, takes every Nth element, joins on spaces. [Try it online](https://pyth.herokuapp.com/?code=jd%25Qcz&input=Lorem+ipsum+dolor+sit+amet%2C+consectetuer+adipiscing+elit.+Aenean+commodo+ligula+eget+dolor.+Aenean+massa.%0A7) # Explanation ``` jd : join on spaces %Q : take every Qth character (Q will have read the input with N) cz : chop the other input on whitespace ``` [Answer] # CJam, 7 bytes ``` q~S/%S* ``` [Test it here.](http://cjam.aditsu.net/#code=q~S%2F%25S*&input=7%20%22Lorem%20ipsum%20dolor%20sit%20amet%2C%20consectetuer%20adipiscing%20elit.%20Aenean%20commodo%20ligula%20eget%20dolor.%20Aenean%20massa.%22) This reads a number and a string (in that order) from STDIN. ## Explanation ``` q~ e# Read and eval input. S/ e# Split on spaces. % e# Take every Nth element. S* e# Join the words back together with spaces. ``` [Answer] # Python, 35 characters ``` lambda n,s:' '.join(s.split()[::n]) ``` [Answer] # KDB(Q), 26 bytes ``` {" "sv#[0N,y;" "vs x][;0]} ``` # Explanation ``` " "vs x / cut x string by space #[0N,y; ] / cut list by y length [;0] / take first of each list " "sv / combine with space { } / lambda ``` # Test ``` q){" "sv#[0N,y;" "vs x][;0]}["The quick brown fox jumped over the lazy dog.";2] "The brown jumped the dog." ``` [Answer] # Julia, 38 bytes ``` (n,s)->join(split(s," ")[1:n:end]," ") ``` This creates an anonymous function that accepts an integer and string as input and returns the required output. To call it, give it a name, e.g. `f=(n,s)->...`. Ungolfed + explanation: ``` function f(n, s) # Split the string into words words = split(s, " ") # Get every nth word starting at 1 every_nth = words[1:n:end] # Join into a single string separated with a space join(every_nth, " ") end ``` Examples: ``` julia> f(2, "The quick brown fox jumped over the lazy dog.") "The brown jumped the dog." julia> f(2, "This is a sentence.") "This a" ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes (language postdates challenge?) ``` ḲmK ``` `Ḳ` splits the first input on spaces; `m` takes every nth element; then `K` joins on spaces again. `m` is missing a second argument, so it takes the second input by default. [Try it online!](https://tio.run/nexus/jelly#@/9wx6Zc7////4dkpCoUlmYmZyskFeWX5ymk5VcoZJXmFqSmKOSXpRYplADlcxKrKhVS8tP1/hsBAA "Jelly – TIO Nexus") [Answer] # 12-basic, 42 bytes ``` ?JOIN(INPUT$().SPLIT(" ")STEP INPUT()," ") ``` [Try](https://12me21.github.io/12-basic/#Ttextarea%3B%3FJOIN(INPUT%24().SPLIT(%22%20%22)STEP%20INPUT()%2C%22%20%22)%7ET%23%5C%24input%3BLorem%20ipsum%20dolor%20sit%20amet%2C%20consectetuer%20adipiscing%20elit.%20Aenean%20commodo%20ligula%20eget%20dolor.%20Aenean%20massa.%0A7%7ECbutton) ]
[Question] [ **Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/191463/edit). Closed 4 years ago. [Improve this question](/posts/191463/edit) # The challenge Write a function that returns the `n`th element of an array even if its out of bound. ``` function safeGet(index, arr) { const safeIndex = ??? return arr[safeIndex] } const arr = ["a", "b", "c"]; safeGet(0, arr) // "a" safeGet(1, arr) // "b" safeGet(2, arr) // "c" safeGet(3, arr) // "a" go back to the beginning safeGet(4, arr) // "b" all over again safeGet(5, arr) // "c" safeGet(30, arr) // "a" safeGet(400, arr) // "b" safeGet(5000, arr) // "c" ``` Negative indices works exactly the same way, but beginning from the end: ``` safeGet(-1, arr) // "c" begin from the end safeGet(-2, arr) // "b" safeGet(-3, arr) // "a" safeGet(-4, arr) // "c" go back to the end again safeGet(-20, arr) // "b" safeGet(-300, arr) // "a" ``` Visually it looks like this: ``` // (For 1-element sized arrays, any natural number is a valid index) // 2 // 1 // 0 // ["a"] // -1 // -2 // -3 // 6 7 8 // 3 4 5 // 0 1 2 // ["a", "b", "c"] // -3 -2 -1 // -6 -5 -4 // -9 -8 -7 // 6 7 8 9 10 11 // 0 1 2 3 4 5 // ["a", "b", "c", "d", "e", "f"] // -6 -5 -4 -3 -2 -1 // -12 -11 -10 -9 -8 -7 ``` # Rules * You can't **mutate** the array. * You can't even **traverse** the array. * Any programming languages will be accepted. * It's a CodeGolf, meaning the smallest answer wins. [Answer] # Python, ~~22~~ 21 bytes -1 byte thanks to ovs This does not mutate the given array. Rather, it makes a n^2 larger copy of it. There's also no explicit iteration being done here. ``` lambda a,n:(n*n*a)[n] ``` [TIO](https://tio.run/##LcxBCoMwEEbhvacYXCXyCzEtLQqeJM1iioYOtKOkLtrTpxXcPj7e@t0ei55KGm/lya/7xMTQwWijDdugsXDONFKoucb5ihDRx0p0mj/ze@8dPNoOF3iH1jsXq7RkEhKlQw1rFt1MMv8TxNryAw) (updated test array) [Answer] # [Stax](https://github.com/tomtheisen/stax), 1 bytes ``` @ ``` [Run and debug it](https://staxlang.xyz/#c=%40&i=[%22a%22,+%22b%22,+%22c%22]+0%0A[%22a%22,+%22b%22,+%22c%22]+1%0A[%22a%22,+%22b%22,+%22c%22]+2%0A[%22a%22,+%22b%22,+%22c%22]+3%0A[%22a%22,+%22b%22,+%22c%22]+4%0A[%22a%22,+%22b%22,+%22c%22]+5%0A[%22a%22,+%22b%22,+%22c%22]+30%0A[%22a%22,+%22b%22,+%22c%22]+400%0A[%22a%22,+%22b%22,+%22c%22]+5000%0A[%22a%22,+%22b%22,+%22c%22]+-1%0A[%22a%22,+%22b%22,+%22c%22]+-2%0A[%22a%22,+%22b%22,+%22c%22]+-3%0A[%22a%22,+%22b%22,+%22c%22]+-4%0A[%22a%22,+%22b%22,+%22c%22]+-20%0A[%22a%22,+%22b%22,+%22c%22]+-300%0A&a=1&m=2) `@` is the array indexing instruction in stax. It works exactly as specified. [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 12 bytes ``` *[0]o&rotate ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwXyvaIDZfrSi/JLEk9b81FxdQwiERKGGgY6hjpGOsY6JjqmOmY65joWMJlC1OrFRIAyrQUTCwRuIYmSDzTM2QeYYmlsYoio1NLEyt/wMA "Perl 6 – Try It Online") Works differently from [guifa's answer](https://codegolf.stackexchange.com/a/191474/76162) in that it first rotates the array by the given amount, then takes the first element. [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 17 9 bytes ``` {*[$_%*]} ``` Explanation ``` {*[$_%*]}($idx)(@arr) # curried input *[$idx % *](@arr) # $_ takes the $index @arr[$idx % *] # first * takes @array @arr[$idx % @arr.elems] # * in [] is number of elems ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwv1orWiVeVSu29r81FxdQ1CERKBpnaADkFSdWKqRpGGhqOCRqWkN5RiYoXFMzFK6hiaUxqnpjEwtTiMB/AA "Perl 6 – Try It Online") [Answer] # [Zsh](https://www.zsh.org/), ~~27~~ 24 bytes ``` <<<${@[(`<&0`%#+#)%#+1]} ``` Turned out a bit more interesting than I thought. Takes array as arguments, index on stdin. ~~[Try it online!](https://tio.run/##qyrO@J@moanx38bGRqXaIVoj0zbBRs0gQVVZU1sj087WQDO29r8mF1eaQqJCkkKyAlCZgoIBKtcQlWuMwtVFldVFkzVF1YvKtbT8DwA "Zsh – Try It Online")~~ [Try it online!](https://tio.run/##qyrO@J@moanx38bGRqXaIVojwUbNIEFVWVtZE0gYxtb@1@TiSlNIVEhSSFYAqlFQMEDlGqJyjVG4uqiyumiypqh6UbmWlv8B "Zsh – Try It Online") Arrays in zsh are one-indexed, and `$a[0]` is empty. Negative indexing works as expected for `-1, -2, ..., -n`. New strategy: While negative indexing seems useful, the empty zero-index makes it less so. So, we just "mod n, add n, mod n" to make everything in the range [0,n-1], then add one. --- Old strategy: * take the index % length, leaving us something in the range [-n+1,n-1]. * if that is non-negative, add 1. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 1 byte ``` § ``` [Try it online!](https://tio.run/##S85ILErOT8z5///Q8v//o6OVEpV0FJSSQESyUqyOgomBQSwA "Charcoal – Try It Online") This is Charcoal's `AtIndex` operator, but as a full program, it automatically accepts array and integer parameter inputs. [Answer] # [Japt](https://github.com/ETHproductions/japt), 2 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) 0-indexed. Input order is irrelevant. ``` gV ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=Z1Y&input=LTQKWzAsMSwyXQ) [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~53~~ ~~32~~ 31 bytes ``` a(b,c,d)int*b;{b=b[(d%c+c)%c];} ``` Thanks to wastl for 31 bytes [Try it online!](https://tio.run/##jY69CsMgEMd3n0ICorYnmGomyZOEDHqhJUNDCd3EZ7dm9ZbCHRy/4/@B5oVYa1QJEDa9H99bCjnNaVGbwDtqgWsotXH@jvuhdGbXHc9zXNw6ZxklyNQWZQnsc7bnUw0C@d8zAOM8qssRuANudQfGHjx64HrgezARCYnxlqDJUmZIHUP6GFLIeKqi1q7FMR1YqT8 "C (gcc) – Try It Online") [Answer] # Javascript, 28 bytes ``` a=>i=>a[(i<0?-i:i)%a.length] ``` [Answer] # [PHP](https://php.net/), 53 bytes ``` function($i,$a){return$a[(($c=count($a))+$i%$c)%$c];} ``` [Try it online!](https://tio.run/##JU7BCsIwDL33K0Kp0LLpzcu64tmr17lDrS0bSFtqC8rct9dMAwmPl/fyEqdY@1OcIiFMp6TfoGCgmrZAb9swdJS4cqq64k2eg@dsbpkWS7K5JM/0wDkzyoTiM0deNGzeMSOwR7lWNLuQAE14eH@UgKBX8ANNI2AhgGXNFICe/d2@uk3xgYt9lkfugMIBmNsy4f@fQIJePZVkrV8 "PHP – Try It Online") * `$i` is the requested index. * `$a` is the array. * `$c` is count of array items. PHP doesn't support negative array indexes to get items from the end (as you can actually have negative indexes in PHP arrays like this: `[-1 => 'X', -2 => 'Y']`). So I'm always returning the array item at this position: `(($i % $c) + $c) % $c` * The above formula for `$i=0` is always 0. * For `$i>0` (positive index) it is same as `$i % $c`, since we add the `$c` to the result once and then get mod of it by `$c` again. For example, for `$c=3` and `$i=5` the resulting position will be 2. * For `$i<0` (negative index) it will get the reversed position as a positive number (which is like getting the position from the end of the array). For example, for `$c=3` and `$i=-5` it will be `((-5%3)+3)%3 = (-2+3)%3 = 1%3 = 1`. If we change `$i` from `-5` to `-6`, the resulting position should be reduced by 1, it will be `((-6%3)+3)%3 = (0+3)%3 = 3%3 = 0` If we change `$i` from `-5` to `-4`, the resulting position should be added by 1, it will be `((-4%3)+3)%3 = (-1+3)%3 = 2%3 = 2` [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 28 bytes ``` a=>b=>b[(a%(a=b.Count)+a)%a] ``` [Try it online!](https://tio.run/##jZHBa4MwFMbv/hUPoZgwXVPXnqxeBtul9x3GDi9pdGm7BDR1h9K/3Wlb1AjCQGL48r3vl/ciqkhUqnk7a7FV2oa3zU5Vdmv4QQqbhY9/lqcNphlvv0@CC4Ipf341Z23pE9IFfjWJVxu1hwpz@S4tkDYNMIRxFnAKF/golZU7pSXJCVLCKU3g6tVYApYlpKDlr1t1gQCDEALeLSKAa@J5DwxhYVfVJiyX4KPf66u7Dkmn80GPx7rwveEydJT6MnahD4UBjuII1oD9lsBlobRWuugL1i4O8HQCU8u2pQKV7m2b/9GZix8ojM20tWHu0Wx2tHJt914gL83PrTWp94M3nqFFk/m4rN61nqAmU2xRk/FEMZslsslLN38 "C# (Visual C# Interactive Compiler) – Try It Online") ]
[Question] [ We've all been burned by the grammar police on the internet. What we need is a regex that can be used in place of "there", "their", and "they're". This would shift burden of grammar parsing from the writer to the reader (a sort of "client-side" grammar, if we you will). So, here's what I have to start with: `the([re]|[ir]|[y're]).` ...but I'm positive there's room for optimization. What's the shortest regex that could be used in place of any variation or the aforementioned homohpones? [Answer] There isn't a lot of room for optimisation here. This seems to be optimal: ``` the(y're|re|ir) ``` The only alternative I can think of avoids the duplication of `re` but ends up at the same byte count (and it's potentially worse in flavours where meta characters need to be escaped to work): ``` the((y')?re|ir) ``` ]
[Question] [ **Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers. --- Questions without an **objective primary winning criterion** are off-topic, as they make it impossible to indisputably decide which entry should win. Closed 9 years ago. [Improve this question](/posts/12355/edit) My challenge is language-specific, but needs a lot of creativity: write a valid C program with only one pair of braces `{}` and none of the keywords `if`, `for`, `while` (all checked after preprocessing, and after substituting trigraphs). I'm looking for preprocessor abuse (but other methods are also welcome) to define a new pseudo-language which supports at least `if`/`else`, then use that language to do something cool. That's pretty easy, and I'll just score this by upvotes since any scoring would be rather arbitrary, but here are some things which would be impressive: * function calls (also arguments, return values); * `else if`; * `switch`/`case` (also `default`, fall-through); * `for` or `while` (super-impressive. Also `break`, `continue`); * having only one semicolon `;` (This one makes the challenge a bit different); * an interesting program; * full portability (portable in practice is good, portable in theory is even better). This isn't about obfuscation. The preprocessor statements will probably be a bit hairy, but the actual code should be very easy to follow. `goto` is allowed, but I believe it won't help much. [Answer] Doesn't seem too hard.... ``` #include <stdio.h> int main(void) { printf("I only used one pair of braces!\n"); printf("This is easy...\n"); printf("Lalalalala\n"); getchar(); return 0; } ``` > > having only one semicolon `;` (This one makes the challenge a bit different); > > > Oh, also easy: ``` int main(void) { return 0; } ``` > > `else if`; > > > How about `goto` and ternary operator abuse? ``` #include <stdio.h> int main(void) { int testNum = 5; void *whichSection = testNum < 0 ? &&ifSection : (testNum == 0 ? &&elseIfSection : &&elseSection); goto *whichSection; ifSection: printf("Number is negative\n"); goto end; elseIfSection: printf("Number is zero\n"); goto end; elseSection: printf("Number is positive and nonzero\n"); goto end; end: return 0; } ``` > > `switch/case` *(kinda)* (also `default` *(kinda)*, fall-through *(yes)*) > > > `for` *(no)* or `while` *(no)* (super-impressive. Also `break` *(yes)*, `continue` *(no)*); > > > My above solution is a bit like that - the `goto` is `break`, the `elseSection` is `default`, fall-through works, etc. > > full portability (portable in practice is good, portable in theory is even better). > > > All of my solutions have this. --- *we code golfers are infamous for bending the rules :D* [Answer] ## No braces Doesn't answer the question, but does answer its title - C without braces ``` main=195; ``` Works on x86 (32bit and 64bit). Does nothing exciting, but starts and terminates without error. [Answer] We can simulate a conditional branch in this manner: ``` int condition = /* insert some condition here, like a == b */ ; void* if_branch[2]; if_branch[1] = &&ifcode; if_branch[0] = &&elsecode; goto if_branch[!!condition]; ifcode: /* code if (condition) is met */ goto afterif; elsecode: /* code if (condition) is not met */ afterif: ``` While convoluted, this shows that you can implement conditional branching without using if statements, ternary statements, or any other form of abuse other than goto pointers. With conditional branching and goto (and all that other good stuff that doesn't require braces like addition, subtraction, etc.), you can build a machine language, and thereby implement all that other stuff that requires braces or "implied" braces, and could (theoretically, anyway) create any C program in this form without using more than one set of braces. ]
[Question] [ # Challenge : Given two non-negative integers `(X and Y > 1)` calculate the sum of digits of their powers . i.e : sum of digits of `X ^ Y` . --- # Input : Two non-negative integers `X` and `Y` --- # Output : The sum of digits of X raised to power Y `X ^ Y`. # Examples : ``` 5 , 2 ---> 7 9 , 4 ---> 18 3 , 17 ---> 27 ``` Both numbers will be greater than 1 --- # Restrictions : This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest code (in bytes) for each language wins. --- # Notes : All input will be valid. i.e : Both inputs will be greater than 1 and will be integers. [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 21 bytes ``` (x,y)->sumdigits(x^y) ``` [Try it online!](https://tio.run/##FcdLCoAgFEbhrfw08sJ10ItoUBsJAykUweLSA3L1VqPzHbFH0F6yw4CsHk6kx/Pe1uDDdapnTpStSExKoEfIEfbrY/FPgcXGqBxDiBjT1DIq86FnNH9rRtkZQ/kF "Pari/GP – Try It Online") [Answer] # C, ~~60~~ 56 Bytes This is my first time golfing, and I think this code can be shortened. Feel free to help and improve this. Edit: Does not work when you give it a and b such that a^b is over 2^31. 4 Bytes saved thanks to Dennis. ``` i,q;f(a,b){for(i=0,q=pow(a,b);q;q/=10)i+=q%10;return i;} ``` [test it by editing the numbers in the printf](https://ideone.com/mTxbHR) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 3 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) Jelly trivialises this task ``` *DS ``` A dyadic link accepting a positive integer, X, on the left and a positive integer, Y, on the right which returns the resulting positive integer. **[Try it online!](https://tio.run/##y0rNyan8/1/LJfj////G/w3NAQ "Jelly – Try It Online")** ### How? ``` *DS - Link: X, Y * - exponentiate X to the Y D - to a list of its digits S - sum ``` [Answer] # [Python 3](https://docs.python.org/3/), 34 bytes ``` lambda a,b:sum(map(int,str(a**b))) ``` [Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSFRJ8mquDRXIzexQCMzr0SnuKRII1FLK0lTU/N/QRFQRCNNw1THSFOTC8az1DFB4hnrGJoDlQIA "Python 3 – Try It Online") [Answer] # APL+WIN, 8 bytes Prompts for y followed by x: ``` +/⍎¨⍕⎕*⎕ ``` [Answer] # [Neim](https://github.com/okx-code/Neim), 2 bytes ``` 𝕎𝐬 ``` Power `𝕎`; implicitly coerce to list; sum `𝐬` [Try it online!](https://tio.run/##y0vNzP3//8PcqX0f5k5Y8/@/EZcpAA "Neim – Try It Online") [Answer] # [Funky](https://github.com/TehFlaminTaco/Funky), 31 bytes ``` a=>b=>{n=0fors in''..a^b n-=-s} ``` [Try it online!](https://tio.run/##SyvNy678n2b7P9HWLsnWrjrP1iAtv6hYITNPXV1PLzEuSSFP11a3uPZ/QVFmXolGmoalpoaJpuZ/AA "Funky – Try It Online") [Answer] # [J](http://jsoftware.com/), 12 bytes 11 bytes -1 byte thanks to Cows quack ``` 1#.,.&.":@^ ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/DZX1dPTU9JSsHOL@a3IpcKUmZ@QrmCqkKRhBmJZApgmEaQxkGppX/AcA "J – Try It Online") `^` power `,.&.":` convert to list of digits `1#.` add up the digits [Answer] # [Haskell](https://www.haskell.org/), ~~29~~ 28 bytes ``` x%y=sum[read[d]|d<-show$x^y] ``` [Try it online!](https://tio.run/##FctBC8IgGAbge7/iPTgoyCA6BMPtslPnjmIgKNto6tAvptB/t3V/nkmnt12WWnNTuvRxMlptpFFfI3iawsbyq6jq9OzRwYQDIPMZRUFwOL3i@PdoWzwpzn4E7/HwdMIFW4gmQbAeo6UheLKe0v7X3REYMhqUesP1/gM "Haskell – Try It Online") -1 byte thanks to user9549915 [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 6 bytes ``` IΣIXNN ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEI7g0F8IIyC9PLdLwzCsoLfErzU0CsjV1FFC4YGD9/78ll8l/3bIcAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` N First input as a number N Second input as a number X Power I Cast to string Σ Sum of digits I Cast to string Implicitly print ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 5 bytes Saved 1 byte thanks to @Shagy ``` pV ìx ``` [Try it online!](https://tio.run/##y0osKPn/vyBM4fCaiv//LXVMAA) [Answer] # Pyth, 6 bytes ``` ssM`^F ``` [Try it online!](http://pyth.herokuapp.com/?code=ssM%60%5EF&input=2%0A5&test_suite=1&test_suite_input=%5B5%2C2%5D%0A%5B9%2C4%5D%0A%5B3%2C17%5D&debug=0) If the list input isn't allowed, you can just replace the `F` with `E` and it'll take in two integers (one on each line) but do the operation in reverse order from input order. [Answer] # [Ruby](https://www.ruby-lang.org/), 24 bytes ``` ->x,y{(x**y).digits.sum} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf165Cp7Jao0JLq1JTLyUzPbOkWK@4NLf2f4FCWrSpjlEsF4hhqWMCYRjrGJrH/gcA "Ruby – Try It Online") [Answer] # [JavaScript (Node.js)](https://nodejs.org), 36 bytes ``` X=>g=(Y,d=X**Y)=>d&&d%10+g(Y,d/10|0) ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/C1i7dViNSJ8U2QksrUtPWLkVNLUXV0EA7HSSob2hQY6D5Pzk/rzg/J1UvJz9dI03DVFPDSFOTC1XQUlPDBEPQWFPD0FxT8z8A "JavaScript (Node.js) – Try It Online") [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 16 bytes ``` (* ***).comb.sum ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPtfQ0tBS0tLUy85PzdJr7g09781F1dxYqVCmoapgo6CkaY1lGcJ5JnAecZAnqG5pvV/AA "Perl 6 – Try It Online") [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~37~~ 32 bytes -5 bytes thanks to @Shaggy. ``` X=>Y=>eval([...''+X**Y].join`+`) ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/C1i7S1i61LDFHI1pPT09dXTtCSysyVi8rPzMvQTtB839yfl5xfk6qXk5@ukaahqmmhpGmJheqoKWmhgmGoLGmhqG5puZ/AA "JavaScript (Node.js) – Try It Online") # Explanation : ``` X => // First input X Y => // second input Y eval( // evaluate [...''+ // convert what is next to string and map to array X**Y]. // X raised to power Y join`+` // join them into a string with a plus sign between each ) // The whole thing gets evaluated using `eval` ``` --- [Answer] # [Gol><>](https://github.com/Sp3000/Golfish), 11 bytes ``` XWaSD}|lR+B ``` [Try it online!](https://tio.run/##S8/PScsszvhv6Ohu7Obp6e5XY/0/Ijwx2KW2JidI2@n/f1MFIy5LBRMuYwVDcwA "Gol><> – Try It Online") A function that accepts X and Y on the stack and leaves the result as the only value on the stack. ### Example full program & How it works ``` 1AGIE;IGN XWaSD}|lR+B 1AG Register row 1 as function G IE; Take input X as int; halt if EOF I Take input Y as int GN Call G with stack [X Y] and print the result as int Repeat indefinitely X n = X**Y W | While top is nonzero... aSD Pop n, push n / 10 and n % 10 } Move the remainder to the bottom Now the stack contains the digits lR+ Sum everything B Return ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), 4 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ║▼δ& ``` [Run and debug it](https://staxlang.xyz/#p=ba1feb26&i=5+2&a=1) Unpacked: ``` |*E|+ ``` [Run and debug this one](https://staxlang.xyz/#c=%7C*E%7C%2B&i=5+2&a=1) Explanation: ``` |*E|+ Full program, implicit input Stack: 5 2 |* Power Stack: 25 E Decimal digits Stack: [ 2, 5 ] |+ Sum array Stack: 7 Implicit output ``` [Answer] ## PHP, 44 Bytes No loop, passing both arguments to the script. [Try it Online](https://tio.run/##K8go@G9jX5BRwKWSWJReZhttrGNoHmvNZW8HFLZNLCpKrIwvLs3VKC4pii8uyMks0QCrizaI1dKCsAxjNTWt//8HAA) **Code** ``` <?=array_sum(str_split($argv[0]**$argv[1])); ``` This just takes both arguments calculates `X to the power of Y`, explodes the string into an array and adds each digit [Answer] # [Husk](https://github.com/barbuz/Husk), 3 bytes ``` Σd^ ``` [Try it online!](https://tio.run/##yygtzv7//9zilLj///8bmv83BgA "Husk – Try It Online") Takes `Y` followed by `X`. ]
[Question] [ **Closed**. This question needs to be more [focused](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Update the question so it focuses on one problem only by [editing this post](/posts/22054/edit). Closed 9 years ago. [Improve this question](/posts/22054/edit) In this challenge, you get to create a language. Although you have to provide code in other languages, you will only be rated based on the language. Here are the requirements. 1. You must invent a programming language that is Turing complete. 2. You will choose a real (as in existed before this question did) language. It must be a different paradigm then the made up language. 3. You will write a boot strapping compiler. This means you write a program in your new language, that will take code in your new language, and translate it to code in your real language. 4. So people can run it initially, you will provide an interpreter (or compiler) in a real language (which may or may not be written the real language you choose above) to run programs in the new language. This does not need to be golfed. Note: Your language can't have builtin functions for generating code in the real language. This basically means that if the real language were proprietary, your language wouldn't violate its copyright by making it to easy to generate its code. Scoring: Your score is the size of your compiler. Your will find your programs' sizes using `roundup(s*log_2(a))` where s is the number of characters in your program and a is the number of available characters in your language (meaning huge penalties if you use Chinese characters or something.) Tip: String characters count too, so if you are looking to really shrink how many characters are available, you will need to find a way to represent strings with few characters. Smallest score wins! So in summary, you invent a turing-complete language X. Then you implement an interpreter or compiler for it in Y. Finally, you implement a compiler for X in X itself. (Based on a comment from Victor.) [Answer] ## Brainfuckoff -> Javascript, 527 characters, 3463 points My language, Brainfuckoff is a brainfuck-derived language with the following changes: * It has a new instruction `*` which sends everything in input to the output, until the end-of-input is reached. * It has a new instruction `^` which sends everything following this and before the following backtick to the output. * It takes a line of the input at a single shot in the start of the program, consuming each char with the `,` instruction. So, here is a partially-golfed javascript compiler for my language: ``` function bfg(j){ w=String.fromCharCode; r='(function(n){m=[];p=0;c=0;t=n.substring(0,0);'; for(x=0;x<j.length;x++){ q=j.charCodeAt(x); if(q==91)r+='while(~~m[p]){'; if(q==93)r+='}'; if(q==62)r+='p++;'; if(q==60)r+='p--;'; if(q==43)r+='m[p]=1+~~m[p];'; if(q==45)r+='m[p]=-1+~~m[p];'; if(q==46)r+='t+=String.fromCharCode(~~m[p]);'; if(q==44)r+='if(c<n.length)m[p]=n.charAt(c++);'; if(q==94){z=j.indexOf(w(96),x+1);r+='t+='+w(34)+j.substring(x+1,z)+w(34)+';';x=z} if(q==42)r+='t+=n.substring(c);c=n.length;' } return r+'return t})' } ``` Here is a brainfuck Hello World program: ``` ++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++. ``` Compiling it: ``` program = '++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.'; jsprogram = bfg(program); alert(jsprogram); ``` The output: ``` (function(n){m=[];p=0;c=0;t=n.substring(0,0);m[p]=1+~~m[p];m[p]=1+~~m[p];m[p]=1+~~m[p];m[p]=1+~~m[p];m[p]=1+~~m[p];m[p]=1+~~m[p];m[p]=1+~~m[p];m[p]=1+~~m[p];while(~~m[p]){p++;m[p]=1+~~m[p];m[p]=1+~~m[p];m[p]=1+~~m[p];m[p]=1+~~m[p];while(~~m[p]){p++;m[p]=1+~~m[p];m[p]=1+~~m[p];p++;m[p]=1+~~m[p];m[p]=1+~~m[p];m[p]=1+~~m[p];p++;m[p]=1+~~m[p];m[p]=1+~~m[p];m[p]=1+~~m[p];p++;m[p]=1+~~m[p];p--;p--;p--;p--;m[p]=-1+~~m[p];}p++;m[p]=1+~~m[p];p++;m[p]=1+~~m[p];p++;m[p]=-1+~~m[p];p++;p++;m[p]=1+~~m[p];while(~~m[p]){p--;}p--;m[p]=-1+~~m[p];}p++;p++;t+=String.fromCharCode(~~m[p]);p++;m[p]=-1+~~m[p];m[p]=-1+~~m[p];m[p]=-1+~~m[p];t+=String.fromCharCode(~~m[p]);m[p]=1+~~m[p];m[p]=1+~~m[p];m[p]=1+~~m[p];m[p]=1+~~m[p];m[p]=1+~~m[p];m[p]=1+~~m[p];m[p]=1+~~m[p];t+=String.fromCharCode(~~m[p]);t+=String.fromCharCode(~~m[p]);m[p]=1+~~m[p];m[p]=1+~~m[p];m[p]=1+~~m[p];t+=String.fromCharCode(~~m[p]);p++;p++;t+=String.fromCharCode(~~m[p]);p--;m[p]=-1+~~m[p];t+=String.fromCharCode(~~m[p]);p--;t+=String.fromCharCode(~~m[p]);m[p]=1+~~m[p];m[p]=1+~~m[p];m[p]=1+~~m[p];t+=String.fromCharCode(~~m[p]);m[p]=-1+~~m[p];m[p]=-1+~~m[p];m[p]=-1+~~m[p];m[p]=-1+~~m[p];m[p]=-1+~~m[p];m[p]=-1+~~m[p];t+=String.fromCharCode(~~m[p]);m[p]=-1+~~m[p];m[p]=-1+~~m[p];m[p]=-1+~~m[p];m[p]=-1+~~m[p];m[p]=-1+~~m[p];m[p]=-1+~~m[p];m[p]=-1+~~m[p];m[p]=-1+~~m[p];t+=String.fromCharCode(~~m[p]);p++;p++;m[p]=1+~~m[p];t+=String.fromCharCode(~~m[p]);p++;m[p]=1+~~m[p];m[p]=1+~~m[p];t+=String.fromCharCode(~~m[p]);return t}) ``` Running that: ``` program = '++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.'; input = ''; jsprogram = bfg(program); alert(eval(jsprogram)(input)); ``` The output: ``` Hello World! ``` This other brainfuckoff's Hello World is simpler: ``` program = '^Hello World!`' input = ''; jsprogram = bfg(program); alert(eval(jsprogram)(input)); ``` The output: ``` Hello World! ``` Great, now a compiler of brainfuckoff to javascript written in brainfuckoff (527 characters): ``` ^(function(j){w=String.fromCharCode;r='(function(n){m=[];p=0;c=0;t=n.substring(0,0);';for(x=0;x<j.length;x++){q=j.charCodeAt(x);if(q==91)r+='while(~~m[p]){';if(q==93)r+='}';if(q==62)r+='p++;';if(q==60)r+='p--;';if(q==43)r+='m[p]=1+~~m[p];';if(q==45)r+='m[p]=-1+~~m[p];';if(q==46)r+='t+=String.fromCharCode(~~m[p]);'; if(q==44)r+='if(c<n.length)m[p]=n.charAt(c++);';if(q==94){z=j.indexOf(w(96),x+1);r+='t+='+w(34)+j.substring(x+1,z)+w(34)+';';x=z}if(q==42)r+='t+=n.substring(c);c=n.length;'}return eval(r+'return t})')})('`*^')` ``` Compiling the compiler: ``` program = "^(function(j){w=String.fromCharCode;r='(function(n){m=[];p=0;c=0;t=n.substring(0,0);';for(x=0;x<j.length;x++){q=j.charCodeAt(x);if(q==91)r+='while(~~m[p]){';if(q==93)r+='}';if(q==62)r+='p++;';if(q==60)r+='p--;';if(q==43)r+='m[p]=1+~~m[p];';if(q==45)r+='m[p]=-1+~~m[p];';if(q==46)r+='t+=String.fromCharCode(~~m[p]);'; if(q==44)r+='if(c<n.length)m[p]=n.charAt(c++);';if(q==94){z=j.indexOf(w(96),x+1);r+='t+='+w(34)+j.substring(x+1,z)+w(34)+';';x=z}if(q==42)r+='t+=n.substring(c);c=n.length;'}return eval(r+'return t})')})('`*^')`"; jsprogram = bfg(program); alert(jsprogram); ``` The compiled compiler: ``` (function(n){m=[];p=0;c=0;t=n.substring(0,0);t+="(function(j){w=String.fromCharCode;r='(function(n){m=[];p=0;c=0;t=n.substring(0,0);';for(x=0;x<j.length;x++){q=j.charCodeAt(x);if(q==91)r+='while(~~m[p]){';if(q==93)r+='}';if(q==62)r+='p++;';if(q==60)r+='p--;';if(q==43)r+='m[p]=1+~~m[p];';if(q==45)r+='m[p]=-1+~~m[p];';if(q==46)r+='t+=String.fromCharCode(~~m[p]);'; if(q==44)r+='if(c<n.length)m[p]=n.charAt(c++);';if(q==94){z=j.indexOf(w(96),x+1);r+='t+='+w(34)+j.substring(x+1,z)+w(34)+';';x=z}if(q==42)r+='t+=n.substring(c);c=n.length;'}return eval(r+'return t})')})('";t+=n.substring(c);c=n.length;t+="')";return t}) ``` Running the compiled compiler to compile the first Hello World: ``` program1 = "^(function(j){w=String.fromCharCode;r='(function(n){m=[];p=0;c=0;t=n.substring(0,0);';for(x=0;x<j.length;x++){q=j.charCodeAt(x);if(q==91)r+='while(~~m[p]){';if(q==93)r+='}';if(q==62)r+='p++;';if(q==60)r+='p--;';if(q==43)r+='m[p]=1+~~m[p];';if(q==45)r+='m[p]=-1+~~m[p];';if(q==46)r+='t+=String.fromCharCode(~~m[p]);'; if(q==44)r+='if(c<n.length)m[p]=n.charAt(c++);';if(q==94){z=j.indexOf(w(96),x+1);r+='t+='+w(34)+j.substring(x+1,z)+w(34)+';';x=z}if(q==42)r+='t+=n.substring(c);c=n.length;'}return eval(r+'return t})')})('`*^')`"; jsprogram1 = bfg(program1); input1 = '++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.' jsprogram2 = eval(jsprogram1)(input1); input2 = ''; alert(eval(jsprogram2)(input2)); ``` The output: ``` Hello World! ``` Calculating the score: ``` roundup(527 * log_2(asciiCharOf('~') - asciiCharOf(' ') + 1)) roundup(527 * log_2(126 - 32 + 1)) roundup(527 * log_2(95)) roundup(527 * 6.5698556083309478416638388523962) roundup(3462.3139055904095125568430752128) 3463 ``` Note: There are indeed some ways to reduce the size of the interpreter in maybe ~20%. But this was already hard enough to do for me. [Answer] ## Score = (Number too long for an SE post \* log\_2(1)) = 0 Given how the score is weighted by the number of characters available in the language, the less the better: **1.)** My language (X) is called Compressed Unary. It is similar to [Unary](http://esolangs.org/wiki/Unary) in that it only has one available character in the language. Unlike Unary, it uses the number "1" instead of "0". It improves on Unary by assigning the operators in a different bit order, with lower values assigned to operations that occur more often. It is proven to be Turing complete in that it can be trivially converted to Brainfuck. The code is a string of 1s, and the length of the code determines the logic (see the description of Unary from the link above for more details. The encoding is as follows: ``` Brainfuck Binary + (1000) - (1001) > (1010) < (1011) . (1100) , (1101) [ (1110) ] (1111) ``` All the binary is combined from left to right and the resulting number is how many "1"s should be in the source code. This should yield much smaller code that Unary, but will absolutely suck as a golfing language. Much better for code bowling (see the compiler below and you'll see why). **2.)** I chose C#. It was easy, I could port an existing BF implementation ([props to the original author](http://sharpecoding.com/projects/random-fun/brainfuck-interpreter/)), and given that log\_2(1) is zero, the length of the code doesn't have any effect my score. **3.)** The source code is too long to include here (stupid 30k character limit), in fact the number is too long to post here (it is 123411 characters in hex notation). The following [link](http://pastebin.com/1KSdmSGB) will give you the number in hex. You can create the bootstrap compiler simply by typing that many ones in a text file. Like I said, this completely sucks as a golfing language. It's much worse than C# for golfing. **4.)** Once you type out the source code (I'd include a download link, but it would take *way too long* even on a fast fiber connection), you can run it through the following interpreter: ``` using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Numerics; using System.Text; namespace CompressedUnary { class Program { static void Main(string[] args) { BigInteger code = new BigInteger(0); int next = 0; try { using (FileStream source = new FileStream(args[0], FileMode.Open, FileAccess.Read)) { next = source.ReadByte(); while (next != -1) { if (next != 49) { System.Console.WriteLine("Syntax error."); break; } code += 1; next = source.ReadByte(); } } } catch (FileNotFoundException oops) { Console.WriteLine(oops.Message); } if (next == -1) { string processed = PreProcess(code); Interpreter runner = new Interpreter(Console.OpenStandardInput(), Console.OpenStandardOutput()); runner.Run(processed); } Console.WriteLine("Done"); } static string PreProcess(BigInteger input) { StringBuilder output = new StringBuilder(""); BigInteger current; while (input > 0) { BigInteger.DivRem(input, 16, out current); switch ((int)current) { case 0: output.Append("+"); break; case 1: output.Append("-"); break; case 2: output.Append(">"); break; case 3: output.Append("<"); break; case 4: output.Append("."); break; case 5: output.Append(","); break; case 6: output.Append("["); break; case 7: output.Append("]"); break; } } return output.ToString(); } enum ILCode : byte { NextCell = (byte)'>', LastCell = (byte)'<', Increment = (byte)'+', Decrement = (byte)'-', Output = (byte)'.', Input = (byte)',', BeginLoop = (byte)'[', EndLoop = (byte)']' } class Machine { public int pointer = 0; private int cell = 0; private readonly byte[] cells; private readonly Stack<int> stack = new Stack<int>(); public Machine(int memory) { cells = new byte[memory]; } public byte CurrentCell { get { return cells[cell]; } set { cells[cell] = value; } } public void Increment() { if (CurrentCell == 255) CurrentCell = 0; else CurrentCell++; pointer++; } public void Decrement() { if (CurrentCell == 0) CurrentCell = 255; else CurrentCell--; pointer++; } public void NextCell() { cell++; pointer++; } public void LastCell() { cell--; pointer++; } public void BeginLoop() { stack.Push(pointer); pointer++; } public void EndLoop() { if (CurrentCell == 0) pointer++; else pointer = stack.Pop(); } } class Interpreter { private readonly Stream output; private readonly StreamReader reader; private readonly Dictionary<byte, Action> actions; private readonly Machine machine; public Interpreter(Stream ioin, Stream ioout, int memorySize = 30000) { output = ioout; reader = new StreamReader(ioin); machine = new Machine(memorySize); actions = new Dictionary<byte, Action> { {(byte) ILCode.BeginLoop, machine.BeginLoop}, {(byte) ILCode.EndLoop, machine.EndLoop}, {(byte) ILCode.Increment, machine.Increment}, {(byte) ILCode.Decrement, machine.Decrement}, {(byte) ILCode.NextCell, machine.NextCell}, {(byte) ILCode.LastCell, machine.LastCell}, {(byte) ILCode.Input, InputCurrentByte}, {(byte) ILCode.Output, OutputCurrentByte}, }; } public void Run(string program) { byte[] instructions = program.Select(c => (byte)c).Where(b => actions.ContainsKey(b)).ToArray(); while (machine.pointer < instructions.Length) { Action action = actions[instructions[machine.pointer]]; action.Invoke(); } byte[] newLine = Environment.NewLine.Select(c => (byte)c).ToArray(); output.Write(newLine, 0, newLine.Length); } private void InputCurrentByte() { byte next = (byte)reader.Read(); machine.CurrentCell = next; machine.pointer++; } private void OutputCurrentByte() { output.WriteByte(machine.CurrentCell); machine.pointer++; } } } } ``` **FORE!** ]
[Question] [ This time I will give you an easy challenge: Print the [Om](https://en.wikipedia.org/wiki/Om) sign with \$\pi\$!(Sorry for many challenges with \$\pi\$) Here is the om sign drawn using pi numbers: ``` 59 0 64 230781 3.14159 26 502884 535 83279 1971 89 433 6939 79 44 937 323 749 510 84 58209 626 ``` ### Here is the sequence I used to order the numbers of \$\pi\$: [![om sign](https://i.stack.imgur.com/Ove4p.png)](https://i.stack.imgur.com/Ove4p.png) # Rules * There will be no input(except it has to be) * The program should print the sign to STDOUT * Its's [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins! * You must include all the spaces and line breaks in the original text. Good luck [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 91 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` •Eó£ƵZ₃|ã xWм7qèý`ÚA¿нÏ9,ÖcPÇŸ›ÎŸt¤,,ûUŨù—¤ï`ÿ¾ζ@η@••7¼P•в•pÏ{ʒÂfƨ¿ZF•15вú•DŠ\•4в£»31DT/: ``` [Try it online.](https://tio.run/##AaQAW/9vc2FiaWX//@KAokXDs8KjxrVa4oKDfMOjCnhX0Lw3ccOow71gw5pBwr/QvcOPOSzDlmNQw4fFuOKAusOOxbh0wqQsLMO7VcOFwqjDueKAlMKkw69gw7/Cvs62QM63QOKAouKAojfCvFDigKLQsuKAonDDj3vKksOCZsSGwqjCv1pG4oCiMTXQssO64oCiRMWgXOKAojTQssKjwrszMURULzr//w) **Explanation:** ``` •Eó£ƵZ₃|ã xWм7qèý`ÚA¿нÏ9,ÖcPÇŸ›ÎŸt¤,,ûUŨù—¤ï`ÿ¾ζ@η@• # Push compressed integer 31746388586852694571167828992290814184914816000404856451284780420784056983357043462437313025051647834765116670748406087616 •7¼P• # Push compressed integer 502885 в # Convert the larger integer to base-502885 as list: # [59,0,64,230781,314159,26,502884,535,83279,1971,89,433,6939,79,44,937,323,749,510,84,58209,626] •pÏ{ʒÂfƨ¿ZF• # Push compressed integer 60230047425392376760356855 15в # Convert it to base-15 as list: # [12,1,1,14,0,6,5,5,0,4,3,0,13,7,3,8,7,3,4,4,11,0] ú # Pad the integers in the first list with leading spaces, # where the amount of spaces is that of the second list at the same indices: # [" 59"," 0"," 64"," 230781","314159"," 26"," 502884"," 535","83279"," 1971"," 89","433"," 6939"," 79"," 44"," 937"," 323"," 749"," 510"," 84"," 58209","626"] •DŠ\• # Push compressed integer 880633 4в # Convert it to base-4 as list: [3,1,1,2,3,3,3,3,2,1] £ # Split the list of strings into parts of that size: # [[" 59"," 0"," 64"],[" 230781"],["314159"],[" 26"," 502884"],[" 535","83279"," 1971"],[" 89","433"," 6939"],[" 79"," 44"," 937"],[" 323"," 749"," 510"],[" 84"," 58209"],["626"]] » # Join each inner list by spaces, and then each string by newlines 31 # Push 31 D # Duplicate it T/ # Divide the copy by 10: 3.1 : # Replace the "31" with "3.1" in the string # (after which the result is output implicitly) ``` Note that all the leading spaces (except for the first integers in the line) are decreased by 1 because the `»` joins by spaces. [See this 05AB1E tip of mine (section *How to compress large integers?* and *How to compress integer lists?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand how the compressed parts works. --- Since I was curious, I also made a program using the actual PI-digits and drawing them in the specified pattern one by one using the Canvas builtin `Λ`. Which surprisingly enough is not that much larger (**97 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)**): ``` 2žs•3]]\´ë:O•23в£J•ΘüÁи‘•11в0šúS•2q₄Beçq̧ßI/ÖÅ?¨L×Σ₃ÛuÌÎvêmtTYx¡n‡¢lΛf4ÙI₁¿çÑv•9в.Λ46Â:„ 4„3..; ``` [Try it online.](https://tio.run/##yy9OTMpM/f/f6Oi@4kcNi4xjY2MObTm82sofyDEyvrDp0GIvIOvcjMN7Djde2PGoYQaQZ2h4YZPB0YWHdwWDFBU@ampxSj28vPBwz@GmQ8sPz/fUPzztcKv9oRU@h6efW/yoqfnw7FKgXF/Z4VW5JSGRFYcW5j1qWHhoUc652Wkmh2d6PmpqPLT/8PLDE8uAxlle2KR3braJ2eEmq0cN8xRMgISxnp71//8A) **Explanation:** ``` 2 # Push a 2 žs # Push an infinite list of PI digits: [3,1,4,1,5,...] •3]]\´ë:O• # Push compressed integer 243177533433411924 23в # Convert it to base-23 as list: [11,2,5,2,3,22,3,3,5,3,2,10,1] £ # Split the PI-digits into parts of that size J # Join each inner list of digits together: # [31415926535,89,79323,84,626,4338327950288419716939,937,510,58209,749,44,5923078164,0] •ΘüÁи‘• # Push compressed integer 342434478685 11в # Convert it to base-11 as list: [1,2,2,2,5,3,3,7,7,1,10,2] 0š # Prepend a 0: [0,1,2,2,2,5,3,3,7,7,1,10,2] ú # Pad the strings with that many leading spaces to the integers: # ["31415926535"," 89"," 79323"," 84"," 626"," 4338327950288419716939"," 937"," 510"," 58209"," 749"," 44"," 5923078164"," 0"] S # And convert it to a flattened list of characters •2q₄Beçq̧ßI/ÖÅ?¨L×Σ₃ÛuÌÎvêmtTYx¡n‡¢lΛf4ÙI₁¿çÑv• # Push compressed integer 1107440116348129217561550864085059321059233554362962027078200378907904337318203317830295973758995759889862300097 9в # Convert it to base-9 as list: # [2,2,2,2,2,4,2,4,6,6,6,5,2,2,3,2,2,3,6,6,6,6,5,2,5,6,6,6,6,1,1,1,2,1,2,2,2,1,2,2,2,2,1,2,2,2,2,2,4,2,2,2,3,2,2,2,5,6,6,2,2,2,5,6,6,6,2,2,5,6,6,6,6,6,2,6,2,2,2,2,7,6,6,6,6,6,6,6,2,2,7,6,6,8,1,1,2,2,2,2,2,2,2,2,2,2,3,2,2,2,2,2,1,6,6,6,6] .Λ # Use the Canvas builtin with these three lists, where # - the 2 is the length of each line # - the list ["3","1","4",...," "," ","0"] are the characters to draw # - the list [2,2,2,...,6,6,6] are the directions 46 # Push 46  # Bifurcate it (short for Duplicate & Reverse copy): 64 : # Replace the 46 with 64 in the string „ 4„3..; # Replace the first " 4" with "3." # (after which the result is output implicitly) ``` [See this 05AB1E tip of mine (section *How to compress large integers?* and *How to compress integer lists?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand how the compressed parts works. So we use the following options for the Canvas builtin: * \$a\$ length: `2` (all lines are of size 2; or basically 1 since they're overlapping previous lines) * \$b\$ the characters we want to display, which are the digits of PI with the spaces we added to travel around * \$c\$ the directions, where `8` is a reset to the origin where we started, and the other directions are: ``` 7 0 1 ↖ ↑ ↗ 6 ← X → 2 ↙ ↓ ↘ 5 4 3 ``` Here some of the first steps: ``` char: 3; direction: 2→ 3 char: 1; direction: 2→ 31 char: 4; direction: 2→ 314 char: 1; direction: 2→ 3141 char: 5; direction: 2→ 31415 char: 9; direction: 2→ 314159 char: 2; direction: 4↓ 314159 2 char: 6; direction: 2→ 314159 26 char: 5; direction: 4↓ 314159 26 5 char: 3; direction: 6← 314159 26 35 char: 5; direction: 6← 314159 26 535 char: space; direction: 6← 314159 26 535 char: 8; direction: 5↙ 314159 26 535 8 char: 9; direction: 2→ 314159 26 535 89 etc. ``` Also note how I take advantage of the palindromized part `535` here so I'm able to draw those digits backwards. With most other digit-substrings I have to first go to the correct position with spaces before drawing the actual digits in direction `2→`. I use this same palindroized approach also for the digit-substrings `323` and `626`. The reason the first `3` of the PI-digits is replaced with a `4` is because we use a length of 2 (since lines are overlapping), which causes a minor issue in this case when we reset to the origin location with 'direction' `8`. Since we had to insert the dot anyway this doesn't really matter too much. The `46` to `64` is because we couldn't move around to the next section with spaces like we did with all the other digits for the final `0`, since it's encapsulated inside other digits and we can't reach it. [See this 05AB1E tip of mine](https://codegolf.stackexchange.com/a/175520/52210) for an in-depth explanation of how the Canvas builtin works. [Answer] # JavaScript (ES8), ~~156 152~~ 151 bytes ``` _=>`Qk2 SH 2755Q 1C.4USW Bq4SGG6 6LxSK4xOC5 13n5Ch2DOE ZbJoBKP 3Zr990 6AS 11gJYN0 7Q8`.replace(/[0-Z]+\w?/g,s=>''.padEnd((n=parseInt(s,36))%16)+(n>>4)) ``` [Try it online!](https://tio.run/##DcjLjoIwFADQ/f0KNxPbKEh5FF2AGRnjiEYljTGiRitU5kFapEb9e/Qszx@/c53Vv9XNkCoXzSVojkF4Sv7tFvsG2/e8BEhkumu2gdHVZZMJBTp/spn7XEYeEEd60Y/9tRxDeo7VaLYCJ60HA6tFPxkQUsTbhQV@0j@ZtahKngnU21lGeujsH8Ne0dVB2G6bFc/HMkdIBhWvtZjKG9Jdh2L8QSjuIBmGLsZNpqRWpTBLVaALescL "JavaScript (Node.js) – Try It Online") ### How? A group of \$k\$ spaces followed by a number \$N\$ is encoded as \$16N+k\$ in base 36 and upper case. *Example:* ``` " 59" -> 16 * 59 + 12 = 956 -> "QK" ``` The following rules apply to separate a string from the next one: * If it's followed by a line-feed or a period, we leave it as-is. * If it ends with a letter, we put it in lower case. * Otherwise, we use one of the spaces that should have been encoded in the next group as a separator. As a result, all strings can be unambiguously matched with `/[0-Z]+\w?/`. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 111 bytes ``` •DIÿ₅εïΩǝ>Î*.}Öδµ¼ËüúMeĀ¡ζ¿†)в¡Óa×CÁØÒвÕï#â’“¡TÞm×a¿ǝ¬=ß/L@&„@’…ë¼ïæW5éÓ#c∞ðbΣh¬Á‚q”›?иøç,G$X•12B'§Åu„ ‡31DT/: ``` [Try it online!](https://tio.run/##AckANv9vc2FiaWX//@KAokRJw7/igoXOtcOvzqnHnT7DjioufcOWzrTCtcK8w4vDvMO6TWXEgMKhzrbCv@KAoCnQssKhw5Nhw5dDw4HDmMOS0LLDlcOvI8Oi4oCZ4oCcwqFUw55tw5dhwr/HncKsPcOfL0xAJuKAnkDigJnigKbDq8K8w6/Dplc1w6nDkyNj4oiew7BizqNowqzDgeKAmnHigJ3igLo/0LjDuMOnLEckWOKAojEyQifCp8OFdeKAniAK4oChMzFEVC86//8 "05AB1E – Try It Online") ``` •...•12B'§Åu„ \n‡31DT/: # trimmed program : # replace... 31 # literal... : # with... 31 # literal... D / # divided by... T # 10... : # in... ‡ # replaced each character of... '§Å # "ab"... u # in uppercase... ‡ # with corresponding character of... „ \n # literal (\n is newline)... ‡ # in... •...• # 12929493392715033775373083693785395621840635578238991913835355382477224495770768407855388223047936086665789536281935915002520324655471900188866985320315060383798192979161318650352714212687144153060399193782953565620356798... B # converted to base... 12 # literal # implicit output ``` [Answer] # [///](https://esolangs.org/wiki////), 147 bytes ``` /a/ //b/ 5/a b9 0 64 aaa 230781 3.14159 a 26 b02884 b35 83279a 1971 89 433aaa 6939 a 79a44aa 937 a 323a749b10 a84a b8209 626 ``` [Try it online!](https://tio.run/##HY07DoMxCIN3TuETNOHxJ3AcIlXq0C33V0rDYOQPLO9v7s97n9Oyoaa1dTeelqUrgA4Mo8zyon06k77Y@An6k4HVxd1o6QNXmZHgmEyV9oCp3uQIvf@ou1mR0Hm9iua0WNwp3W6nSw8aMs75AQ "/// – Try It Online") [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 122 bytes ``` l59b0b64¶n230781¶3.14159¶f26f502884¶e535a83279e1971¶c89a433n6939¶g79d44i937¶g323d749e510¶d84l58209¶626 {`[a-z] $& T`l`_l ``` [Try it online!](https://tio.run/##Dco9DgIhEEDhnlNYGDsNzA/M3MPOGGGFNZuQLYyV3osDcDGke8n73uWz7WkMU1kXu3jqbQe0QVxveHHkWHtbwa9sQWTewshJEIIWp2Gqp2gixN0rTvoKmok2xTAbAXMgLexsb1mosoCdyIM3v3hL5@/dHI4nc401PuoYfw "Retina 0.8.2 – Try It Online") Uses letters to run-length encode spaces. (The `a`s could be spaces but I couldn't be bothered to special-case them in the [encoder](https://tio.run/##VY6xDsIwDET3fIXHVggUx05iS1T9iW6Amg4MSBVD1YmfD5C2iN5293wnT/f58Rxy7hKkwRymLvVjGlPVnpsr1tVlOL5utek@UZ@KqdpmCXOGP3kFsACBDezkyEZBQydk9LpCF9aSdSJrw5MHIRe1ONSI31wUmGg/GZS2IVjOmX9QKW6MXClGXiY92kKEd3@Ls2qCC28 "Retina 0.8.2 – Try It Online").) [Answer] # [Perl](https://www.perl.org/) + `-p`, 117 bytes This program contains unprintables so the TIO link is to a Bash program that loads the program from a reversible hex dump. ``` }{s// u0z Q0�1 3.HI9 TlV� o5�U9M� �e3a �f �7 Z3�9m0 � tN9 x6/;s/[^\d .]/15>($x=ord$&)?$"x$x:$x-58/ge ``` [Try it online!](https://tio.run/##fZJNb9NAEIbP7K94BVELh4zX@@0mhEt7bCVK4cCX5NhrGimNozqhBsRvD7OOEYUDe1jtzM48fuddL8vu9tD3Nab3oNVmu9/RbtVige1qutpM2zvarmfiocK0epxCvjhRMzxDd9s@dMhzj@W3Xeyw2uDNzfnF9bXYxvs1ptu/uubzOU5PZ0JU5Y6Di6tz/lJWx6/ZZr9eH37@6LKM9iTpu6DXknKhifaCbmj9jgS1luhtQZd8JIp8VaZD84S8oPccFnQnU2Z3VYjeZbMu@/D5Yy3oU5bbxfNJ/7K9rycnL15NnvaT/mzST23IvsQDqzjIcZ3B134Jr1UD1cgK3koFLXnzpSwho805DAF4JJaSWHEk5MzQOZdqrSIq7y1kKR2s4c1V1iHEBLKuAXJKA9JxQKJ2ZKjEsDJHqK2FLqSFqUOeQBqF5gtntWYxnhm/TaHRlJGhmeGSDulDAWmcgywKD@2HnE0CpUEwugDK1NwQeToaOTIMM1honQzgJhMiZOUNTOQmWfoA7dgovfQaYPPpaD4N5o8MywzV2CVstBWcYZCKtuacZietjlBBGfiga2B4MPrzYCPDpVkar7idS5VTBXSTToolKJN0lANDMePfRx4ZfvBUc33jPPuH/63hx/gF "Bash – Try It Online") This was [generated using the following program](https://tio.run/##bZDdjtMwEIXv/RSjbkQTljZxEjc2VUGIq72Gu3ZZuY3bRKR2ZHu3XQGvTrDdFFEJK5F/zsx3ZqYXuiPDcAfG6rYHtd@DbQRYzduulQeQ4uR2gUy6kVGaLhG6cwGtAS36ju@EAd51oJ@lcblg@vB0am0TMJ@@fH54gF3DtY/XwghpPdVr8vm4FTrghBbA3S/Fi9BwVO5oGy4Bl1diK4GDLwSO/LsntBYEN69gFdTtfu8IjsytcLy9VkdQnhqcjas9hmSD36a7RsedkAfbxNGbJEkPIvQzthI6uVRlIMbZDFOW/LcXboFQuB@DIWawWo06qRLnh9fZjD5u6p9rPGNuD86E3jvXq@lXP0T3ObSEk@a979H71GKnak89Ne2ugVqJEORkNxwj/Jj9lW/Vi0hQ9LSa/vph0nQ6j57m03Rp0vW3TY3mjykmH@LovFK6drYfo8k5Or@PzjNCXQnTJep1Ky1cxvFuAttXKwxCk@UwwD@LMIAMYFEiuFl5kVUUo2KOS0zYKOaLMSnLKR0zSEGAFnnFwg2zCvt3yqAsilvkghVXEFzCy/KvyIrqqhV5SKzKC5LgLCi0vKmb5hlDi3zxW/W2VdIMs6z/Aw "Perl 5 – Try It Online") which uses RLE for spaces and stores runs of digits as bytes where possible. [Answer] # [Deadfish~](https://github.com/TryItOnline/deadfish-), 842 bytes ``` {i}cc{i}{i}ii{c}cc{i}{i}iciiiic{d}{d}dddddcc{i}iiiiiic{d}ddddddcc{i}{i}iicddc{{d}iiiiii}ddc{i}{i}ii{c}cccc{i}{i}ddcicdddc{i}dddcic{d}iiic{{d}iiiiii}ic{{i}dddddd}icdddddciiiciiicdddciiiiciiiic{{d}iiiii}iiic{i}{i}iicccccc{i}{i}ddciiiic{d}{d}ddcccccc{i}{i}icdddddciiciiiiiiccddddc{{d}iiiiii}ddc{i}{i}iiccccc{i}{i}icddciic{d}{d}dc{i}{i}iiiicdddddcdciiiiiciic{d}{d}dddddccccc{i}{i}dddc{i}ddcddcddddddc{{d}iiiiii}ic{i}{i}iiccc{i}{i}iiiicic{d}{d}dddddc{i}{i}cdcc{d}{d}i{c}cccc{i}{i}iiciiicddddddciiiiiic{{d}iiiii}iiic{i}{i}iiccccccc{i}{i}iiiciic{d}{d}dddddcccc{i}{i}cc{d}{d}ccccccccc{i}{i}iiiiicddddddciiiic{{d}iiiiii}dddddc{i}{i}iiccccccc{i}{i}dcdcic{d}{d}icccc{i}{i}iiicdddciiiiic{d}{d}dddddccccc{i}{i}icddddcdc{{d}iiiiii}iic{i}{i}iicccc{i}{i}iiiicddddc{d}{d}{c}cc{i}{i}iciiicddddddcddc{i}dc{{d}iiiii}iiic{{i}dddddd}iiiicddddciiiic{{d}iiiiii}ddddc ``` [Try it online!](https://tio.run/##hVJBDgMhCHxRH9UMbcq5R@PbLSIokN3UmM0ywgyM0utJb/5@HmM07oB8ZDM3nAAsC426bJpLT5gdpgMqDgma4CujzyiyeqLgM1VPSYNVE2tnwCbQNXsmsrYE@/f@vGpxeC/IgnGSeHa4YYMpcDNHKcQh3SnsjEuUUS0MbZkF0F1l0yyBPdOtA8xbUDRbfQxzz/4YdoQu@jYtg4FakpWyhVRd3C6A9kicO9g93xi45JBdyxOVWzGi@si9bbuQ6lB4iZvoakKM8QM "Deadfish~ – Try It Online") The longest answer so far, and proud of it. ]
[Question] [ > > ***Warning: This challenge is only valid for languages with a compiler.*** > > > Make a program (which is perfectly valid code) that outputs `Hello, World`, even before runtime. How? Let me explain. Many languages have a compiler. Some operations are made in the compile-time, and others, in runtime. You trick the compiler to output the text `Hello, World` in compile-time. The text can be anywhere, like the build log.(Not errors. sorry for invalidating all those answers. at least theres pragma tho) > > You can use C, C++ or C#, but I wouldn't encourage you to. It's simply a game breaker. > > > p.s. I wrote this challenge because the tag [compile-time](/questions/tagged/compile-time "show questions tagged 'compile-time'") is both unused, and used wrong. [Answer] # C#, 51 bytes [Try it online](https://tio.run/##Sy7Wzc3Py///X7k8sSgvMy9dwSM1JydfRyE8vygnhSs5J7G4WCGkurgksSQzWaEsPzNFwTcxM09Ds7q29v9/AA) ``` #warning Hello, World class P{static void Main(){}} ``` Prints the following to the Error List (but still compiles): ``` warning CS1030: #warning: `Hello, World' ``` [Answer] # FreePascal, 29 characters ``` begin{$INFO Hello, World}end. ``` Maybe other Pascal variants too, not sure whether the [`$INFO`](https://www.freepascal.org/docs-html/prog/progsu35.html) directive is FreePascal only or not. Sample run: ``` bash-4.4$ fpc compile-time-message.pas Free Pascal Compiler version 3.0.2+dfsg-2 [2017/04/09] for x86_64 Copyright (c) 1993-2017 by Florian Klaempfl and others Target OS: Linux for x86-64 Compiling compile-time-message.pas User defined: Hello, World Linking compile-time-message /usr/bin/ld.bfd: warning: link.res contains output sections; did you forget -T? 0 lines compiled, 0.0 sec ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~22~~ 18 bytes ``` Hello, World;main; ``` This compiles just fine with gcc (and clang), although the program it produces crashes immediately. [Try it online!](https://tio.run/##S9ZNT07@/98jNScnX0chPL8oJ8U6NzEzz/r/fwA "C (gcc) – Try It Online") ### Compiler output gcc 6.3.1 produces the following debugging information. ``` .code.tio.c:1:1: warning: data definition has no type or storage class Hello, World;main; ^~~~~ .code.tio.c:1:1: warning: type defaults to ‘int’ in declaration of ‘Hello’ [-Wimplicit-int] .code.tio.c:1:8: warning: type defaults to ‘int’ in declaration of ‘World’ [-Wimplicit-int] Hello, World;main; ^~~~~ .code.tio.c:1:14: warning: data definition has no type or storage class Hello, World;main; ^~~~ .code.tio.c:1:14: warning: type defaults to ‘int’ in declaration of ‘main’ [-Wimplicit-int] ``` --- # [C (gcc)](https://gcc.gnu.org/), 15 bytes ``` Hello, World; ``` If compiling to an object file is allowed, this works just as well. The resulting file simply declares two global variables. The byte count includes **+3 bytes** for the compiler flag `-c`. [Try it online!](https://tio.run/##S0oszvifnFiiYKeQUa6XrGBjo6D33yM1JydfRyE8vygnxfq/HhdXenKygm4yRIWRnZohV0FRZl5JmoJ6bmJmnoZmda06UH9efoFeMlgpUF0@lKunn6iXX1ryHwA "Bash – Try It Online") ### Compiler output ``` hw.c:1:1: warning: data definition has no type or storage class Hello, World; ^~~~~ hw.c:1:1: warning: type defaults to ‘int’ in declaration of ‘Hello’ [-Wimplicit-int] hw.c:1:8: warning: type defaults to ‘int’ in declaration of ‘World’ [-Wimplicit-int] Hello, World; ^~~~~ ``` --- # [C (gcc)](https://gcc.gnu.org/), 20 bytes ``` main(Hello, World){} ``` This compiles to a program that exits cleanly. [Try it online!](https://tio.run/##S9ZNT07@/z83MTNPwyM1JydfRyE8vygnRbO69v9/AA "C (gcc) – Try It Online") ### Compiler output ``` .code.tio.c:1:1: warning: return type defaults to ‘int’ [-Wimplicit-int] main(Hello, World){} ^~~~ .code.tio.c: In function ‘main’: .code.tio.c:1:1: warning: type of ‘Hello’ defaults to ‘int’ [-Wimplicit-int] .code.tio.c:1:1: warning: type of ‘World’ defaults to ‘int’ [-Wimplicit-int] ``` [Answer] ## Haskell, ~~25~~ 24 bytes ``` m@main=m ``` 8 bytes from the code plus 16 bytes for the compiler flag `-W'Hello, World'`. Gives the warning `unrecognised warning flag: -WHello, World` and compiles the program. Depending on the shell (or the absence of a shell) you can omit the single quotes in the flag for two bytes less. TIO works this way. ### Haskell, TIO environment, 22 bytes [Try it online!](https://tio.run/##y0gszk7Nyfn/P9chNzEzzzb3//9/yWk5ienF/3XDPYAy@ToK4flFOSkA "Haskell – Try It Online") Edit: @Dennis saved a byte. Thanks! [Answer] ## Perl, 15 bytes 14 bytes of code + `-w` flag. ``` "Hello, World" ``` When ran with `-w` flag, it produces the compile-time warnings: ``` $ perl -we '"Hello, World"' Useless use of a constant ("Hello, World") in void context at -e line 1. ``` And if you wonder if it really happens at compile time, you can add `-c` flag, which causes the program to be compiled but not ran, and the warning is still here. [Answer] # [C (gcc)](https://gcc.gnu.org/), 23 bytes ``` main(){"Hello, World";} ``` [Try it online!](https://tio.run/##S9ZNT07@/z83MTNPQ7NaySM1JydfRyE8vygnRcm69v9/AA "C (gcc) – Try It Online") Gives the warning: ``` warning: return type defaults to ‘int’ [-Wimplicit-int] main(){"Hello, World";} ^~~~ ``` --- # [C (gcc)](https://gcc.gnu.org/), 38 bytes ``` #pragma message"Hello, World" main(){} ``` [Try it online!](https://tio.run/##Sy4o0E1PTv7/X7mgKDE9N1EhN7W4ODE9VckjNScnX0chPL8oJ0WJKzcxM09Ds7r2/38A "C++ (gcc) – Try It Online") Rather than using compiler warnings, this answer uses a built-in `pragma` directive that allows printing notes to stdout. Works in C and C++ (as I *think* all the rest of these do). --- # [C (gcc)](https://gcc.gnu.org/), 23 + 1 = 24 bytes ``` #define f"Hello, World" ``` [Try it online!](https://tio.run/##S9ZNT07@/185JTUtMy9VIU3JIzUnJ19HITy/KCdF6f//f8lpOYnpxf91kwE "C (gcc) – Try It Online") Prints "Hello, World!" as part of an error message, which says: ``` warning: ISO C99 requires whitespace after the macro name #define f"Hello, World!" ^~~~~~~~~~~~~~~ ``` This is a default warning in GCC; no flags need to be added to achieve this. The extra byte comes from the `-c` flag, which successfully compiles the program without linking, which means it accepts not having a `main` function. However, the resulting output file cannot be executed. If this is unacceptable, then: # [C (gcc)](https://gcc.gnu.org/), 31 bytes ``` #define f"Hello, World" main=0; ``` [Try it online!](https://tio.run/##S9ZNT07@/185JTUtMy9VIU3JIzUnJ19HITy/KCdFiSs3MTPP1sD6/38A "C (gcc) – Try It Online") This will run, but will segfault every time. If *that*'s not acceptable, then: # [C (gcc)](https://gcc.gnu.org/), 32 bytes ``` #define f"Hello, World" main(){} ``` [Try it online!](https://tio.run/##S9ZNT07@/185JTUtMy9VIU3JIzUnJ19HITy/KCdFiSs3MTNPQ7O69v9/AA "C (gcc) – Try It Online") [Answer] # [Scala](http://www.scala-lang.org/), 36 bytes ``` object F extends App{"Hello, World"} ``` [Try it online!](https://tio.run/##K05OzEn8/z8/KSs1uUTBTSG1oiQ1L6VYwbGgoFrJIzUnJ19HITy/KCdFqfb/fwA "Scala – Try It Online") Gives the warning: ``` warning: a pure expression does nothing in statement position; you may be omitting necessary parentheses object F{"Hello, World"} ``` [Answer] ## GNU C, 31 bytes Nothing clever here. I'm mostly posting it for reference. ``` main(){printf("Hello, World");} ``` GCC will throw the following warning at compilation time: ``` hello.c: In function ‘main’: hello.c:1:8: warning: incompatible implicit declaration of built-in function ‘printf’ [enabled by default] main(){printf("Hello, World");} ^ ``` ]
[Question] [ **Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/34286/edit). Closed 9 years ago. [Improve this question](/posts/34286/edit) I have read a question similar to this. I found it interesting, and difficult so I rephrased the question as a code golf. (that question is closed ) Challenge: > > In 1 million and 1 numbers, all the numbers having the duplicate except only one number . Write a program that can find this unique number. > > > Input form: > > a text file containing 1000001 integer seperated by space. > The numbers are shuffled > > > Output form: > > a single number > > > Note: Using standard library functions to compare values is not allowed the (in case you intend to use something as `strcmp()` in c or anything similar in other languages) a simple algorithm that can achieve the job. This is code golf, so the shortest code win. All languages are allowed. ( I prefer c/c x86 assembly if possible because i have no experience in any other language) add some explanation to your source code if possible. Good luck. [Answer] ## Golfscript, 6 characters ``` ~]{^}* ``` This simply XORs all numbers: assuming the input file consists of the numbers `a b b c c d d ...` in any order, this calculates `a^b^b^c^c^d^d^...` (XOR is commutative/associative, so the order of numbers doesn't matter). Since `x^x == 0`, this effectively leaves only the number that hasn't been duplicated. Run it like this: `golfscript unique.gs < inputfile` [Answer] # [Pyth](https://github.com/isaacg1/pyth/blob/master/pyth.py), 10 characters Note: Does not fail even if there are more than 2 copies of duplicated numbers. ``` JPw)'ocJNJ ``` Explanation: ``` JPw) J=input.split() 'oJNJ print first element of J sorted by count of element in J. ``` ]
[Question] [ **Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/1245/edit). Closed 7 years ago. [Improve this question](/posts/1245/edit) I found the code below today after much hair pulling. Shorten it down (code golf) and fix the bug that I found (bonus). ``` #define LN_SOME_TEXT_FIELD 256 void GetSomeText(LPTSTR text) { TCHAR buf[LN_SOME_TEXT_FIELD + 1]; short i; LPTSTR curChar; curChar = text; i = 0; while (*curChar != NULL) { if (*curChar != '&') { buf[i] = *curChar; i++; } curChar++; } buf[i] = NULL; SomeOtherUIFunction(buf); } ``` **EDIT** Added a tail call, this is what the real function does, sorry for not including it earlier. [Answer] Are you sure you didn't fix the bug already? I don't see a flaw in the logic, but I do see a few obvious problems: * The output buffer is never returned, so this function is a no-op. The post was changed so the `buf` is used now. * The output buffer has a fixed-width. This is fine, as long as the input's length does not exceed LN\_SOME\_TEXT\_FIELD. * Using `NULL` instead of `'\0'`. `NULL` expands to `((void*) 0)`, meaning it's a pointer. It should not be used to refer to the null character. Anyway, here is a nicer (in my opinion) version of the code above: ``` void GetSomeText(const char *in, char *out) { for (; *in != '\0'; in++) { if (*in != '&') *out++ = *in; } *out = '\0'; } ``` [Answer] ### Perl, 5 chars ``` s/&// ``` Or ``` sub GetSomeText{$@[0]~=s/&//} ``` if you insist on wrapping something so trivial in a subroutine. [Answer] ## Haskell, 13 characters ``` filter(/='&') ``` or, not golf'd: ``` getSomeText :: String -> String getSomeText = filter (/='&') ``` But, I'm guessing that this isn't the desired function, but probably something that unescapes. If so, then the function is `g`, 36 characters: ``` g('&':a:z)=a:g z;g(a:z)=a:g z;g _=[] ``` or, not golf'd: ``` getSomeText :: String -> String getSomeText ('&':a:as) = a : getSomeString as getSomeText ( a:as) = a : getSomeString as getSomeText [] = [] ``` Seriously, *this* is exactly [why functional programming matters](http://www.cse.chalmers.se/~rjmh/Papers/whyfp.pdf). "Turn on, tune in, [learn Haskell!](http://learnyouahaskell.com/)" ]
[Question] [ Given no input, output the following: ``` _ | ~-_ | o ~-_ | ~ ~-_ | \~~~~~~ | * \ | \ |~~~~~~~~~~\ ``` Note the backslashes are actually `\`, which is `U+FF3C` Trailing whitespace is allowed, however leading whitespace is not. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so fewest bytes **in each language** wins! [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 50 bytes ``` •ζ1VS¹Tšã¦1d’sΩç!ÙT>_äтÿÀ†{ECZ{Ý•7ÝJ"_ -~|\*o"‡8¡» ``` [Try it online!](https://tio.run/##AVsApP8wNWFiMWX//@KAos62MVZTwrlUxaHDo8KmMWTigJlzzqnDpyHDmVQ@X8Ok0YLDv8OA4oCge0VDWnvDneKAojfDnUoiXyAtfnzvvLwqbyLigKE4wqHCu///QUJD "05AB1E – Try It Online") --- First I created a translation table as follows: ``` 0 | "_" 1 | " " 2 | "-" 3 | "~" 4 | "|" 5 | "\" 6 | "*" 7 | "o" 8 | "\n" ``` I then proceeded to replace each unique character in the flag with the number corresponding to the character at that specific position to get the number: ``` 108413208417113208413111113208411115333333841161115841111111158433333333335 ``` Here's the same pattern with the newlines (makes it more obvious): ``` 10 41320 41711320 41311111320 411115333333 41161115 4111111115 433333333335 ``` [I then compressed the number into base-255 using 05AB1E](https://tio.run/##MzBNTDJM/f/f0MDCxNDYCESaG0IZxoYgAGEDgakxGIA4ZiAuRNQQwjSGA1MFI1NTp///AQ) (To compress a base-10 number to base 255 simply run 255B in 05AB1E). Then, see the code explanation for how I rebuild it from the number. --- ``` •ζ1VS¹Tšã¦1d’sΩç!ÙT>_äтÿÀ†{ECZ{Ý• # Push the number we discussed. 7ÝJ # Push 01234567. "_ -~|\*o" # Push "_ -~|\*o". ‡ # Replace 0-7 with the appropriate block. 8¡» # Split on 8's and print with newlines. ``` [Answer] # Python 2, ~~94~~ ~~92~~ 96 bytes ``` print(""" _ | ~-_ | o ~-_ | ~ ~-_ | \~~~~~~ | * \ | \ |~~~~~~~~~~\""") ``` [Try it online!](https://tio.run/##K6gsycjPM/7/v6AoM69EQ0lJSSGeq0ahThdE5itAGXUKIABhA8H7PXvqwADE1YIIQGQUYJw6OABygaZq/v8PAA) [Answer] # [SOGL](https://github.com/dzaima/SOGL), 49 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) ``` ⁰∑J“ζ"Ω‰Θx(;╝φ╚○Δ§∆qσG⅛>K█׀IR'ΚΧqΞ⅞≥№█▼¡└+Β8‘# ~ŗ ``` If the flag used any other character than `~`, this would be 4 bytes shorter. [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~83 79~~ 78 bytes (UTF-8) ``` " _ | ~-_ | o ~-_ | ~ ~-_ | \~~~~~~ | * \ |{8ç}\ |{Aç'~}\ ``` Hardcodes most of the string [Try it online!](http://ethproductions.github.io/japt/?v=1.4.5&code=IiBfCnwgfi1fCnwgbyAgfi1fCnwgfiAgICAgfi1fCnwgICAgXHVmZjNjfn5+fn5+CnwgICogICBcdWZmM2MKfHs4531cdWZmM2MKfHtB5yd+fVx1ZmYzYw==&input=) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~76~~ ~~74~~ ~~72~~ 66 bytes -6 bytes thanks to @carusocomputing ``` '~T×ð8×'~6×ð5×" _ | ~-_ | o ~-_ | ~ÿ~-_ | \ÿ | * \ |ÿ\ |ÿ\" ``` String interpolation replaces the `ÿ`s. In order from first to last, it is: 5 spaces, 6 `~`s, 8 spaces, and then 10 `~`s [Try it online!](https://tio.run/##MzBNTDJM/f9fvS7k8PTDGywOT1evMwOxTA9PV1KI56pRqNMFkfkKUEbd4f0QBhC837Pn8H4QUwvC4ao5vB9BKf3/DwA "05AB1E – Try It Online") [Answer] # C#, 89 bytes ``` _=>@" _ | ~-_ | o ~-_ | ~ ~-_ | \~~~~~~ | * \ | \ |~~~~~~~~~~\" ``` Any formatting options in C# for this require too many extra bytes that it is just cheaper to hard code the output as far as I can tell. [Answer] # Java 8, 96 bytes ``` ()->" _\n| ~-_\n| o ~-_\n| ~ ~-_\n| \~~~~~~\n| * \\n| \\n|~~~~~~~~~~\" ``` Boring, but it probably can't be shortened by using some fancy `.replace` or loops anyway in Java.. [Try it here.](https://tio.run/##PY9BDoIwEEX3nuKHVTGBCxC9gWxcqjG1VFPElkAhMUpPxp08Ag5Q@Gkz8zrJ/N@ctzwypdR59hxEwesaB670ZwMobWV150IiHRE42krpBwQLE@KOLp3acqsEUmjsMLAw2ge4nvUXLpqKwdK5cccCpF/fu0kTb@cXP8NKbhVxMCSza9ncCnL15q1RGV4Um80RTxfw0Gd@11a@YtPYuKSRZTqm/P4D3fAH) [Answer] # Mathematica, 84 bytes ``` "_ | ~-_ | o ~-_ | ~ ~-_ | \~~~~~~ | * \ | \ |~~~~~~~~~~\" ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~51~~ 50 bytes ``` “ ½|~-o*_‘;65340Ọ“ßṆiṣ€|ʂwĊeḌ\<S@DƝbƘשṗþ8¥Ḅ3Zȥ ’ṃ ``` [Try it online!](https://tio.run/##AV4Aof9qZWxsef//4oCcIMK9fH4tbypf4oCYOzY1MzQw4buM4oCcw5/huYZp4bmj4oKsfMqCd8SKZeG4jFw8U0BExp1ixpjDl8Kp4bmXw744wqXhuIQzWsilIOKAmeG5g/// "Jelly – Try It Online") [Answer] # Bubblegum, 40 Not sure why no-one posted the bubblegum answer yet - Is bubblegum frowned upon these days? xxd dump: ``` 00000000: 5388 e7aa 51a8 d305 91f9 0a50 469d 0210 S...Q......PF... 00000010: 40d9 40f0 7ecf 9e3a 3000 71b5 2002 1019 @.@.~..:0.q. ... 00000020: 0518 a70e 0e80 5c00 ......\. ``` [Try it online](https://tio.run/##bY4xDsIwFEN3TuETfPkn/STp1IkZxMqStCkLDAysXD1EFImFN3ix/OTyLOVWr897a/wywnyMqCFnmOaIxdOQdE1gNmLYpwV0SuAsIif5cDz02G0G7Y6BS@qxEqHOK1L1Gb53CFoMjnRQagImmeQlMlIegp/DdQdNI3JgBWskbO7zv2wXLtLaGw). [Answer] # [Retina](https://github.com/m-ender/retina), ~~60~~ 59 bytes ``` 1_!1~-_!1o2~-_!1~5~-_!4\""!2*3\!8\!"""~\ " ~~~ ! ¶| \d $* ``` [Try it online!](https://tio.run/##K0otycxL/P@fyzBe0bBOF0jkG4GpOlMQZfJ@zx4lJUUjLWMgQ9ECRCgpKdUBaS4lrrq6Oi5FrkPbarhiUrhUtBT@/wcA "Retina – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 37 bytes ``` ←×~χ↑⁷ _P¶¶o¶~¶¶ *F³¶~-_↓←×~⁶F⁴«\↘ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMPKJzWtREchJDM3tVhDqU5JR8HQQFPTmgsqG1qgo2AO5yopxCsBOb6lOSWZBRCRmLyYvPyYvDoQraAFkk3LL1LQMNZUCIApqNOF6MovS9Wwcskvz0MYj2G5mSbMBBNNhWouTqgh7/fsARnBiTAjKDM9owQoVPv//3/dshwA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ←×~χ ``` Print the bottom `~`s. ``` ↑⁷ ``` Print the left `|`s. ``` _P¶¶o¶~¶¶ *F³¶~-_ ``` Print the upper right line and the interior decoration. ``` ↓←×~⁶ ``` Print the middle `~`s. ``` F⁴«\↘ ``` Print the lower right line. [Answer] # [Deadfish~](https://github.com/TryItOnline/deadfish-), 459 bytes ``` {iii}iic{iiiiii}iiic{{d}ii}dddddc{{i}}{i}iiiic{{d}i}ddc{{i}d}iiiic{{d}ii}dc{iiiii}c{{d}ii}dddddc{{i}}{i}iiiic{{d}i}ddc{{i}dd}dc{{d}ii}icc{{i}d}iiiic{{d}ii}dc{iiiii}c{{d}ii}dddddc{{i}}{i}iiiic{{d}i}ddc{{i}d}iiiic{{d}i}ddddccccc{{i}d}iiiic{{d}ii}dc{iiiii}c{{d}ii}dddddc{{i}}{i}iiiic{{d}i}ddcccc{iiiiii}c{iii}iiiicccccc{{d}}{d}ddddddc{{i}}{i}iiiic{{d}i}ddcc{i}c{d}ccc{iiiiii}c{{d}ii}ddc{{i}}{i}iiiic{{d}i}ddcccccccc{iiiiii}c{{d}ii}ddc{{i}}{i}iiiicii{c}{ddd}ddddc ``` [Try it online!](https://tio.run/##rVBJDoAwCHyRjzKMxjl7JLy9gtDEHkyaKBdgmKUpthU7z2NpTUkaKdFz9Fnh3RDlC830PtTFCsUD860sbFqO0CSX8ovjiDka9dE4HNjp9UOUcoYLkPJXvYYQNvj02PdMmeCTKp6PfIG0dgE "Deadfish~ – Try It Online") Uses backslashes instead. ]
[Question] [ I find `NullPointerException` to be interesting since there are no explicit pointers in Java. Here is a program that throws such an exception. ``` class c { public static void main(String[]s) { throw new NullPointerException(); } } ``` What is the shortest Java program that throws `NullPointerException`? [Answer] # Java 8 - ~~56~~ 53 bytes (11 byte snippet) ``` interface P{static void main(String[]a){throw null;}} ``` **[ideone](http://ideone.com/EdRkRn)** From [the documentation](http://docs.oracle.com/javase/7/docs/api/java/lang/NullPointerException.html): > > ### Class NullPointerException > > > ... > > Thrown when an application attempts to use null in a case where an object is required. These include: > > ... > > > * Throwing null as if it were a Throwable value. > > > [Answer] ## 62 Bytes (17 byte statement) -2 bytes thanks to @PeterTaylor. ``` class C{public static void main(String[]s){s=null;s.clone();}} ``` Without knowing about the `throw` trick, this is the first thing that occurred to me. Using the main class's type is the shortest one available, and casting `null` is shorter than declaring `C c=null;`. `notify` is also the shortest method on an object that doesn't throw an exception. ]
[Question] [ **Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/48068/edit). Closed 8 years ago. [Improve this question](/posts/48068/edit) This challenge is to generate a random floating-point number between 2 limits. You may use any language so long as it can be called from the command line, and runs on linux. It must also be able to work with negative numbers. Due to the comment below: You may use fixed point math to come up with a result in-fact fixed point math is preferable in this case. # Input Requirements Accept a lower and upper limit, no verification required. # Output Requirements * Must be between the 2 specified limits * Print it out to the console * or come up with a way to return it to the shell. ## Example ``` $ prog -1 1 -.445 ``` The program would not spit out a result that is not between those 2 limits. And it would be inclusive of the 2 limits # Win Condition As with all of these challenges the smallest number of bytes wins. [Answer] # Cjam, 9 bytes ``` q~1$-dmr+ ``` Assumes that the first input number is the lower limit and the second one is the upper limit. Pretty straight forward code: ``` q~ "Read the input as a string and evaluate it. This puts the two input"; "integers on stack"; 1$ "Copy the first smaller integer and put it on top of stack"; - "Take difference of smaller and larger integer"; d "Convert the integer to double"; mr "Get a random double float from 0 to the difference of two integers"; + "Add the random double to the smaller integer to get random in range"; ``` [Try it online here](http://cjam.aditsu.net/#code=q%7E1%24-dmr%2B&input=34%2037) [Answer] # Ruby, 34 bytes ``` a,b=$*.map &:to_f $><<a+(b-a)*rand ``` Takes inputs via command-line argument as in the usage example. [Answer] # Pyth - 9 bytes Works the obvious way like all the others. ``` +*-vzQOZQ ``` Pyth's random range function when called with zero as the argument acts as a [0, 1) floating point generator. ``` + Add and implicitly print * Times - Difference vz Input 1 Q Input 2 OZ Float RNG Q Input 2 ``` [Try it here](http://pyth.herokuapp.com/?code=%2B*-vzQOZQ&input=-100%0A100). [Answer] # R, 34 Setup for running from command-line ``` i=scan('stdin');runif(1,i[1],i[2]) ``` Takes input from STDIN Example on windows ``` C:\Program Files\R\R-3.1.3\bin\x64>rscript -e "i=scan('stdin');runif(1,i[1],i[2])" 1 2 ^Z Read 2 items [1] 1.249665 C:\Program Files\R\R-3.1.3\bin\x64> ``` [Answer] # C#, ~~142~~ 141 bytes C# has too much boilerplate... Anyways, it is the only language I know and am sure can be compiled and run in Linux. ``` using System;class A{static void Main(string[]a){var b=double.Parse(a[0]);Console.Write(new Random().NextDouble()*(double.Parse(a[1])-b)+b);} ``` Ungolfed: ``` using System; class A { static void Main(string[] a) { var b = double.Parse(a[0]); Console.Write(new Random().NextDouble() * (double.Parse(a[1]) - b) + b); } } ``` Also, I just noticed that every example's input was integral. In that case... # C#, 135 bytes, integral input ``` using System;class A{static void Main(string[]a){int b=int.Parse(a[0]);Console.Write(new Random().NextDouble()*(int.Parse(a[1])-b)+b);} ``` Ungolfed: ``` using System; class A { static void Main(string[] a) { int b = int.Parse(a[0]); Console.Write(new Random().NextDouble() * (int.Parse(a[1]) - b) + b); } } ``` ]
[Question] [ # Guidelines ### Task Given a DNA strand, return its RNA complement (per RNA transcription). Both DNA and RNA strands are a sequence of nucleotides. The four nucleotides found in DNA are adenine (**A**), cytosine (**C**), guanine (**G**) and thymine (**T**). The four nucleotides found in RNA are adenine (**A**), cytosine (**C**), guanine (**G**) and uracil (**U**). Given a DNA strand, its transcribed RNA strand is formed by replacing each nucleotide with its complement: * `G` -> `C` * `C` -> `G` * `T` -> `A` * `A` -> `U` --- ### Rules * The input will always be either a string or an array/list of characters * The output should always be either a string or an array/list of characters * In the case of invalid input, you should output `'Invalid Input'` as a string or an array/list of characters * You can assume that you will only be given printable ASCII characters. * This is code golf so the person with the least amount of bytes winsx --- ### Examples `'C' -> 'G'` `'A' -> 'U'` `'ACGTGGTCTTAA' -> 'UGCACCAGAAUU'` `'XXX' -> 'Invalid Input'` `'ACGTXXXCTTAA' -> 'Invalid Input'` --- ### Other info This task was taken from [Exercism](https://exercism.io), which was founded by Katrina Owen and is licensed under the MIT License. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 23 bytes ``` „—ÄGu©ÃQi®"GUAC"‡ë”Í¼î® ``` [Try it online!](https://tio.run/##AT4Awf8wNWFiMWX//@KAnuKAlMOER3XCqcODUWnCriJHVUFDIuKAocOr4oCdw43CvMOuwq7//0FDR1RHR1RDVFRBQQ "05AB1E – Try It Online") **Explanation** ``` „—ÄGu© # push "CATG" and store a copy in register à # keep only those letters of input Qi # if the result equals the input ®"GUAC"‡ # translate "CATG" to "GUAC" ë”Í¼î® # else, push "Invalid Input" ``` [Answer] # [K (oK)](https://github.com/JohnEarnest/ok) / [K4](http://kx.com/download/), 38 bytes **Solution:** ``` (x;"Invalid Input")@|/^x:"CGAU""GCTA"? ``` [Try it online!](https://tio.run/##y9bNz/7/X6PCWskzrywxJzNFwTOvoLRESdOhRj@uwkrJ2d0xVEnJ3TnEUcleydHZPcTdPcQ5JMTRUen/fwA "K (oK) – Try It Online") **Examples:** ``` q)k)(x;"Invalid Input")@|/^x:"CGAU""GCTA"?"C" "G" q)k)(x;"Invalid Input")@|/^x:"CGAU""GCTA"?"C" "G" q)k)(x;"Invalid Input")@|/^x:"CGAU""GCTA"?"G" "C" q)k)(x;"Invalid Input")@|/^x:"CGAU""GCTA"?"ACGTGGTCTTAA" "UGCACCAGAAUU" q)k)(x;"Invalid Input")@|/^x:"CGAU""GCTA"?"XXX" "Invalid Input" q)k)(x;"Invalid Input")@|/^x:"CGAU""GCTA"?"ACGTXXXCTTAA" "Invalid Input" ``` **Explanation:** The mapping is trivial. 25 bytes for the "Invalid Input" portion. ``` (x;"Invalid Input")@|/^x:"CGAU""GCTA"? / the solution "GCTA"? / return index in left list "CGAU" / index into this list x: / save as x ^ / null, any nulls in x? |/ / take max @ / index into ( ; ) / two item list "Invalid Input" / result if null found x / result if no nulls found ``` [Answer] ## [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~36~~ 31 bytes ``` T`GCTAp`CGAUx K'x`Invalid input ``` [Try it online!](https://tio.run/##K0otycxLNPyvquGe8D8kwd05xLEgwdndMbSCy1u9IsEzrywxJzNFITOvoLTk/39nLkcuR2f3EHf3EOeQEEdHroiICLAAkAYLAAA "Retina – Try It Online") ### Explanation ``` T`GCTAp`CGAUx ``` Perform the required character substitutions as a transliteration, while also replacing all invalid characters with `x`. ``` K'x`Invalid input ``` If the result contains `x` (i.e. the input contained an invalid character), replace it with the constant string `Invalid input`. [Answer] # GNU sed, ~~70~~ 43 bytes ``` s/^.*[^ATCG].*$/Invalid Input/ y/ATCG/UAGC/ ``` [Try it online!](https://tio.run/##K05N0U3PK/3/v1g/Tk8rOs4xxNk9Vk9LRd8zrywxJzNFwTOvoLREn6tSHySjH@ro7qz//78jl6Oze4i7e4hzSIijI1dERARYAEiDBQA "sed – Try It Online") [Answer] # [C (clang)](http://clang.llvm.org/) or MinGW, 110 bytes ``` f(s){for(char*t="GCTA",*o=s=strdup(s),*q;*o;o++)(q=strchr(t,*o))?*o="CGAU"[q-t]:(s="Invalid input!");puts(s);} ``` [Try it online!](https://tio.run/##TY7BCsIwDIbP9ilqQGi7@QKWKqOH4r3CQDyMyeZA263tvMiefWYehqck//eRpN7Xz8q189ywyD@ND6x@VEEkBUbbAnLhVVQxhfvYo5CLQQovfZZxNixx/QgsocT5CU3QprjAddin24FFBWf3rp7dnXauH9MWuMQScY2c5rfHvP0doyJy8iGbPnQuNQx2kaojhZyiSDbLX5JMhCCkr6pz7Ce3DDQsHJtibbSxxlhtbbFmZVn@YxxXPM1f "C (clang) – Try It Online") [Answer] # [Red](http://www.red-lang.org),118 114 bytes ``` func[s][t: copy{}foreach c s[append t switch/default to-word c[G[{C}]C[{G}]T[{A}]A[{U}]][return"Invalid Input"]]t] ``` [Try it online!](https://tio.run/##Xcq9CsIwFEDh3ae4ZBd3t5AhdJUIhcsdSn5ooSQhvbFIyLNXwUFxO3yc4t1x8w6QIFyPUKPFjZCvYFN@th5S8ZOdwcKGU84@OmDY9oXtfHE@THVl4HTeU3FgUWNTnRQ23clgk50ktnsnwuK5liiG@JjWxcEQc2VBxHTkskSGAEKK07eVNlobZYz85XEc/6a3fKbjBQ "Red – Try It Online") Ungolfed: ``` f: func [s] [ t: copy {} ; initialize t to an empty string foreach c s [ ; for each character c of the input append t switch/default to-word c [ ; append to t the following if c is one of GCTA G [{C}] C [{G}] T [{A}] A [{U}] ] [ return "Invalid Input" ] ; otherwise return "Invalid Input" ] t ; return t ] ``` [Answer] # Python, ~~103~~ ~~95~~ 86 bytes ``` def f(b): try:return["CGAU"["GCTA".index(i)]for i in b] except:return"Invalid Input" ``` Or, if lowercase inputs count: ``` def f(b): try:return["cgau"["gcta".index(i.lower())]for i in b] except:return"Invalid Input" ``` [Answer] # [Coconut](http://coconut-lang.org/), ~~75~~ 70 bytes ``` s->set(s)-set('ACGT')and'Invalid Input'or["UCG A"[ord(c)%5]for c in s] ``` [Try it online!](https://tio.run/##NUw9C8MgFNz7Kx6B8hTi2KVQQRwku4VA2yGYBoRUJc9kyn9PTUqX@@LuXHQxzHkbbs@NhKR3ZsTFTqi0sci70GMTlm70PTQhzRnjBJ8uMSdkddcGVPWIU88cP19eNfFVjp7KX2kR@ACosQZUB5RDY6y2Vh2@bdt/XOQvvp4AynCVMOyQJh/y9gU "Coconut – Try It Online") A mix of [ovs' Python answer](https://codegolf.stackexchange.com/a/156059/56433) and my [Haskell answer](https://codegolf.stackexchange.com/a/156067/56433). *Edit: -5 bytes thanks to ovs!* [Answer] # [CJam](http://cjam.readthedocs.io/en/latest/index.html), 43 bytes ``` l{"GCTA"#"CGAU "=}%_S#){];"Invalid input"}& ``` Online interpreter: <http://cjam.aditsu.net/> [Answer] # [Python 3](https://docs.python.org/3/), ~~82~~ ~~79~~ 67 bytes thanks to Laikoni for -3 bytes! -12 bytes by looking at this 3 years later. ``` lambda s:{*s}-{*'ACGT'}and'Invalid Input'or s.translate('UCG A'*17) ``` [Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUaHYqlqruFa3Wkvd0dk9RL02MS9F3TOvLDEnM0XBM6@gtEQ9v0ihWK@kKDGvOCexJFVDPdTZXcFRXcvQXPN/GkhOITNPQd1ZXUdB3RFMAI1xdw9xDglxBPMjIiJgwkAmRNiKS0GhoCgzr0QjTaNYU/M/sh4A "Python 3 – Try It Online") [`str.translate`](https://docs.python.org/3/library/stdtypes.html#str.translate) takes any kind of collection of characters or codepoints that can be indexed into with an integer, in this case we use a string. | `c` | `ord(c)` | `ord(c)%5` | `('UCG A'*20)[ord(c)]` | | --- | --- | --- | --- | | `'A'` | `65` | `0` | `'U'` | | `'C'` | `67` | `2` | `'G'` | | `'G'` | `71` | `1` | `'C'` | | `'T'` | `84` | `4` | `'A'` | [Answer] ## Batch, 192 bytes ``` @echo off set/ps= set t=%s:A=% set t=%t:C=% set t=%t:G=% set t=%t:T=% if not "%t%"=="" echo Invalid Input&exit/b set s=%s:A=U% set s=%s:C=A% set s=%s:G=C% set s=%s:A=G% echo %s:T=A% ``` Takes input on STDIN. [Answer] # JavaScript (ES6), 78 bytes ``` f=([c,...r],s='',k='GCTA'.indexOf(c))=>c?~k?f(r,s+'CGAU'[k]):'Invalid input':s ``` ### Test cases ``` f=([c,...r],s='',k='GCTA'.indexOf(c))=>c?~k?f(r,s+'CGAU'[k]):'Invalid input':s console.log(f('C' )) // 'G' console.log(f('A' )) // 'U' console.log(f('ACGTGGTCTTAA')) // 'UGCACCAGAAUU' console.log(f('XXX' )) // 'Invalid Input' console.log(f('ACGTXXXCTTAA')) // 'Invalid Input' ``` --- ### Without input validation (non-competing) 47 bytes using `search()`: ``` f=([c,...r])=>c?'CGAU'['GCTA'.search(c)]+f(r):r ``` 48 bytes using a hash: ``` f=([c,...r])=>c?'UCG_A'[parseInt(c,36)%5]+f(r):r ``` [Answer] # [Haskell](https://www.haskell.org/), 75 bytes ``` f s|all(`elem`"GCTA")s=["UCG A"!!mod(fromEnum c)5|c<-s] f _="Invalid Input" ``` [Try it online!](https://tio.run/##bY7NCsJADITvfYqYy7ZgvXmzQgiyCHpyC4UidukPirurWPWiPnttrYKClzD5mMlkq@t9aUzTVFDftTF@VprSZihZEQZ1lGLMEggHA3so/Op0sDN3sZAH43s@Ceu1V8Emwrm7arMrYO6OlzM2Vu8cRGD1cQl@S1bn08LBCKogRcYhIL0GSyWlYqXotSdJ8sGt7PHau4WeYAHhFIQUnqBexp38yr@pZGImSRR3hvZKz3/eeyc/FX8d4aN5Ag "Haskell – Try It Online") The mapping is done by taking the character values mod 5 and indexing into the string `"UCG A"`. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~24~~ 23 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` “ɠ{>dʠ»ɓ,Ṛ;⁾TUyðḟ?“TGCA ``` A full program printing the result (a monadic link is ~~25~~ 24 with a closing `”` appended) **[Try it online!](https://tio.run/##ATsAxP9qZWxsef//4oCcyaB7PmTKoMK7yZMs4bmaO@KBvlRVecOw4bifP@KAnFRHQ0H///8iQUNHVENUVEFBIg "Jelly – Try It Online")** ### How? ``` “ɠ{>dʠ»ɓ,Ṛ;⁾TUyðḟ?“TGCA - Main Link: list of characters “TGCA - literal list of characters = ['T','G','C','A'] ? - if... ḟ - ...condition: filter discard (empty is falsey) “ɠ{>dʠ» - ...then: compressed string = "Invalid Input" ɓ ð - ...else: dyadic chain with swapped arguments: Ṛ - reverse = ['A','C','G','T'] , - pair = [['T','G','C','A'],['A','C','G','T']] ⁾TU - literal list of characters = ['T','U'] ; - concatenate = [['T','G','C','A'],['A','C','G','T'],'T','U'] y - translate... - ... 1: {'T'->'A';'G'->'C';'C'->'G';'A'->'T'} - ... 2: {'T'->'U'} ``` [Answer] # C, 128 bytes ``` k,l;f(S){char*s=S,b[l=strlen(s)],*t=b;for(;*t++=(k=*s++)-65?k-67?k-71?k-84?0:65:67:71:85;);puts(strlen(b)-l?"Invalid Input":b);} ``` [Try it online!](https://tio.run/##XYyxCoMwAER3v0KcEjVQoUZJCCIO4mwGoXQwtrZimhaTdhG/3WZoi/SG43h3XIcuXbeuYyhpD2o4d9d28jWrQ3GQTJtJnhXQ8Bj6hgna3ydAfRMEDIzM10EAEY6zEeHEWhJZS/fZjuCY4IQkEUljCunjaTT4PAmIZOZV6tXK4eRWynYeEZAu66CMe2sHBaAzO65VD7zCg/Sb820uSl6WvOA83@Kmaf5GlvxGy/oG) **Unrolled:** ``` k, l; f(S) { char *s=S, b[l=strlen(s)], *t=b; for(; *t++ = (k=*s++)-65 ? k-67 ? k-71 ? k-84 ? 0 : 65 : 67 : 71 : 85;); puts(strlen(b)-l ? "Invalid Input" : b); } ``` [Answer] ## [Perl 5](https://www.perl.org/) with `-p`, 39 bytes ``` y/GCTA/CGAU/<y///c?$_="Invalid Input":0 ``` Saved 1 byte thanks to [wastl](https://codegolf.stackexchange.com/users/78123/wastl)! [Try it online!](https://tio.run/##K0gtyjH9/79S3905xFHf2d0xVN@mUl9fP9leJd5WyTOvLDEnM0XBM6@gtETJyuD/f2cuRy5HZ/cQd/cQ55AQR0euiIgIsACQBgv8yy8oyczPK/6vW5ADAA "Perl 5 – Try It Online") [Answer] # [R](https://www.r-project.org/), 75 bytes ``` function(s)"if"(grepl("[^ACGT]",s),"Invalid Input",chartr("ACGT","UGCA",s)) ``` [Try it online!](https://tio.run/##Jcq9CoAgFAbQvaeIb7oX7A1aoiHaa4oCsSwhLMzCt7e/7QzHRZ3mWdSnVd5slg6G0aDZTftK6IairJoe4mCB2l5yNWNa2/30EGqRzjvCOyDQVmXxPo6aEEIAJw@kmv2vr3G8AQ "R – Try It Online") [Answer] # APL+WIN, 66 bytes Prompts for screen input of original string ``` ('CGAU',⊂'Invalid Input')[(((⍴n)×~m)↑n),(m←0<+/(n←,'GTCA'⍳⎕)=5)↑5] ``` ]
[Question] [ **Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers. --- Questions without an **objective primary winning criterion** are off-topic, as they make it impossible to indisputably decide which entry should win. Closed 5 years ago. [Improve this question](/posts/173152/edit) You have 2 numbers, both stored separate as **numeric data type**. First number is always 6 digits long. Second number can vary between 1 and 4 digits. If it's less than 4 digits, it needs to be padded with numeric value 0. End result always needs to be 10 digits number. Order has to be respected. n1|n2 **Example #1:** ``` n1 = 111111 n2 = 2222 result = 1111112222 ``` **Example #2:** ``` n1 = 333333 n2 = 44 result = 3333330044 ``` The **rule** is that you can only use **numeric data types** (number, int, float, decimal) to get the desired result. [Answer] # [MathGolf](https://github.com/maxbergmark/mathgolf), 3 bytes ``` ♫*+ ``` [Try it online!](https://tio.run/##y00syUjPz0n7///RzNVa2v//G4KBghEQAAA "MathGolf – Try It Online") ### Explanation: ``` Implicit input ♫* Multiply first argument by 10000 + Add the two arguments Implicit output ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 5 bytes ``` 1e4*+ ``` Uses only addition and multiplication. [Try it online!](https://tio.run/##y00syfn/3zDVREv7/39jMOAyMQEA "MATL – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 4 bytes ``` 4°*+ ``` [Try it online!](https://tio.run/##yy9OTMpM/f/f5NAGLe3//43BgMvEBAA "05AB1E – Try It Online") [Answer] # Ruby, 14 bytes ``` ->a,b{a*1e4+b} ``` [Answer] # [brainfuck](https://github.com/TryItOnline/brainfuck), 45 bytes ``` ,.,.,.,.,.,.,[-->+++>+++>+++<<<],[<,]>>>>[.<] ``` [Try it online!](https://tio.run/##SypKzMxLK03O/v9fRw8JRuvq2mlra8OwjY1NrE60jU6sHRBE69nE/v9vDAYKJgA "brainfuck – Try It Online") Assumes the inputted numbers are separated by a single space ]
[Question] [ # The Challenge Your task is to create a program that can solve an algebraic equation. ## Input Input will consist of a `String`. The string will be an equality involving the variable `x`, and follows the following rules: * the equation will always be linear * The valid operations in the equation are `+ - * /` * Parenthesis will not be used * Order of operations must be respected * The coefficients of `x` will always have `*` in between the coefficient and `x` * You can assume that there will be exactly one solution for `x` ## Output Output will be through the `stdout` (or an acceptable equivalent). The output should be the value of `x` that satisfies the equality. (You can round to the nearest thousandth if the decimal expansion is too long.) --- ## Test cases ``` x=5 => 5 2*x=5 => 2.5 3*x/2=7 => 4.667 2*x=x+5 => 5 3*x+3=4*x-1 => 4 3+x*2+x=x+x/2+x/2 => -3 ``` ## Scoring Because this is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest solution (in bytes) wins. (NOTE: You may not use built-ins that trivialize the problem.) [Answer] # Perl, 49 bytes Ah, builtins got disallowed. I'll leave this solution up for reference though it is now non competing. Includes +2 for `-lp` (-l can be dropped but is ugly) Run with the equation on STDIN: ``` perl -lp algebra.pl <<< "x=5" ``` `algebra.pl`: ``` s'x'$.'g;$_=s/=(.*)/-($1)//(1-eval()*$.--/eval) ``` [Answer] # Javascript, 62 bytes Without builtins, but with eval. ``` (s,f=eval("x=>"+s.replace(/=(.*)/,"-($1)")))=>f(0)/(f(0)-f(1)) ``` Uses eval to transform `foo(x) = bar(x)` into a function `f(x) = foo(x) - bar(x)`, then calculates `x = f(0) / (f(0) - f(1))`. [Answer] # Python 3, *587* bytes ``` from re import sub as r,findall as f a=input() i=int;s=str;l=len;d=r"(\d+\.?\d*)";d=d,d a=r(r"%s\*%s"%d,(lambda x:s(i(x.group(1))*i(x.group(2)))),a) a=r(r"%s\/%s"%d,(lambda x:s(i(x.group(1))/i(x.group(2)))),a) a=r(r"%s\-%s"%d,(lambda x:s(i(x.group(1))-i(x.group(2)))),a) a=r(r"%s\+%s"%d,(lambda x:s(i(x.group(1))+i(x.group(2)))),a) a=f(r"(\d+\.?\d*.)",a+"=") if l(a)==0 or a[0][1]!="*":a[0:0]=["1"] if l(a)==1 or a[1][1]!="=":a[1:1]=["0"] if l(a)==2 or a[2][1]!="*":a[2:2]=["1"] if l(a)==3 or a[3][1]!="=":a[3:3]=["0"] a=[int(x[0])for x in a] z=a[1]-a[3] print(z/(z-a[0]-a[1]+a[2]+a[3])) ``` The only longer answers I've seen use 80% of the code to store a big data table. But unlike eval-based solutions, it only uses `e` twice! (In `re` and `len`.) Log, Day 20: Used `Solve`. `Solve` got banned. Learned `re`. Used `re`. Slept. [Answer] # Matlab, 61 bytes ``` x=[1 0];a=eval([strrep(input(''),'=','-(') ')']);a(2)/diff(a) ``` Uses the same algorithm as Ton Haspel to solve the equation. Replaces the `=` by `-(` and adds a `)` at the end to make the string an equation that should equal zero, and solves (Newton's method is exact for linear functions). Input is just a string, e.g.: `'3+x*2+x=x+x/2+x/2'`. Matlab has a nice builtin for this too, ``` solve(input('')) ``` ]
[Question] [ **Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/59822/edit). Closed 8 years ago. [Improve this question](/posts/59822/edit) Your task is to create an interpreter for a calculator. It has to parse commands like `5 + 5` and return the answer. It has to be able to add, subtract, multiply, and divide. The interpreter only needs to accept two numbers (ex. `9 * 5` and `3 + 3`) The interpreter will take input from a console/whatever, not a file. **`Eval` isn't allowed** --- **Examples:** Input: `5 * 5` Output: `25` --- Input: `8 / 2` Output: `4` --- # Bonus If you're really bored you can add these to the interpreter, if you'd like: **Simple mathematical functions** like `sqrt`. **Make the interpreter be able to accept more than two numbers** (ex. `55 + 55`) [Answer] # Pyth, 1 byte ``` Q ``` For some reason, multiplication and division don't work in the online interpreter. The [Python interpreter](https://github.com/isaacg1/pyth) behaves as expected. [Answer] **Perl, ~~10~~ 8 chars** I hope this is not cheating ;) 8 chars (7 chars code + 1 for -p): Thanks to Dennis ``` perl -pe '$_=eval' ``` 10 chars: ``` say eval<> ``` Takes input from STDIN and needs `perl v5.10` and above. [Answer] ## ><>, 14 Bytes Thanks @Sp3000 for saving 2 bytes Quick, but kinda cool solution. Probably not an ideal golf, but utilizes an interesting feature of ><>. ``` <v ip02ii n<,; ``` Receives input through the numerical interpretation of ascii characters (i.e. a is 97). It places the second character read (the operator) in the space after `<v`. Because dividing in ><> uses `,`, not `/`, I make use of the fact that `/` reflects the pointer to accommodate for that case. Alternate solution if that's invalid (+4 Bytes): ``` <v %cip02i%ci n<,; ``` For this we just take mod 12 (`c` pushes 12) of the input since `0` is 48 and there are only 10 characters. If `,` could be used in place of `/`, this would be a lot shorter (something like `ii60pi n;` or `ic%ia0pic% n;`) Golf suggestions gladly welcome -- I'm rather tired right now. [Answer] # JavaScript ES6, ~~10~~ 4 bytes Anonymous function. ``` eval ``` [Answer] # MATLAB, 4 bytes (or 0 bytes) ``` eval s ``` Pretty simple really. MATLAB will evaluate the string `s` you pass it, and voila. For example the following operators work: `* / + - ^ sqrt() min() max()`. Well pretty much anything that you can think of. Heck you can even print `Hello World!` if you want - `eval 'disp(''Hello World!'')'`. To be honest given that MATLAB is already a calculator, you can call it `0` if you omit eval and simply type in the string: ``` >> 8/2 ans = 4 ``` ]
[Question] [ I made a joke the other day and sent it to some friends. One replied back "I love the irony!" and I looked at it and realized there was some irony in it. But that wasn't the irony she saw - the irony she was was the punchline of the joke, which wasn't ironic in the slightest. And it got me thinking about a certain other instance that isn't ironic at all. And I have to admit, [I love that song](https://www.youtube.com/watch?v=Jne9t8sHpUc). Have you read it's lyrics before? They're so deep! > > An old man turned ninety-eight > > He won the lottery and died the next day > > It's a black fly in your Chardonnay > > It's a death row pardon two minutes too late > > And isn't it ironic... don't you think > > > > It's like rain on your wedding day > > It's a free ride when you've already paid > > It's the good advice that you just didn't take > > Who would've thought... it figures > > > > "Mr. Play It Safe" was afraid to fly > > He packed his suitcase and kissed his kids goodbye > > He waited his whole damn life to take that flight > > And as the plane crashed down he thought > > "Well isn't this nice..." > > And isn't it ironic... don't you think > > > > It's like rain on your wedding day > > It's a free ride when you've already paid > > It's the good advice that you just didn't take > > Who would've thought... it figures > > > > Well life has a funny way > > Of sneaking up on you > > When you think everything's okay > > And everything's going right > > And life has a funny way > > Of helping you out when > > You think everything's gone wrong > > And everything blows up in your face > > > > A traffic jam when you're already late > > A no-smoking sign on your cigarette break > > It's like ten thousand spoons when all you need is a knife > > It's meeting the man of my dreams > > And then meeting his beautiful wife > > And isn't it ironic...don't you think > > A little too ironic...and, yeah, I really do think... > > > > It's like rain on your wedding day > > It's a free ride when you've already paid > > It's the good advice that you just didn't take > > Who would've thought... it figures > > > > Life has a funny way of sneaking up on you > > Life has a funny, funny way of helping you out > > Helping you out > > > > You know what I could really use? I could use a program that would spit out these lyrics. But, just like how this song has nothing ironic in it, you also will not be permitted to use anything ironic in *your* submission. That means no upper or lowercase `i`, `r`, `o`, `n`, or `c` may appear in your program. The program requires no input, and will output the exact text in the quote. Newlines included, but any trailing whitespace is accidental and you should ignore that. Any punctuation is required. The usual loopholes are obviously disallowed, and since this is code golf, the lowest score wins. What would be ironic would be if the restrictions on this make any submission automatically longer than the actual dump of the text. [Answer] # CJam, 922 bytes ``` 0000000: 226d24ae 76dd5d8d d392ac33 f8d0411a e39f4a4d e06683df "m$.v.]....3..A...JM.f.. 0000018: 111b4840 812cd834 74417bdd 80a53e6d 7d821401 8dcca95d ..H@.,.4tA{...>m}......] 0000030: b89cfb35 4cbab681 8c9388f1 671a4716 4cc4dbb7 bd140682 ...5L.......g.G.L....... 0000048: fe99dbee 429084d0 cd8b1a5e c9b45ad9 84a46cf6 ca92db54 ....B......^..Z...l....T 0000060: bd3946ba 8f1da9d6 7459e9bc 5b355308 11ca8980 93b89bc1 .9F.....tY..[5S......... 0000078: c99970a0 62095d5c 22775afc 9186a457 e560be57 f8802b5e ..p.b.]\"wZ....W.`.W..+^ 0000090: b6d1673a 2801fcca de4aa5f4 dcc1467c 85c2753b 34830614 ..g:(....J....F|..u;4... 00000a8: 98a450c1 0000f7a2 054164dd 03f7b0e1 fcbddaad 65fc061e ..P......Ad.........e... 00000c0: e3f6ca3f 989db84b fe839256 cdfa77b6 faf437e4 4af60f6b ...?...K...V..w...7.J..k 00000d8: 4264eabc 7aaceec4 ca8d4bfd 8b9b5c39 fa15d96a 0c36187e Bd..z.....K...\9...j.6.~ 00000f0: 5c220d89 e135beda 1c3b7ea8 1c5a76e5 7c26f929 a5405b1f \"...5...;~..Zv.|&.).@[. 0000108: 81e4e48c 06139775 66c6d8f1 7be3f55f 70e11e2d f8e68407 .......uf...{.._p..-.... 0000120: acce45d9 7b45864b 5c227ffe 3511097f f4df5fec 9fa51d02 ..E.{E.K\"..5....._..... 0000138: ed188eb4 d5f659f0 86ed7ef7 e4fb3d2c ab9b290b 648116db ......Y...~...=,..).d... 0000150: 50793fea 1aea5dc7 35e40f94 85e8e923 76427675 838b930b Py?...].5......#vBvu.... 0000168: d41f5717 b4da8b45 04319e95 dea4c038 f7a31746 b0c2e427 ..W....E.1.....8...F...' 0000180: 48b7f974 a1a86a11 f1333294 349685f4 c2c19cf3 c2f72aef H..t..j..32.4.........*. 0000198: e1960cd2 beee3eb0 283f0780 08af8afc 1758b3ca 289f3400 ......>.(?.......X..(.4. 00001b0: 44ede560 ada22ae4 b047cd0f 38c386ca 156544c7 9d1b0f8f D..`..*..G..8....eD..... 00001c8: fa1a78bc add29de3 d164b548 19a7e766 7ff7a0d7 048b4a97 ..x......d.H...f......J. 00001e0: 5fe076cf ae5c2224 ab1cf23b 54e50911 35775489 deb0c744 _.v..\"$...;T...5wT....D 00001f8: 50958144 c6e5edc8 e72f8bd2 f6ead64d 37d6858a 05838c65 P..D...../.....M7......e 0000210: ddee157c 20a993da 5f2a3366 263d38ed 0e2f39ea 15862e7b ...| ..._*3f&=8../9....{ 0000228: e66426e8 eeb5e1d0 b3a69187 e576c185 c5d818fd 76a933b2 .d&..........v......v.3. 0000240: 1ea9b31a 20030048 81ea5c22 f6ba7e2c 9ab81f9e 5a9802f1 .... ..H..\"..~,....Z... 0000258: 1413edac dbc87a36 94c5a59c d80efd5f 36f70ee5 e6e8c40f ......z6......._6....... 0000270: c27b3feb 99b18b1c bbe32b4c b080056d 5082ed6c 20135c11 .{?.......+L...mP..l .\. 0000288: 6098307e 9105f9c1 98fbef3c 7c18af20 e3d26dee e551c95b `.0~.......<|.. ..m..Q.[ 00002a0: c438dbd5 08ac18e9 53ee9db8 a9df7950 502e1077 efc23f28 .8......S.....yPP..w..?( 00002b8: fb3e7dee 2d254c2d 5fbd2a47 e0215ace 8a3b06f7 68bd9692 .>}.-%L-_.*G.!Z..;..h... 00002d0: 83e782c9 0f9827a0 0ad637ca d316ceaa 1c35aff6 d14d4024 ......'...7......5...M@$ 00002e8: cd5a59b6 30f97e6c 18c6088e 07c17673 3a0b58b1 9bdde15b .ZY.0.~l......vs:.X....[ 0000300: a6f1cad0 ca8e3e8f bb8ffb60 e44867ea eb4a7d57 bebcb540 ......>....`.Hg..J}W...@ 0000318: 7d37712d cc16dd7b 0e5b33f4 03dabc21 fae78a91 8df8eac6 }7q-...{.[3....!........ 0000330: 3f231dd0 4b6b5c22 c5f1ae77 bc99c3b2 eb96bbf6 da7ab52b ?#..Kk\"...w.........z.+ 0000348: bdf913c6 e55f54cb 105015f2 c76d3cc4 2227ff2c 224b5451 ....._T..P...m<."'.,"KTQ 0000360: 50452232 662d5f65 6c2b2d66 23323435 62343362 220e2426 PE"2f-_el+-f#245b43b".$& 0000378: 2b303132 45474c4d 50515354 575b5d22 34666d32 352c2761 +012EGLMPQSTW[]"4fm25,'a 0000390: 662b2b66 3d27712f 292a f++f='q/)* ``` The above is a reversible xxd dump. The source code contains way to many unprintable characters for the online interpreter... The source code is generated by the following program: ``` q" It's like rain on your wedding day It's a free ride when you've already paid It's the good advice that you just didn't take Who would've thought... it figures ":X/Xa+'q*"^N$&+012EGLMPQSTW[]"4fm25,'af++f#43b245b'ÿ,"KTQPE"2f-_el+-f=`"'ÿ,\"KTQPE\"2f-_el+-f#245b43b\"^N$&+012EGLMPQSTW[]\"4fm25,'af++f='q/)*" ``` Here, `^N` represents the control character with code point 14. ### Verification ``` $ LANG=en_US $ xxd -r -ps > gen.cjam <<< 71220a0a49742773206c696b65207261696e206f6e20796f75722077656464696e67206461790a49742773206120667265652072696465207768656e20796f7527766520616c726561647920706169640a497427732074686520676f6f6420616476696365207468617420796f75206a757374206469646e27742074616b650a57686f20776f756c642776652074686f756768742e2e2e20697420666967757265730a0a223a582f58612b27712a220e24262b30313245474c4d50515354575b5d2234666d32352c2761662b2b66233433623234356227ff2c224b545150452232662d5f656c2b2d663d602227ff2c5c224b545150455c2232662d5f656c2b2d6623323435623433625c220e24262b30313245474c4d50515354575b5d5c2234666d32352c2761662b2b663d27712f292a22 $ cjam gen.cjam < song | grep -i IRONIC $ cjam gen.cjam < song | wc -c 922 $ cjam <(cjam gen.cjam < song) | md5sum - song 3b1a473c910233d91d0e283a43cbcab2 - 3b1a473c910233d91d0e283a43cbcab2 song ``` ### Explanation The code starts by placing a string of characters (the encoded song) on the stack. ``` 'ÿ, e# Push the string of all characters with code points below 255. "KTQPE"2f- e# Push "IRONC" by subtracting 2 from each code point. _el+ e# Concatenate with the lowercase counterparts. - e# Remove these characters from the string. f# e# Replace each character from the encoded song by its index in this string. 245b43b e# Convert the resulting array of integer from base 245 to base 43. "^N$&+012EGLMPQSTW[]\"4fm e# Subtract 4 from each code point. 25,'af++ e# Append the lower case letters from a to y to that string. f= e# Replace each integer in the base 245 array by the corresponding character. 'q/ e# Split the result at all occurrences of 'q'. )* e# Pop the last string (chorus) and insert it between the remaining chunks. ``` [Answer] # Ironic, Java, 4009 bytes, ~~312.49%~~ 256.82% size of original. ``` publ\u0069\u0063 \u0063lass \u0049\u0072\u006F\u006e\u0069\u0063{publ\u0069\u0063 stat\u0069\u0063 v\u006F\u0069d ma\u0069\u006e(St\u0072\u0069\u006eg[]a\u0072gs){System.\u006Fut.p\u0072\u0069\u006et("A\u006e \u006Fld ma\u006e tu\u0072\u006eed \u006e\u0069\u006eety-e\u0069ght\\u006e"+"He w\u006F\u006e the l\u006Ftte\u0072y a\u006ed d\u0069ed the \u006eext day\\u006e"+"\u0049t's a bla\u0063k fly \u0069\u006e y\u006Fu\u0072 \u0043ha\u0072d\u006F\u006e\u006eay\\u006e"+"\u0049t's a death \u0072\u006Fw pa\u0072d\u006F\u006e tw\u006F m\u0069\u006eutes t\u006F\u006F late\\u006e"+"A\u006ed \u0069s\u006e't \u0069t \u0069\u0072\u006F\u006e\u0069\u0063... d\u006F\u006e't y\u006Fu th\u0069\u006ek\\u006e"+"\\u006e"+"\u0049t's l\u0069ke \u0072a\u0069\u006e \u006F\u006e y\u006Fu\u0072 wedd\u0069\u006eg day\\u006e"+"\u0049t's a f\u0072ee \u0072\u0069de whe\u006e y\u006Fu've al\u0072eady pa\u0069d\\u006e"+"\u0049t's the g\u006F\u006Fd adv\u0069\u0063e that y\u006Fu just d\u0069d\u006e't take\\u006e"+"Wh\u006F w\u006Fuld've th\u006Fught... \u0069t f\u0069gu\u0072es\\u006e"+"\\u006e"+"\"M\u0072. Play \u0049t Safe\" was af\u0072a\u0069d t\u006F fly\\u006e"+"He pa\u0063ked h\u0069s su\u0069t\u0063ase a\u006ed k\u0069ssed h\u0069s k\u0069ds g\u006F\u006Fdbye\\u006e"+"He wa\u0069ted h\u0069s wh\u006Fle dam\u006e l\u0069fe t\u006F take that fl\u0069ght\\u006e"+"A\u006ed as the pla\u006ee \u0063\u0072ashed d\u006Fw\u006e he th\u006Fught\\u006e"+"\"Well \u0069s\u006e't th\u0069s \u006e\u0069\u0063e...\"\\u006e"+"A\u006ed \u0069s\u006e't \u0069t \u0069\u0072\u006F\u006e\u0069\u0063... d\u006F\u006e't y\u006Fu th\u0069\u006ek\\u006e"+"\\u006e"+"\u0049t's l\u0069ke \u0072a\u0069\u006e \u006F\u006e y\u006Fu\u0072 wedd\u0069\u006eg day\\u006e"+"\u0049t's a f\u0072ee \u0072\u0069de whe\u006e y\u006Fu've al\u0072eady pa\u0069d\\u006e"+"\u0049t's the g\u006F\u006Fd adv\u0069\u0063e that y\u006Fu just d\u0069d\u006e't take\\u006e"+"Wh\u006F w\u006Fuld've th\u006Fught... \u0069t f\u0069gu\u0072es\\u006e"+"\\u006e"+"Well l\u0069fe has a fu\u006e\u006ey way \\u006e"+"\u004Ff s\u006eeak\u0069\u006eg up \u006F\u006e y\u006Fu\\u006e"+"Whe\u006e y\u006Fu th\u0069\u006ek eve\u0072yth\u0069\u006eg's \u006Fkay \\u006e"+"A\u006ed eve\u0072yth\u0069\u006eg's g\u006F\u0069\u006eg \u0072\u0069ght\\u006e"+"A\u006ed l\u0069fe has a fu\u006e\u006ey way \\u006e"+"\u004Ff help\u0069\u006eg y\u006Fu \u006Fut whe\u006e\\u006e"+"Y\u006Fu th\u0069\u006ek eve\u0072yth\u0069\u006eg's g\u006F\u006ee w\u0072\u006F\u006eg \\u006e"+"A\u006ed eve\u0072yth\u0069\u006eg bl\u006Fws up \u0069\u006e y\u006Fu\u0072 fa\u0063e\\u006e"+"\\u006e"+"A t\u0072aff\u0069\u0063 jam whe\u006e y\u006Fu'\u0072e al\u0072eady late\\u006e"+"A \u006e\u006F-sm\u006Fk\u0069\u006eg s\u0069g\u006e \u006F\u006e y\u006Fu\u0072 \u0063\u0069ga\u0072ette b\u0072eak\\u006e"+"\u0049t's l\u0069ke te\u006e th\u006Fusa\u006ed sp\u006F\u006F\u006es whe\u006e all y\u006Fu \u006eeed \u0069s a k\u006e\u0069fe\\u006e"+"\u0049t's meet\u0069\u006eg the ma\u006e \u006Ff my d\u0072eams\\u006e"+"A\u006ed the\u006e meet\u0069\u006eg h\u0069s beaut\u0069ful w\u0069fe\\u006e"+"A\u006ed \u0069s\u006e't \u0069t \u0069\u0072\u006F\u006e\u0069\u0063...d\u006F\u006e't y\u006Fu th\u0069\u006ek\\u006e"+"A l\u0069ttle t\u006F\u006F \u0069\u0072\u006F\u006e\u0069\u0063...a\u006ed, yeah, \u0049 \u0072eally d\u006F th\u0069\u006ek...\\u006e"+"\\u006e"+"\u0049t's l\u0069ke \u0072a\u0069\u006e \u006F\u006e y\u006Fu\u0072 wedd\u0069\u006eg day\\u006e"+"\u0049t's a f\u0072ee \u0072\u0069de whe\u006e y\u006Fu've al\u0072eady pa\u0069d\\u006e"+"\u0049t's the g\u006F\u006Fd adv\u0069\u0063e that y\u006Fu just d\u0069d\u006e't take\\u006e"+"Wh\u006F w\u006Fuld've th\u006Fught... \u0069t f\u0069gu\u0072es\\u006e"+"\\u006e"+"L\u0069fe has a fu\u006e\u006ey way \u006Ff s\u006eeak\u0069\u006eg up \u006F\u006e y\u006Fu\\u006e"+"L\u0069fe has a fu\u006e\u006ey, fu\u006e\u006ey way \u006Ff help\u0069\u006eg y\u006Fu \u006Fut\\u006e"+"Help\u0069\u006eg y\u006Fu \u006Fut");}} ``` ### Instructions: Place in file named: `Ironic.java` Compile with: `javac Ironic.java` Run with: `java Ironic` [Answer] # PHP, 956 Bytes compressed string -> base64 encoded -> replacement of not allowed chars ``` <?=((gz.(k&m).(J^"$").flate)((base64_de.(k&g).(j|g).de)((st.(v&z).t.(v&z))("3VTBbtswDL37K4h)em]zD8EuK7BhA3}}dmQs2lIt<4FE1fPfj5TTpg2y+zAgh1h6e]zvkdIhAU)HMyaQmhM5S(G=_A8U=</dV4KFd)sT=BahvAImBy4}0BYT/=ZwuHaP)l)A4=<x]2(IK4QEK9)MXzxmxyldMI5QPG=e4[S2QBaG{aQqVE(YIaJQd9Ay}aQ7ga(/z(]0+/0eFK9LyqzlQ5q6jTSG<S(j1u=z2YW)(2]8qG3IpKDg1JK]B_t7J)(Y(d2qW}Lbk{Z_ZHaA7jX0p[+4VXyp=)0GZw}EJ+qePWs8[T}jEs9VIz{=q]gIY81Uum73Pe/hZ8QVHgWe)KAdLKhyBpW_GbKFZTGf[Dg[1Y)(pQbpsV(Legql][e]4EpTdlypdQaD]L)Wz5HU7Jw0<4GM1x=u2}fYemmJ4mbvFDE=9BmLVwLHSwL/7qDbPV{M5/DF2DV7Ul+7/6YpzWALym[TUV[a[)+1+zFASYSTyay]s3Ll3L=t/}Be9SLY31GV8aTHLJhPqyMbQ34P/m/FPMWTIY2)q7QUul+3K42sTVs09fGq]l47X}_pfbt1A/bUdQeQjMMQe]jB+=JwvgS8XTVI/FBmbqZLG(8[68{ImfTew1Hx04e+(qUWb_EZLSfmVLY(qMmamU=ks6J+p6Tet6MzkVg=66Y9{TzAvIJT7_k0T2IUbygbvS[hlTDU(Iux3B7A6/k7qEa=S{01eUep0]tY(f09PIKWjPpK{d6{6Pa/P7XfbsyQ=XhjYK+h959PXE2dP<afvv8A",["("=>K&G,")"=>k&g,"<"=>K&M,"<"=>k&m,"["=>j^"$","]"=>J^"$","{"=>J|G,"}"=>j|g,"="=>V&Z,_=>v&z])))); ``` [Try it online!](https://tio.run/nexus/php#LZPbiqtYFEX/JTTFFkN5jRc6@zRKjPEGilsTI3ZQ3CpGQTE3Tfntdaw@vR7WGqzJfBzf238gAOX0Ca4fLfEJzH9Xf62Iz6JJb5gAIEsHLPCXHP/k5ZLXX8vOf6Lh9gkeHxPx@f8lwIoLkZrdhufO5kSLrwjcJtNO0u6WqFYKN8956w1sY9y2/F5jCreoNwh1JTuSk1JWTCXgZHpcc6NSAuLgjKnXVs7GBzq8KFIAt1Qe8tY@JwYE1bR6KEarjvxMqxGi4Pl5P6Qu0RAKD7evhAWGxXuaJRPOaXq1r7HJHWPjuTrEfOyznprq79TrQw1ERmp6uayMc@qJZQqoCSQ0SdF4b8n22E@Nt@mFGvn61gc1c4cTGx0JwCZSr3NGZ@1KxrQS9XITTQJEIGf742xn1/f5cj6kilif6C4m@fA0dpCg9fNz1kyyx@5xkGI019ogh8b0hn1SGpHEBPdW5FxMVWfJCw/lEROWkttWNard8aJn1v6M9CLelTETEaDzsm4IgY3LvklinPBah/Jm7HIv3SU2cZw2h0A0n/SW1x3mBe/sXES4bU2@zR77nQZltbXDp33wnzYl9rvMDd/Ohtrt2V0oBg0pUkLUTUfFHtsYBWGcxgTJkNNe8SMfjemYDJzdcDa8UbOKZd@OOEYPpRQdbLNy@9HJPI53qZbau84RGRFL9KIX3BuSs3h2QOFAy4XeJw0vnuZLV2Q3RqGyIPewVzuOh5NaJaH5fJS@dEKhQe3VNuvPtg6kWJDeRlsg/GQOL5rHJOiDY3bRzrZftKEdgd5p0zaA10EwyU5A@CY40zUsoSBE8htNysMwkXi50og1gmwss4cfVw3aBcC4vzhVVATqKvZaCv03zeAAd3Ryi0BBy65hHWu3s9658BbclHLFU5ENowdPVR1ZZCVvZPeksbm7TYvHQ1JW63gFVvCX9aGvV8QCiz/r1fa/j/MHFuPWq3iB@ke69SpZ0PyD7x/8WprzT/y1NOEC4cd5fYG/FtsSYpm/v79/Aw "PHP – TIO Nexus") ]
[Question] [ Warning: This is a bit lengthy I have decided to build my own random function I call it "**Random Cake**" This function should get an integer value between 0 and 99999 ***Ingredients*** ``` 1 x DateTime function 1 x Sin : Radians 1 x Absolute Value 1 x π a dash of multiplication, division and addition ``` Here is the recipe ***Recipe*** > > Get Current Date and Time ..... (1) > > > ``` "23/05/2019 17:39:42.631" ``` Break it into milliseconds, seconds, minutes, hours, days, months, and years > > Add 1 to the milliseconds ..... (2) > > > ``` 1 + 631 = 632 ``` > > Add 1 to the seconds ..... (3) > > > ``` 1 + 42 = 43 ``` > > Multiply both results in (2) & (3) and stir ..... (4) > > > ``` 632 * 43 = 27,176 ``` > > Divide the result from (4) by 360 and then Use the Sin (Rad not degrees) where Sin(π) = 0 and Sin(π/2) = 1 ..... (5) > > > ``` 27,176 / 360 = 75.48888889 Sin(75.48888889) in Rad = 0.09054103861 ``` > > then multiply step 5 result by 1000 ..... (6) > > > ``` 0.09054103861 * 1000 = 90.54103861 ``` Note this value might be negative, no problem here Keep this in the fridge until it cools down > > In another bowl we add 3 to the Hours and multiply by the minutes ..... > (7) > > > ``` (3 + 17) * 39 = 780 ``` > > Now we add last step's results (7) to the cooled mix in step (6) ..... > (8) > > > ``` 780 + 90.54103861 = 870.54103861 ``` We are almost there, be patient > > Get the absolute value of step (8) as it could be negative ..... (9) > > > ``` Abs(870.54103861) = 870.54103861 ``` and add the flavor of the recipe which is > > The first 2 digits (without leading zeroes) in the result of step (9) > will represent the location of our flavor, which is the 5 digits of π after that position in the decimal representation of π..... (10) > > > For example: ``` Here is the value of π: 3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117067982148086513282306647093844609550582231725359408128481 Results of step (9) was 870.54103861 First 2 non zero digits are 87 So we go to digit number 87 after the decimal point in π for the length of 5 digits which is 48253 if your result was 0.001045678 then your 2 non zero digits are 10 the point is the number does not start with 0 so if your number anything like 0.000012345 then plz ignore all initial zeros till you get to the meat > 0 ``` in some languages you get more accurate than the other so I think you have to complete the rest of the digits manually :) if your language gives you π = 3.14 then you have to add 159265358979323846264338327950288419716939937510582097494459230... to it > > Add the number in step (10) to the result in step (9) ..... (11) > > > ``` 48253 + 870.54103861 = 49,123.54103861 ``` ***Decoration*** > > Multiply day and month with the end result in step (11) ..... (12) > > > ``` 23 *5 * 49,123.54103861 = 5,649,207.21944015 ``` > > Ignore decimals and flip the value you got ..... (13) > > > ``` 5,649,207.21944015 ==> 5,649,207 ==> 7029465 ``` > > Just take first 5 digits of this number ...... (14) > > > ``` 7029465 ==> 70294 ``` Put it in the oven and serve warm and that is our random number Bon Appétit... another example another test case ``` Step 1 : Date Time = "23/07/2016 04:59:31.407" Step 2 : 1 + 407 = 408 Step 3 : 1 + 31 = 32 Step 4 : 408 * 32 = 13,056 Step 5 : 13,056 / 360 = 36.26666667 Sin(36.26666667) = -0.9904447352 Step 6 : -0.9904447352 * 1000 = -990.4447352 Step 7 : (3 + 04) * 59 = 413 Step 8 : 413 + (-990.4447352) = -577.4447352 Step 9 : Abs(-577.4447352) = 577.4447352 Step 10 : First 2 digits (without leading zeroes) ==> 57 π Position 57 (5 numbers)==> 49445 Step 11 : 49445 + 577.4447352 = 50,022.4447352 Step 12 : 50,022.4447352 * 23 * 07 = 8,053,613.6023672 Step 13 : 8,053,613.6023672 ==> 8,053,613 8,053,613 ==> 3163508 Step 14 : First 5 Number 3163508 ==> 31635 ``` [Answer] # [Python 3](https://docs.python.org/3/), 223 bytes ``` import datetime,math,sympy d=datetime.datetime.now() x=abs(math.sin((1+d.microsecond//1e3)*-~d.second/360)*1e3+(d.hour+3)*d.minute) print(str(int(d.day*d.month*(int(str(sympy.pi.evalf(5+int(str(x)[:2])))[-5:])+x)))[:-6:-1]) ``` [Try it online!](https://tio.run/##PY7LDoIwEEX3fIXLGQpFJLIg4UsIC6Q1NLGPtIPCxl9HasTV3Jwzk7lupcmaatuUdtbTSQwkSWmZ6YGmLKzarYloD8r/wdgXYLK0wy1AXOVBGYCSCa7V6G2QozWiKEpZYZq/Bf@Bqj5jukMGgk929mzX8cTMJDFxXhmCQB7iFPu3NVpraErhUN9O3Ckun8PjDld2iAW75tIjYpdfmx7ZEmOT101e9rhtHw "Python 3 – Try It Online") -2 bytes thanks to ValueInk [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 50 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` žd₄/îžc>*360/Ž₄*ža3+žb*+ÄDþ0K2£žss.$5£J+žežfPïR5£ ``` [Try it online.](https://tio.run/##yy9OTMpM/f//6L6UR00t@ofXHd2XbKdlbGagf7j10F6gkNbRfYnG2kf3JWlpH25xObzPwNvo0OKj@4qL9VRMDy32AsqkHt2XFnB4fRCQ@/8/AA) **Explanation:** ``` žd # Push current microseconds ₄/ # Divide by 1000 î # Round up (we now have milliseconds + 1) (2) žc> # Push current seconds + 1 (3) * # Multiply both with each other (4) 360/ # Divide it by 360 Ž # Get the sine of this (5) ₄* # Multiply by 1000 (6) ža3+ # Push the current hours + 3 žb* # Multiply it with the current minutes (7) + # Add it to the earlier number (8) Ä # Get the absolute value of this (9) D # Duplicate it þ # Only leave the digits of the copy, removing the decimal dot 0K # Remove all 0s 2£ # Only leave the first two digits žs # Push an infinite list of PI digits s # Swap to get the number of two digits to the top of the stack .$ # Remove that many leading digits from PI 5£ # And then only leave the first 5 digits of the remainder of PI J # Join the digits together to a single string/integer (10) + # Add it to the earlier number that we've duplicated (11) že # Push the current day žf # Push the current month P # Take the product of all three values on the stack (12) ï # Truncate any decimals R # Reverse this integer (13) 5£ # Only leave the first five digits (14) # (which is output implicitly as result) ``` ]
[Question] [ **This question already has answers here**: [Alphabet Position Finder](/questions/165809/alphabet-position-finder) (39 answers) Closed 5 years ago. # Challenge : *Inspired by [Alphabet Position Finder](https://codegolf.stackexchange.com/questions/165809/alphabet-position-finder)* Given an string and one of two possible mathematical operator (`+` or `-`) as input, your task is to return the operation of each alphabet position from the string. # Example : ``` Input: "Hello World", "+" => "Hello World" = [8, 5, 12, 12, 15, 23, 15, 18, 12, 4] (converted to their equivalents) => sum alphabet positions = [8 + 5 + 12 + 12 + 15 + 23 + 15 + 18 + 12 + 4] Output: 124 ``` --- # Note : * Ignore non-alphabetical characters * You must use 1-indexing (a = 1, b = 2, ..., z = 26) * If empty string submitted return a falsy value * Operator can be taken as `+`/`-`. `1`/`-1`, truthy/falsey, etc. # Test Cases : ``` "Hello World", "-" => -108 "I Love golfing", "+" => 133 "She doesnt love you :(", "+" => 224 "@#t%489/*-o", "-" => 5 "", "-" => 0 "a", "-" => 1 ``` [Answer] # [Java (JDK 10)](http://jdk.java.net/), 79 bytes ``` s->o->{int r=0,i=0;for(int c:s)r+=(c&=95)%32*(c>64&c<91?i++<1?1:o:0);return r;} ``` [Try it online!](https://tio.run/##pY9BT8JAEIXv/IqJBrILdKWKRlpaNCZGEj1x8EA4rNsWFpedZndL0hB@e10IHg0mnCYz8@ab99Z8y4N19t3ITYnGwdr3rHJSsaLSwknUrBu3hOLWwgeXGnYtgLL6UlKAddz5skWZwcbvyMwZqZfzBXCztPQoBXg9ccZixc180Z9q9ztKoUgaG6QYpDupHZhk0JfJIC7QkEMvIktNLyGik4zuafvutktE@jDsiPEonMhebxxOwgijAY1N7iqjwcT7Jj5@ndXW5RuGlWOlN@WUJgXjZalqcvWWK4XwiUZlV8zhi/f1bAyvCaUnSRBSep4zhXfc5rBEVfjYf6D@RZqtcsgwtz6zOiBrrCAilxCfrl17@Di66QZ4UcYzx/vWvvkB "Java (JDK 10) – Try It Online") ### Original answer before the question was clarified [Java (JDK 10)](http://jdk.java.net/), 46 bytes ``` s->o->s.chars().reduce(0,(a,b)->a+b%32*(44-o)) ``` [Try it online!](https://tio.run/##hY4xa8MwEIV3/woRCJESS5Q2W1pDl7aBlg6hdCgdzracyJV1QjobTMlvd0WSqUum4917991rYQDZ1j@T6TwGYm3SqidjVdO7igw6tdxklYUY2RsYx34zxnxfWlOxSEBpDGhq1iWP7ygYt//6ZhD2UZyijD1dOPdnN986@nAQxnevAxCGgjUPU5QFyiKq6gAhcqGCrvtK85ucQ14KWcCqnN/dLvl6LVGIaXMi78ZIulPYk/IJTdbxRoH3duSzF20tfmKw9Uycd48xfeYLuRDi@vn2FQf9jLZJjf8BVhfAMTtOfw "Java (JDK 10) – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), ~~70~~ 66 bytes ``` lambda s,o:eval(o.join(`ord(c)%32`for c in s if c.isalpha())or'0') ``` [Try it online!](https://tio.run/##Vc29CsIwFAXg3ae4tBQTtdofBS0ojgpuDi4OxiZpIzG3pLXQp486aOl4Dt/hVF1Tokmc3F6dZs87Z1DPMBMt0wTnD1SG3NByktMgTW4SLeSgDNSgJORzVTNdlYxQinYcjamrrDINSOIdhNYIF7SaezPwQo@CD9sdhHG0Hv3VEU7YCihQS2WKL5z@YJymvTuXAjiK@pP0d9DhCzIy8Emy7P3eb4LlerOYhDh4X/Vk0EfuDQ "Python 2 – Try It Online") [Answer] # Japt v2.0a0, ~~12~~ 13 bytes +1 bytes to handle empty strings :( ``` r\L ¬®c uHÃrV ``` [Try it](https://ethproductions.github.io/japt/?v=2.0a0&code=clxMIKyuYyB1SMNyVg==&input=IkhlbGxvIFdvcmxkIiwgIi0iIA==) Original 12 byte version which would be valid if an error counts as a falsey value. ``` f\L ®c uHÃrV ``` [Try it](https://ethproductions.github.io/japt/?v=2.0a0&code=ZlxMIK5jIHVIw3JWVA==&input=IiIKIi0i) --- ## Explanation ``` :Implicit input of string U and operator string V r :Remove \L : /[^a-z]/gi ¬ :Split ® :Map c : Character code u : Modulo H : 32 à :End map rV :Reduce by V ``` [Answer] # Japt 2.0 `-F0`, ~~19~~ 15 bytes ``` OvUf\l ®c %HÃqV ``` [Test it online](https://ethproductions.github.io/japt/?v=2.0a0&code=T3ZVZlxsIK5jICVIw3FW&input=IkhlbGxvIFdvcmxkIiwgIi0iIAoKLUYw) ## Explanation: ``` OvUf\l ®c %HÃqV Ov // Japt eval: U // First input f\l // Match [A-Za-z] ® à // Map; At each item: c // Char-Code %H // %32 qV // Join with Second input (operator) -F0 // If the first input (string) is empty, output 0 ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 92 82 67 bytes ``` t=>o=>t?eval(t.match(/[a-z]/gi).map(x=>parseInt(x,36)-9).join(o)):0 ``` [Try it online!](https://tio.run/##dc1BC4IwGIDhe79iGOG3ahoUkcKsY0K3Dh2iw9Cpk7VPdIn15y0PXSKvLw@8pWhFk9SqssxgKvuM95ZHyCO7l63QYL27sEkB/lWw183PFf2ECjoeVaJuZGwsdMv1lrKAeiUqA0hpuOoTNA1q6WnMIQPnKLVGcsFapw4Fl7mUTn5ITE7YSpKjzpTJB7X4o86FJCnKxliiB/7EBwlhTB@mdrbZBf6c4dj22/s3 "JavaScript (Node.js) – Try It Online") [Answer] # [JavaScript (Node.js)](https://nodejs.org), 52 bytes ``` T=>_=>eval([...T].map(a=>a.charCodeAt()%32).join(_)) ``` [Try it online!](https://tio.run/##bcq9CsIwFEDh3ae4FKS5aFPQTUhBXCy4WXAQkdCmf8TcksZKnz62oIs4Hs7XykH2uW06FxkqlC@Fz0RyF4kapGZXznl24w/ZMSkSyfNa2sPE9o7hcrtB3lJj2B3R52R60oprqljJgqPSmuBCVhcBsjAKERc/JIUTDQoq0mVjqlmt/qhzraAg1RsHeuYjPb8U4nhaJnTwImvHNaSfdESwQ/8G "JavaScript (Node.js) – Try It Online") --- # Explanation : ``` T => // first input for lambda function `text` (T) _ => // second input, the separator eval( // evaluate a string [...T] // conver `T` into a comma separated array of its char .map(a=> // map over them `a` is representing the char a.charCodeAt() // a.charCodeAt(0) % 32) // find remainder of it when divided by 32 .join(_) // and join them using the separator ) // end eval ``` --- # Note : This completely ignores non-alphabetic words since the challenge seems to change after every two minutes, I chose this. (Can be changed if OP wants me to) --- I posted this on the other challenge, just changed .join to .join(o) : # [JavaScript (Node.js)](https://nodejs.org), 57 bytes ``` t=>o=>t.match(/[a-z]/gi).map(i=>parseInt(i,36)-9).join(o) ``` [Try it online!](https://tio.run/##bcqxCsIwFIXh3ae4uDTBphkEQSGdLbg5OIhDaNM0JeaWJFbqy8cWdBHH85@vl6MMtTdDZA4blVqRoihRlLG4y1h3hF8le924NnQOAzGiHKQPqnKRmHy7o2xPix6NI0hTjS6gVYVFTVqyPiprES7obbOmJGMZpasfUsEJRwUabWucXtTmjzp3ChpUwUWwC5/w8aXA@Xy5LMITvZ9yqD4zIsKBpjc "JavaScript (Node.js) – Try It Online") --- [Answer] # [CJam](https://sourceforge.net/p/cjam), 24 bytes ``` q~el{'`-_0>*}%{},0+':@+~ ``` [Try it online!](https://tio.run/##S85KzP3/v7AuNadaPUE33sBOq1a1ulbHQFvdykG77v9/JW0lBSWP1JycfIXw/KKcFCWFVGUFWzsFQyMTrlRlJV3ssrqGBhYgaZBmTwWf/LJUhfT8nLTMvHS4fmNjmILgjFSFlPzU4rwShRyQysr8UgUrDZhCI4RFDsolqiYWlvpauvlgWZC0KUwSpt4AAA "CJam – Try It Online") Could probably be more efficient, had to add 0 to the array to handle the empty string. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` áÇ32%Iý.E ``` Semi-port of [*@JonathanAllan*'s 05AB1E answer for the linked challenge](https://codegolf.stackexchange.com/a/165825/52210). Outputs nothing as falsey values if the input doesn't contain any letters. No TIO, because `.E` isn't on TIO yet. Here an alternative version that does `.E` manually `áÇ32%Iý“…¢(“s')J.e`: [Try it online](https://tio.run/##MzBNTDJM/f//8MLD7cZGqp6H9z5qmPOoYdmhRRpARrG6ppceUNYjNScnXyE8vygnhUsXAA) or [verify all test cases](https://tio.run/##MzBNTDJM/W/q9v/wwsPtxkaqnof3PmqY86hh2aFFGkBGsbqml17q//8eqTk5@Qrh@UU5KVy6XJ4KPvllqQrp@TlpmXnpXNpcwRmpCin5qcV5JQo5IJnK/FIFKw2gBFCxg3KJqomFpb6Wbj6XLgA). **Explanation:** ``` á # Only keep letters of the first input-string # i.e. "Hello World" → "HelloWorld" Ç # Get the list of the unicode values of each letter # i.e. "HelloWorld" → [72,101,108,108,111,87,111,114,108,100] 32% # modulo-32 each # i.e. [72,101,108,108,111,87,111,114,108,100] → [8,5,12,12,15,23,15,18,12,4] Iý # Join it with the operator input # [8,5,12,12,15,23,15,18,12,4] and "-" → "8-5-12-12-15-23-15-18-12-4" .E # Run it as Python-eval # i.e. "8-5-12-12-15-23-15-18-12-4" → -108 ``` [More details on the commit of `.E`, prove it works, and the alternative version here in a similar answer of mine.](https://codegolf.stackexchange.com/a/166131/52210) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes ``` ŒuØAiⱮḟ0jV ``` [Try it online!](https://tio.run/##ASsA1P9qZWxsef//xZJ1w5hBaeKxruG4nzBqVv///yJAI3QlNDg5LyotbyL/Il8i "Jelly – Try It Online") # Explanation ``` ŒuØAiⱮḟ0jV Main link Œu Uppercase the input Ɱ For each character i take its index in ØA the uppercase alphabet ḟ0 Filter; remove 0s j String-join by the right element V Evaluate ``` -4 bytes thanks to Mr. Xcoder ]
[Question] [ **Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/121781/edit). Closed 6 years ago. [Improve this question](/posts/121781/edit) Given text, remove leading and trailing whitespace (spaces, tabs, and newlines). Alternate title: Implement your own string trimming. # Input ASCII text (printable + spaces, tabs (`\t`), and newlines (`\n`)), in whatever format you would like. Carriage returns (`\r`) are outside of the scope of the input. # Output The same text in the same format, but with (only) trailing and leading spaces, tabs, and newlines removed. \*Note: If your language naturally outputs a trailing space/newline, please note that in your answer. # Test Cases This test case ensures that you can handle `\s` and the like. Please note whitespace in it. Input ```  \s test \t\n   ``` Output ``` \s test \t\n ``` For the following test cases (but not the above), `\s` is space, `\t` is tab, `\n` is newline. `=>` splits input and output. ``` \s\t\n\s => (empty string) \stest\s => test \nt\n\st\t => t\n\st _ => _ \s\s\n\s1\s+\s1\n => 1\s+\s1 ||_\s => ||_ ``` No builitins allowed that trim either specific characters or given characters. Builtins that remove arbitrary characters from the beginning/end of a string, or that remove given characters from any position in a string (by default) are allowed. [Answer] # [Retina](https://github.com/m-ender/retina), 10 bytes ``` ^\s+|\s+$ ``` [Try it online!](https://tio.run/nexus/retina#@x8XU6xdA8QqXP//c5VwKZRwAgA "Retina – TIO Nexus") Trailing newline is added automatically and is unavoidable. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes ``` >⁶TṬo\Tị ``` [Try it online!](https://tio.run/nexus/jelly#@2/3qHFbyMOda/JjQh7u7v7//z8nZ1JiUiVXWWJeZk5OIpQHAA "Jelly – TIO Nexus") [Answer] # JS (ES6), 27 bytes ``` i=>i.replace(/^\s+|\s+$/g,"") ``` [Answer] # [Carrot](https://github.com/kritixilithos/Carrot/), 21 bytes ``` #^//\S([\s\S]*\S)?/gS ``` [Try it online!](http://kritixilithos.github.io/Carrot/) ### Explanation Carrot has several global variables, one for each type: string, float and array. The program starts in string-mode, where all the operators will affect the global string variable. And I call these variables the "stack". ``` #^ Set the stack-string to the value of all of the input / Get matches of this regex: /\S([\s\S]*\S)?/g And set the stack-array to the array containing these matches There will only ever be one or zero matches S Convert to string-mode by joining the elements of the array ``` The `S` operator is supposed to take a string or number as an argument to join the array on, but apparently it is not needed in this case (I don't understand why). [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~11~~ 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) -2 bytes thanks to Dennis (use direct character conversion, similar to his answer `O>32` -> `>⁶` -1 byte thanks to Dennis (removing a redundant quick) ``` >⁶TṂr$Ṁị ``` **[Try it online!](https://tio.run/nexus/jelly#@2/3qHFbyMOdTUUqD3c2PNzd/f//f4WYYoWS1OIShZiSmDwuBQA)** Steering clear of anything that could be considered "trimming". ### How? ``` >⁶TṂr$Ṁị - Main link: list of characters (a.k.a. string) e.g. " t xt " ⁶ - literal space character > - greater than (vectorises) [0,0,1,0,1,1,0,0] T - truthy indexes [ 3, 5,6 ] $ - last two links as a monad Ṃ - minimum 3 r - inclusive range [[3],[3,4,5],[3,4,5,6]] Ṁ - maximum [3,4,5,6] ị - index into the input "t xt" ``` [Answer] # PHP, 40 Bytes Regex Version ``` <?=preg_replace("#^\s+|\s+$#","",$argn); ``` [Try it online!](https://tio.run/nexus/php#s7EvyCjgUkksSs@zVVKIKVGIyVMwVNBWMIzJU7Lmsrf7b2NvW1CUmh5flFqQk5icqqGkHBdTrF0DxCrKSjpKSjpgvZrW//8DAA "PHP – TIO Nexus") ## PHP, 77 Bytes The Regex version was so boring so I would try it without a Regex ``` <?=substr($a=$argn,strspn($a,$c="\t\n "),-strspn(strrev($a),$c)?:strlen($a)); ``` [Try it online!](https://tio.run/nexus/php#LYsxDoAgEAR7XnEhFF7EglZAPkKDhmhhCAH0@3gaq83s7BqXj8xEKHuyHHwDn0DBCMonrplbunG2XmttZRDBfjtJUHMilmKz3De6cJTTX1OUeJNF0uhm4jO@a0Td@wM "PHP – TIO Nexus") [Answer] # C (gcc) & preprocessor, ~~152~~ 149 bytes ``` #define f(x)(x==32|x==9|x==10) char*t(char*o){int i=strlen(o);for(;--i>0;){if(!f(o[i]))break;o[i]=0;};while(1){if(f(*o))o=o+1;else break;}return o;} ``` -3 bytes: Ironically, I forgot to remove my spaces. A function that takes in a `char*` (pointer to the first character of the string (how C implements strings)), and returns a pointer to the first non-space character in the string, and also replaces all trailing spaces with null bytes, C's string terminator. Ungolfed: ``` #define isspace(x) (x==32|x==9|x==10) // save bytes by not using this whole thing each time // (32 is ' ', 9 is '\t', 10 is '\n') char *trim(char *original) { int i=strlen(original); for(;--i>0;){ // start at the end of the string, work backwards if(!isspace(original[i])) break; // if the character not is a space character, stop working backwards original[i]=0; // else: replace the character with a null byte, C's string terminator } while(1){ if(isspace(original[0]))// shift the pointer until the first char is not a space original = original + 1; else break; } return original; // return the modified pointer } ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 9 bytes ``` e"^%s|%s$ ``` [Try it online](http://ethproductions.github.io/japt/?v=1.4.4&code=ZSJeJXN8JXMk&input=IiAgIHRlc3QgCQoiCi1R) (`-Q` flag used for visualisation only) [Answer] # C#, 60 bytes ``` s=>System.Text.RegularExpressions.Replace(s,"^\s+|\s+$",""); ``` If I could use built-ins this is only 12 bytes: ``` s=>s.Trim(); ``` [Answer] # [Python 2](https://docs.python.org/2/), 44 bytes ``` lambda s:re.sub(r'^\s*|\s*$','',s) import re ``` [Try it online!](https://tio.run/nexus/python2#LcZBCsIwEAXQdecUfyEklZIDFNx5AA8QhIlJIWBjmRkXgnePWbh48LZL7E/eU2boKiXoO3lx96jn73Byi3OLzlT34yUGKf0//SgdUpth8@NBLdcWpHD289wBRIUVNUSLjQhgJJ4ePFkhWq/DjSj8AA "Python 2 – TIO Nexus") ## Non-regex: 62 bytes Takes input as list of characters. Outputs by reference. ``` def f(s):exec'while s[%s].isspace():del s[%s]\n'*2%(0,0,-1,-1) ``` ]
[Question] [ **Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/266943/edit). Closed 3 months ago. [Improve this question](/posts/266943/edit) A loaded question is something like 'Have you stopped swearing?' in which both yes and no answers mean that I have swore, meaning it is impossible to answer the question if I haven't swore. However, the constructed language Lojban has a word na'i, which means there is something wrong with what you just said. Your input should be a list of newline-seperated strings containing the following tokens: 1. `start` followed by any integer (e.g. `-1`, `0`, `1`) 2. `stop` + integer 3. `haveYouStopped` + integer You can assume that each `stop` *n* is followed by the corresponding `start` *n*. Then for each `haveYouStopped` *n* in the code: * Print `Yes, I have.` + a newline if the last `stop` *n* occurs before the last `start` *n* * Print `No, I have not.` + a newline if the last `stop` *n* occures after the last `start` *n*, or at least one `start` *n* but no `stop` *n* is found in the previous line * Print `.i na'i` + a newline if no `start` *n* occurs in the previous lines. The last newline is optional. Examples: ``` start 1 stop 1 haveYouStopped 1 ``` Output: Yes, I have. ``` start 1 haveYouStopped 1 ``` Output: No, I haven't. ``` haveYouStopped 1 ``` Output: .i na'i All code is counted in UTF-8 bytes. Codepoints outside the UTF-8 range are not allowed. Use any language, shortest code wins. Also, no external sources are allowed. [Answer] # [Scala 3](https://www.scala-lang.org/), 255 bytes 255 bytes. It can be golfed much more. --- Golfed version. [Attempt This Online!](https://ato.pxeger.com/run?1=ZZHBTgIxEIbvPsWkF9oEmhgvZs2aeOCgCXggHggSUnYL1JS2aQeUII_hyQsXvfhEPI3OwqIJnmbmm87MP9P3z1Qoqy6-Bqzl_LOKjg13d378pAuEjjIO1mcAZh58RNg_lcbLnl_EQp8mCm8tlRnv5HyBamy1HH0scNK63H2XegKBY9bDaNy0WWYdFQZ1cDDD_D_iQmQPzmC-RpmCNcjZo2NCToxFHbse-Uia1J4HXBH0Uatitrb59VJZuIlRrXjRXIrcHouBiSsz4QVJdUjLJc4SE6Lk9OiEB-Ksr1MTbmGmlloybZNmXX8EroEHBoG0onW8lFON97FNjC-bTBpwqmGoz2ZTn-ENoDrEnEZwFacpO6istx6KDKptId8fHaBaA_ULgX0IwBirPYDXhIpOf_4HKlV9v-ihD0GXvxkqkokGhA6NNG5P6SuoryB_c1aL224P9gc) ``` def p(t:String,d:Map[String,String]=Map[String,String]()):Unit={t.split("\n").filterNot(_.isEmpty).foreach{l=>val Array(c,v)=l.split(" ");if(c.contains("s"))d(v)=if(c.contains("p"))"Yes, I have."else"No, I haven't."else println(d.getOrElse(v,".i na'i"))}} ``` Ungolfed version. [Attempt This Online!](https://ato.pxeger.com/run?1=fVK9TiMxEJauzFOM3GBLiSVEg6KjoKCgCBThCgQRMhtvMPLalj3LgSBPQkMDDW_E0zDe9SYCIRpbnvl-Zsbz_JYqZdXe-wWbOP9fRccWL68t1pP9jz_v_vpWVwgzZRw8jgBME3xE6CjSeDn3baz090TlrSWa8U42Laprq0cEWeoaQvSVTulM3yNHOqYwx2jcagxLU9GrwOVMhYsh098LOPgty4WYwj9nkGC5UIA7ZcEapxNFspVMwRrk7NIxIWtjUccTj_xKmnTUBHwQHav2EXimwd9JTxdFr1c8jFE98Mo3jXLLcQ61WpBDhg4OwERhmBoGLA3FIY0xcZaY2IpC1znfCP1MCZnCznUawzHcqDstGWibNLATP4TcDkpWVNfl7jBbq0CzQut4tpQrjafxiAC9-RiYNODUjiGvLzL5XA8_2FBBXMVVmvazKB-x-Gn8eexwULQYY5s6nhIq2pbdbSA3cO7bOfoQ9HKTIZJMZBBmZGncqG_i6w6Jrrx1v7NldV_K_Qk) ``` object Main { import scala.io.Source import scala.collection.mutable def processText(text: String, dict: mutable.Map[String, String] = mutable.Map[String, String]()): Unit = { val lines = text.split("\n").filterNot(_.isEmpty) for (line <- lines) { val Array(command, value) = line.split(" ") if (command.contains("s")) { dict(value) = if (command.contains("p")) "Yes, I have." else "No, I haven't." } else { println(dict.getOrElse(value, ".i na'i")) } } } def main(args: Array[String]): Unit = { val text = """ |start 1 |haveYouStopped 1 """.stripMargin processText(text) } } ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), (68† [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)) 107 bytesUTF-8 † Since the challenge states the answers should be counted in UTF-8 bytes for some reason.. -\_- ``` |ηʒθ'hÅ?}ε€#R.¡θ}н€н€θDgi".i na'i"ëJ…dptQi“Yes, I€¡.“ë“No, I€¡€–.“]» ``` [Try it online.](https://tio.run/##yy9OTMpM/f@/5tz2U5PO7VDPONxqX3tu66OmNcpBeocWnttRe2EvkAMmzu1wSc9U0stUyEtUz1Q6vNrrUcOylIKSwMxHDXMiU4t1FDyBig4t1ANyD68GEn75MCEg8ahhMkgi9tDu//8zEstSI/NLg0vyCwpSUxQMuYpLEotKFIygtK4xkJFfAKLRVBqhC@gaAwA) **Explanation:** ``` | # Get all inputs as a list of strings η # Pop and push its prefixes ʒ } # Filter this list of prefixes, keeping those where: θ # The last string of the prefix Å? # ends with 'h '# an "h" ε # Map over each prefix ending with "haveYouStopped" €# # Split each inner string by spaces R # Reverse this list of pairs .¡ } # Then group it by: θ # The last item of the pair (the numbers) н # Keep the first group (of the reversed list) €н # Keep the strings of each inner pair €θ # Keep the last letter of each string Dg # Duplicate, pop and push the amount of characters in this list i # If this length is 1 (thus only "haveYouStopped"): ".i na'i" # Push string ".i na'i" ë # Else: J # Join the list of 2 or 3 characters to a string …dptQi # If it's equal to "dpt" (thus "haveYouStopped,stop,start"): “Yes, I€¡.“ # Push dictionary string "Yes, I have." ë # Else: “No, I€¡€–.“ # Push dictionary string "No, I have not." ] # Close both if-else statements and map » # Join the list of strings by newlines # (after which it is output implicitly with additional trailing newline) ``` [See this 05AB1E tip of mine (section *How to use the dictionary?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `“Yes, I€¡.“` is `"Yes, I have."` and `“No, I€¡€–.“` is `"No, I have not."`. [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~92~~ ~~75~~ 74 bytes ``` L$ms`d( \S+)$(?<=([pt])\1$.+?)? $2.i na'i p.+ YesI. t.+ NoIn't. I , I have ``` [Try it online!](https://tio.run/##bcmxCsIwEIDh/Z7ihkATogdxVjIHxKVTsYKBBsxgcjSnrx/t3uXng39Nkkt0vV/Vuz0XjfNojdL@fNF3loeZnSLrjQd1oowlDhmYLEypBQL561ZDGYQgwAEDvuI39b51qp9RKnNa8OigSVxlw96qvHt@ "Retina – Try It Online") Link includes test cases. Explanation: ``` L$ms`d( \S+)$(?<=([pt])\1$.+?)? $2.i na'i ``` For each `haveYouStopped` line, look for a previous `start` or `stop` line with that signed integer, and if so prefix the output with the final `t` or `p`, otherwise just output `.i na'i`. ``` p.* YesI. t.* NoIn't. I , I have ``` If a start or stop was found then decode it to the desired output string. Edit: Saved 17 bytes and corrected the Yes/No order thanks to @tsh. Since this question counts in UTF-8, I didn't post a [Charcoal](https://github.com/somebody1234/Charcoal) answer, but had it been allowed it would have been 59 SBCS bytes: ``` ≔⦃⦄θWS¿№ιs§≔θΣι⪫⪪⎇№ιp¦Yes,.¦No,n't.¦,¦, I have⟦∨§θΣι.i na'i ``` [Attempt This Online!](https://ato.pxeger.com/run?1=bU8xTgMxEOzzipWbrCXnJDqkqwLVUQDS0URRCnNxcisZ27HXAYR4CU0KEDyGD-Q3OBxFJNLsrmZ2Znbfvrpex85ru9t9ZF5Nzvff05Ro7fDlVcFG1qPHnqwBbFzI3HIkt0YpgVaAlz47RlIgkijQoJty45bmCTcK2vyAJBVceXLYBkuMdyY6HZ-PpEGUDTEzSVWiDNdeuTFXv6AaKjTQ660pETUYmwzcliMY5zcR_4UdBBWB02MSciHr93Tfpb_PPudisrVisb842M18btmHYJZwNkqsI5d-gvDhFD44_gA) Link is to verbose version of code. Takes input as a list of newline-terminated strings. Explanation: ``` ≔⦃⦄θ ``` Start with all questions being impossible. ``` WS ``` Loop through the input strings. ``` ¿№ιs ``` Does this string resolve a question? ``` §≔θΣι⪫⪪⎇№ιp¦Yes,.¦No,n't.¦,¦, I have ``` If so then save the appropriate answer. ``` ⟦∨§θΣι.i na'i ``` Otherwise, output the saved answer, or the impossible answer if one wasn't saved. [Answer] ## Python, ~~160~~ 158 bytes ``` def d(t,i={}): for l in t.strip().split("\n"): c,v=l.split() if"s"in c:i[v]="Yes, I have."if"p"in c else"No, I haven't." else:print(i.get(v,".i na'i")) ``` -2 thanks to UndoneStudios (Assumes that you are referring to taking input as a newline-delimited string) ### Ungolfed version ``` def decode(text): data = {} for line in text.strip().split("\n"): command, value = line.split() if "s" in command: data[value] = "Yes, I have." if "p" in command else "No, I haven't." else: print(data.get(v, ".i na'i")) ``` ]
[Question] [ **Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/153349/edit). Closed 6 years ago. [Improve this question](/posts/153349/edit) Is there a better way to calculate the number of leap years between two given years? I want to make my code shorter (in Python). Do you have any suggestions? Here is my solution: ``` i=int r=raw_input t=i(r()) while t: b,d=map(i,r().split()) c=0 for y in range(b,d+1): if y%400==0 or y%4==0 and y%100:c+=1 print c t-=1 ``` [Answer] ### Quick wins (-6 bytes) Using `i=int` actually costs 2 bytes, because the shortened expression is only used twice in the code. We can save 4 other bytes by using `<1` instead of `==0` and removing useless whitespace. ``` r=raw_input t=int(r()) while t: b,d=map(int,r().split()) c=0 for y in range(b,d+1): if y%400<1or y%4<1and y%100:c+=1 print c t-=1 ``` ### Getting rid of the for loop (-7 bytes) Using **sum()**, **map()** and a lambda is shorter than a **for** loop with an additional variable. However, we need an explicit test on `y%100` to turn the result into a boolean. ``` r=raw_input t=int(r()) while t: b,d=map(int,r().split()) print sum(map(lambda y:y%400<1or y%4<1and y%100>0,range(b,d+1))) t-=1 ``` ### Using a built-in function and tweaking the way input is taken (-16 bytes) Finally, importing and using `calendar.isleap` saves 7 more bytes. `input()` instead of `int(r())` saves another byte. Dropping `r=raw_input` and using it directly in the loop saves another 4 bytes. Finally, removing all unnecessary newlines saves 4 bytes too. ``` from calendar import* t=input() while t:b,d=map(int,raw_input().split());print sum(map(isleap,range(b,d+1)));t-=1 ``` [Try it online!](https://tio.run/##LctBDsIgEIXhPaeYJWhtoCu14SwGLVoSGCYwTdPTIzGu3uL/Hh28Zpxae5ec4OWix8UVCIly4ZNgG5A2lkrsa4ge@P4cFpscyYA8FLc//n2sFENfNVPpCeqW5I/V6B11iR8v@/dsVDd8saY1I8xNa5i0uX4B "Python 2 – Try It Online") *Saved 3 bytes thanks to @user202729* ### Not using a built-in function anymore... (-3 bytes) ``` t=input() while t:b,d=map(int,raw_input().split());print sum(y%400<1or y%4<1<=y%100for y in range(b,d+1));t-=1 ``` [Try it online!](https://tio.run/##LYzNCoMwEITvPsVehEht2ZUe@pM8i6TU1gWNS1yRPH0aoaf5ho8ZSTouoctZHQfZ1DTVPvI0gD5e7dvNXgwHbaPf@7@/rDJxyeYpsShYt9mk@opoaYlQyJJ1qSbEz9GBA0QfvoMpfycqMz07ypkquiNCh3T7AQ "Python 2 – Try It Online") All these changes have shortened the source code to **110 bytes**. ]
[Question] [ *I've searched around, and cannot find a challenge too similar to this one--however, it would not surprise me if this is not the first of its kind. My apologies if I've overlooked something.* # The Challenge This challenge is intended to amuse those of every skill level and users of every language. Your task, in itself, is very simple. Write a program (or function) that prints the longest sentence in 140 bytes. # The Input Your code should not receive input from anywhere. You may not take any arguments, any values from STDIN, or any word lists. Additionally, built-ins or libraries that generate word lists or manipulate word lists are also banned. Output should be generated by the program itself. # The Output Your output should abide by the following rules: * For simplicity, the output must be in **English**, and must not contain any characters other than `a-z A-Z .,:;()!?-`. (Tabs and newlines should not be present in your sentence, and exactly one space should exist between words) * Your output may include trailing or leading whitespace, but these do not count toward your final score. * Your output must be a singular, valid, punctuated, grammatically correct sentence. * As long as the sentence is syntactically valid, meaning is unimportant. Please refrain from vulgarity. * Your output should only include words recognized by dictionary.com. * Your output must not repeat any singular word more than 3 times. [Conjunctions](http://en.wikipedia.org/wiki/Conjunction_%28grammar%29) and [articles](http://en.wikipedia.org/wiki/Article_%28grammar%29) are an exception to this rule and may be repeated any number of times. * Your output must be **finite**. * Any output method is acceptable--whether it be to STDOUT, a file, a returned string, whatever. # The Rules * Your score is the length, in bytes, of the sentence your program generates. * Program source code should not exceed 140 bytes. *Insert witty comment about how my only method of communication is Twitter here.* * Your program should terminate within a minute on any modern machine. * Sufficiently clever code or valid output larger than the code itself may be eligible for a bounty! * [Standard loopholes](http://meta.codegolf.stackexchange.com/questions/1061/standard-loopholes-which-are-no-longer-funny) apply. *Questions, comments, concerns? Let me know!* [Answer] # CJam, 140 bytes → 2301 characters [Try it online.](http://cjam.aditsu.net/#code=%22I'm%20%22%22jd%C3%87%C3%89%14%C3%9B7%C2%93%C2%AA%25%C3%B9%C3%9Et%C3%9B%C3%B9%09%C2%B1%C3%A7V(%19ex%13%C3%A73%C3%A5%24Z%C2%B1%C2%B3R%C3%8C%C3%8A%0AD%C2%BBl%C2%B0%C3%98E%C3%B8%1Cv%C2%B8x%C2%A1%C2%B7%C3%B0Q%C3%A0%02%5C%2B%C3%9C%C2%B5j%C2%90R%C2%A12%1D%3E%C3%A3q%C2%9E%C2%A7S%C3%A3%C2%BE%1Bi%13PL%C3%9B%22252b27b'%60f%2B'%60%2F2%2F%7B~%22ing%2C%20%22%2Bf%2B~%7D%2F%22and%20%22%5C7%3C%5D%5D3*%22%20while%20%22*'.) ### Code ``` "I'm ""jdÇÉÛ7ª%ùÞtÛù ±çV(exç3å$Z±³RÌÊ D»l°ØEøv¸x¡·ðQà\+ܵjR¡2>ãq§Sã¾iPLÛ"252b27b'`f+'`/2/{~"ing, "+f+~}/"and "\7<]]3*" while "*'. ``` ### Output ``` I'm bagging, fagging, gagging, lagging, nagging, ragging, sagging, tagging, wagging, bailing, failing, hailing, jailing, mailing, nailing, railing, sailing, tailing, wailing, capping, lapping, mapping, napping, rapping, sapping, tapping, yapping, zapping, bearing, fearing, gearing, hearing, nearing, rearing, searing, tearing, wearing, bending, fending, lending, mending, pending, rending, sending, tending, vending, wending, betting, getting, jetting, letting, netting, petting, setting, vetting, wetting, dipping, hipping, kipping, nipping, pipping, ripping, sipping, tipping, yipping, zipping, bobbing, dobbing, fobbing, gobbing, jobbing, lobbing, mobbing, robbing, sobbing, bulling, culling, dulling, fulling, gulling, hulling, lulling, mulling, and pulling while I'm bagging, fagging, gagging, lagging, nagging, ragging, sagging, tagging, wagging, bailing, failing, hailing, jailing, mailing, nailing, railing, sailing, tailing, wailing, capping, lapping, mapping, napping, rapping, sapping, tapping, yapping, zapping, bearing, fearing, gearing, hearing, nearing, rearing, searing, tearing, wearing, bending, fending, lending, mending, pending, rending, sending, tending, vending, wending, betting, getting, jetting, letting, netting, petting, setting, vetting, wetting, dipping, hipping, kipping, nipping, pipping, ripping, sipping, tipping, yipping, zipping, bobbing, dobbing, fobbing, gobbing, jobbing, lobbing, mobbing, robbing, sobbing, bulling, culling, dulling, fulling, gulling, hulling, lulling, mulling, and pulling while I'm bagging, fagging, gagging, lagging, nagging, ragging, sagging, tagging, wagging, bailing, failing, hailing, jailing, mailing, nailing, railing, sailing, tailing, wailing, capping, lapping, mapping, napping, rapping, sapping, tapping, yapping, zapping, bearing, fearing, gearing, hearing, nearing, rearing, searing, tearing, wearing, bending, fending, lending, mending, pending, rending, sending, tending, vending, wending, betting, getting, jetting, letting, netting, petting, setting, vetting, wetting, dipping, hipping, kipping, nipping, pipping, ripping, sipping, tipping, yipping, zipping, bobbing, dobbing, fobbing, gobbing, jobbing, lobbing, mobbing, robbing, sobbing, bulling, culling, dulling, fulling, gulling, hulling, lulling, mulling, and pulling. ``` ### Explanation As I'm sure you can tell, my main tactic was to generate a large number of very similar words. My plan was to find groups of words that all had the same spelling after the first letter with a large number of possible first letters, as these could be heavily compressed. To find the best candidates, I grabbed the whole dictionary, grouped words by their spelling after the first letter, and sorted these groups in descending order by the sum of the lengths of all words in the group. Upon doing this, I discovered that many of the top entries were the present tense of verbs, in the form "\_\_\_ing." This was great, because it meant that not only could I abstract the "ing" out of every group, but also every word could simply be thrown in a big list in the sentence because they were all of a form of speech that allowed it. The big mess of characters in the middle of the code encodes as much of this data as I could fit, using multiple compression methods. As for the sentence structure generated, it's fairly simple. It's certainly a bit redundant, repeating the main phrase 3 times for maximal length, but I believe it's grammatically correct. With the innards of the verb lists cut out, the sentence looks like this: ``` I'm bagging, ... , and pulling while I'm bagging, ... and pulling while I'm bagging, ... and pulling. ``` [Answer] # Python - Code: 140, Output: 476 NOTE: Currently needs to be modified. Any help on replacing a couple words within the byte limit? I made use of the built-in documentation for the integer type, and so far I am confident that this is one of the most unique, if not the most creative, approach(es). Most of the code was overhead used to remove newlines and combine the documentation into a single sentence. Annoyingly, I also had to replace a couple of occurrences of the word "string". ``` import re;print'Cattle, c'+re.sub('a string','a key',re.sub(' ',', but ',re.sub(r'\. ',', and',re.sub(r'\n',' ',int.__doc__.lower()))[28:])) ``` Output: ``` Cattle, convert a key or number to an integer, if possible, and a floating point argument will be truncated towards zero (this does not include a key representation of a floating point number!), but when converting a key, use the optional base, and it is an error to supply a base when converting a non-string, and if base is zero, the proper base is guessed based on the string content, and if the argument is outside the integer range a long object will be returned instead. ``` Run it here: <http://repl.it/fsM> [Answer] # JAVA - Code: 122, length: 153 words, 464 bytes Java, yep, java. Ok, so I had to make it a function instead of a program. The boilerplate was just too much. Golfed code: ``` void p(){int i=0;char c=1;while(i++<3){for(c=65;c<90;System.out.print(c+++" and "));}System.out.print(c+" are letters.");} ``` Readable version: ``` void p(){ int i=0; char c=1; while(i++<3){ for(c=65;c<90;System.out.print(c+++" and ")); } System.out.print(c+" are letters."); } ``` Output: A and B and C and D and E and F and G and H and I and J and K and L and M and N and O and P and Q and R and S and T and U and V and W and X and Y and A and B and C and D and E and F and G and H and I and J and K and L and M and N and O and P and Q and R and S and T and U and V and W and X and Y and A and B and C and D and E and F and G and H and I and J and K and L and M and N and O and P and Q and R and S and T and U and V and W and X and Y and Z are letters. Each letter is defined under dictionary.com as a valid word in response to its ordinal position in the alphabet. Each word is used at most three times. [Answer] # Haskell, code: around 104 bytes, output: as many as your computer can produce within the 1min limit ``` f = let n=4 in putStr $ "Corollary: "++ (replicate n '(') ++ "a-b" ++ (replicate n ')') ++ " equals c." ``` Output example: ``` Corollary: ((((a-b)))) equals c. ``` Of course you can change `n` to any number you want (including expressions like `100^100` to stay within the 140 byte limit) to increase the number of parentheses. [Answer] **Excel** (because ... :) ): Code: 135 Output: 211 [edit] corrected beginning of sentence, the previous one really wasn't correct, this version is slightly better. Still a bit of a grammar "hack", but still valid by the rules in any case :) [/edit] ``` =CONCATENATE("Where ",REPT("someone thinks that ",3),rept("everyone understands when ",3),rept("they believe what ",3),"nobody cares.") ``` **Output:** ``` Where someone thinks that someone thinks that someone thinks that everyone understands when everyone understands when everyone understands when they believe what they believe what they believe what nobody cares. ``` ]
[Question] [ Write a program that when given five integers as input, outputs the value given by the following integral: ![enter image description here](https://i.stack.imgur.com/7lk8G.png) * Input is five integers (in any reasonable format) in the order `a b c d e` where each number corresponds to the variables in the image above. * No built in integral functions allowed. * Output must be a base ten float, precise to `+/- 1e-3`. Least number of bytes wins. [Answer] # CJam, ~~46~~ 43 bytes ``` l~\:D-A3#:K*),])\f{\dK/D+\~\Z$*+@_*@*+K/}:+ ``` The arguments are read via STDIN like ``` 1 2 3 4 7 ``` and the output is printed to STDOUT like ``` 135.04650050000018 ``` You can increase the precision by changing the `3` in `A3#:K` to a higher number. The higher the number, the longer the program will take to finish. [Try it online here](http://cjam.aditsu.net/) [Answer] # CJam, 27 bytes ``` q~W%2/~~[2*\~3*\6*0]fb:-6d/ ``` Example input: ``` [1 2 3 4 8] ``` Output: ``` 209.33333333333334 ``` [Answer] # R, 71 bytes If the input is a vector `x <- c(a, b, c, d, e)` then you can compute the integral directly as per @feersum's comment. ``` e=x[5];d=x[4];x[1]*e^3/3+x[2]*e^2/2+x[3]*e-x[1]*d^3/3-x[2]*d^2/2-x[3]*d ``` [Answer] # JavaScript, 52 bytes ``` (a,b,c,d,e)=>a*e^3/3+b*e^2/2+c*e-a*d^3/3-b*d^2/2-c*d ``` Calculates the indefinite integral at `e` and `d`, then subtract. ]
[Question] [ **This question already has answers here**: [Primes and Twin Primes](/questions/219980/primes-and-twin-primes) (23 answers) Closed 2 years ago. Your challenge is to write a Python program to print all the primes (separated by whitespace) less than a given integer `N` with an asterisk (`*`) next to each twin prime in **ONE statement**. A [twin prime](https://en.wikipedia.org/wiki/Twin_prime) is a prime number that is either two more or two less than another prime. All output should be to stdout and input should be read from stdin. (Hardcoding outputs is allowed, but it is not likely to result in very short code.) Shortest code wins! For the less restricted version of the challenge for all languages, click [here](https://codegolf.stackexchange.com/questions/219980/primes-and-twin-primes). ## Input * `N` is always one of 50, 100, 1000, 1000000, or 10000000 ## Output * Possible output for input `12` could be ``` 2 3* 5* 7* 11* ``` (However, the input will never be 12, as specified above. Your program need not work for this input.) ## Restrictions * No new lines or semicolons * Do not use eval or exec [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 119 bytes ``` print(*[str(i)+'*'*(p(i-2)|p(i+2))for i in range(2,int(input()))if(p:=lambda x:all(x%i for i in range(2,x))*(x>1))(i)]) ``` Reads from stdin. [Try it online!](https://tio.run/##Zc1BCsIwEEbhq2QjnT9VaONGCnqR4iKi1YE4HcYUInj3WNeu3urj6Ts/Ztkf1GpVY8nkx1c2YrSNbzwp8S7gs6YNwDSbY8fiLMr9RmH7Ayy6ZALAE@lwTPF5uUZXhpgSlQ27P1QAT@XUA@vmjFr7rvsC "Python 3.8 (pre-release) – Try It Online") ]
[Question] [ **This question already has answers here**: [Calculate π with quadratic convergence](/questions/47912/calculate-%cf%80-with-quadratic-convergence) (5 answers) Closed 5 years ago. [Inspired by Nicola Sap's Challenge](https://codegolf.stackexchange.com/questions/171168/without-using-numbers-get-the-highest-salary-you-can-but-dont-exaggerate) # Goal Your challenge is to simply produce π with 232-1 digits. However today's twist, like the title implies, is to produce it without using any numbers or any π constants in your source-code. # Input/Output Your program will not be provided usable input. It can output in any reasonable format. # Rules * Standard Loop-Holes forbidden * You cannot use numbers in your source code nor can you use a pi constant if it exists. If your language also has tau defined as 2pi, that's also banned. Numbers are in the range [0-9] * ~~You must output as many digits as you can~~ You must output 2^32-1 digits of pi, including the 3. (This has been changed due to the arbitrary nature of the original task) * Your Program must terminate, or at least theoretically terminate given enough time. Crashing is an acceptable way to terminate. # Scoring This is code golf so shortest answer wins. [A Million Digits of Pi for your use](https://www.piday.org/million/) [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 67 bytes ``` {$!=.FatRat²/$!+$_+$_-?e}for 𐄳²…¹;say substr ⁴/$!,^²³² ``` [Try it online!](https://tio.run/##K0gtyjH7/79aRdFWzy2xJCix5NAmfRVFbZV4INK1T61Nyy9S@DChZfOhTY8alh3aaV2cWKlQXJpUXFKk8KhxC1CpTtyhTYeA0v//AwA "Perl 6 – Try It Online") Takes a *very* long time to compute. As an example here's an altered version that only prints the first [1000 digits](https://tio.run/##K0gtyjH7/79aRdFWzy2xJCix5NAmfRVFbZV4INK1T61Nyy9SMDIwMHjUsOzQTuvixEqF4tKk4pIihUeNW4AKdeIMDQyM/v8HAA "Perl 6 – Try It Online"). [Answer] # Mathematica, ~~42~~ 39 bytes `N[Log[-(d=I/I)]/I,((c=d+d)^c^c^c)^c-d]&` ~~Output~~ Returns exactly 4294967295 digits as requested. If more digits were allowed, then by outputting 7.76e17 digits (if even possible lol), 26 bytes would be possible: `N[Log[-E/E]/I,E^(E^E*E)]&` ### Sorry but `Pi = Ln(-1)/i`. [Answer] # [GolfScript](http://www.golfscript.com/golfscript/), ~~70~~ 85 bytes ``` ;''!..):t{](..+.*:a@~@*\a(*@)\@}t.+.+t+:T t..*.*t*?(:b?*@;\{.@[\].~/\~%T*@}b*;;]("."@ ``` *+15 bytes because I can't read.* [Try it online!](https://tio.run/##DchBCoMwEAXQq1ihGH/gd58snENk52ShgqUgWOrsxFw99i3fe9/WY/l9vlZr7LoH2Qc7syM9ESYpAp0cpFe57H/efEiNkSAMgwvzAIl6UkbNLC8tzwS5ZsSYXctWar0B "GolfScript – Try It Online") Or, actually, don't. [Try this online instead](https://tio.run/##DcmxCoAgEADQXykh0hOuXYfuI9w6BwuKICjqtshfN9f3tvNYn@XeLynF932LaJy8USNaBJcoE3DSQIbpk2pWrAuN1JtHIM8v0sQR88C5C0DfDN5HrVBRKT8 "GolfScript – Try It Online"), which calculates 4 digits. ]
[Question] [ **Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/143827/edit). Closed 6 years ago. [Improve this question](/posts/143827/edit) In this polyglot challenge, you will work together to figure out how to output all the 26 letters of the English alphabet! **How does this work?** For each answer, you must pick a new language (or a new major version of a language, for example, python 2 and python 3 are counted separately) that prints the next letter after the previous one. **Example of an answer.** Python 3 (Letter a): ``` print("a") ``` **Other rules.** 1. All letters are in lowercase. 2. Language must be Turing complete. 3. The same person cannot post twice in a row. 4. If an answer is found to be invalid it must be deleted. 5. Two users who post "at the same time" will have to let the earlier submission stand. 6. The same language must not be posted more than once. 7. Once we were done we keep going and start back at a. 8. It should print in all previous languages what it did in their original challenge **More things:** 1. Set the sorting to oldest so this post works well. 2. Try not to make it impossible for the other person or else your post may be set as invalid. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 3 bytes ``` a⎚b ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z/xUd@spP//AQ "Charcoal – Try It Online") :P [Answer] # Mathematica, 1 byte ............... ``` a ``` ]
[Question] [ **This question already has answers here**: [List of primes under a million](/questions/5977/list-of-primes-under-a-million) (113 answers) Closed 9 years ago. Write a function which gets as input a number (`0 <= n <= 255`) stored in 32-bit variable and returns non-zero integer if `n` is prime number and `0` otherwise. Consider`n = 0` and `n = 1` as non-primes. Arrays and pointers are not allowed. **Score:** 1 - for `| & ^ ~ >> <<` operators 1.1 - for `+ - < > <= >= == != ! && ||` operators and branches & loops 1.2 - for `*` operator 2 - for `/ %` operators 10 - for casting to/using other types (other than 32-bit integer) Score for operators inside loops is score \* max iterations count. Answer with lowest score wins. If many answers with identical score, wins first one. [Answer] # Python (4) ``` f = lambda n: (3622934801701902697686555901643181168549895964810913375391936802953324275884 >> n) & 1 ``` Damn casting. No trickery here, just magic. Number generated with J: `#.x:1 p: i._256`. Output: ``` for i in enumerate(map(f,range(256))): ...: print i ...: (0, 0L) (1, 0L) (2, 1L) (3, 1L) (4, 0L) (5, 1L) (6, 0L) (7, 1L) (8, 0L) (9, 0L) (10, 0L) (11, 1L) (12, 0L) (13, 1L) (14, 0L) (15, 0L) (16, 0L) (17, 1L) (18, 0L) (19, 1L) (20, 0L) (21, 0L) (22, 0L) (23, 1L) (24, 0L) (25, 0L) (26, 0L) (27, 0L) (28, 0L) (29, 1L) (30, 0L) (31, 1L) (32, 0L) (33, 0L) (34, 0L) (35, 0L) (36, 0L) (37, 1L) (38, 0L) (39, 0L) (40, 0L) (41, 1L) (42, 0L) (43, 1L) (44, 0L) (45, 0L) (46, 0L) (47, 1L) (48, 0L) (49, 0L) (50, 0L) (51, 0L) (52, 0L) (53, 1L) (54, 0L) (55, 0L) (56, 0L) (57, 0L) (58, 0L) (59, 1L) (60, 0L) (61, 1L) (62, 0L) (63, 0L) (64, 0L) (65, 0L) (66, 0L) (67, 1L) (68, 0L) (69, 0L) (70, 0L) (71, 1L) (72, 0L) (73, 1L) (74, 0L) (75, 0L) (76, 0L) (77, 0L) (78, 0L) (79, 1L) (80, 0L) (81, 0L) (82, 0L) (83, 1L) (84, 0L) (85, 0L) (86, 0L) (87, 0L) (88, 0L) (89, 1L) (90, 0L) (91, 0L) (92, 0L) (93, 0L) (94, 0L) (95, 0L) (96, 0L) (97, 1L) (98, 0L) (99, 0L) (100, 0L) (101, 1L) (102, 0L) (103, 1L) (104, 0L) (105, 0L) (106, 0L) (107, 1L) (108, 0L) (109, 1L) (110, 0L) (111, 0L) (112, 0L) (113, 1L) (114, 0L) (115, 0L) (116, 0L) (117, 0L) (118, 0L) (119, 0L) (120, 0L) (121, 0L) (122, 0L) (123, 0L) (124, 0L) (125, 0L) (126, 0L) (127, 1L) (128, 0L) (129, 0L) (130, 0L) (131, 1L) (132, 0L) (133, 0L) (134, 0L) (135, 0L) (136, 0L) (137, 1L) (138, 0L) (139, 1L) (140, 0L) (141, 0L) (142, 0L) (143, 0L) (144, 0L) (145, 0L) (146, 0L) (147, 0L) (148, 0L) (149, 1L) (150, 0L) (151, 1L) (152, 0L) (153, 0L) (154, 0L) (155, 0L) (156, 0L) (157, 1L) (158, 0L) (159, 0L) (160, 0L) (161, 0L) (162, 0L) (163, 1L) (164, 0L) (165, 0L) (166, 0L) (167, 1L) (168, 0L) (169, 0L) (170, 0L) (171, 0L) (172, 0L) (173, 1L) (174, 0L) (175, 0L) (176, 0L) (177, 0L) (178, 0L) (179, 1L) (180, 0L) (181, 1L) (182, 0L) (183, 0L) (184, 0L) (185, 0L) (186, 0L) (187, 0L) (188, 0L) (189, 0L) (190, 0L) (191, 1L) (192, 0L) (193, 1L) (194, 0L) (195, 0L) (196, 0L) (197, 1L) (198, 0L) (199, 1L) (200, 0L) (201, 0L) (202, 0L) (203, 0L) (204, 0L) (205, 0L) (206, 0L) (207, 0L) (208, 0L) (209, 0L) (210, 0L) (211, 1L) (212, 0L) (213, 0L) (214, 0L) (215, 0L) (216, 0L) (217, 0L) (218, 0L) (219, 0L) (220, 0L) (221, 0L) (222, 0L) (223, 1L) (224, 0L) (225, 0L) (226, 0L) (227, 1L) (228, 0L) (229, 1L) (230, 0L) (231, 0L) (232, 0L) (233, 1L) (234, 0L) (235, 0L) (236, 0L) (237, 0L) (238, 0L) (239, 1L) (240, 0L) (241, 1L) (242, 0L) (243, 0L) (244, 0L) (245, 0L) (246, 0L) (247, 0L) (248, 0L) (249, 0L) (250, 0L) (251, 1L) (252, 0L) (253, 0L) (254, 0L) (255, 0L) ``` [Answer] The most obvious solution scores 32.3. [Test Ideone](https://ideone.com/ZBlPHe) ``` int p(int v) { return (v > 1) & (v == 2 || (v % 2)) & (v == 3 || (v % 3)) & (v == 5 || (v % 5)) & (v == 7 || (v % 7)) & (v == 11 || (v % 11)) & (v == 13 || (v % 13)); } ``` ]
[Question] [ **Closed**. This question needs to be more [focused](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Update the question so it focuses on one problem only by [editing this post](/posts/63041/edit). Closed 8 years ago. [Improve this question](/posts/63041/edit) Can you think of a regular expression that does not match itself? [Answer] A few on 2 chars ``` ^$ \s \d \n \t \r ``` And many more consisting of a \ and a lowercase character. ]
[Question] [ Objective/Restrictions: 1. May only be answered with programming language that has function syntax (or procedure, method, lambda, macro, statement grouping and labelling) . 2. Create a function with at least 2 argument/parameter, that generates an array containing 7 random strings, each string contains 3 characters, string may only contain alphanumeric characters `[a-zA-Z0-9]`. The number 7 and 3 passed into the function 3. Create a function that sort those strings using in special alphabetical ascending order: number first, alphabet later (lower-case then upper-case), for example: ``` 1aa 2ac aab abc Aab bAA BZ2 ``` 4. Create a function to print each string in descending order from the last one to the first one without mutating the ascending ordered array. 5. Call all three function and produce the correct output 6. Shortest code wins! **Note**: if possible, give the [ideone](http://ideone.com/FYVgb4) (this one also example implementation in Ruby) or any other online compiler link to test the correctness. [Answer] # Perl 5 - 181 chars Ungolfed ``` @z=(0..9,a..z,A..Z); sub d{ map{ tr/A-Za-z/a-zA-Z/; $_ } @_ } # n - number of strings to generate # l - length of strings sub a{ ($n,$l) = @_; $a .= $z[rand@z] for 1..$n*$l; ($a=~/(.{$l})/g) } sub b{ d(sort d(@_)) } sub c{ for(-$#_..0){ print "$_[-$_]\n" } } c b a 7,3 ``` Golfed ``` @z=(0..9,a..z,A..Z);sub d{map{tr/A-Za-z/a-zA-Z/;$_}@_}sub a{($n,$l)=@_;$a.=$z[rand@z]for 1..$n*$l;($a=~/(.{$l})/g)}sub b{d(sort d(@_))}sub c{for(-$#_..0){print"$_[-$_]\n"}}c b a 7,3 ``` [Answer] # Perl6   145 chars ``` #! /usr/bin/env perl6 my@a='a'..'z'; my@b='A'..'Z'; my@c=^10,@a,@b; # first argument $^a is the number of strings # second argument $^b is the length of the strings sub a{@c.roll($^b).join xx$^a}; # sub b{@_.sort} # numbers then upper then lower sub b{@_.sort(*.trans(@a,@b Z=>@b,@a))}; # swaps upper and lower sub c{say @_.reverse}; c b a 7,3 ``` ``` my@a='a'..'z';my@b='A'..'Z';my@c=^10,@a,@b;sub a{@c.roll($^b).join xx$^a};sub b{@_.sort(*.trans(@a,@b Z=>@b,@a))};sub c{say @_.reverse};c b a 7,3 ``` After removing the comments and all of the newlines, I get 145 characters. If the requirements were changed so that the strings were sorted by numbers then uppercase then lowercase, I could remove 25 characters from the `b` subroutine. [Answer] # Ruby, 141 Fairly straightforward solution. Uses recursion to generate the random `String`s and makes use of `String#tr` to make the sorting short and sweet. ``` O=[*?0..?9]+[*?A..?Z]+[*?a..?z] r=->i,s{i<1?[]:([O.sample(s)*'']+r[i-1,s])} s=->a{a.sort_by{|e|e.tr"A-Za-z","a-zA-Z"}} p=->a{puts a.reverse} ``` Usage: `p[s[r[7,3]]]`. [Answer] # J - 70 chars ``` a=:'0123456789',6}.26|.a.{~65+i.58 b=:{&a@?@$&62 c=:/:62&#.@(a&i.) d=:\:~ ``` Usage: `d c b 7 3` [Answer] # Ruby - 339 chars ``` X=[*('0'..'9')]+[*('a'..'z')].map{|c|[c,c.upcase]}.flatten Y={};v=0;X.each{|c|Y[c]=(v+=1)} def x n;n.times.to_a.map{X[(rand()*X.length).to_i]}.join '';end def y m,n;m.times.to_a.map{x n};end def z r;r.sort{|a,b|v=-1;w=0;a.each_char{|c|d=b[v+=1];next if c==d;w=(Y[c]<Y[d]?-1:1);break};w};end def a b;b.reverse_each{|c|puts c};end a z(y 7,3) ``` verify [here](http://ideone.com/FYVgb4) ]
[Question] [ I have this function to generate UUID's: ``` function uuid($v=4,$d=null,$s=false)//$v-> version|$data-> data for version 3 and 5|$s-> add salt and pepper { switch($v.($x='')) { case 3: $x=md5($d.($s?md5(microtime(true).uniqid($d,true)):''));break; case 4:default: $v=4;for($i=0;$i<=30;++$i)$x.=substr('1234567890abcdef',mt_rand(0,15),1);break; case 5: $x=sha1($d.($s?sha1(microtime(true).uniqid($d,true)):''));break; } return preg_replace('@^(.{8})(.{4})(.{3})(.{3})(.{12}).*@','$1-$2-'.$v.'$3-'.substr('89ab',rand(0,3),1).'$4-$5',$x); } ``` This is far from being short! The idea is to reduce this at maximum! Criteria to meet: * It MUST have the format `xxxxxxxx-xxxx-vxxx-yxxx-xxxxxxxxxxxx`, being x a hexadecimal number, y MUST be 89AB and v has to be the version! (**required**) * Only `v`can be generated randomly for all versions (non-standard, **optional**) * Version 3 and 5 have to generate ALWAYS the same UUID (except for the rule above, **required**) * You must provide a method of making the UUID somewhat random (**required**, except for version 4) * Version 3 uses `md5` to "pack" the data, while version 5 uses `sha1` (leaving a few chars behind, **required**) * Function name **MUST** be `uuid` (required) Scoring: * Lower number of chars wins * The score is calculated using (number chars)\*0.75 * Readable code is calculated using (number chars)\*0.50 * If one of the required criteria from above isn't met, the multiplier is increased by 0.5 for each criteria, except for the last which is 1.25 (maximum will be (number chars)\*4.00, which means that 1 char is counting as 4) * Comments don't count but anything else between `function uuid(...){` and `}` counts! For example: My function would have a crappy result: It has 451 chars on linux. Since it is somewhat hard to read, it is \*0.75. Since I fulfilled all the criteria, it stays \*0.75. Result: 451\*0.75 = 338,25! [Answer] ## PHP - 189 × 0.75 = 141.75 ``` function uuid($v,$d,$s=''){ $u=hash($v^3?sha1:md5,$v^4?$d.$s:gmp_strval(gmp_random(4))); $u[12]=$v;$u[16]=dechex(+"0x$u[16]"&3|8); return substr(preg_replace('/^.{8}|.{4}/','\0-',$u,4),0,36); } ``` This implementation should be fully compliant with [RFC 4122](http://www.ietf.org/rfc/rfc4122.txt). If `$s` is provided, it is expected to be the byte string represention of the UUID for the applicable namespace. Otherwise, the default ("NULL") namespace is used. `gmp_random(4)` is used to generate the 128 bits of entropy, which is just about the best PHP has. If the `gmp` module isn't available, you could also use this: `openssl_random_pseudo_bytes(16))` (requires `openssl` module to be enabled) or, as a last resort: `for(;$i++<4)$r.=mt_rand();` Sample usage: ``` echo uuid(3,'MyCoolNewApp'); ``` Sample output: ``` c478211b-224d-30b1-9116-c06048999ce2 ``` ]
[Question] [ if you have a range of numbers with values missing, eg `l=[1,2,9,10,99]`, you can always use modulus and subtraction to make all the numbers in the list cover a smaller range, for example: `l%99%6=[1,2,3,4,0]`. your task is to take in a list of numbers and output an equation which will map them to unique numbers in the range `0..len(list)`. a sample method for determining such an equation for any range is below, but there are likely easier ways to do this as it's just something I came up with right now. the sample list will be `l=[2,1,5,3,99,7,6]` 1. to get it into a format we can work with, sort the list and subtract the minimum value from each number: * `sorted(l)-1=[0,1,2,4,5,6,98]` 2. to find the first break, subtract the index of each number: * `tmp=[0,0,0,1,1,1,92]` 3. subtract the number which came after the break: * `sorted(l)-1-4=[-4,-3,-2,0,1,2,94]` 4. mod your whole list by `highest-lowest+1`: `(94)-(-4)+(1)` * `(sorted(l)-1-4)%99=[95,96,97,0,1,2,94]` ``` repeat ``` 1. `sorted((sorted(l)-1-4)%99)-0=[0,1,2,94,95,96,97]` 2. `tmp=[0,0,0,90,91,92,93]` 3. `sorted((sorted(l)-1-4)%99)-0-94=[-94,-93,-92,0,1,2,3]` 4. `(sorted((sorted(l)-1-4)%99)-0-94)%98=[4,5,6,0,1,2,3]` now that we have a 0-6 range, we can output our equation: `((l-5)%99-94)%98` (which gives us `[2,1,4,3,0,6,5]` on the original input) by the nature of the way this method works you'll never need to loop more than `len(list)` times, looping extra times will not affect the values in the list, and you can stop as soon as you get a `tmp` with all 0 values. [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest code in bytes wins. to be considered valid, a solution must be able to take input representing a unique, non-negative list of numbers and give back something representing an equation which will make the list of numbers have unique, non-negative values between 0 and one less than the length of the list. you may assume that each value of the initial list will be unique, but you may **not** assume they will be in order, and they do **not** need to end up in the same order. (eg your equation may transform a list [8,0,2,3,5] to anything like [4,1,2,3,0] or [3,1,4,2,0] or [2,3,4,0,1] etc). you do not need to worry about parenthesis if you don't want to, you can just output a series of subtraction and modulus operations in order (just say in your answer what format your output takes). [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 53 bytes ``` ≔lηWΦθ⁻…⌊θκθ«≔⊕⁻⌈θ⌊θζ≔⪫⟦(η-⌊ι)%ζ⟧ωη≧⁻⌊ιθ≧﹪ζθ»η¿⌊θ⁺-⌊θ ``` [Try it online!](https://tio.run/##bY9Pa8MwDMXPzacQhoEE6qEb2yg97TJoIVB6DTmY1EvEHGf515aWfXbPwdu6wg4Cy3q/p6ei0l3RaOv9S99L6VBZxVDRKjlWYg3gq9jBdNgypOLGHnfalQbDW@qxxpYY3kO1RASXZPZtsnZFZ2rjBrPHiKX69AtcYQrdOez64TaNOMwUThEY1FxdxRKkiu7CzzlnOFIMOUv1R2R3UlZDXHYLtf/Jmv1om2AVx5/JthM34OQob/DnOoI42dpww02eKfzK@yy75wU/8gMvl/zMT3nu5wf7BQ "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ≔lη ``` Start with just the name of the list. ``` WΦθ⁻…⌊θκθ« ``` Repeat while there is a break in the list. ``` ≔⊕⁻⌈θ⌊θζ ``` Calculate the span of the list. ``` ≔⪫⟦(η-⌊ι)%ζ⟧ωη ``` Update the equation for the break and span. ``` ≧⁻⌊ιθ≧﹪ζθ ``` Update the list for the break and span. ``` »η ``` Output the equation. ``` ¿⌊θ⁺-⌊θ ``` Handle the case where there was no break in the list. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes ``` ṢṚ+J-;Ɱ ``` * [Try it online!](https://tio.run/##y0rNyan8///hzkUPd87S9tK1frRx3f///410DHVMdYx1LC11zHXMAA "Jelly – Try It Online") * [Test suite](https://tio.run/##y0rNyan8H696bO2xSQ7HJv1/uHPRw52ztL10rR9tXPc/3Ppwu47h0YZDS1Ue7tz3qGlN1qOGOQq6dgqPGuZyHW4HCkRyWVpWmEcAWYe2PmrcFXhs4qE1Kof2P9y59lHjjsPt//9Hc0Ub6RjqmOoY61ha6pjrmMXqcEVD@CY6RiCOqZGOqaWOqbGOqamOqUUsVywA "Jelly – Try It Online") A monadic link which is called as a monad with a single argument, an unsorted list of non-negative integers, and returns a list structured as `[[s1, m1], [s2, m2], …]` where there are pairs of subtraction (`- sn`) and modulo (`% mn`) steps. The test suite has three fixed examples followed by a randomly generated fourth example. It also proves that the supplied result works; the header encodes a dyadic link that takes the result as detailed above as its left argument and the original list of integers as the right; it returns the list of integers from 0..(len(n) - 1) that results from applying the specified transformations. ## Explanation ``` Ṣ | Sort Ṛ | Reverse +J | Add 1-indexed indices -;Ɱ | Prepend each with -1 ``` Extends [@l4m2’s observation](https://codegolf.stackexchange.com/a/268792/42248) that a series of plus ones can be used to simplify the task. ## Original answer, [Jelly](https://github.com/DennisMitchell/jelly), 25 bytes ``` ’¹ƇŻÄạ ṢI’k$§$żçɗṀ_Ṃ‘ƲṖṭṂ ``` * [Try it online!](https://tio.run/##AU4Asf9qZWxsef//4oCZwrnGh8W7w4ThuqEK4bmiSeKAmWskwqckxbzDp8mX4bmAX@G5guKAmMay4bmW4bmt4bmC////MiwxLDUsMyw5OSw3LDY) * [Test suite](https://tio.run/##JYu9CsIwGEX3PEWHun0OtsYaBHF1dFIppZNL9QF0iyJ01sEf0EFBuugiCKaKQkIDPkbyIjEiXLj3HLjJYDSamDguyYtctn6xbTTdcibT4iHmKj8gxY5tq4Yuz9ziKbLPWjEaKzbTdCOviq0Uu1gy3YZIoVJQfnIVe@nZOdF055SbjqZ7JFIr@oiQcdCzi9/0NO/IBT@7/G3/enoXqTEhCj2oAAYfCIEAahGg8M9V8H6APcAEsA8YA65HKPoC "Jelly – Try It Online") A pair of links which is called as a monad with a single argument, an unsorted list of non-negative integers, and returns a list structured as `[s0, [[s1, m1], [s2, m2]]]` where `s0` is an initial subtraction step and then there are zero or more pairs of subtraction (`- sn`) and modulo (`% mn`) steps. The test suite has three fixed examples followed by a randomly generated fourth example. It also proves that the supplied result works; the header encodes a dyadic link that takes the result as detailed above as its left argument and the original list of integers as the right; it returns the list of integers from 0..(len(n) - 1) that results from applying the specified transformations. ## Explanation ``` ’¹ƇŻÄạ ṢI’k$§$żçɗṀ_Ṃ‘ƲṖṭṂ­⁡​‎‎⁡⁠⁡‏⁠‎⁡⁠⁢‏⁠‎⁡⁠⁣‏⁠‎⁡⁠⁤‏⁠‎⁡⁠⁢⁡‏⁠‎⁡⁠⁢⁢‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁡‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁢‏⁠‎⁡⁠⁣‏‏​⁡⁠⁡‌⁤​‎‎⁡⁠⁤‏‏​⁡⁠⁡‌⁢⁡​‎‎⁡⁠⁢⁡‏‏​⁡⁠⁡‌⁢⁢​‎‎⁡⁠⁢⁢‏‏​⁡⁠⁡‌⁢⁣​‎‏​⁢⁠⁢‌⁢⁤​‎‎⁢⁠⁡‏⁠‎⁢⁠⁢‏⁠‎⁢⁠⁣‏⁠‎⁢⁠⁤‏⁠‎⁢⁠⁢⁡‏⁠‎⁢⁠⁢⁢‏⁠‎⁢⁠⁢⁣‏⁠‎⁢⁠⁢⁤‏⁠‎⁢⁠⁣⁡‏⁠‎⁢⁠⁣⁢‏⁠‎⁢⁠⁣⁣‏⁠‎⁢⁠⁣⁤‏⁠‎⁢⁠⁤⁡‏⁠‎⁢⁠⁤⁢‏⁠‎⁢⁠⁤⁣‏⁠‎⁢⁠⁤⁤‏⁠‎⁢⁠⁢⁡⁡‏⁠‎⁢⁠⁢⁡⁢‏‏​⁡⁠⁡‌⁣⁡​‎‎⁢⁠⁡‏‏​⁡⁠⁡‌⁣⁢​‎‎⁢⁠⁢‏‏​⁡⁠⁡‌⁣⁣​‎‎⁢⁠⁣⁢‏⁠‎⁢⁠⁣⁣‏⁠‎⁢⁠⁣⁤‏⁠‎⁢⁠⁤⁡‏⁠‎⁢⁠⁤⁢‏⁠‎⁢⁠⁤⁣‏‏​⁡⁠⁡‌⁣⁤​‎‎⁢⁠⁢⁣‏‏​⁡⁠⁡‌⁤⁡​‎‎⁢⁠⁣‏⁠‎⁢⁠⁤‏⁠‎⁢⁠⁢⁡‏‏​⁡⁠⁡‌⁤⁢​‎⁠‎⁢⁠⁢⁢‏‏​⁡⁠⁡‌⁤⁣​‎‎⁢⁠⁢⁤‏⁠‎⁢⁠⁣⁡‏⁠‎⁢⁠⁣⁢‏‏​⁡⁠⁡‌⁤⁤​‎‎⁢⁠⁤⁤‏‏​⁡⁠⁡‌⁢⁡⁡​‎‎⁢⁠⁢⁡⁡‏⁠‎⁢⁠⁢⁡⁢‏‏​⁡⁠⁡‌­ ’¹ƇŻÄạ # ‎⁡Helper link: takes a list of increments as its left argument and the range + 1 of the original list as its right and returns the modulos needed (with a redundant final one) ’ # ‎⁢Subtract 1 ¹Ƈ # ‎⁣Keep only those which are non-zero Ż # ‎⁤Prepend a zero Ä # ‎⁢⁡Cumulative sum ạ # ‎⁢⁢Absolute difference (from the range + 1) ‎⁢⁣ ṢI’k$§$żçɗṀ_Ṃ‘ƲṖṭṂ # ‎⁢⁤Main link Ṣ # ‎⁣⁡Sort I # ‎⁣⁢Increments ɗṀ_Ṃ‘Ʋ # ‎⁣⁣Following as a dyad, with the increments as the left argument and (max - min + 1) of the original list as the right $ # ‎⁣⁤- Following as a monad: ’k$ # ‎⁤⁡ - Split the list of increments after any which are >1 § # ‎⁤⁢ - Sum inner lists żçɗ # ‎⁤⁣- Zip with the results of calling the helper link with the increments as the left argument and the range + 1 as the right Ṗ # ‎⁤⁤Remove the last member of the list ṭṂ # ‎⁢⁡⁡Tag onto the minimum of the original list 💎 ``` Created with the help of [Luminespire](https://vyxal.github.io/Luminespire). In brief, this works by separately constructing the right hand arguments needed for subtraction and the modulo separately. The arguments for subtraction are the increments, except where there are consecutive numbers (i.e. increments of 1), these are collapsed into the next non-consecutive one. The arguments for modulo start with the range + 1 and decrease each time by the non-consecutive gaps - 1. [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 56 bytes by Nick Kennedy ``` lambda x:[[-1,z+i]for(i,z)in enumerate(sorted(x)[::-1])] ``` [Try it online!](https://tio.run/##LYxLCsMgFEXnruJNCkpfoLb0EyErsQ7SRKnQmGAMGDdvbZrR/XA40xreo7s8Jp9NA8/8aYdX30IUUlYc09EqM3pqMTHrQLtl0L4Nms6jD7qnkUkhKq6YyhEakGfkeMUL1jXe8abI5K0L1BSOkV4bCHoOZQgCa8EjgSKHDora/O/tlzRBBZ08KQaHklxtXPpxqyLgdVh8qWT371aWvw "Python 3.8 (pre-release) – Try It Online") Each pair to subtract then modulo # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 93 bytes ``` lambda x:['-',p:=min(x)]+g(sorted(x),p) g=lambda x,p:x and['+',1,'%',x[-1]+1-p]+g(x[:-1],p-1) ``` [Try it online!](https://tio.run/##XY9LCsMwDET3OYU2RTZRFmnoL@CTuFmk5FND6hg7FPf0rtJQKF0IZoY3SHKv5T7b6ux8GhRc09Q@bl0LsdZYILlaPYwVUTb5KMLsl75jQ05mo/qSDEVobacxRyoJd0hRF2WTl4Vba1HX7MgVpUxeDULvmTpQRZcLnejYyMx5YxfhZTbMHiIYC/9MnQEEUIDIYqXMSvk1BjADBKUQN7eB5qP7KfTfNHLaP9tJhMXzD5Azx8PGSPnT/KzYLooyvQE "Python 3.8 (pre-release) – Try It Online") That's why I need `+` [Answer] # Google Sheets, 87 bytes ``` =let(a,transpose(split(A1,",")),index(a-sort(mod(sequence(count(a)),count(a)),a,1))) ``` Put a string like `2,1,5,3,99,7` in cell `A1` and the formula in cell `B1`. > > *something representing an equation which will make the list of numbers have unique, non-negative values between 0 and one less than the length of the list* > > > The output is returned as a vertical array with values like `0,0,1,0,99,1,1`. It is a list of numbers to subtract from each value in `A1` in turn, using an equation like \$r\$\$i\$ = \$a\$\$i\$ - \$o\$\$i\$ where \$i\$ ∈ (0, length of list]. ]
[Question] [ Your task is to make a script *with the shortest byte count*, that reverses a word then replaces each letter with the next letter next in the alphabet. Examples: ``` input: hi output: ji input: hello output: pmmfi input: test output: utfu ``` A few notes: * Should the letter's value be 27 (`z`+1), assume it is an `a`. * Symbols, numbers (and any other characters not found in the alphabet) as inputs should error [Answer] # Whispers v1, ~~349~~ 343 bytes ``` >> #2 > Input >> [13] >> LⁿR >> Each 20 27 >> Each 4 29 30 > 0 > 65 > 90 > 97 > 122 >> 8…9 >> 10…11 >> [12] >> Then 14 3 >> Then 3 >> Then 15 >> 7-L >> ≻L >> ?L >> 'L >> L∈R >> 2ⁿL >> LⁱR >> (1] >> Each 18 25 >> Each 23 26 >> 1⋅16 >> 1⋅17 >> Each 22 5 28 >> Each 24 6 5 >> Each 19 31 >> Each 4 6 32 >> Each 21 33 >> Output 34 ``` [Try it online!](https://tio.run/##K8/ILC5ILSr@/9/OTkHZiMtOwTOvoLSEC8iLNjSOBdE@jxr3B4EYronJGQpGBgpG5nCeiYKRpYKxAVAbCJuZAglLEMsSqETB0MgIpNDiUcMySxDD0ADIMjSEmG0ENjskIzVPwdBEwRjOQbAMTUFMc10fEPWoczeYtgeT6j4Qh3V0gB1mBHQhVKRxI1hEwzAW7kZDCwUjU4T7jRWMzMCuedTdaohgIfxkZKRgqmBkgeCbKJgpIAwwBHrYECkAzBSMjRBqDRWMwT7wLy0BBqOCscn//4lJySmpaekZmVnZObl5@QWFRcUlpWXlFZVVjk7OLq5u7h6eXt4@vn7@AYFBwSGhYeERkVEA) In Whispers, the last line is executed first. The other lines are executed when they are referenced in an executing line. Since this program contains many nested operations, I will try to explain it in a bottom-up approach. For better understanding, I will go through the explanation using the example input `HelloWorld`. **Input:** 2 `>> Input` Takes the first line of input. Example: `HelloWorld` **Constants:** 7 `> 0` 8 `> 65` 9 `> 90` 10 `> 97` 11 `> 122` Simple integers. 12 `>> 8…9` Returns the set {result of *line 8* .. result of *line 9*}, so we get `{65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90}`. 13 `>> 10…11` We get `{97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122}`. 14 `>> [12]` Converts the result of *line 12* into a list. We get `[65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90]`. Since this array occurs several times in this explanation, I will call it `A`. 3 `>> [13]` `[97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122]`. We call this array `B`. 15 `>> Then 14 3` ``` [A, B] ``` 16 `>> Then 3` ``` [B] ``` 17 `>> Then 15` ``` [[A, B]] ``` **Functions:** Functions take an argument `L` and/or an argument `R` from a previously executed line. 4 `>> LⁿR` Returns the `R`th position of `L`. 18 `>> 7-L` Takes the result from *line 7*, subtracts it with `L` and returns it. Since the result of *line 7* is `0` *line 18* simply negates its argument. 19 `>> ≻L` Increments `L`. 20 `>> ?L` Returns the integer representation of `L`. 21 `>> 'L` Returns the string representation of `L`. 22 `>> L∈R` Returns true if `L` is in `R`, else false. 23 `>> 2ⁿL` Returns the `L`th position of the result of *line 2*. Since *line 2* is our example input `HelloWorld` it will return the `L`th character of this word. 24 `>> LⁱR` Returns the index of `R` in `L`. **Variables:** 1 `>> #2` Returns the length of result of *line 2*. In this example it is `10`. 25 `>> (1]` Returns the set {1 .. result of *line 1*}, so we get `{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}`. The `Each` command iterates over the second argument and applies the function given by the first argument. If two arrays are passed, they are zipped. 26 `>> Each 18 25` ``` [-1, -2, -3, -4, -5, -6, -7, -8, -9, -10] ``` 27 `>> Each 23 26` ``` dlroWolleH ``` 5 `>> Each 20 27` ``` [100, 108, 114, 111, 87, 111, 108, 108, 101, 72] ``` 28 `>> 1⋅16` ``` [B, B, B, B, B, B, B, B, B, B] ``` 29 `>> 1⋅17` ``` [[A, B], [A, B], [A, B], [A, B], [A, B], [A, B], [A, B], [A, B], [A, B], [A, B]] ``` 30 `>> Each 22 5 28` ``` [True, True, True, True, False, True, True, True, True, False] ``` 6 `>> Each 4 29 30` ``` [B, B, B, B, A, B, B, B, B, A] ``` 31 `>> Each 24 6 5` ``` [3, 11, 17, 14, 22, 14, 11, 11, 4, 7] ``` 32 `>> Each 19 31` ``` [4, 12, 18, 15, 23, 15, 12, 12, 5, 8] ``` 33 `>> Each 4 6 32` ``` [101, 109, 115, 112, 88, 112, 109, 109, 102, 73] ``` 34 `>> Each 21 33` ``` emspXpmmfI ``` **Output:** 35 `>> Output 34` Outputs the result of *line 34*. But why the strange order? Because [the order is essential](https://codegolf.stackexchange.com/a/219842/90812). The *lines 1-6* are called several times. So they should better be on a small number line. [Answer] # [Python 3](https://docs.python.org/3/), 109 bytes ``` p=input() print(''.join(chr(ord(c)+1)for c in p[::-1]).replace('{','a').replace('[','A')if p.isalpha()else 0) ``` [Try it online!](https://tio.run/##TcixCgIxDADQvV/RLQlq8XA7cPA7DodSczRSmtDWQfz46ugbn71H1nqZ065S7TWQnDWpAwHCU6Viyg21PTDRYaFdm09eqrdtXU/LnUJjKzExwgeOEOEvtl/cgGT3FqTHYjkicenszzRnFpe5FHWD@/gC "Python 3 – Try It Online") This is working also for uppercase letters, since also them are included in the alphabet. Code explanation: ``` p=input() # takes the input from the prompt if p.isalpha() # main check: if the string contains all alphabetic characters chr(ord(c)+1)for c in p[::-1] # reverse the word and returns a list of the next characters in the alphabet (ascii value +1) ''.join # creates a string from the list .replace('{','a').replace('[','A') # substitutes in the new string the characters '{' (='z' + 1) and '[' (='Z' + 1), to remap 'Z' 'z' to 'A' 'a' print # returns the modified word or 0 if a non letter character is present in the input string ``` ]
[Question] [ **Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers. --- Questions without an **objective primary winning criterion** are off-topic, as they make it impossible to indisputably decide which entry should win. Closed 5 years ago. [Improve this question](/posts/165570/edit) Write a function in Python 2.7 that takes a list of integers as an argument. It should return True or False depending on whether there are any 2 integers in the argument list that sum to zero. [4,-4,9,6,5] > > > > > > True > > > > > > > > > [6,5,-3,2] > > > > > > False > > > > > > > > > [Answer] # [Python 2](https://docs.python.org/2/), 32 bytes ``` lambda a:any(-n in a for n in a) ``` **[Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSHRKjGvUkM3TyEzTyFRIS2/SAHC1PwPYpekFpeAuBrRJjq6JjqWOmY6prE6CtFASkfXWMcoVtOKSwEICooy80o0QKp1FNR17dR1FNLAPE3N/wA "Python 2 – Try It Online")** [Answer] # [R](https://www.r-project.org/), 23 bytes ``` function(x)any(-x%in%x) ``` [Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP0@jQjMxr1JDt0I1M0@1QvN/mkayhqGCjpGCjomCjqmCjpmCjiWYNAWLmCvo6Jppav4HAA "R – Try It Online") If full programs are allowed: ### [R](https://www.r-project.org/), 21 bytes ``` any((x=scan())%in%-x) ``` [Try it online!](https://tio.run/##K/r/PzGvUkOjwrY4OTFPQ1NTNTNPVbdC87@hgpGCiYKpgpmCJRCbAtnmCrpm/wE "R – Try It Online") ]
[Question] [ **This question already has answers here**: [Determine if Strings are equal [closed]](/questions/23860/determine-if-strings-are-equal) (82 answers) Closed 9 years ago. Compare if three string variables with the same content, return `true` if they are or `false` if they are not without using conditional operators and bitwise operators. e.g. in C# without `&& || ?:` ``` return (string1==string2)==(string1==string3)==true; ``` PS: initial idea came from these [question](https://stackoverflow.com/q/22484127/352101) [Answer] # GolfScript ``` 1$=:a;=a+2="true""false"if ``` This program assumes three strings on the stack. [Test online](http://golfscript.apphb.com/?c=OyAiYWJjIiAiYWJjIiAiYWJjIgoKMSQ9OmE7PWErMj0idHJ1ZSIiZmFsc2UiaWY%3D) How it works: 1. `1$` copies the second element on the stack (the second string) to the top of the stack. 2. `=:a;` returns `1` if the two top elements (the second and the third string) are equal; otherwise, `0`. Then, it stores this result in the variable `a` and it pops it from the stack. Now only the first and the second string remain on the stack. 3. `=` checks whether the first and the second string are equal. 4. `a+` puts the value of `a` on the stack and calculates the sum of `a` and the result of the previous comparison. 5. `2="true""false"if` puts `"true"` on the stack if the sum of the comparison results is equal to `2`: in this case, both comparisons returned true. If the sum is `1` or `0` then it puts `"false"` on the stack. This value is now the only one on the stack, and at the and of a program, GolfScript always outputs the values on the stack. [Edit] Thanks to Peter Taylor for pointing out that variables are not necessary: ``` 1$=@@=+2="true""false"if ``` [Answer] # Perl The function `CompareStrings` takes *any* number of strings and returns the strings `true` or `false`: * `true` is returned if there are one or more strings and all strings are equal. * `false` is returned if there is no string or at least two different strings. ``` sub CompareStrings (@) { my %hash = map { $_ => 1 } @_; return ('false', 'true')[not scalar(keys %hash) - 1]; } ``` The strings are put as keys in a hash. If there is at least one string and all strings are equal, then the hash has one key exactly. Otherwise there are zero or two or more keys. After 1 is subtracted the operator `not` maps the cases to the empty string and `1` that are used to select the result string (the empty string becomes 0). ``` sub CompareStrings (@) { my %hash = map { $_ => 1 } @_; return ('false', 'true')[not scalar(keys %hash) - 1]; } ``` **Complete script with test cases:** ``` #!/usr/bin/env perl use strict; $^W=1; sub CompareStrings (@) { # several variants to initialize the hash, whose keys are the strings: # my %hash; @hash{@_} = (1) x @_; # my %hash; $hash{$_} = 1 for @_; my %hash = map { $_ => 1 } @_; return ('false', 'true')[not scalar(keys %hash) - 1]; } # Testing $\ = "\n"; print CompareStrings qw[]; # false print CompareStrings qw[foobar]; # true print CompareStrings qw[hello hello]; # true print CompareStrings qw[Hello World]; # false print CompareStrings qw[abc abc abc]; # true print CompareStrings qw[abc abc def]; # false print CompareStrings qw[abc def ghi]; # false print CompareStrings qw[a a a a a a a a]; # true print CompareStrings qw]a a a a oops a a]; # false __END__ ``` ]
[Question] [ **This question already has answers here**: [Is this number a prime?](/questions/57617/is-this-number-a-prime) (367 answers) Closed 3 years ago. **Problem Statement**: Consider a number `n` in base-10. Find the smallest base-10 integer `i` greater than `n`, such that both the decimal and binary representations of `i` are prime (when viewed in decimal). --- **Input**: a number in decimal **Output**: The smallest base-10 number greater than `n`, which when viewed in both binary and decimal, is prime. --- **Examples**: *Input*: * 1 * 3 * 100 * 1234567 *Output*: * 3 * 5 * 101 * 1234721 *Explanations*: * 3 is prime. 3 in binary is 11, which is also prime. 3 is the smallest number larger than 1 which satisfies these properties. * 5 is prime. 5 in binary is 101, which is also prime. 5 is the smallest number larger than 3 which satisfies these properties. * 101 is prime. 101 in binary is 1100101, which is also prime. 101 is the smallest number larger than 100 which satisfies these properties. * 1234721 is prime. 1234721 in binary is 100101101011100100001, which is also prime. 1234721 is the smallest number larger than 1234567 which satisfies these properties. --- Here are your test cases, ordered in ascending difficulty according to my own naive implementation. Please include a [Try it online!](https://tio.run) in your answer: *Input*: * `n = 1325584480535587277061226381983816`, a.k.a. `(((((((1 + 2) * 3) ** 4) + 5) * 6) ** 7) + 8) * 9` * `n = 1797010299914431210413179829509605039731475627537851106401`, a.k.a `((3^4)^5)^6` * `n = 2601281349055093346554910065262730566475782`, a.k.a `0^0 + 1^1 + 2^2 + ... + 28^28 + 29^29` * `n = 20935051082417771847631371547939998232420940314`, a.k.a. `0! + 1! + ... + 38! + 39!` * `n = 123456789101112131415161718192021222324252627282930` *Output*: * `1325584480535587277061226381986899` * `1797010299914431210413179829509605039731475627537851115949` * `2601281349055093346554910065262730566501899` * `20935051082417771847631371547939998232420981273` * `123456789101112131415161718192021222324252627319639` If you manage to get the correct outputs for these 5 test cases in under 3 seconds total, your code can be considered. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest code in bytes wins. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 7 bytes I saw in the comments that you may remove the time limit, so **consider this as an answer only in case you are removing the time limit**, since it times out even for `1234567`. ``` [ÅNDbp# ``` Explanation: ``` [ÅNDbp# Input is at the top of the stack [ Infinite loop ÅN Next prime D Duplicate that b Binary representation p Is it a prime number? # Break the loop if it is, printing the top of the stuck, which is the next number that match both conditions. ``` [Try on online!](https://tio.run/##yy9OTMpM/f8/@nCrn0tSgfL//4YGBgA) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ‘ÆnBḌẒ¬Ʋ¿ ``` A monadic Link accepting an integer, `n`, that yields a list conting just one element, the next prime above `n` which is prime and has a decimal-read binary representation which is prime. As a full program the integer is implicitly printed to STDOUT. **[Try it online!](https://tio.run/##ASQA2/9qZWxsef//4oCYw4ZuQuG4jOG6ksKsxrLCv////zEyMzQ1Njc "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##PY8rTgNgEISv0gNU7Ox7LXfBkAZf1yDAoFAcogpFMCRt0nu0F/mZVGA2m803OzNPj7vdfq3b4fP8@vxw/X6//nycjpev0@86v91ejmthu7HtBiIcah5ZXEwj2r0ljEtplSRU0xrTHEmmpgSiMwN3g0IcxmvrhExKiE0ZvCK1wqoDkHShoaZAG@YjQdbMM8KHITKUtElkUlithAmEBKTVUVVorzRYIbzG6N9q6sRcaPdfo/kPYC4eEUhQiVFRFrkL7lbKuCZ/ "Jelly – Try It Online"). ### How? ``` ‘ÆnBḌẒ¬Ʋ¿ - Link: n ‘ - increment n -> k=n+1 ¿ - while... Ʋ - ...condition: last four links as a monad - f(k): B - int to binary list Ḍ - decimal list to int Ẓ - is prime? ¬ - NOT Æn - ...do: (k=) next prime - yield k ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 68 bytes ``` (t=NextPrime)[#//.x_/;!PrimeQ@FromDigits@IntegerDigits[t@x,2]:>x+1]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n277X6PE1i@1oiSgKDM3VTNaWV9fryJe31oRzA90cCvKz3XJTM8sKXbwzCtJTU8tgvCiSxwqdIxirewqtA1j1f4DVeeVKDikRxsaG5maWpiYWBiYGgMZ5kbm5gZmhkZGZsYWhpYWQMIs9v9/AA "Wolfram Language (Mathematica) – Try It Online") [Answer] # [SageMath](https://doc.sagemath.org/), 61 bytes ``` f=lambda n,p=is_prime:p(n+1)and p(f'{n+1:b}')and n+1or f(n+1) ``` [Try it online!](https://sagecell.sagemath.org/?z=eJydU9uK3DAMfc9X-C0JTYsulmUPpD_SljI7k0BgJxMSL7Qd5t-rZFkI04dua7CRben46Fjq2-fj5el8dGMztcPyfZqHS3eYqvED1sfx7KaqL2-2OTzdy-3A7Ovs-s2hyN2SF9e6ChvHjUMAW4i9BG0K9zaQSSR6H0HYDCVVCEgUOGKKtoS9syYFBEopofeMhOCR7TRSEkgBBDgpo1cJpMIaBRGCB9yBUACkiOwTiAUx-yDik_ELQhbGICEYgkbaR5mngCBE8qiqGL0GRlYUr4mNUSQmb24ejMCe9GvO0V5ANMp2i4IBDQITAVmyW-T2OFkmDHXR_Zi6U-7Oq34mnqz64at-Svts_iphiCk9-P-PiijJP-C8S0gB_IPA-7WMaDAP7P9FTsYUONXFvOpYfn0h9afSbQZyWRfDZbrO2S0_l8Lmp6XLc3d6mZfhOj4PlyFXlsw66qK3ws5N54bR_Rqmaivuxr19U33YOK7l3le53jbWLWNeOyTf3cfP7rbc3W3-srRt983a5TdUXbvi&lang=sage&interacts=eJyLjgUAARUAuQ==) [Answer] # [Python 3](https://docs.python.org/3/) (145 bytes) I am the author of this question; this is a non-golfed example if anyone doesn't understand the task. You don't need to upvote this. ``` from sympy import isprime for case in range(5): n = int(input()) i = n + 1 while True: if isprime(int(bin(i)[2:])) and isprime(i): print (i) break i += 1 ``` It runs in approx. 2.79 seconds on [Try on online!](https://tio.run/##RU/NTsMwDL73KXxstYt/4jiZtLfghjh00EEETauuE9rTF28DcYns79eZr@vHVGXbTss0wvk6zlco4zwtK5TzvJRxaE7TAq/9eYBSYenr@9Bqt28AKhwcWttS58vadp1DxaEKOyCfvz/K1wBPy2W4iZ07/SW2N9ex1LZ0z7x/6Tro69s/2T30AL7XFRz43Y/L0H8@smB3ANo2ElZNISRU8cHYDCMxR0mUkz@xIcuGhJxzphCEmDCQOJo4K@aIipJNKJhGNhVLSoQxIDUckTiRhIzqUpEQVUMmxKjsYkGN0X2WuGHnFZUwcSAzoxQsComRBsvi7YmFg8sCellDLEGjJU8j8qMcI6VIbqTMyP6Ju/5exH6r4A8) ]
[Question] [ **Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/189155/edit). Closed 4 years ago. [Improve this question](/posts/189155/edit) Create a quine that cannot be golfed. Your score is your byte count, where higher is better. If someone finds a shorter version, their score is your original byte count, and you lose points Scoring example: original submission, 34 bytes // score is 34 ``` function(this){self.printquine();} ``` golfed, 31 bytes // score is 34, original submission is scored 31 ``` function(this){_.printquine();} ``` golfed again by someone else, 18 bytes // score is 31, first golfed submission is scored 18 ``` this.printquine(); ``` Here "golfing" is defined as creating a shorter version of **someone else's** source file exclusively by removing characters or rearranging existing characters (without affecting its quine-ness). This seems like a good way to define it because otherwise googling the shortest quine in a given language would be the only reasonable starting point. Standard loopholes apply, unless you have a creative use of one then go for it. Use this site's definition of a valid [quine](https://codegolf.meta.stackexchange.com/questions/4877/what-counts-as-a-proper-quine), if you can actually find one that's agreed on. [Answer] # [HQ9+](https://esolangs.org/wiki/HQ9%2B), 1 byte I guess I'm not winning any points for creativity. ``` Q ``` ]
[Question] [ **Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/177356/edit). Closed 5 years ago. [Improve this question](/posts/177356/edit) Write a regular expression substitution string which can base64 decode a string using only a regular expression engine built into the language. Eg: ``` # Example in python import re print(re.sub(..., ..., "SGVsbG8gd29ybGQK")) # "Hello world\n" # ^^^ ^^^ # These count towards your byte count, the rest doesn't ``` Rules: * No libraries * No tools like `base64` in bash * Must be a regular expression * Must decode [RFC 4648 based base64](https://www.rfc-editor.org/rfc/rfc3548) * Any programming language (eg: Python, JavaScript, PHP, Ruby, Awk, Sed) * Length of your find string + Length of your replace string = Byte count * Shortest byte count wins [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 4 + 87 = 91 bytes ``` S/(.)*/{:64[first(.ord,:k,flat 65..90,97..122,48..57,43,47)for $0].polymod(256 xx*).chrs.flip}/ ``` [Try it online!](https://tio.run/##BcFNC4IwGADge7/iRSI2Ga@25vyIzh46hdAlOmi2kiaTzYND/O3reaa31TKMHg4KLrCGJiFI42StpHiowbqZoLE9q35M6XYGmSGWKStzxCPnTBSIWc7EiYmcKmNhnz5xMtqPpic8k7AsMcXX1zpUepi2JGy7nWs9KBI19d11dfHpeem7@naN6Dn8AQ "Perl 6 – Try It Online") Assumes that the input is padded with ending `=`s and uses `+` and `/` as 62 and 63. Really, the first half selects everything while the second half is just a code block to translate base64... ]
[Question] [ **Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/121207/edit). Closed 6 years ago. [Improve this question](/posts/121207/edit) **OUTPUT:** The number of seconds since midnight on January 1, 1 A.D., as an integer. **INPUT:** None, you must pull the current timestamp yourself. **TASK:** This is code-golf, shortest answer in bytes wins. Standard loopholes apply. [Answer] # Bash + GNU utilities, 26 ``` date +62135596800\ %s+p|dc ``` This doesn't attempt to do anything special wrt Julian vs. Gregorian or leap-seconds or timezones - I'm just assuming GNU `date` is doing the right thing. The 62135596800 is the output of `date -ud 1/1/1 +%s` multiplied by -1. `date`'s `%s` format specifier gives the number of seconds since the unix epoch (1970), and so is a negative number for 1/1/1. [Try it online](https://tio.run/nexus/bash#@5@SWJKqoG1mZGhsamppZmFgEKOgWqxdUJOS/P//17x83eTE5IxUAA). ]
[Question] [ **Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/67575/edit). Closed 8 years ago. [Improve this question](/posts/67575/edit) Given a string input, your task is to write a program that prints a [truthy value](http://meta.codegolf.stackexchange.com/q/2190/20634) to STDOUT or equivalent if the input contains "2016" anywhere in it without using any built-in `contains`, `match`, `replace`, `split` or other functions that use patterns or regexes. A truthy value also must be printed if the input contains "2016" with the *same* number of spaces between each number. ## Test Cases ``` 2016 => true "2016" => true 2202012016016166 ^^^^ => true 220201 2 0 1 6 016166 => true Happy New Year! It's 2016! => true 2016 is coming! => true 2_0_1_6 => false 22001166 => false It's not 2015 any more => false 6102 => false 201.6 => false 20 16 => false 2 0 1 6 => false ``` ## Rules * Regexes and pattern matching cannot be used * Built-in `contains`, `match`, and `replace` cannot be used * Built-in `split` functions cannot be used (the only exception is when splitting the string into individual characters for looping through them, such as `input.split("")`) * The code cannot contain the string "2016" in any form (unicode literals and constructing the string included - that *doesn't* mean that the characters 0, 1, 2, or 6 can't be used) * The input may either be taken from `STDIN` or as an argument to a function * It is safe to assume that the input will *not* contain linefeeds or newlines. * The input may contain any printable ASCII characters (spaces included) * A [truthy value](http://meta.codegolf.stackexchange.com/q/2190/20634) must be printed to `STDOUT` or equivalent if the input contains **2016**. * A [falsey value](http://meta.codegolf.stackexchange.com/q/2190/20634) must be printed to `STDOUT` or equivalent if the input does *not* contain **2016** * If using a function, instead of using `STDOUT`, the output can be the return value of the function * The truthy/falsey value cannot be printed to `STDERR`. * [Standard loopholes](http://meta.codegolf.stackexchange.com/q/1061/20634) apply * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest program in bytes wins. Good luck! ## Bonus **-30 Bytes** if the input also returns a truthy value if the spaces between the characters in 2016 are the same. ``` Happy 2 0 1 6 => true I can't wait for 2 0 1 6 => true It's almost 2 0 1 6 => false ``` ## Leaderboard This is a Stack Snippet that generates both a leaderboard and an overview of winners by language. To ensure your answer shows up, please start your answer with a headline using the following Markdown template ``` ## Language Name, N bytes ``` Where N is the size, in bytes, of your submission If you want to include multiple numbers in your header (for example, striking through old scores, or including flags in the byte count), just make sure that the actual score is the *last* number in your header ``` ## Language Name, <s>K</s> X + 2 = N bytes ``` ``` var QUESTION_ID=67575;var OVERRIDE_USER=20634;function answersUrl(e){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"http://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(-?\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i; ``` ``` body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px} ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> ``` [Answer] # CJam, 35 - 30 = 5 bytes ``` qS*_,,_Sf*{"2 0 1 6"\*}%\:)@few:+&` ``` ## Explanation ``` qS* Push s p a c e d i n p u t. _,, Push [0..N-1] where N = len(input). _Sf* Push ["", " ", " ", " ", ...]. {"2 0 1 6"\*}% Make it ["2 0 1 6", "2 0 1 6", ...]. \ Swap [0..N-1] to top of stack. :) Increment each, giving [1..N]. @ Rotate spaced input I to top of stack. few Push [I1ew I2ew .. INew], i.e. :+ when concatenated, all substrings of I. & Intersect sets. ` Print as CJam syntax. ``` Essentially, given an input string `abcd`, this executes a "substring search" by intersecting the sets: * `2 0 1 6`, `2 0 1 6`, ... up to `2*len(input())-1` = more than enough spaces, * `a`, , `b`, ..., `a b`, ... `a b c d`. If a result is found, such a spaced `2016` string appeared as a substring of the input, and a truthy list containing this result is printed, like `["2 0 1 6"]`. Otherwise, the empty list is printed. The string `"2016"` is never constructed as the code runs; only its spaced-out versions are. [Answer] # JavaScript (ES6), 125 - 30 = 95 bytes ``` x=>(y=[...x]).map((_,i)=>y.map((_,j)=>r?0:(n=x.substr(j,a.length),r=n<a&n>b),s=" ".repeat(i),a=2+s+0+s+1+s,b=a+5,a+=7),r=0)|r ``` ## Explanation Returns `1` if it matched, otherwise `0`. Brute forces every possible combination of spaces between `2016` and checks for a match at each substring. Note that it never constructs the string `2016` because it generates `a` as `2017` and `b` as `2015` (both with spaces) and checks if `b < substring < a`. ``` x=> // x = input string (y=[...x]) // y = input as array .map((_,i)=> // loop over every possible amount of spaces between digits y.map((_,j)=> // loop over every character to check for a match r?0:( // if r is set we don't have to do anything, if not: n=x.substr(j,t.length), // n = substring to compare r=n<a&n>b // check if r is 2016 ), s=" ".repeat(i), // s = spaces between letters a=2+s+0+s+1+s, // get string to compare with b=a+5, // b = 2015 (with spaces) a+=7 // a = 2017 (with spaces) ), r=0 // r = result ) |r // return result ``` ## Test ``` var solution = x=>(y=[...x]).map((_,i)=>y.map((_,j)=>r?0:(n=x.substr(j,a.length),r=n<a&n>b),s=" ".repeat(i),a=2+s+0+s+1+s,b=a+5,a+=7),r=0)|r ``` ``` <input type="text" id="input" value="I can't wait for 2 0 1 6" /> <button onclick="result.textContent=solution(input.value)">Go</button> <pre id="result"></pre> ``` [Answer] ## Swift 2, ~~307~~ 297 - 30 = 267 Bytes ``` func d(s:String)->Int{var c=0;var n=0;var l=0;for v in s.characters{if(v=="2"){c=1;l=0;n=0};if(c==1&&v=="0"){c=2;l=n;n=0};if(c==2&&v=="1"){c=(l==n ?3:0);l=n;n=0};if(c==3&&v=="6"){if(l==n){return 1}else{c=0}};if(!(v=="2" || v=="0" || v=="1" || v=="6")){if(v==" "){n++}else{c=0;l=0;n=0;}}};return 0} ``` ### Ungolfed ``` func d(s: String) -> Int{ var c=0 var n=0 var l=0 for v in s.characters{ if(v == "2"){ c = 1 l = 0 n = 0 } if(c == 1 && v == "0"){ c = 2 l = n n = 0 } if(c == 2 && v == "1"){ c = (l == n ? 3 : 0) l = n n = 0 } if(c == 3 && v == "6"){ if(l == n){ return 1 } else{ c = 0 } } //you may be wondering why I didn't use &&. It's because //using && would require me to use !=, which needs spaces //on both sides if(!(v == "2" || v == "0" || v == "1" || v == "6")){ if(v == " "){ n++ } else{ c=0 l=0 n=0 } } } return 0 } ``` ]
[Question] [ **Goal:** The goal of this challenge is to take a simple 6 row by 6 column XML file (without the standard XML header) and parse it out so that the program can return the value of a cell given it's coordinates. The entry with the shortest overall length by language and overall will be declared the winner. **Additional information:** The XML syntax will always be an HTML table with each inner level being indented by four single spaces. You may assume that every file put into the program will be exactly like the one given below. If your program uses imports you do not need to include them in the golfed version of your code but you must submit a copy of the program in the explanation that shows all imports used. This explanation will not effect your entries byte count. **Rules:** * The XML file cannot be hardcoded * XML libraries/functions cannot be used **Extra Credit:** * Can pretty print the table if given the `--all` flag (20 bytes off of total) * Can print all entries of a column given the column number in `--col=number` (20 bytes off of total) * Can print all entries of a row given the row number in `--row=number` (20 bytes off of total) * Can parse any size file as long as #rows = #columns (40 bytes off of total) **XML File:** ``` <table> <tr> <th>Foo</th> <th>Bar</th> <th>Baz</th> <th>Cat</th> <th>Dog</th> <th>Grinch</th> </tr> <tr> <th>Something</th> <th>Something</th> <th>Darkside</th> <th>Star</th> <th>Wars</th> <th>Chicken</th> </tr> <tr> <th>Star</th> <th>Trek</th> <th>Xbox</th> <th>Words</th> <th>Too</th> <th>Many</th> </tr> <tr> <th>Columns</th> <th>Not</th> <th>Enough</th> <th>Words</th> <th>To</th> <th>Fill</th> </tr> <tr> <th>Them</th> <th>So</th> <th>I</th> <th>Will</th> <th>Do</th> <th>My</th> </tr> <tr> <th>Best</th> <th>To</th> <th>Fill</th> <th>Them</th> <th>All</th> <th>Up</th> </tr> </table> ``` [Answer] # JavaScript (*ES6*), 158 bytes A function, parameters: * xml * row number (1 to n) * col number (1 to n or 0 to get the whole row as an array) It works with an xml string with any number of rows and columns (formatted as in the example, no extra tags inside rows or cells). I don't claim any bonus as the input mode is not what requested (--row=, etc) Using this same expression in any language that implements regexps (perl maybe) you can have a stand-alone program. Test running the snipper below (ES6 so Firefox only) ``` F=(t,r,c)=>( m=t.match(RegExp(`(<tr>(\\s*<th>(.*?)</th>\\s*){${c}}[\\s\\S]*?</tr>\\s*){${r}}`,"i")), c?m[3] // single cell :m[1].split(/<th>(.*?)<\/th>/g).filter((v,i)=>i&1) // clean row value ) // test function test() { var r=+R.value, c=+C.value, t=T.value X.value=F(t,r,c) } ``` ``` #X { width: 440px; } #T { width: 440px; height: 10em; } #R,#C { width: 3em; } ``` ``` Row: <input id=R value=1> (1 ... n) Col: <input id=C value=1> (1...n, 0 for whole row) <button onclick="test()">Get</button> <br><input readonly id=X> <br>Xml:<br> <textarea id=T><table> <tr> <th>Foo</th> <th>Bar</th> <th>Baz</th> <th>Cat</th> <th>Dog</th> <th>Grinch</th> </tr> <tr> <th>Something</th> <th>Something</th> <th>Darkside</th> <th>Star</th> <th>Wars</th> <th>Chicken</th> </tr> <tr> <th>Star</th> <th>Trek</th> <th>Xbox</th> <th>Words</th> <th>Too</th> <th>Many</th> </tr> <tr> <th>Columns</th> <th>Not</th> <th>Enough</th> <th>Words</th> <th>To</th> <th>Fill</th> </tr> <tr> <th>Them</th> <th>So</th> <th>I</th> <th>Will</th> <th>Do</th> <th>My</th> </tr> <tr> <th>Best</th> <th>To</th> <th>Fill</th> <th>Them</th> <th>All</th> <th>Up</th> </tr> </table></textarea> ``` ]
[Question] [ Write a full program to calculate the inverse of a 4-by-4 matrix. # Rules The sixteen values of the initial matrix must be hard-coded to variables, as follows: ``` _ _ |a b c d| |e f g h| |i j k l| |m n o p| - - ``` Then print the values of the inverse matrix, row by row, with each number separated by some delimiter. You may assume that the given matrix has an inverse. The results must be completely accurate, limited only by the programming language. For example, you may assume that (1 / 3) \* 3 = 1, there's no such thing as integer overflow, and so on. You may use only the following operations: * Addition - 10 points * Subtraction - 15 points * Multiplication - 25 points * Division - 50 points * Assignment to a variable - 2 points * Printing a variable (not an expression) and a delimiter - 0 points * Recalling a variable or numeric constant - 0 points For example: `x = (a + b) / (a - 2)` would score 77 points. To clarify, you **may not** use any other operations or structures, such as arrays, functions (outside the main method, if needed), if-statements, etc. The initial hard-coding of the variables does not give any points. Fewest points wins. # Testcases Note that all testcases can be used in reverse. ``` a=1; b=1; c=2; d=-1; e=-2; f=0; g=-2; h=1; i=-1; j=2; k=1; l=0; m=2; n=-1; o=0; p=2 ``` Print, in order: `9 7 -4 1 10 8 -4 1 -11 -9 5 -1 -4 -3 2 0` ``` a=1; b=2; c=3; d=0; e=2; f=2; g=1; h=0; i=4; j=4; k=4; l=4; m=2; n=1; o=-2; p=0 ``` Print, in order: `-5 7 0 -4 6 -8 0 5 -2 3 0 -2 1 -2 .25 1` ``` a=-.25; b=.5; c=0; d=.5; e=1; f=.25; g=-.5; h=0; i=-1; j=-.5; k=.5; l=.25; m=.25; n=1; o=0; p=0 ``` Print, in order: `-2 4 4 2 .5 -1 -1 .5 -3.75 5.5 7.5 4.25 .5 3 3 .5` [Answer] # Java: 3974 Now this is a totally new version of the prgoram, that satisfies the updated conditions. Note that I did use an array for printing in this version here, but I counted as if every assignment was an own new variable. The for loops save some space for those who want to see the code here... I am using the only possible approach (i think) under the restrictions via minor determinats that form the adjoint matrix. [For those who want to check the correctness of the formula.](http://www.wolframalpha.com/input/?i=%7B%7Ba%2Cb%2Cc%2Cd%7D%2C%7Be%2Cf%2Cg%2Ch%7D%2C%7Bi%2Cj%2Ck%2Cl%7D%2C%7Bm%2Cn%2Co%2Cp%7D%7D%5E-1) ## Stats: ``` = : 2* 42 + : 10* 44 - : 15* 60 * : 25*100 / : 50* 1 public static void main(String[] args){ double a=4,b=1,c=1,d=2, e=4,f=4,g=1,h=5, i=2,j=1,k=5,l=1, m=4,n=2,o=4,p=3; double af=a*f; double kp=k*p; double lo=l*o; double ag=a*g; double jp=j*p; double ln=l*n; double ah=a*h; double jo=j*o; double kn=k*n; double be=b*e; double bg=b*g; double lm=l*m; double bh=b*h; double io=i*o; double km=k*m; double ce=c*e; double cf=c*f; double ip=i*p; double ch=c*h; double in=i*n; double jm=j*m; double de=d*e; double df=d*f; double dg=d*g; double z = 1/(af*(kp-lo)+ag*(ln-jp)+ah*(jo-kn)+be*(lo-kp) +bg*(ip-lm)+bh*(km-io)+ce*(jp-ln)+cf*(lm-ip) +ch*(in-jm)+de*(kn-jo)+df*(io-km)+dg*(jm-in)); double[] inv = {h*(jo-kn)+g*(ln-jp)+f*(kp-lo) , d*(kn-jo)+b*(lo-kp)+c*(jp-ln) , (ch-dg)*n+(df-bh)*o+(bg-cf)*p , (dg-ch)*j+(bh-df)*k+(cf-bg)*l, h*(km-io)+g*(ip-lm)+e*(lo-kp) , d*(io-km)+c*(lm-ip)+a*(kp-lo) , (dg-ch)*m+(ah-de)*o+(ce-ag)*p , (ch-dg)*i+(de-ah)*k+(ag-ce)*l, h*(in-jm)+f*(lm-ip)+e*(jp-ln) , d*(jm-in)+a*(ln-jp)+b*(ip-lm) , (bh-df)*m+(de-ah)*n+(af-be)*p , (df-bh)*i+(ah-de)*j+(be-af)*l, g*(jm-in)+e*(kn-jo)+f*(io-km) , c*(in-jm)+b*(km-io)+a*(jo-kn) , (cf-bg)*m+(ag-ce)*n+(be-af)*o , (bg-cf)*i+(ce-ag)*j+(af-be)*k}; for(int u=0;u<16;u++){ inv[u] = inv[u]*z; //counting as 16 assignments and 16 multiplicatiosn } //printing all the values for(int u=0;u<16;u++){ if(u%4 == 0){ System.out.println(""); } System.out.print(inv[u]+" "); } } ``` ]
[Question] [ **Closed**. This question needs to be more [focused](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Update the question so it focuses on one problem only by [editing this post](/posts/28309/edit). Closed 9 years ago. [Improve this question](/posts/28309/edit) As stated, write a program that is capable to, in an automated manner, write more code and another program and execute that program from itself. In short, you are asked to write a program that can write another self-standing program itself and enable it to execute in any function. Do this in the shortest amount of code possible, with the one restriction being that it has to be written in [one of these languages](http://en.wikipedia.org/wiki/Compiled_language#languages). If you need even more specific details, read on: > > You are asked to write a program that will (in an automated manner) > write the lines of code needed for another program, and compile that > program/execute it from the programmatic structure of the main program > itself. The program is not executing the program, but is programmed to > write code and then compile/get the OS to execute it while it's still > running separately. > > > [Answer] # C: ~~41~~ 38 characters Pretty much the most trivial solution possible in C. ``` main(){system("gcc -xc -<<<'main;'");} ``` ]
[Question] [ **Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/12964/edit). Closed 10 years ago. [Improve this question](/posts/12964/edit) A bitonic program is a program every string of which is bitonic. A bitonic string is a string S with S[0]<= . . . <=S[k]>= . . . >=S[n-1] for some k, 0<=k< n. (n is the length of the string) **Examples of Bitonic strings:** * abcd * dcba * vyzcba * adgf The goal is to write the shortest bitonic program to find the maximum of two numbers. **Note:** * Two group of characters separated by one or more spaces(' '), tabs('\t'), backspaces or line-break('\n') are considered as two different strings. * Comments in the code are not allowed. * Other than tabs, spaces, backspaces or line-breaks, the code must contain at least 3 other characters. **EDIT:** * Inbuilt function not allowed. * Conditional statements not allowed. * <(less than) and >(greater than) signs not allowed [Answer] ## APL, 3 ``` ⎕⌈⎕ ``` Can this be beaten? ]
[Question] [ **Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers. --- Questions without an **objective primary winning criterion** are off-topic, as they make it impossible to indisputably decide which entry should win. Closed 2 years ago. [Improve this question](/posts/221266/edit) # Introduction I've always liked the idea of finding the most possible bang-for-your-buck squeezed out of a tiny chip, like the 6502. Of course, I'll need to start small. Filling the screen on 6502asm.com should be easy enough. # Challenge Fill the entire program output screen on 6502asm.com with the color white using the least amount of unique executed bytes as possible. Or, set every memory space between 0x0200 and 0x05FF with any byte whose lower nybble is 1. No self modifying code. (executing bytes that were changed after being assembled) Try to keep the memory changed to a minimum, don't go changing bytes willy-nilly. [Answer] Here's my attempt: ``` lda #1 ldx #$02 fill_screen: stx $01 draw_segment: sta ($00),Y iny bne draw_segment inx cpx #$06 bne fill_screen ``` And as hex: ``` 0600: a901 a202 8601 9100 c8d0 fbe8 e006 d0f4 ``` That's exactly 16 bytes of memory used as code, with 2 external bytes used as program storage. ]
[Question] [ **This question already has answers here**: [Sum of all integers from 1 to n](/questions/133109/sum-of-all-integers-from-1-to-n) (222 answers) Closed 5 years ago. [Sum-It](https://github.com/dylanrenwick/sum-it) is a language I created (quite late) for the Language Design Contest in TNB, for which the theme was "Range". Naturally I interpreted this as "Mountain Range" and created a language about mountains. Sum-It code takes the form of several ASCII art mountains, using only the `/` and `\` characters. The mountains are then parsed to a number representing the size of the mountain, and that number is used as either an opcode or a data value. While developing the parser for this language, I noticed something quite interesting regarding mountain sizes: The size of a standalone (ie: not overlapped) mountain is equivalent to double the sum of all integers lower than the mountain's height in characters. So for example, the following mountain: ``` /\ <- 1 / \ <- 2 / \ <- 3 ``` Has a character height of 3. Its "size" as far as Sum-It is concerned, is calculated as such: ``` /\ /##\ /####\ ``` And is therefore 6. This lines up with the above formula, because the sum of all integers lower than 3 is `1 + 2 = 3`, which doubled is 6. ## The challenge Your challenge is, given a positive integer representing a mountain's height, output the Sum-It size of the mountain, using the above formula. ## Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so fewest bytes wins! ## Test Cases Test cases are represented as `input => output => formula` ``` 1 => 0 => 2() 2 => 2 => 2(1) 3 => 6 => 2(1+2) 4 => 12 => 2(1+2+3) 5 => 20 => 2(1+2+3+4) 6 => 30 => 2(1+2+3+4+5) 7 => 42 => 2(1+2+3+4+5+6) 8 => 56 => 2(1+2+3+4+5+6+7) 9 => 72 => 2(1+2+3+4+5+6+7+8) 10 => 90 => 2(1+2+3+4+5+6+7+8+9) 15 => 210 => 2(1+2+3+4+5+6+7+8+9+10+11+12+13+14) 20 => 380 => 2(1+2+3+4+5+6+7+8+9+10+11+12+13+14+15+16+17+18+19) 25 => 600 => 2(1+2+3+4+5+6+7+8+9+10+11+12+13+14+15+16+17+18+19+20+21+22+23+24) 30 => 870 => 2(1+2+3+4+5+6+7+8+9+10+11+12+13+14+15+16+17+18+19+20+21+22+23+24+25+26+27+28+29) 40 => 1560 => 2(1+2+3+4+5+6+7+8+9+10+11+12+13+14+15+16+17+18+19+20+21+22+23+24+25+26+27+28+29+30+31+32+33+34+35+36+37+38+39) 50 => 2450 => 2(1+2+3+4+5+6+7+8+9+10+11+12+13+14+15+16+17+18+19+20+21+22+23+24+25+26+27+28+29+30+31+32+33+34+35+36+37+38+39+40+41+42+43+44+45+46+47+48+49) 60 => 3540 => 2(1+2+3+4+5+6+7+8+9+10+11+12+13+14+15+16+17+18+19+20+21+22+23+24+25+26+27+28+29+30+31+32+33+34+35+36+37+38+39+40+41+42+43+44+45+46+47+48+49+50+51+52+53+54+55+56+57+58+59) 70 => 4830 => 2(1+2+3+4+5+6+7+8+9+10+11+12+13+14+15+16+17+18+19+20+21+22+23+24+25+26+27+28+29+30+31+32+33+34+35+36+37+38+39+40+41+42+43+44+45+46+47+48+49+50+51+52+53+54+55+56+57+58+59+60+61+62+63+64+65+66+67+68+69) 80 => 6320 => 2(1+2+3+4+5+6+7+8+9+10+11+12+13+14+15+16+17+18+19+20+21+22+23+24+25+26+27+28+29+30+31+32+33+34+35+36+37+38+39+40+41+42+43+44+45+46+47+48+49+50+51+52+53+54+55+56+57+58+59+60+61+62+63+64+65+66+67+68+69+70+71+72+73+74+75+76+77+78+79) 90 => 8010 => 2(1+2+3+4+5+6+7+8+9+10+11+12+13+14+15+16+17+18+19+20+21+22+23+24+25+26+27+28+29+30+31+32+33+34+35+36+37+38+39+40+41+42+43+44+45+46+47+48+49+50+51+52+53+54+55+56+57+58+59+60+61+62+63+64+65+66+67+68+69+70+71+72+73+74+75+76+77+78+79+80+81+82+83+84+85+86+87+88+89) 100 => 9900 => 2(1+2+3+4+5+6+7+8+9+10+11+12+13+14+15+16+17+18+19+20+21+22+23+24+25+26+27+28+29+30+31+32+33+34+35+36+37+38+39+40+41+42+43+44+45+46+47+48+49+50+51+52+53+54+55+56+57+58+59+60+61+62+63+64+65+66+67+68+69+70+71+72+73+74+75+76+77+78+79+80+81+82+83+84+85+86+87+88+89+90+91+92+93+94+95+96+97+98+99) ``` [Answer] # APL+WIN, ~~8~~ 6 bytes ``` +/2×⍳⎕ ``` Prompts for input integer, creates a vector of integers from 1 to integer -1, multiplies by 2 and sums the result. Saved 2 bytes thanks to Adam by switching to index origin zero. [Answer] # [C (gcc)](https://gcc.gnu.org/), 31 bytes ``` i;f(n,a){for(;--n;i+=n);a=i*2;} ``` [Try it online!](https://tio.run/##S9ZNT07@r5yZl5xTmpKqYFNckpKZr5dh9z/TOk0jTydRszotv0jDWlc3zzpT2zZP0zrRNlPLyLr2f2ZeiUJuYmaehiZXNVdBEZCbpqGkmhKTp6STpmGoqWmNKWiAVdQUm6gZWG3tfwA "C (gcc) – Try It Online") EDIT: By using a global variable multiple execution of the functions wil lget wrong results. I'm not sure wether that's ok or no. Pretty new to PPCG. Here's the corrected version: # [C (gcc)](https://gcc.gnu.org/), 34 bytes ``` f(n,i,a){for(i=0;--n;i+=n);a=i*2;} ``` [Try it online!](https://tio.run/##S9ZNT07@r5yZl5xTmpKqYFNckpKZr5dh9z9NI08nUydRszotv0gj09bAWlc3zzpT2zZP0zrRNlPLyLr2f2ZeiUJuYmaehiZXNVdBEZCbpqGkmhKTp6STpmFoqqlpjSFqZgASrf0PAA "C (gcc) – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), 13 bytes ``` f(x){x*=x--;} ``` [Try it online!](https://tio.run/##FYpBCsIwFET3OcVQKeTbRtBtmp7ETUmMBvRXaoVAydnT39k8mPe8eXpfT4n9@x8eGH5rSPPlNdaoM2357LIxttTEKz5TYk1qU0CcF@jjYzhcrWDATdh1TKKPRPZdJIm6aQPciDbcuem5j5qJrBRFlboD "C (gcc) – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), 10 bytes ``` (*)=<<pred ``` [Try it online](https://tio.run/##LYpLDoIwAAX3nuKFuAD5pKDswBPoyiUQ02BLjaU2bQ23t1J192bmCWofTErP0aL38S5pm0YbdvMzvavVzVSfr4h7lR@hX@7izElhCyueCxTSFBHWEoX1dTGHShI4Zp3FIphhG/ypRVcWRUmGcO7KOqtIVtU/2pPsQEIkg3@PXNLJ@nzU@gM "Haskell – Try It Online"), using [`(<*>)`](https://tio.run/##LYpBDoIwAATvvmJDPLRQSItyE16gJ49ATINFjFAbWsPvrVS97czsIO1DjaPvUaLxJKaHuDKzuvpJ3vXqJmlOF5BGpxXMy53dfNTYwg7PBRpJgghricL6OtJDUwqnrLNYBjWrDf5UohZZJngbzrUoWM5ZXvxox9meh8hb/@76Ud6sTztjPg "Haskell – Try It Online") would work too since multiplication is commutative.. ## Alternative, 9 bytes I'm not completely sure if this is allowed, according to [this](https://codegolf.meta.stackexchange.com/a/12747/48198) I believe it is: ``` id<>(-1+) ``` Takes input as `Product` type, [try it online!](https://tio.run/##PU9Na4NAEL37Kx6hFEV30bS5hOilpVBooJBjEsqiqy7Vddkdkfz52rWRHgbexzzmTSvct@y6WfVmsIRXQYIfBz2oCiE@7VCNJYWcR0gQHooIURDUyHGZVXUoQpbF0dwLpb3UC3P8QnjRrIAZ6UT2Q@MBrh0maMQxNvDOZkF/WjhZYd6gowgkHTlMrbQywMpynDPOs/S6BM7ZLtmmyXZ3Z09p8pwuZnoNfIAxvAzakfVdcRp7Rjcj8QhjJdGNGas0Kd34zfvJ/R7vmmQj7dJohf9ujkbS@jk4aj8rm3/KuhONm1lpzC8 "Haskell – Try It Online") [Answer] # [Catholicon](https://github.com/okx-code/Catholicon), 2 bytes ``` *Ẏ ``` Explanation: ``` * multiply (the implicit input) Ẏ by the implicit input decremented ``` [Answer] # [Japt](https://github.com/ETHproductions/japt) `-mx`, 1 bytes ``` Ñ ``` `-m` implicity flag creates a range from `0` to `input - 1` `Ñ` multiply each value in the range by 2 Flag `-x` implicity outputs the sum of the result [Try it online!](https://tio.run/##y0osKPn///DE//8tFXRzKwA) ]
[Question] [ **Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/101750/edit). Closed 7 years ago. [Improve this question](/posts/101750/edit) Write a Java method to check if a given string matches any value in a given enum. Your method will take two parameters, one a string and one an enum, and return `true` if the string representation of any of the enum's elements matches the given string, or `false` otherwise. Note that your method should still function normally if the String parameter is `null`, and that you aren't allowed to use any external libraries. Test cases: ``` public enum E { A, B, C; } public enum F { X, Y, Z; } check("a", E.A); // is false (because "A" is uppercase) check(null, E.A); // is false check("C", E.A); // is true check("X", F.X); // is true check(null, F.X); // is false check("y", F.X); // is false ``` The method has access (as a solver correctly understood) to a generic type E that has the only bound that "E extends Enum(E)". Reference implementation (Ungolfed): ``` boolean <E extends Enum<E>> check(String s, E e){ for(E ex : e.getDeclaringClass().getEnumConstants()) if(ex.toString().equals(s)) return true; return false; } ``` Another possible implementation (due to a solution) is (Ungolfed): ``` public static <E extends Enum<E>> boolean check(String s, E e){ return java.util.stream.Stream.of(e.getDeclaringClass().getEnumConstants()).anyMatch(x->x.name().equals(s)); } ``` What I'm looking for is the shortest thing I could put after return (or, as a solutor did, after "(String s,E e)->)". This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so fewest bytes wins! [Answer] # Java 8, 86 bytes ``` (String s,E e)->java.util.stream.Stream.of(E.values()).anyMatch(x->x.name().equals(s)) ``` [Try it online!](https://tio.run/nexus/java-openjdk#jY7BbsIwEETv@YpRTrYUzAekRQKU3jhxrHpY3AVMHceNbQRCfHvqlqhIVQ/sZVezuzPPtL7rIw50JJWisWqbnI6mc2phXsaxLgp2qUWDC@YVFhWWNa5Z9WljjYa2FAJWZBwuRYFc4yJEirkdO/OONq/FOvbG7V7fQP0uyHyNse5hT7ebCk1O6jrL5GbQe9YfeMYwOiBUDVhOZnfuEHumVq1vrduKRh3JJg5CSkXuvKKo9@I0mZ2Uo5aFVPyZyAYRpBzqX5D1OUTO/ykqn5OideInXJH39ixKKjOZmktZYzqFCdhmD4bYsKaUh3JefqvJe@41BZZ41Nola//zfhht@Rct9un2fS2K6/AF "Java (OpenJDK) – TIO Nexus") [Answer] # Java 4+, 96 bytes ``` boolean c(String a,Enum e){for(E f:values())if(f.toString().equals(a))return true;return false;} ``` Test code: ``` public enum E { A,B,C,D,E,F; public static void main(String[]a) { System.out.println(E.c("a",E)); System.out.println(E.c("B",E)); System.out.println(E.c("d",E)); System.out.println(E.c("C",E)); System.out.println(E.c("D",E)); System.out.println(E.c("e",E)); System.out.println(E.c("F",E)); } boolean c(String a,Enum e){for(E f:values())if(f.toString().equals(a))return true;return false;} } ``` Output: ``` false true false true true false true ``` ]
[Question] [ Most people can't easily do modulus (or work out if a number is divisible by another number) in their heads because long division is harder than addition, subtraction and multiplication. The following method describes a way to calculate modulus in your head, as long as you can remember just a few different numbers. This challenge is to write some code that replicates this method instead of using the built-in modulo operator. I apologise in advance for all of the restrictions, they are there to (hopefully) stop people from trying to work around the problem, instead of solving it the way it's presented. Another way of thinking about this is to assume that division is prohibitively expensive but the other three basic operators are relatively cheap to perform. --- Decimal-multiplication modulo (*d* mod *n*) works by splitting the dividend (*d*) into chunks of the same length as the divisor (*n*), working from **right to left**. Then, working from **left to right**, each chunk is summed to a running total and the total is multiplied by a constant (*c*) before summing the next chunk. *c* is calculated by subtracting *n* from the next highest power of 10. * You **may** use any method to calculate the lowest power of 10 that is greater than *n*, including logarithms * You **may** keep subtracting *n* from *c* until *c* is less than *n* (but not negative) * You **must not** use division or modulo to calculate *c* * You **must not** convert any number to any base other than base 10 * You **may** use any method to split *d* into groups of decimal digits, including division and modulo if it makes your code easier * You **must only** use the following mathematical operators on the chunks + addition: `+`, `++` + subtraction: `-`, `--` (not on numbers with more digits than *n* has) + multiplication: `*` (only by *c*) + comparison (`<`, `>`, `==`, `<=`, `>=`, `!=`/`<>`) * You **must not** use subtraction on any number with more digits than *n*, except when calculating *c* * You **must not** subtract any value other than *c*, except when calculating *c* * You **must not** multiply by any value other than *c* * You **must not** use negative numbers at any point, including as the result of any calculation You don't have to implement the method exactly as described here as long as you stick to its principles. E.g., if the divisor is 37 and one of the chunks is 56, you can subtract 37 from 56 to give 19 before using it further. Your code will take two integers or string representations of decimal integers, whichever is most natural for your language. The first will be non-negative (*d* ≥ 0), the second will be positive (*n* ≥ 1). Your code will output a decimal integer or a string representation containing the result 0 ≤ *d* mod *n* ≤ n - 1. ### Example **1234** mod **37** The lowest power of 10 higher than **37** is 100 c = 100 - **37** = 63 (26 is also acceptable as it is 63 - **37**) **37** has two digits so split **1234** into two-digit chunks: ``` 1234 % 37 ==== 12 34 -> vv -- 26 * 0 + 12 = 12 -- 26 * 12 + 34 = 346 ``` 346 has more than two digits, repeat the process: ``` 346 % 37 ==== 3 46 -> vv -- 26 * 0 + 3 = 3 -- 26 * 3 + 46 = 124 ``` 124 also has more than two digits, repeat the process once more: ``` 124 % 37 ==== 1 24 -> vv -- 26 * 0 + 1 = 1 -- 26 * 1 + 24 = 50 ``` Since 50 has two digits and is larger than **37**, subtract **37** from it as many times as needed to bring the total below **37**. ``` 50 - 37 ==== 13 ``` 13 is indeed **1234** mod **37**. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the lowest score wins! [Answer] ## ES7, 86 bytes ``` f=(d,n,t=10**(''+n).length)=>d<n?d:f(d<t?d-n:(g=d=>d<t?d:g((d-d%t)/t)*(t-n)+d%t)(d),n) ``` Ungolfed: ``` function modulo(d, n) { var t = Math.pow(10, 1 + Math.floor(Math.log10(n))); var c = t - n; function chunk(p) { if (p < t) return p; // reached the leftmost chunk // first recursively process the left part of the number return chunk(Math.floor(p / t)) * c + p % t; } while (d >= t) d = chunk(d); while (d >= n) d -= n; return d; } ``` ]
[Question] [ **Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers. --- This question does not appear to be about code golf or coding challenges within the scope defined in the [help center](https://codegolf.stackexchange.com/help/on-topic). Closed 8 years ago. [Improve this question](/posts/69162/edit) ## LOOP This challenge is based around a modified version of the programming language [LOOP](http://www.eugenkiss.com/projects/lgw/). A program may be of any of the following forms: * `P;Q`, where `P` and `Q` are subprograms + Subprogram P is executed, then subprogram Q is executed. * `x++`, where `x` is a variable + Variable names are the letter `x` followed by a whole number (`0`, `1`, `2`, etc.). The value of variable x is incremented and assigned to variable x. * `x:=y`, where `x` and `y` are variables + The value of variable y is assigned to variable x * `LOOP x DO P END`, where `x` is a variable, and `P` is a subprogram + Subprogram P is executed a number of times equal to the value of x at the start of the loop. If the value of x changes during the loop, the number of iterations does not change. Spaces and newlines may be inserted anywhere. For this challenge, you may not use constants. For example, the code `LOOP x1 DO x2 := x2 + 1; LOOP x2 DO x1++ END END` will set `x1` to the `x1`th triangle number, by adding 1, then 2 etc. ## Task All variables are initialized to 0. The output of the program is the final value of x0, and the length of a program is the total count of increment/decrement/assignment/loop. The goal is to output 2016 with a program that is as short as possible. [Here](https://github.com/KSFTmh/PPCGLOOP/blob/master/interpreter.py) is an interpreter for the modified language used in this challenge. [Answer] # Naive attempt, 15 statements This uses the factorization of 2016 into `2^5*3^2*7`. ``` x1++; x1++; x2:=x1; x2++; x3:=x2+x2; x3++; LOOP x1 DO LOOP x1 DO LOOP x1 DO LOOP x1 DO LOOP x1 DO LOOP x2 DO LOOP x2 DO LOOP x3 DO x0++ END END END END END END END END ``` I've gotten this to run on the provided interpreter by replacing things like `x1++;` with `x1:=x1+1;`, although I did not use "strict mode." ]
[Question] [ **Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/45747/edit). Closed 9 years ago. [Improve this question](/posts/45747/edit) Given a URI like: ``` postgres://username:password@hostname:PORT/dbname ``` Extract it all into an array data-structure, like so: ``` ['postgres', 'username', 'password', 'hostname', 'PORT', 'dbname'] ``` More info: <http://en.wikipedia.org/wiki/URI_scheme#Generic_syntax> ### Rules * No use of external libraries or web-services ### Scoring * Your score will be the number of bytes in your code (whitespace not included) multiplied by your bonus. Initial bonus is 1.0. * Concision is king (codegolf!) * Use of regular expressions will increase your bonus by 0.50 * Use of internal libraries (that need explicit importing) will increase your bonus by 0.50 * Extra -0.8 bonus for getting query string also [Answer] # CJam, 15 bytes \* 0.8 = 12 ``` l":@?#"'/er'/%p ``` Reads the uri via STDIN. Updated to parse query string and fragments too. **Code explanation**: ``` l "Read a line from STDIN"; ":@?#" "Put this string on stack"; '/er "Replace all occurrences of characters in above string by /"; '/% "Split on runs of /"; p "Print the array"; ``` [Try it online here](http://cjam.aditsu.net/#code=l%22%3A%40%3F%23%22%27%2Fer%27%2F%25p&input=postgres%3A%2F%2Fusername%3Apassword%40hostname%3APORT%2Fdbname%3Fkey1%3Dvalue1%26key2%3Dvalue2%26key3%3Dvalue3%23anchorORfragment) [Answer] ## APL, 24 ``` {⍵⊂⍨⍵∊⎕AV[∊65 17+¨⊂⍳26]} ``` Example: ``` ]display {⍵⊂⍨⍵∊⎕AV[∊65 17+¨⊂⍳26]}'postgres://username:password@hostname:PORT/dbname' ┌→────────────────────────────────────────────────────────────┐ │ ┌→───────┐ ┌→───────┐ ┌→───────┐ ┌→───────┐ ┌→───┐ ┌→─────┐ │ │ │postgres│ │username│ │password│ │hostname│ │PORT│ │dbname│ │ │ └────────┘ └────────┘ └────────┘ └────────┘ └────┘ └──────┘ │ └∊────────────────────────────────────────────────────────────┘ ``` Note: ⎕ML variable must be set to 3 in Dyalog APL [Answer] # Ruby, 43 ``` %w[:// : @ /].map{|t|u.gsub! t,' '} u.split ``` Since the OP doesn't specify how to take input and produce output, I'm assuming the URI is located in `u` as a `String`. There is no output; `u.split` returns an Array in the correct format (`["postgres", "username", "password", "hostname", "PORT", "dbname"]`). The code itself is simple. Replace `"://"`, `":"`, `"@"` and `"/`" with a space, then split on whitespace. [Answer] ## Python (characters: 207, score: 240) ``` reduce(list.__add__,reduce(list.__add__,map(lambda e: map(lambda i: i.split('/'),e),map(lambda j: j.split(':'),(lambda e:e[e.find('/')+2:].split('@'))('postgres://username:password@hostname:PORT/dbname'))))) ``` ### Expanded out ``` reduce(list.__add__, reduce(list.__add__, map(lambda e: map(lambda i: i.split('/'), e), map(lambda elem: elem.split(':'), (lambda e: e[e.find('//') + 2:].split('@'))( 'postgres://username:password@hostname:PORT/dbname' ) ) ) ) ) ``` Note: in real-cases use `from operator import add` ]