text
stringlengths
180
608k
[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/54472/edit). Closed 8 years ago. [Improve this question](/posts/54472/edit) You have N lists ``` A = [5, 6, 10, 15] B = [3, 0, 7, 4] C = [49, 59, 29] D = [19, 29, 39] E = [9, 15, 3, 10] ``` You have to combine them such that: Two lists which have a common elements they should be next to each other. In this case answer is: ``` A,E,B,C,D [5, 6, 10, 15, 9, 3, 0, 7, 4, 49, 59, 29, 19, 39] ``` **E** comes after **A** as they have 2 common elements. After **E** the **B** comes as they have common elements. **B** do not have common elements with **C** or **D** so anything can come (**C** or **D**), lets say **C** comes. Now **C** should be followed by **D** as they have common elements. **Note:** This is also acceptable solution ``` B,E,A,C,D C,D,A,E,B .... ``` Thus the main condition is if two lists have common elements they should be next to each other. **Note 2:** For simplicity we assume a list can have common elements with maximum 2 other lists. However there can be list which have no common elements with any other list. **Note 3:** Output format : preferably both, the name of list and the number sequence. [Answer] # CJam, ~~47~~ 44 bytes ``` q~]e!{_2ew[{~_,@@\-,-}/]:+_W>{:W;:L}&}/];L:p ``` Explanation: ``` e# L = [], W = -1 q~ e# Evaluate input ] e# Wrap in array e! e# Push all unique permutations { }/ e# For each permutation: _2ew e# Push all overlapping slices of length 2 { }/ e# For each slice: ~_,@@\-,- e# Push number of common elements [ ]:+ e# Sum the number of common elements from all the slices _W>{ }& e# If sum > W: :W; e# Assign sum to W and pop off the stack :L e# Assign the permutation to L ]; e# Clear the stack L:p e# Print each list in L ``` [Try it online](http://cjam.aditsu.net/#code=q~%5De!%7B_2ew%5B%7B~_%2C%40%40%5C-%2C-%7D%2F%5D%3A%2B_W%3E%7B%3AW%3B%3AL%7D%26%7D%2F%5D%3BL%3Ap&input=%5B5%206%2010%2015%5D%20%5B3%200%207%204%5D%20%5B49%2059%2029%5D%20%5B19%2029%2039%5D%20%5B9%2015%203%2010%5D). ]
[Question] [ **Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers. --- Closed 8 years ago. * 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). * Questions without an **objective primary winning criterion** are off-topic, as they make it impossible to indisputably decide which entry should win. [Improve this question](/posts/53656/edit) # Background A question wanted to solve a problem in a way that made it unreasonably complex: <https://stackoverflow.com/a/31551257/29347> The problem in the original question is: > > Take a list of (key, value) and produce a dict such that {key: sum(value)} > > > # My Problem I want to use dict compression with `list.count` or `str.count` but constructing the iterable, iterating and referencing it in one motion has me stumped. ``` a = [("a",1), ("b",3), ("a",5)] # b = "abbbaaaaa" b = "".join(b[0] * b[1] for b in a) # dict_a = {'a': 6, 'b': 3} dict_a = {e[0]: b.count(e) for e in b} ``` # Goal Remove the need for the variable b thus merging the two lines whilst staying true to the solution. [Answer] ``` dict_a = {t[0] : sum(tp[1] for tp in a if tp[0] == t[0]) for t in a} ``` Horribly slow, but hey it's a one liner! ]
[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/49945/edit). Closed 8 years ago. [Improve this question](/posts/49945/edit) # The Question Given a two dimensional array, `o[][]`, create a 2-dimensional graph such that `o[xCoordinate][yCoordinate]` is the hue of the point at (xCoordinate, yCoordinate), and the value and saturation are always 100. Let the hue go from -50 to 50, where -50 and 50 are 0 and 100 respectively. # Rules * You may use any language you wish * Lowest bytes wins * Include seperate byte amount for points taken off from extra # Extra If you want extra points (or, less actually) you can include a snippit of code in the same language such that `o[x][y]` is equal to sin x · cos y, in less than 25 bytes more than your original snippit. Extra points removes 10 bytes from your score. ### Example Language: 89 [79] (Extra: 113) [Answer] # Mathematica: 68 ``` Graphics@Raster@Reverse[List@@Hue[#/100]~ColorConvert~"RGB"&/@#&/@o] ``` Still figuring out the extra. ]
[Question] [ I have a lot of java projects and I am often making new ones. I have a few helper classes (Vector, Logger, etc.) and it takes a lot of time correcting the first line to the correct package, I would really need a little program to help me fix it automatically. Your program will first take the name of the package the files are moved to (eg. com.google.raycasting), after that each file with `****<FILENAME>****` between them. You read the input however you want (STDIN, program arguments, file, etc.). When an EOF is reached, the program should output each file in the same way as in the input, but with the package declaration changed. Example: Input: ``` com.loovjo.tetris ****Vector.java**** package com.loovjo.someoldproject; class Vector { public Vector (int x, int y) { System.out.println(x + ", " + y); } } ****Logger.java**** package com.loovjo.someoldproject; class Logger { public String name; public Logger(String name) { this.name = name; } } ``` (Of course these aren't the real files.) Output: ``` ****Vector.java**** package com.loovjo.tetris; class Vector { public Vector (int x, int y) { System.out.println(x + ", " + y); } } ****Logger.java**** package com.loovjo.tetris; class Vector { public Vector (int x, int y) { System.out.println(x + ", " + y); } } ``` Further specification on Input/Output: * The package declaration will not always be on the first line, the input may contain some newlines/spaces before it. If this is the case, those characters must be there in the output. * The files in the input will always have correct syntax. Remember, this is **Code Golf**, so the shortest code wins! [Answer] # Mathematica, 106 bytes ``` StringReplace[Rest@#~StringRiffle~"\n","package "~~__~~";"->"package "<>#[[1]]<>";"]&@StringSplit[#,"\n"]& ``` Works by splitting the string into its lines and returning all but the first line with any package declarations replaced with the new package. [Answer] # Java, 286 bytes ``` import java.util.*;class P{public static final void main(String[]a){Scanner s=new Scanner(System.in);for(String p="package "+s.nextLine(),e;(e=s.findWithinHorizon("(package[^;]+)|\"([^\"]|\\\\.)*\"|//.*|/\\*([^*]|\\*[^/])*|.|\n",0))!=null;System.out.print(s.match().start(1)>=0?p:e));}} ``` Take input from STDIN. Test case: ``` com.loovjo.tetris ****Foo.java**** package something; ****Bar.java**** package something.something ; "package aaa;" // package bbbb; /** * package cccc; */ ****Baz.java**** //comment: package dddd; ``` Output: ``` ****Foo.java**** package com.loovjo.tetris; ****Bar.java**** package com.loovjo.tetris; "package aaa;" // package bbbb; /** * package cccc; */ ****Baz.java**** //comment: package com.loovjo.tetris; ``` Cannot work with things like `package/*;*/stuff`, because regex. ]
[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/40085/edit). Closed 9 years ago. [Improve this question](/posts/40085/edit) So a colleaque came with this problem lately and I want to challange you to solve the problem in the code-golf style, shortest solution in any language wins. **The Problem:** Given is a random set of values, where the values themselfs are not the concern, but the amount (which is random as well)of values. To keep the posts readable, let's limit the amount of values to 200, but the program must be able to handly any amount of values, which the language supports. **Input:** No Input needet, due the programm should set an random amount of values (limited to 200). **Output:** Can be text or graphic(px) I recommend to use single digits as values if you use text based output, to keep the output clear. **Example:** ``` {1,2,3,4,5,6,7,8,9,1,2,3,4,5,6,7} -- Amount : 16 ``` Now you should sort these values in a approcimated square matrix like: ``` 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 (4 x 4) ``` Pretty simple so far, if not boring. **But now the challange:** The number of fields in the matrix must be equivalent to the amount of values given. No empty fields or ignored values are allowed. As an example, with 12 values, an square matrix is not possible, so you have to find the next aproximitation to it, which is 3x4 or 4x3 but NOT 4x4. For any prime, the matrix would be **1 x prime** **Examples:** For 12 Values: ``` 1 2 3 4 5 6 7 8 9 1 2 3 X X X X <- NOT ALLOWED, it makes the matrix square, but inserts non existing values. ``` or ``` 1 2 3 4 5 6 7 8 9 1 2 3 ``` For 35 Values: ``` 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 ``` [Answer] ## Mathematica, 91 bytes ``` n=RandomInteger@199+1 TableForm@Partition[Range@9~RandomChoice~n,Divisors@n~Nearest~Sqrt@n] ``` I hope I got this right: * Generate a random length between `1` and `200` (inclusive). * Generate a list of that length with numbers from `1` to `9` (inclusive). * Find one of the two divisors closest to the square root, with `Divisors@n~Nearest~Sqrt@n`. * Break the list into rows of that length. * Display the grid with `TableForm`. Example run: ![enter image description here](https://i.stack.imgur.com/3kNhW.png) [Answer] ## Javasript, ~~156 or 119~~ 152 or 115 Output numbers 1 to 9: **152** ``` for(q=~~Math.sqrt(n=new Date%200);~~(w=n/q)!=w;--q);i=q=0;alert("".replace.call(Array(n+1),/./g,function(){return(++q>9?q=1:q)+(++i==w?i=0||"\n":" ")})) ``` Output zeroes: **115** ``` for(q=~~Math.sqrt(n=new Date%200);~~(w=n/q)!=w;--q);alert(Array(q+1).join("".replace.call(Array(w+1),/./g,0)+"\n")) ``` ]
[Question] [ **fastest relay time** = lowest possible total integer value of (a freestyle swimmers time) + (1 breastroke swimmers time) + (another backstroke swimmers time) + (another butterfly swimmers time) * Each swimmer must be unique to the relay (no duplicates) * Each stroke must be used once Input Data: array of dictionaries, where each single dictionary represents a swimmer's swim times for each stroke. Each dictionary has the named properties of 'fly','back','breast','free': Example Input: ``` [ {'Fly': 10, 'Breast': 48.26, 'Free': 28.43, 'Back': 34}, {'Fly': 47.51, 'Breast': 24, 'Free': 28.47, 'Back': 10}, {'Fly': 26, 'Breast': 46.44, 'Free': 10, 'Back': 30}, {'Fly': 37.81, 'Breast': 10, 'Free': 24, 'Back': 49}, {'Fly': 38.31, 'Breast': 29, 'Free': 20, 'Back': 10} ] ``` Example Output: ``` 40 ``` (this is an easy case where the best relay is simply the fastest person in each stroke; other times you might need to have the 3rd fastest breastroker swim breastroke in order to get the lowest overall time!) Example Measurement of a relay using the first 4 swimmers in the data set above: ``` swimmer 1 swims fly and his time is 10 total += 10 swimmer 2 swims back and his time is 10 total += 10 swimmer 3 swims fly and his time is 10 total += 10 swimmer 4 swims breast and his time is 10 best relay total for these 4 people = 40 ``` Output Data: should be a single float or integer value representing the total time of the best relay. (a legal relay includes a fly swimmer, a back swimmer, a breast swimmer, and a free swimmer, each leg of the relay swam by a unique swimmer) EDIT: brute force vs dynamic parameter removed. [Answer] Meh, I'm no Python programmer by any stretch of the imagination. Hell, some would even hesitate to call me a programmer. But as nobody else has answerred this, why not post my solution? If anything else, it was fun just to brush up on the very Python basics: ``` swimmers = [{'Fly': 10, 'Breast': 48.26, 'Free': 28.43, 'Back': 34}, {'Fly': 47.51, 'Breast': 24, 'Free': 28.47, 'Back': 10}, {'Fly': 26, 'Breast': 46.44, 'Free': 10, 'Back': 30}, {'Fly': 37.81, 'Breast': 10, 'Free': 24, 'Back': 49}, {'Fly': 38.31, 'Breast': 29, 'Free': 20, 'Back': 10}] bestTime = float('inf') for fly in range(len(swimmers)): for breast in range(len(swimmers)): for free in range(len(swimmers)): for back in range(len(swimmers)): if len(set([fly,breast,free,back])) > 3: current = swimmers[fly]['Fly'] + swimmers[breast]['Breast'] + swimmers[free]['Free'] + swimmers[back]['Back'] if current < bestTime: bestTime = current print bestTime ``` ]
[Question] [ Ok lets say we get a input the following csv file (all entries are quoted strings) ``` ID, Before, After, Value 1, 3, 5, Cat 2, 5, , Apple 3, 4, 1, Dog 4, , 3, Elephant 5, 1, 2, Banana ``` Output a csv file in which the entries are usage sequence order. ``` ID, Before, After, Value 2, 5, , Apple 5, 1, 2, Banana 1, 3, 5, Cat 3, 4, 1, Dog 4, , 3, Elephant ``` **Notes:** The Values may not necessarily appear in alphabetical order all the time, just that in this example they are. No revaluing of the IDs being use. They must be the same as input. Input and Output files will be pass as args to program. [Answer] # Ruby ~~109~~ 108 Saved one whole character by using randomization instead of searching! ``` h,*t=[*$<] t.shuffle!until t.each_cons(2).all?{|c|a,b=c.map{|y|y.lstrip.split /[,\s]+/} a[1]==b[0]} puts h,t ``` This only prints to stdout, so to save to a file use `ruby csv.rb in.csv > out.csv`. ``` $ cat test.csv ID, Before, After, Value 1, 3, 5, Cat 2, 5, , Apple 3, 4, 1, Dog 4, , 3, Elephant 5, 1, 2, Banana $ ruby csv.rb test.csv ID, Before, After, Value 2, 5, , Apple 5, 1, 2, Banana 1, 3, 5, Cat 3, 4, 1, Dog 4, , 3, Elephant ``` ### Old version ``` puts gets,[*$<].permutation.find{|x|x.each_cons(2).all?{|c|a,b=c.map{|y|y.lstrip.split /[,\s]+/} a[1]==b[0]}} ``` It simply finds the permutation of the lines where, for each line, the second column (*Before*) equals the first column (*ID*) of the next line. [Answer] ## VB.net (Non-Golfed) ``` Module Module3 Public Sub Main(ParamArray args() As String) Dim items = CSVFileReader(args(0)).ToDictionary(Function(x) x(0)) Dim Current = items.First(Function(kvp) kvp.Value(2) = "").Value Using out As New IO.StreamWriter(args(1), False) With {.AutoFlush=True } Do out.WriteLine("""{0}"",""{1}"",""{2}"",""{3}""", Current(0), Current(1), Current(2), Current(3)) If Current(1) <> "" Then Current = items(Current(1)) Loop Until Current(1) = "" out.WriteLine("""{0}"",""{1}"",""{2}"",""{3}""", Current(0), Current(1), Current(2), Current(3)) End Using End Sub Public Iterator Function CSVFileReader(fn As String) As IEnumerable(Of String()) Using t As New FileIO.TextFieldParser(fn) With {.Delimiters ={","},.HasFieldsEnclosedInQuotes = True, .TextFieldType=FileIO.FieldType.Delimited } While Not t.EndOfData Yield t.ReadFields End While End Using End Function End Module ``` Probably a lot of room to golf that code. [Answer] ## C#, 272 bytes Not a great answer, but it works. If I understand Linq correctly, this opens the input file repeatedly, once for each line it writes to the output. ``` namespace System.Linq{ class P{ static void Main(string[]a) { var v=IO.File.ReadAllLines(a[0]).Select(y=>y.Split(',').ToList()); var l=v.First(); var s="\"\""; for(;;){ IO.File.AppendAllText(a[1],string.Join(",",l)+"\n"); l=v.FirstOrDefault(x=>x[2]==s); if(l==null)break; s=l[0]; } } } } ``` Input file: ``` "ID","Before","After","Value" "1","3","5","Cat" "2","5","","Apple" "3","4","1","Dog" "4","","3","Elephant" "5","1","2","Banana" ``` Output file: ``` "ID","Before","After","Value" "2","5","","Apple" "5","1","2","Banana" "1","3","5","Cat" "3","4","1","Dog" "4","","3","Elephant" ``` ]
[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/19467/edit). Closed 10 years ago. [Improve this question](/posts/19467/edit) Six degrees of separation is the theory that everyone and everything is six or fewer steps away, by way of introduction, from any other person in the world. Your challenge here is to write a program which crawls to find out what is exactly 6 links away but connected back to the starting URL through a series of links. For example if your program is given a starting url of <http://vimeo.com> it would then potentially (this is a made up example) crawl to: 1. <http://www.abc.com> links to -> 2. <http://www.widgets.com> links to -> 3. <http://www.gadgets.net> links to -> 4. <http://www.techcrunch.com> links to -> 5. <https://twitter.com/techcrunch> links to -> 6. <http://www.youtube.com/user/techcrunch> (finish as we are now 6 links away from the starting URL.) Rules: * You can choose your own starting URL. * Any programming language can be used. * You most obey sites robots.txt files and not crawl any areas sites disallow. * Each step must be a new URL from the one you are currently on. * URLS should only be visited once per crawl. * You must output the starting URL and each link followed in sequence. Winner: * This is a popularity contest so the solution with the most up-votes wins. [Answer] ## Java, 8623 bytes It isn't perfect. It has some issues connecting to some URLs and fails to parse the robots.txt properly. However, it's a start. ``` package info.varden.codegolf.sixdegreeslink; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.net.URLConnection; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.Map.Entry; import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Main { private static HashMap<String, String> entities = new HashMap<>(); private static HashMap<String, ArrayList<String>> robotstxts = new HashMap<>(); public static void main(String[] args) { long startTime = System.currentTimeMillis(); String init = ""; for (String s : args) { init += s + "%20"; } init = init.substring(0, init.length() - 3); try { System.out.println("Resolving entites (step 1 of 3)..."); entities.putAll(getEntitiesFromEnt("http://www.w3.org/TR/html4/HTMLlat1.ent")); System.out.println("Resolving entites (step 2 of 3)..."); entities.putAll(getEntitiesFromEnt("http://www.w3.org/TR/html4/HTMLsymbol.ent")); System.out.println("Resolving entites (step 3 of 3)..."); entities.putAll(getEntitiesFromEnt("http://www.w3.org/TR/html4/HTMLspecial.ent")); System.out.println(entities.size() + " entites resolved.\n"); } catch (Exception e) { e.printStackTrace(); } System.out.println("Starting search from: " + init + "\n"); IterationInfo initInfo = new IterationInfo(); IterationInfo info = initInfo; try { initInfo.scanLink = init; initInfo.links.add(init); initInfo.domains.add(getDomain(init)); info = getSixStepsRecursive(initInfo); } catch (URISyntaxException e) { e.printStackTrace(); } long diffTime = System.currentTimeMillis() - startTime; long second = (diffTime / 1000) % 60; long minute = (diffTime / (1000 * 60)) % 60; long hour = (diffTime / (1000 * 60 * 60)) % 24; diffTime = diffTime % 1000; String time = String.format("%02d:%02d:%02d.%d", hour, minute, second, diffTime); System.out.println("\nCompleted in " + time); System.out.println("\nRESULTS:"); if (info.success) { for (int i = 0; i < info.links.size(); i++) { System.out.println(info.links.get(i)); } } else { System.out.println("Can't find six degrees step separation!"); } } private static IterationInfo getSixStepsRecursive(IterationInfo info) { IterationInfo returnInfo = info; String[] urls = new String[0]; try { String content = downloadString(info.scanLink); content = content.replace("\t", " ").replace("\r", " ").replace("\n", " "); while (content.contains(" ")) content = content.replace(" ", " "); urls = content.split("\\Q<a href=\"\\E"); } catch (Exception ex) { ex.printStackTrace(); } for (int i = 1; i < urls.length; i++) { try { if (info.iteration == 6) { returnInfo.success = true; return returnInfo; } returnInfo = info; urls[i] = stripHTMLEntities(urls[i].split("\"")[0]); if (urls[i].startsWith("//")) urls[i] = "http:" + urls[i]; if (!urls[i].startsWith("http://") && !urls[i].startsWith("https://")) { System.out.println("Iter " + info.iteration + " - URL failed: Relative or non-HTTP link (" + urls[i] + ")"); continue; } if (!canGetRobotsTxt(urls[i])) { System.out.println("Iter " + info.iteration + " - URL failed: Blocked by robots.txt (" + urls[i] + ")"); continue; } if (returnInfo.links.contains(urls[i])) { System.out.println("Iter " + info.iteration + " - URL failed: Exact link already passed (" + urls[i] + ")"); continue; } if (returnInfo.domains.contains(getDomain(urls[i]))) { System.out.println("Iter " + info.iteration + " - URL failed: Domain already passed (" + getDomain(urls[i]) + ") (" + urls[i] + ")"); continue; } System.out.println("Iter " + info.iteration + " - URL valid: Distict domain (" + getDomain(urls[i]) + ") (" + urls[i] + ")"); returnInfo.links.add(urls[i]); returnInfo.domains.add(getDomain(urls[i])); returnInfo.iteration = info.iteration + 1; returnInfo.scanLink = urls[i]; returnInfo = getSixStepsRecursive(returnInfo); if (returnInfo.success) { return returnInfo; } } catch (Exception ex) { } } return returnInfo; } private static boolean canGetRobotsTxt(String url) { try { URI cur = new URI(url); if (!robotstxts.containsKey(cur.getHost())) { String rtxt = downloadString("http://" + cur.getHost() + "/robots.txt"); String[] lines = rtxt.split("\n"); ArrayList<String> ar = new ArrayList<>(); for (String line : lines) { if (line.endsWith("\r")) line = line.substring(0, line.length() - 1); if (line.toLowerCase().startsWith("disallow: ")) { line = line.substring(10); ar.add(line); } else if (line.toLowerCase().startsWith("allow: ")) { line = line.substring(7); ar.remove(line); } } robotstxts.put(cur.getHost(), ar); } ArrayList<String> a = robotstxts.get(cur.getHost()); for (String s : a) { String[] sw = s.split("\\Q*\\E"); String s2 = "^i"; for (String s3 : sw) { s2 += "\\Q" + s3 + "\\E(.+)"; } s2 = s2.substring(0, s2.length() - 4); Pattern p = Pattern.compile(s2); Matcher m = p.matcher(cur.getPath()); if (m.find()) { return false; } } return true; } catch (Exception e) { return true; } } private static HashMap<String, String> getEntitiesFromEnt(String url) throws Exception { HashMap<String, String> e = new HashMap<>(); String ent = downloadString(url); while (ent.contains(" ")) ent = ent.replace(" ", " "); String[] lines = ent.split("\n"); for (String line : lines) { if (line.startsWith("<!ENTITY")) { String[] f = line.split(" "); e.put("&" + f[1] + ";", f[3].substring(1, f[3].length() - 1)); } } return e; } private static String downloadString(String url) throws Exception { URL cur = new URL(url); URLConnection conn = cur.openConnection(); conn.setRequestProperty("User-Agent", "URLConnection/1.7 (Any system) VardenCG/3.0"); BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String content = "", line; while ((line = in.readLine()) != null) content += line + "\n"; in.close(); return content; } private static String stripHTMLEntities(String html) { for (Entry<String, String> e : entities.entrySet()) html = html.replace(e.getKey(), e.getValue()); Pattern ep = Pattern.compile("&#(\\d+);"); Matcher m = ep.matcher(html); while (m.find()) { if (!m.group(1).equals("38")) html = html.replace("&#" + m.group(1) + ";", String.valueOf((char)Integer.parseInt(m.group(1)))); } Pattern ep1 = Pattern.compile("&(x|X)([\\da-fA-F]+);"); Matcher m2 = ep1.matcher(html); while (m2.find()) { if (!m.group(1).equals("26")) { html = html.replace("&x" + m2.group(2) + ";", String.valueOf((char)Integer.parseInt(m2.group(2), 16))); html = html.replace("&X" + m2.group(2) + ";", String.valueOf((char)Integer.parseInt(m2.group(2), 16))); } } html = html.replace("&#38;", "\0").replace("&x26;", "\0").replace("&X26;", "\0").replace("\0", "&"); return html; } private static String getDomain(String url) throws URISyntaxException { URI uri = new URI(url); String host = uri.getHost().toLowerCase(); String[] subDomainTree = host.split("\\."); String[] commonSLs = {"ac", "co", "com", "gov", "ltd", "me", "net", "org"}; boolean isCommonSL = false; try { String secondLevel = subDomainTree[subDomainTree.length - 2]; for (String sl : commonSLs) { if (sl.equals(secondLevel)) { isCommonSL = true; } } } catch (ArrayIndexOutOfBoundsException ex) { return host; } try { if (isCommonSL) { return subDomainTree[subDomainTree.length - 3] + "." + subDomainTree[subDomainTree.length - 2] + "." + subDomainTree[subDomainTree.length - 1]; } else { return subDomainTree[subDomainTree.length - 2] + "." + subDomainTree[subDomainTree.length - 1]; } } catch (ArrayIndexOutOfBoundsException ex) { return subDomainTree[subDomainTree.length - 2] + "." + subDomainTree[subDomainTree.length - 1]; } } private static class IterationInfo { public ArrayList<String> domains = new ArrayList<>(); public ArrayList<String> links = new ArrayList<>(); public String scanLink = ""; public int iteration = 1; public boolean success = false; } } ``` Parameter used: `http://codegolf.stackexchange.com/` Output: <http://pastebin.no/34cd> (Had to post on other site because it was too big for codegolf) There's a lot of stuff going on here. First of all, I have to parse HTML entities like &em &39; and &x2F. The named entities have to be translated, I do that by downloading the definitions from W3C. I also need to figure out the host of the URL, taking into account common second level domains like co, edu etc. (.co.uk, .edu.uk, ...) Then I need to parse robots.txt. I don't have time to write more now, but oh well, there's my contribution. -- bilde2910 ]
[Question] [ **This question already has answers here**: [Hangman wordgame golf](/questions/2161/hangman-wordgame-golf) (10 answers) Closed 10 years ago. Although there was a [hangman competition](https://codegolf.stackexchange.com/questions/2161/hangman-wordgame-golf) before, I don't feel it was beautiful enough. The challenge is to implement a clone of <http://inventwithpython.com/chapter9.html> but as in the previous competition you can input the list of words in any way you want. The main difference is therefore just that you have to draw the gallows in ascii as the game goes on. [Answer] # Python 3 You will need to put the lists in a folder named wordlists, which is placed in the same folder as the source. You can download the full .zip here: <https://github.com/OddLlama/ascii-gallows-club>. This program allows 7 guesses until completion, and allows guessing the full word in one blow, if you think you know it. It has a debug mode, where you enter 'debug' instead of the number of players, and does not allow you to enter a guess more than once. It also allows 2-player mode, where one player enters the word, and a second player guesses it. In this mode, the entered word does not display while being typed. Other features are score-keeping and displaying special characters (although the lists haven't been updated to represent that): ``` #!/usr/bin/env python3 import random # for choosing a word import os # for finding files in wordlists directory import textwrap # for ASCII art dedentation import time # for sleeping at the end import getpass # for 2 player # grab all the filenames categories = [f.split('.')[0] for f in os.listdir('wordlists')] debug_mode = False def debug(s): if debug_mode: print('[DEBUG] ' + s) def print_ASCII(ascii_str): "Print ASCII art." print(textwrap.dedent(ascii_str)) def header(): "Print the header." print_ASCII(""" /=======================\\ | Welcome to Hangman!!! | \\=======================/ """) def choose_category(): "Request the user to input a category." for i, cat in enumerate(categories): # print the categories & numbers print('%i. %s' % (i, cat)) choice = input('Please enter a category name or number: ').lower() if choice.isdigit() and 0 <= int(choice) < len(categories): choice = categories[int(choice)] for i, cat in enumerate(categories): if choice == str(i): choice = cat while choice not in categories: # loop until user enters a valid category choice = input('Invalid category. Try again: ') if choice.isdigit() and 0 <= int(choice) < len(categories): choice = categories[int(choice)] return choice def get_word(category): "Retrieve a random word from a category." with open('wordlists/%s.txt' % category) as f: # use `with` for automatic file closure words = f.readlines() return random.choice(words).rstrip('\n').strip().lower() def get_guess(guessed): "Get the user to guess a letter." guess = input('Guess: ').lower() while guess in guessed: guess = input('You already guessed that. Try again: ').lower() return guess # draw gallows def draw_board(bad_guesses, word): length = len(bad_guesses) # this is also always drawn print_ASCII(""" ______________ | / | |/ | |{0} {2}{1}{3} | {4} | {5} | {6} {7} | | | {8} |________________|""".format(' ' if length == 1 else '', 'O' if length > 0 else '', '__' if len(bad_guesses) > 1 else '', '__' if len(bad_guesses) > 2 else '', '|' if length > 3 else '', '|' if length > 4 else '', '/' if length > 5 else '', '\\' if length > 6 else '', ' '.join(map(lambda s: '[%s]' % s, bad_guesses))).strip('\n')) def hangman(word): # main function """ Plays hangman! Returns True if the user won, False otherwise. """ debug('The word is %s' % word) # the lines showing the word so far guess = ['_' if char.isalnum() else char for char in word] # already guessed and wrong guesses guessed = [] bad_guesses = [] while len(bad_guesses) < 7: # main loop # print letters so far print(' '.join(guess)) # request input letter = get_guess(guessed) guessed.append(letter) # check if letter is correct or not if letter in word or letter == word: # update chars guessed so far guess = [letter if char == letter else guess_char for char, guess_char in zip(word, guess)] if letter == word: guess = list(word) # did they win? if ''.join(guess) == word: print('Congratulations, you guessed the word: %s!' % word) return True else: bad_guesses.append(letter) print('%s is not in the word.' % letter) # add a little separation print() draw_board(bad_guesses, word) # if program reaches here, user failed print('You couldn\'t guess the word. It was %s.' % word) return False if __name__ == '__main__': header() players = input('How many players? 1 for playing against computer, 2 for playing against another human: ') while players not in ['1', '2', 'debug']: players = input('Invalid input. Please try again: ') # debug mode stuff if players == 'debug': debug_mode = True debug('Debug mode has been turned on.') while players not in ['1', '2']: players = input('Number of players: ') print() # spacing if players == '1': wins, losses = 0, 0 if hangman(get_word(choose_category())): wins += 1 else: losses += 1 while True: print('You have won %i time%s and lost %i time%s.' % (wins, '' if wins == 1 else 's', losses, '' if losses == 1 else 's')) again = input('Play again? (y/n): ').lower() == 'y' print() # separation if again: if hangman(get_word(choose_category())): wins += 1 else: losses += 1 else: break else: while True: word = getpass.getpass('Word maker: enter your word (the input will not be shown): ') hangman(word) again = input('Play again? (y/n): ').lower() == 'y' print() # separation if not again: break print('Goodbye!') time.sleep(2) ``` ]
[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/17908/edit). Closed 2 years ago. [Improve this question](/posts/17908/edit) # Description Here's a challenge with a somewhat practical use, at least for us golfers. Your mission, should you choose to accept it, is to write a program that can take arbitrary binary data (either from stdin, or a file) and output some valid source code which provides access to the data. The generator and target languages need not be the same. # Scoring Your program will be run against two inputs: a 1 KiB file of random characters, and the lyrics of Never Gonna Give You Up by Rick Astley. The program with the lowest score wins. Your score is calculated as follows: > > (**A** + **B**) × loge(**Z**) > > > Where: * **A** is the number of bytes in the output for the random data; * **B** is the number of bytes in the output for Never Gonna Give You Up; and * **Z** is the number of useful bytes in the target programming language *(useful is a very broad definition and may be refined in the future)* For example: * in C++ the generally allowed characters are `"\t \r\nABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!\"#%&'()*+,-./:;<=?[\\]^_{|}~"` which would give **Z** = 94 * in Brainfuck the only non-ignored characters are `"<>+-.,[]"` which gives **Z** = 8 # Examples Two examples in Python, both generating python source: *Python allows files encoded in UTF-16, so the valid python bytes are from 0x00-0xFF* ### Using Repr ``` import sys print 'data=',repr(sys.stdin.read()) ``` Score: (2898 + 2098) × loge(256) = 27,704 ### Using Base64 ``` import sys from base64 import b64encode print 'from base64 import b64decode;data=b64decode("'+b64encode(sys.stdin.read())+'")' ``` Score: (1416 + 2640) × loge(256) = 22,491 # Data The data is given here encoded in base64, these files should be decoded prior to passing to your program. The decoding is outside of the scope of this challenge. ### Random ``` 2moE8CGQCSSr8V4uHaeKMvtJUtStqVwvgn3xGgCWIlRWaEjVTLmF/fn0heXYh7GIPAUSZmEa2pR5 KTuLfLVtPMi8eUg5903zd/b57BIVJEPGVOyBhzxGTlzYEVG3uaUwnSOlpw9zP5SK/vjDNDCdF4IJ ZBg8cHloaoxqw1Bm306GV6v6/Gzx+MHcCOsUyT0MyqOAgbuA4t568QTT82zd/nbZQ2BE9Q6bmIwo tfBCTPwV0TShetCufxZJBbnVrNlDW8BDnKMGzqws/dJT+C03ndd64sszj/Quvri74Earfg6/07ea Gh5KY8onMhpRiB/k/M6aHpA/glmaFNE5Gu0TsKVgNCHUCP1Dqb9MKR3FU21Dg6fNttR4m+ZJNtbU yMy6nWTuBx/N7hcUXIdn5FF6X5r+EdUtJxV1pegaDPsKO1Weag1TT5FqeIFEKyw2L9NX7QAsXuva 8Y/6/+iEH/ldIEe/ZHzPc5kqPtuip6l/y2+zleXLw7W4jQ1vLL0xbI4J0lQhpLniCc1K+5699TN8 +k01C16JdSQfEAx+dVlRq6m9Vf0uWonUWgrYsmvtY4hmC1AqKDIr9p6rB6zRL3d/8ctHeKwLZlmh HCQYqyZURixVJnOkamIk8JP6xk82lC3PyCfP9fwHitguwK4Lnz6x22snqHvk8fW9iZbydWjjFW1+ SX2KE5M4pr7SKs+WzbGWks9FZNoHlGF4Ju1rT8zlYWUwX/3qZ2hHKuc+tXwedb75vj8NDeTiBAgD /3L3ckt8Xw0JyFKCXv3nCJx3rC7oA1x1U7ZewlQTgCipPkUrRFehKYCjM42h8XCj1yVrbuL5fTvu ZL5R/xOALz8XK0yxPqN5WgUtD4UFcxsmvAZ6OrbFysciud5hNHkZlr9Tr2oUtFvtx8o6eWH/eHO3 OJFyKiKdqDE/RzwnaPeND9DaZ3A2Jn/5RL+IHfWRlA5Q9i5plOg6v3ZMuGhPJX7tfqjtVW7z5OnR pTZ2vpDMVwWUdygDbmjXg6xIFuVZzXR+hdoF3dGb0iBOkOlsvASNnmLs+ZSgJFYe03ydjFe8CVG8 Dogi7Ca9FtaGvOem8MqsjVS2sHDdLaQ6AHX0y3HEvhK+O3udAoTztIb/VILyaA9NVnxwiK5MCdfB l0CHlRxmV2oDYaxxa58U2llEqn9adcTdp/eH/QVhfu32+c1x4pMMDPZxG9HBtOe5oIFEPUYth6zz ttD/mfa0VRPM+Za1OWpa+SpFsV8spYc38c9d5t8x2ihNf2B0vN/t8Y3R0ge8iq6n/Tt2EGBRop7x Vv013OMy5UUA7qiGexIv4xS2OUW8gSUbwxt2a+8Q5WQBw1LU7GLT6mDsZvQ+vsHqi34POcI+cQ== ``` ### Never Gonna Give You Up ``` V2UncmUgbm8gc3RyYW5nZXJzIHRvIGxvdmUNCllvdSBrbm93IHRoZSBydWxlcyBhbmQgc28gZG8g SQ0KQSBmdWxsIGNvbW1pdG1lbnQncyB3aGF0IEknbSB0aGlua2luZyBvZg0KWW91IHdvdWxkbid0 IGdldCB0aGlzIGZyb20gYW55IG90aGVyIGd1eQ0KSSBqdXN0IHdhbm5hIHRlbGwgeW91IGhvdyBJ J20gZmVlbGluZw0KR290dGEgbWFrZSB5b3UgdW5kZXJzdGFuZA0KDQpOZXZlciBnb25uYSBnaXZl IHlvdSB1cA0KTmV2ZXIgZ29ubmEgbGV0IHlvdSBkb3duDQpOZXZlciBnb25uYSBydW4gYXJvdW5k IGFuZCBkZXNlcnQgeW91DQpOZXZlciBnb25uYSBtYWtlIHlvdSBjcnkNCk5ldmVyIGdvbm5hIHNh eSBnb29kYnllDQpOZXZlciBnb25uYSB0ZWxsIGEgbGllIGFuZCBodXJ0IHlvdQ0KDQpXZSd2ZSBr bm93biBlYWNoIG90aGVyIGZvciBzbyBsb25nDQpZb3VyIGhlYXJ0J3MgYmVlbiBhY2hpbmcgYnV0 DQpZb3UncmUgdG9vIHNoeSB0byBzYXkgaXQNCkluc2lkZSB3ZSBib3RoIGtub3cgd2hhdCdzIGJl ZW4gZ29pbmcgb24NCldlIGtub3cgdGhlIGdhbWUgYW5kIHdlJ3JlIGdvbm5hIHBsYXkgaXQNCkFu ZCBpZiB5b3UgYXNrIG1lIGhvdyBJJ20gZmVlbGluZw0KRG9uJ3QgdGVsbCBtZSB5b3UncmUgdG9v IGJsaW5kIHRvIHNlZQ0KDQpOZXZlciBnb25uYSBnaXZlIHlvdSB1cA0KTmV2ZXIgZ29ubmEgbGV0 IHlvdSBkb3duDQpOZXZlciBnb25uYSBydW4gYXJvdW5kIGFuZCBkZXNlcnQgeW91DQpOZXZlciBn b25uYSBtYWtlIHlvdSBjcnkNCk5ldmVyIGdvbm5hIHNheSBnb29kYnllDQpOZXZlciBnb25uYSB0 ZWxsIGEgbGllIGFuZCBodXJ0IHlvdQ0KDQpOZXZlciBnb25uYSBnaXZlIHlvdSB1cA0KTmV2ZXIg Z29ubmEgbGV0IHlvdSBkb3duDQpOZXZlciBnb25uYSBydW4gYXJvdW5kIGFuZCBkZXNlcnQgeW91 DQpOZXZlciBnb25uYSBtYWtlIHlvdSBjcnkNCk5ldmVyIGdvbm5hIHNheSBnb29kYnllDQpOZXZl ciBnb25uYSB0ZWxsIGEgbGllIGFuZCBodXJ0IHlvdQ0KDQooT29oLCBnaXZlIHlvdSB1cCkNCihP b2gsIGdpdmUgeW91IHVwKQ0KKE9vaCkNCk5ldmVyIGdvbm5hIGdpdmUsIG5ldmVyIGdvbm5hIGdp dmUNCihHaXZlIHlvdSB1cCkNCihPb2gpDQpOZXZlciBnb25uYSBnaXZlLCBuZXZlciBnb25uYSBn aXZlDQooR2l2ZSB5b3UgdXApDQoNCldlJ3ZlIGtub3cgZWFjaCBvdGhlciBmb3Igc28gbG9uZw0K WW91ciBoZWFydCdzIGJlZW4gYWNoaW5nIGJ1dA0KWW91J3JlIHRvbyBzaHkgdG8gc2F5IGl0DQpJ bnNpZGUgd2UgYm90aCBrbm93IHdoYXQncyBiZWVuIGdvaW5nIG9uDQpXZSBrbm93IHRoZSBnYW1l IGFuZCB3ZSdyZSBnb25uYSBwbGF5IGl0DQoNCkkganVzdCB3YW5uYSB0ZWxsIHlvdSBob3cgSSdt IGZlZWxpbmcNCkdvdHRhIG1ha2UgeW91IHVuZGVyc3RhbmQNCg0KTmV2ZXIgZ29ubmEgZ2l2ZSB5 b3UgdXANCk5ldmVyIGdvbm5hIGxldCB5b3UgZG93bg0KTmV2ZXIgZ29ubmEgcnVuIGFyb3VuZCBh bmQgZGVzZXJ0IHlvdQ0KTmV2ZXIgZ29ubmEgbWFrZSB5b3UgY3J5DQpOZXZlciBnb25uYSBzYXkg Z29vZGJ5ZQ0KTmV2ZXIgZ29ubmEgdGVsbCBhIGxpZSBhbmQgaHVydCB5b3UNCg0KTmV2ZXIgZ29u bmEgZ2l2ZSB5b3UgdXANCk5ldmVyIGdvbm5hIGxldCB5b3UgZG93bg0KTmV2ZXIgZ29ubmEgcnVu IGFyb3VuZCBhbmQgZGVzZXJ0IHlvdQ0KTmV2ZXIgZ29ubmEgbWFrZSB5b3UgY3J5DQpOZXZlciBn b25uYSBzYXkgZ29vZGJ5ZQ0KTmV2ZXIgZ29ubmEgdGVsbCBhIGxpZSBhbmQgaHVydCB5b3UNCg0K TmV2ZXIgZ29ubmEgZ2l2ZSB5b3UgdXANCk5ldmVyIGdvbm5hIGxldCB5b3UgZG93bg0KTmV2ZXIg Z29ubmEgcnVuIGFyb3VuZCBhbmQgZGVzZXJ0IHlvdQ0KTmV2ZXIgZ29ubmEgbWFrZSB5b3UgY3J5 DQpOZXZlciBnb25uYSBzYXkgZ29vZGJ5ZQ0KTmV2ZXIgZ29ubmEgdGVsbCBhIGxpZSBhbmQgaHVy dCB5b3U= ``` [Answer] ## PHP 8986 ``` <?php $data = file_get_contents('php://stdin'); printf('$var=gzuncompress(base64_decode("%s"));', base64_encode(gzcompress($data))); ``` ### Binary 1417 ``` $var=gzuncompress(base64_decode("eJwBAAT/+9pqBPAhkAkkq/FeLh2nijL7SVLUralcL4J98RoAliJUVmhI1Uy5hf359IXl2IexiDwFEmZhGtqUeSk7i3y1bTzIvHlIOfdN83f2+ewSFSRDxlTsgYc8Rk5c2BFRt7mlMJ0jpacPcz+Uiv74wzQwnReCCWQYPHB5aGqMasNQZt9Ohler+vxs8fjB3AjrFMk9DMqjgIG7gOLeevEE0/Ns3f522UNgRPUOm5iMKLXwQkz8FdE0oXrQrn8WSQW51azZQ1vAQ5yjBs6sLP3SU/gtN53XeuLLM4/0Lr64u+BGq34Ov9O3mhoeSmPKJzIaUYgf5PzOmh6QP4JZmhTRORrtE7ClYDQh1Aj9Q6m/TCkdxVNtQ4OnzbbUeJvmSTbW1MjMup1k7gcfze4XFFyHZ+RRel+a/hHVLScVdaXoGgz7CjtVnmoNU0+RaniBRCssNi/TV+0ALF7r2vGP+v/ohB/5XSBHv2R8z3OZKj7boqepf8tvs5Xly8O1uI0Nbyy9MWyOCdJUIaS54gnNSvuevfUzfPpNNQteiXUkHxAMfnVZUaupvVX9LlqJ1FoK2LJr7WOIZgtQKigyK/aeqwes0S93f/HLR3isC2ZZoRwkGKsmVEYsVSZzpGpiJPCT+sZPNpQtz8gnz/X8B4rYLsCuC58+sdtrJ6h75PH1vYmW8nVo4xVtfkl9ihOTOKa+0irPls2xlpLPRWTaB5RheCbta0/M5WFlMF/96mdoRyrnPrV8HnW++b4/DQ3k4gQIA/9y93JLfF8NCchSgl795wicd6wu6ANcdVO2XsJUE4AoqT5FK0RXoSmAozONofFwo9cla27i+X077mS+Uf8TgC8/FytMsT6jeVoFLQ+FBXMbJrwGejq2xcrHIrneYTR5GZa/U69qFLRb7cfKOnlh/3hztziRcioinagxP0c8J2j3jQ/Q2mdwNiZ/+US/iB31kZQOUPYuaZToOr92TLhoTyV+7X6o7VVu8+Tp0aU2dr6QzFcFlHcoA25o14OsSBblWc10foXaBd3Rm9IgTpDpbLwEjZ5i7PmUoCRWHtN8nYxXvAlRvA6IIuwmvRbWhrznpvDKrI1UtrBw3S2kOgB19MtxxL4Svjt7nQKE87SG/1SC8mgPTVZ8cIiuTAnXwZdAh5UcZldqA2GscWufFNpZRKp/WnXE3af3h/0FYX7t9vnNceKTDAz2cRvRwbTnuaCBRD1GLYes87bQ/5n2tFUTzPmWtTlqWvkqRbFfLKWHN/HPXebfMdooTX9gdLzf7fGN0dIHvIqup/07dhBgUaKe8Vb9NdzjMuVFAO6ohnsSL+MUtjlFvIElG8MbdmvvEOVkAcNS1Oxi0+pg7Gb0Pr7B6ot+DznCPnHYlQQF")); ``` ### ASCII 561 ``` $var=gzuncompress(base64_decode("eJztlD1uwzAMhXcDvgM3N0AvEaBA4KUdg46yRVtuZDLQTwzfvpSctHGDbu0QtJuhRz195JO8x8ohEIMPTlGPzkNgsHzCsnjlCAfiCYJBcNGiB0UaPINmqMtiC120FloexyGMSKHyMBkVoK5G2TPQYaAeuFucJo5WUxWgx5BUD53jURxnYDnAQR/nsqjhLfoAkyJSEFDsZ9lrBCKZdohWPMtixyEoGNUBsx5JC3kQurIoi2c8JTtOFv1wOpcc14IVirSueaK14iKBciyeuV2NHl2uXZd9HN66ea14NcsX62bGtZD7kaMHzM4mXnzLYo+VgKZpE6BqzXkmHbs0b8upaZmiA4PKpUE3iILZmjTiJoaspigDS5ZmTikmjkGUmvygESaERlyXSFNOF5eec06UKD4D79W4YE75iiwdHO3ZcyvC0OX+lT+AlN5k9MQp7dzzmCd1wWtE1xkQ8V7zukfmhxc2j9e0m+/XNrctPgJ9WZHS3Q/tvH4Bd/EA/u6v6p/595nfAV47k5c=")); ``` ### Z 94 Assumed the same character set as given for C++ in the question. There's not really much wiggle room on how to accomplish this aside from compression and base64 encoding. The only "step up" I can think of would be finagling base128 encoding, but there aren't enough "safe" characters to accomplish this given the variability of extended-ASCII. [Answer] # Ruby Long version: ``` require 'tempfile' tf=Tempfile.new('r') while $stdin.gets{tf.puts $_} tf.rewind print "data='" print IO.read(tf).gsub(/'/,"\\'") print "'" ``` Golfed-up version ``` require 'tempfile' t=Tempfile.new('r');while gets{t.puts $_};t.rewind;p "data='"+IO.read(t).gsub(/'/,"\\'")+"'" ``` ]
[Question] [ You have an array of working time period pairs (from, till) received from user input and written according 24-hour clock format convention. You have to merge these periods if the intersect each other. For example, if you have (10, 12), (11, 13), (12, 14) you should merge them into (10,14). Also (23, 0) and (0, 1) should be merged into (23, 1). UPDATE: @dmckee Let assume that the set of pairs like (10:00, 12:00) is the valid input. @dude We don't consider Sundays and holidays so all merges should be performed for the common twenty-four hours range. @steven-rumbalski The result of (0,8), (8,16), (16,0) may be any (x,x) pair, for example, (00:00,00:00). **Example 1** Input ``` (09:00,12:00),(11:00,13:00),(17:00,19:00) ``` Output ``` (09:00,13:00),(17:00,19:00) ``` --- **Example 2** Input ``` (00:00,08:00),(08:00,16:00),(16:00,00:00) ``` Output ``` (00:00) ``` [Answer] # Python (198 chars) ``` r=[] p=r.append l=r+sorted(a<b and (a,b)or p((0,b))or(a,24)for a,b in input()) r[:]=[] a,b=l[0] for c,d in l[1:]: if c>b:p((a,b));a,b=c,d elif b<d:b=d if b>23:b=a and r.pop(0)[1] p((a,b)) print r ``` Example: ``` > python merge.py (10, 12), (11, 13), (12, 14) [(10, 14)] > python merge.py (23,0),(0,1) [(23, 1)] > python merge.py (0,8), (8,16), (16,0) [(0, 0)] ``` ]
[Question] [ Write shortest code that detect how many swaps (minimum) are needed to sort (in increasing order) any array of unique positive integers. It should be fast enough to detect number of swaps in array of 1'000'000 integers in decreasing order in 1-2 minutes. ### Refs * [Bubble Sort on Wiki](http://en.wikipedia.org/wiki/Bubble_sort) * [Example implementations of bubble sort](http://en.wikibooks.org/wiki/Algorithm_implementation/Sorting/Bubble_sort) ### Score ``` [time elapsed]s/60s * [length of code] ``` [Answer] ## Python - 262 chars \* 45 / 60 = 196.5 Edit: much faster sorting algorithm. First it will sort all the items in the list by what hundred they are in (0, 100, 200, etc), in a list in `m` (note: I count these as 1 step each, so a list of 1,000,000 items will automatically have 1,000,000 steps initially) Then it will sort the lists within `m` using the bubble sorting function `c` This is greatly sped up from using `c` on the original list to be sorted, because the amount of time it takes to sort 1000 items is small (~0.04 seconds), but exponentially increases the larger the list gets (~45 seconds at 10,000 items). But if you sort 100 lists of 100 items, it only takes .4 seconds, to sort, more than 100 times faster than sorting 1 list of 10,000 items. It should therefor take 4 seconds to sort 100,000 items, and 40 seconds to finally sort 1,000,000 In actuality, it took 45 seconds to sort the reversed 1,000,000 item list this way, and results in 50,500,000 steps: ``` python bubblesortcount.py 50500000 44.6600000858 ``` This functon works with the given case (reverse ordered list), as well as any random case. No negative integers, though. ``` r=range def b(l): m=[[]for i in r(len(l)//100+1)];t=[];o=0 for e in l:m[e//100].append(e);o+=1 for e in m:x=c(e);t+=x[0];o+=x[1] return t,o def c(l): s=0 for p in r(len(l)-1,0,-1): for i in r(p): if l[i]>l[i+1]:l[i],l[i+1]=l[i+1],l[i];s+=1 return l,s ``` test: ``` import random,time a=time.time() d=b(range(1000000)[::-1]) #reversed list #d=b(random.sample(range(1000000),1000000)) #scrambled list z=(time.time()-a) #print d[0] # comment to not print a gigantic list print d[1] # number of steps print z # time it took ``` Edit: by changing the amount the helper function sorts by to 100, I reduced the average time it takes to sort the list to 45 seconds. also reduces character count by 2 edit again: you know what? maybe what I'm doing isn't valid. I can change the amount the helper function sorts by to just 1 and it will sort a million items in 5 seconds.. is this valid? ]
[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/269946/edit). Closed 7 days ago. [Improve this question](/posts/269946/edit) ***CANTERO NUMBERS*** **Definition and method:** Given a number N belonging to the naturals: 1. Square N 2. Add each of the digits from step 1) with its next neighbor, both left and right, except the first and last element. 3. If the result of 2) is not less than 8, continue performing step 2) 4. The final result, for the majority, is a 1, 4, 6, or 9. Except the numbers that do not break the cycle, called CANTERO NUMBERS **Examples**: 9 \* 9 = 81 --> 9 > 8 => 9 \* 9 26 \* 26 = 676 --> 13,13 --> 26 > 8 => 26 \* 26 37 \* 37 = 1369 --> 4,9,15 --> 13,24 --> 37 > 8 => 37 \* 37 64 \* 64 = 4096 --> 4,9,15 --> 13,24 --> 37 > 8 => 37 \* 37 ... 296 \* 296 = 87616 --> 15,13,7,7 --> 28,20,14 --> 48,34 --> 82 > 8 ==> 82 \* 82 = 6724 --> 13.9,6 --> 22.15 --> 37 > 8 ==> 37 \* 37 The first 27 numbers below the first thousand numbers: N\_QUARTER = [ 9, 26, 37, 64, 82,139,148,210,267, 285,296,546,548,558,564,576,584,601, 752,794,800,833,854,890,909,939,974] **Purpose:** Find all CANTERO numbers, if there is an upper bound, and if it is possible to generate a formula. ]
[Question] [ Given a string consisting of only printable ascii (letters, numbers, symbols, and spaces), how many keystrokes are required minimally to type out this string from scratch? That is, *current text* is initially an empty string and should end up being equal to the input string. These are the allowed actions and their cost in keystrokes: * Add a character from printable ascii to the right-hand side of the current text (1 keystroke) * `Ctrl-C` copy *any* contiguous substring of the current text to the overwrite-only clipboard (2 keystrokes) * `Ctrl-V` paste the string last copied to the clipboard to the right-hand end of the current text (1 keystroke) * `Backspace` delete the rightmost character from the current text (1 keystroke) For example, the string "cbaabcbabaacba" can be typed in 12 keystrokes, which is optimal. ``` cba => 3 keystrokes <copy> => 2 keystrokes ab => 2 keystrokes <paste> => 1 keystroke baa => 3 keystrokes <paste> => 1 keystroke ``` ## Test Cases ``` cbaabcbabaacba => 12 ababcc => 6 aaaaaaaaaaaaa => 9 abcdefabcde => 9 abcdefabcdefabcde => 11 abcdefabcdefabcdefabcde => 12 ``` ## Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code wins! ]
[Question] [ Your task is simple: Write a program (or function) that takes no input and outputs something like this: ``` ## *name*, *length* bytes *code* ``` Where `*name*` is the name of the language you are using, `*length*` is the number of bytes in your code, and `*code*` is your program's source code. If `*code*` contains multiple lines, it have four spaces before each line. Here's a 124-byte example implementation in Python 3: ``` s = "## Python 3, 124 bytes{2} s = {1}{0}{1}{2}print(s.format(s,chr(34),chr(10)))" print(s.format(s,chr(34),chr(10))) ``` The output is: ``` ## Python 3, 124 bytes s = "## Python 3, 124 bytes{2} s = {1}{0}{1}{2}print(s.format(s,chr(34),chr(10)))" print(s.format(s,chr(34),chr(10))) ``` Which in Markdown is: > > ## Python 3, 124 bytes > > > > ``` > s = "## Python 3, 124 bytes{2} s = {1}{0}{1}{2}print(s.format(s,chr(34),chr(10)))" > print(s.format(s,chr(34),chr(10))) > > ``` > > This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer (in bytes) wins. [Answer] # RProgN 2, 28 Bytes ``` «" %s"F"#RProgN 2, 28 Bytes" ``` [Answer] # Underload, 48 bytes ``` (#Underload, 48 bytes )(~:S( ):S*aSaS(:^)S):^ ``` [Answer] ## Python 2, 58 bytes ``` _='## Python 2, 58 bytes\n _=%r;print _%%_';print _%_ ``` [Answer] ## reticular, 58 bytes ``` "'34'c: 4*91+c:s:e:t:y:b: 85: :,:r:a:l:u:c:i:t:e:r: :#dqO; ``` [Try it online!](http://reticular.tryitonline.net/#code=IiczNCdjOiA0KjkxK2M6czplOnQ6eTpiOiA4NTogOiw6cjphOmw6dTpjOmk6dDplOnI6IDojZHFPOw&input=) Explanation: `:c` pushes the single-char string `c`. This builds the string "## reticular, 58 bytes", backwards character by character, reverses the stack, and `O`utputs everything, including the string captured by the initial quote. [Answer] ## CJam, 33 bytes ``` {"## CJam, 33 bytes"N@S4*\"_~"}_~ ``` Works a lot like the Underload answer. Stack trace (`N` represents `\n`) ``` {"## CJam, 33 bytes"N@S4*\"_~"} {"## CJam, 33 bytes"N@S4*\"_~"} {"## CJam, 33 bytes"N@S4*\"_~"} {"## CJam, 33 bytes"N@S4*\"_~"} "## CJam, 33 bytes" {"## CJam, 33 bytes"N@S4*\"_~"} "## CJam, 33 bytes" N "## CJam, 33 bytes" N {"## CJam, 33 bytes"N@S4*\"_~"} "## CJam, 33 bytes" N {"## CJam, 33 bytes"N@S4*\"_~"} " " "## CJam, 33 bytes" N {"## CJam, 33 bytes"N@S4*\"_~"} " " 4 "## CJam, 33 bytes" N {"## CJam, 33 bytes"N@S4*\"_~"} " " "## CJam, 33 bytes" N " " {"## CJam, 33 bytes"N@S4*\"_~"} "## CJam, 33 bytes" N " " {"## CJam, 33 bytes"N@S4*\"_~"} "_~" <implicit output> ``` [Answer] # V, 25 bytes ``` ñi#V, 25 bytes<esc>o´ Ñ<esc>~"qpx ``` --- (This is not counted in the generated markdown, because I like providing explanations for my code :P) Here is a hexdump, since the source code contains unprintable/non-ASCII characters: ``` 00000000: f169 2356 2c20 3235 2062 7974 6573 1b6f .i#V, 25 bytes.o 00000010: b420 d11b 7e22 7170 78 . ..~"qpx ``` This answer is just a trivial modification of the standard [extensible V quine](https://codegolf.stackexchange.com/a/100426/31716). Explanation: ``` ñ " Run the following code one time, storing it in " register 'q' i " Enter insert mode #V, 25 bytes<esc> " And insert the header o " Open up a newline, and enter insert mode again ´ Ñ " Enter four spaces, then a 'Ñ' character. " (The reason we insert it uppercase, is because " lowercase would end the loop now) <esc> " Return to normal mode ~ " Toggle the case of the char under the cursor ('Ñ') "qp " Paste the contents of register 'q' (this is the " same as the entire program minus the initial 'ñ', " followed by a 'ÿ' character because V is weird) x " Delete the last character (the ÿ) ``` [Answer] # JS, ~~50~~ ~~49~~ ~~27~~ 30 bytes ``` f=_=>`#JS, 30 bytes\n f=`+f ``` --- ## Try It ``` f=_=>`#JS, 30 bytes\n f=`+f console.log(f()) ``` [Answer] # [Go](https://go.dev), 102 bytes ``` import.`fmt`;func f(){s:="## Go, 102 bytes\n import.`fmt`;func f(){s:=%q;Printf(s,s)}";Printf(s,s)} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70oPX_BmoLE5OzE9FSF3MTMvKWlJWm6FjfTMnML8otK9BLScksSrNNK85IV0jQ0q4utbJWUlRXc83UUDA2MFJIqS1KLY_IUgACnetVC64CizLySNI1inWLNWiUUHsS2TWD1INuBWriA-rigEgsWQGgA) From my variant in a [comment](https://codegolf.stackexchange.com/questions/69/golf-you-a-quine-for-great-good/123763#comment564137_123763) under the post below. A callable function. Prints: ``` ## Go, 102 bytes import.`fmt`;func f(){s:="## Go, 102 bytes\n import.`fmt`;func f(){s:=%q;Printf(s,s)}";Printf(s,s)} ``` ## [Go](https://go.dev), 134 bytes ``` package main;import.`fmt`;func main(){s:="## Go, 134 bytes\n package main;import.`fmt`;func main(){s:=%q;Printf(s,s)}";Printf(s,s)} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70oPX_BgqWlJWm6FjfbChKTsxPTUxVyEzPzrDNzC_KLSvQS0nJLEqzTSvOSwcIamtXFVrZKysoK7vk6CobGJgpJlSWpxTF5CkBAtH7VQuuAosy8kjSNYp1izVolFB7ENVBHwRwHAA) Using the quine found [here](https://codegolf.stackexchange.com/a/123763/77309). A full program. Prints: ``` ## Go, 134 bytes package main;import.`fmt`;func main(){s:="## Go, 134 bytes\n package main;import.`fmt`;func main(){s:=%q;Printf(s,s)}";Printf(s,s)} ``` [Answer] # [Factor](https://factorcode.org/), 80 bytes ``` "# Factor, 80 bytes\n %uUSE: formatting dup printf"USE: formatting dup printf ``` [Try it online!](https://tio.run/##S0tMLskv@h8a7OnnbqWQnVqUl5qjYP1fSVnBDSyjo2BhoJBUWZJaHJOnAASqpaHBrlYKaflFuYklJZl56QoppQUKBUWZeSVpSril/v8HAA "Factor – Try It Online") ]
[Question] [ **This question already has answers here**: [Exact Partial Sum of Harmonic Series](/questions/168700/exact-partial-sum-of-harmonic-series) (17 answers) [Fraction to exact decimal](/questions/89215/fraction-to-exact-decimal) (6 answers) Closed last month. Consider the sequence 1/2, 1/3 + 1/2, 1/4 + 1/3 + 1/2, and so on. In mathematical symbols, this is $$S(n)=\sum\_{m=2}^{n+1}\frac{1}{m}$$ where S is the function that makes the sequence. Outputting this sequence as a fraction would not be complicated. To add depth to the challenge, you must output as a repeating decimal. To represent non-repeating decimals, simply output the decimal. To represent repeating decimals, put an R before the repeating part. For example, 1/7 can be represented by `0.R142857`, and 11/9 by `1.R2` Your task is to output the nth number in this sequence, and because this is code-golf the shortest program will win. ]
[Question] [ The [Fibonacci sequence](http://oeis.org/A000045) is a sequence of numbers, where every number in the sequence is the sum of the two numbers preceding it. The first two numbers in the sequence are both 1. Here are the first few terms: ``` 1 1 2 3 5 8 13 21 34 55 89 ... ``` --- Write the shortest code that either: * Generates the Fibonacci sequence without end. * Given `n` calculates the `n`th term of the sequence. (Either 1 or zero indexed) You may use standard forms of input and output. (I gave both options in case one is easier to do in your chosen language than the other.) --- For the function that takes an `n`, a reasonably large return value (the largest Fibonacci number that fits your computer's normal word size, at a minimum) has to be supported. --- ### Leaderboard ``` /* Configuration */ var QUESTION_ID = 85; // Obtain this from the url // It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe"; var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk"; var OVERRIDE_USER = 3; // This should be the user ID of the challenge author. /* App */ var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page; function answersUrl(index) { return "https://api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER; } function commentUrl(index, answers) { return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER; } function getAnswers() { jQuery.ajax({ url: answersUrl(answer_page++), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { answers.push.apply(answers, data.items); answers_hash = []; answer_ids = []; data.items.forEach(function(a) { a.comments = []; var id = +a.share_link.match(/\d+/); answer_ids.push(id); answers_hash[id] = a; }); if (!data.has_more) more_answers = false; comment_page = 1; getComments(); } }); } function getComments() { jQuery.ajax({ url: commentUrl(comment_page++, answer_ids), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { data.items.forEach(function(c) { if (c.owner.user_id === OVERRIDE_USER) answers_hash[c.post_id].comments.push(c); }); if (data.has_more) getComments(); else if (more_answers) getAnswers(); else process(); } }); } getAnswers(); var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/; var OVERRIDE_REG = /^Override\s*header:\s*/i; function getAuthorName(a) { return a.owner.display_name; } function process() { var valid = []; answers.forEach(function(a) { var body = a.body; a.comments.forEach(function(c) { if(OVERRIDE_REG.test(c.body)) body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>'; }); var match = body.match(SCORE_REG); if (match) valid.push({ user: getAuthorName(a), size: +match[2], language: match[1], link: a.share_link, }); else console.log(body); }); valid.sort(function (a, b) { var aB = a.size, bB = b.size; return aB - bB }); var languages = {}; var place = 1; var lastSize = null; var lastPlace = 1; valid.forEach(function (a) { if (a.size != lastSize) lastPlace = place; lastSize = a.size; ++place; var answer = jQuery("#answer-template").html(); answer = answer.replace("{{PLACE}}", lastPlace + ".") .replace("{{NAME}}", a.user) .replace("{{LANGUAGE}}", a.language) .replace("{{SIZE}}", a.size) .replace("{{LINK}}", a.link); answer = jQuery(answer); jQuery("#answers").append(answer); var lang = a.language; lang = jQuery('<a>'+lang+'</a>').text(); languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang, user: a.user, size: a.size, link: a.link}; }); var langs = []; for (var lang in languages) if (languages.hasOwnProperty(lang)) langs.push(languages[lang]); langs.sort(function (a, b) { if (a.lang_raw.toLowerCase() > b.lang_raw.toLowerCase()) return 1; if (a.lang_raw.toLowerCase() < b.lang_raw.toLowerCase()) return -1; return 0; }); for (var i = 0; i < langs.length; ++i) { var language = jQuery("#language-template").html(); var lang = langs[i]; language = language.replace("{{LANGUAGE}}", lang.lang) .replace("{{NAME}}", lang.user) .replace("{{SIZE}}", lang.size) .replace("{{LINK}}", lang.link); language = jQuery(language); jQuery("#languages").append(language); } } ``` ``` body { text-align: left !important; display: block !important; } #answer-list { padding: 10px; width: 290px; float: left; } #language-list { padding: 10px; width: 290px; float: left; } table thead { font-weight: bold; } 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="https://cdn.sstatic.net/Sites/codegolf/all.css?v=ffb5d0584c5f"> <div id="language-list"> <h2>Shortest Solution 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> <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> <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] ## Brainfuck, 22 bytes ``` +>++[-<<[->+>+<<]>>>+] ``` Generates the Fibonacci sequence gradually moving across the memory tape. [Answer] ## Haskell, ~~17~~ ~~15~~ 14 bytes ``` f=1:scanl(+)1f ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P83W0Ko4OTEvR0Nb0zDtf25iZp6CrUJBUWZeiYJGSWJ2qoKhgYGCikKa5n8A "Haskell – Try It Online") [Answer] # Perl 6, 10 chars: Anonymous infinite fibonacci sequence list: ``` ^2,*+*...* ``` Same as: ``` 0, 1, -> $x, $y { $x + $y } ... Inf; ``` So, you can assign it to an array: ``` my @short-fibs = ^2, * + * ... *; ``` or ``` my @fibs = 0, 1, -> $x, $y { $x + $y } ... Inf; ``` And get the first eleven values (from 0 to 10) with: ``` say @short-fibs[^11]; ``` or with: ``` say @fibs[^11]; ``` Wait, you can get too the first 50 numbers from anonymous list itself: ``` say (^2,*+*...*)[^50] ``` That returns: ``` 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 17711 28657 46368 75025 121393 196418 317811 514229 832040 1346269 2178309 3524578 5702887 9227465 14930352 24157817 39088169 63245986 102334155 165580141 267914296 433494437 701408733 1134903170 1836311903 2971215073 4807526976 7778742049 ``` And some simple benchmark: ``` real 0m0.966s user 0m0.842s sys 0m0.080s ``` With: ``` $ time perl6 -e 'say (^2, *+* ... *)[^50]' ``` EOF [Answer] ## C# 4, 58 bytes **Stream (69; 65 if weakly typed to `IEnumerable`)** (Assuming a `using` directive for `System.Collections.Generic`.) ``` IEnumerable<int>F(){int c=0,n=1;for(;;){yield return c;n+=c;c=n-c;}} ``` **Single value (58)** ``` int F(uint n,int x=0,int y=1){return n<1?x:F(n-1,y,x+y);} ``` [Answer] ## GolfScript, 12 Now, just 12 characters! ``` 1.{[[email protected]](/cdn-cgi/l/email-protection)+.}do ``` [Answer] # [Hexagony](https://github.com/mbuettner/hexagony), ~~18~~ ~~14~~ 12 Thanks Martin for 6 bytes! ``` 1="/}.!+/M8; ``` Expanded: ``` 1 = " / } . ! + / M 8 ; . . . . . . . ``` [Try it online](http://hexagony.tryitonline.net/#code=MT0iL30uISsvTTg7&input=) --- Old, answer. This is being left in because the images and explanation might be helpful to new Hexagony users. ``` !).={!/"*10;$.[+{] ``` Expanded: ``` ! ) . = { ! / " * 1 0 ; $ . [ + { ] . ``` This prints the Fibonacci sequence separated by newlines. [Try it online!](http://hexagony.tryitonline.net/#code=ISkuPXshLyIqMTA7JC5bK3td&input=) Be careful though, the online interpreter doesn't really like infinite output. ### Explanation There are two "subroutines" to this program, each is run by one of the two utilised IPs. The first routine prints newlines, and the second does the Fibonacci calculation and output. The first subroutine starts on the first line and moves left to right the entire time. It first prints the value at the memory pointer (initialized to zero), and then increments the value at the memory pointer by `1`. After the no-op, the IP jumps to the third line which first switches to another memory cell, then prints a newline. Since a newline has a positive value (its value is 10), the code will always jump to the fifth line, next. The fifth line returns the memory pointer to our Fibonacci number and then switches to the other subroutine. When we get back from this subroutine, the IP will jump back to the third line, after executing a no-op. The second subroutine begins at the top right corner and begins moving Southeast. After a no-op, we are bounced to travel West along the second line. This line prints the current Fibonacci number, before moving the memory pointer to the next location. Then the IP jumps to the fourth line, where it computes the next Fibonacci number using the previous two. It then gives control back to the first subroutine, but when it regains control of the program, it continues until it meets a jump, where it bounces over the mirror that was originally used to point it West, as it returns to the second line. --- Preliminary Pretty Pictures! The left side of the image is the program, the right hand side represents the memory. The blue box is the first IP, and both IPs are pointing at the next instruction to be executed. [![enter image description here](https://i.stack.imgur.com/tiqRU.gif)](https://i.stack.imgur.com/tiqRU.gif) Note: Pictures may only appear pretty to people who have similarly limited skill with image editing programs :P I will add at least 2 more iterations so that the use of the `*` operator becomes more clear. Note 2: I only saw [alephalpha's answer](https://codegolf.stackexchange.com/a/62716/31625) after writing most of this, I figured it was still valuable because of the separation, but the actual Fibonacci parts of our programs are very similar. In addition, this is the smallest Hexagony program that I have seen making use of more than one IP, so I thought it might be good to keep anyway :P [Answer] ## J, 10 chars Using built-in calculation of Taylor series coefficients so maybe little cheaty. Learned it [here](http://www.jsoftware.com/jwiki/Essays/Fibonacci%20Sequence#Generating_functions). ``` (%-.-*:)t. (%-.-*:)t. 0 1 2 3 4 5 10 100 0 1 1 2 3 5 55 354224848179261915075 ``` [Answer] # Python 2, 34 bytes Python, using recursion... here comes a StackOverflow! ``` def f(i,j):print i;f(j,i+j) f(1,1) ``` [Answer] ## [><>](http://esolangs.org/wiki/Fish) - 15 characters ``` 0:nao1v a+@:n:<o ``` [Answer] ## [COW](http://esolangs.org/wiki/COW), 108 ``` MoO moO MoO mOo MOO OOM MMM moO moO MMM mOo mOo moO MMM mOo MMM moO moO MOO MOo mOo MoO moO moo mOo mOo moo ``` [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), 3 bytes ``` +¡1 ``` [Try it online!](http://jelly.tryitonline.net/#code=K8KhMQ&input=MjA) ### How it works ``` +¡1 Niladic link. No implicit input. Since the link doesn't start with a nilad, the argument 0 is used. 1 Yield 1. + Add the left and right argument. ¡ For reasons‡, read a number n from STDIN. Repeatedly call the dyadic link +, updating the right argument with the value of the left one, and the left one with the return value. ``` ‡ `¡` peeks at the two links to the left. Since there is only one, it has to be the body of the loop. Therefore, a number is read from input. Since there are no command-line arguments, that number is read from STDIN. [Answer] # [Hexagony](https://github.com/mbuettner/hexagony), 6 bytes ``` 1.}=+! ``` Ungolfed: ``` 1 . } = + ! . ``` It prints the Fibonacci sequence without any separator. [Answer] # Ruby, 29 27 25 24 bytes ``` p a=b=1;loop{b=a+a=p(b)} ``` Edit: made it an infinite loop. ;) [Answer] # Golfscript - single number - 12/11/10 12 chars for taking input from stdin: ``` ~0 1@{.@+}*; ``` 11 chars for input already on the stack: ``` 0 1@{.@+}*; ``` 10 chars for further defining 1 as the 0th Fibonacci number: ``` 1.@{.@+}*; ``` [Answer] # [Prelude](http://esolangs.org/wiki/Prelude), 12 bytes One of the few challenges where Prelude is actually fairly competitive: ``` 1(v!v) ^+^ ``` This requires [the Python interpreter](https://web.archive.org/web/20060504072747/http://z3.ca/~lament/prelude.py) which prints values as decimal numbers instead of characters. ## Explanation In Prelude, all lines are executed in parallel, with the instruction pointer traversing columns of the program. Each line has its own stack which is initialised to zero. ``` 1(v!v) ^+^ | Push a 1 onto the first stack. | Start a loop from here to the closing ). | Copy the top value from the first stack to the second and vice-versa. | Print the value on the first stack, add the top two numbers on the second stack. | Copy the top value from the first stack to the second and vice-versa. ``` The loop repeats forever, because the first stack will never have a `0` on top. Note that this starts the Fibonacci sequence from `0`. [Answer] ## DC (20 bytes) As a bonus, it's even obfuscated ;) ``` zzr[dsb+lbrplax]dsax ``` EDIT: I may point out that it prints *all* the numbers in the fibonacci sequence, if you wait long enough. [Answer] **Mathematica, 9 chars** ``` Fibonacci ``` If built-in functions are not allowed, here's an explicit solution: **Mathematica, ~~33~~ ~~32~~ 31 chars** ``` #&@@Nest[{+##,#}&@@#&,{0,1},#]& ``` [Answer] # TI-BASIC, 11 By legendary TI-BASIC golfer Kenneth Hammond ("Weregoose"), from [this site](http://adriweb.free.fr/upload/ti/weregoose.html). Runs in O(1) time, and considers 0 to be the 0th term of the Fibonacci sequence. ``` int(round(√(.8)cosh(Anssinh‾¹(.5 ``` To use: ``` 2:int(round(√(.8)cosh(Anssinh‾¹(.5 1 12:int(round(√(.8)cosh(Anssinh‾¹(.5 144 ``` How does this work? If you do the math, it turns out that `sinh‾¹(.5)` is equal to `ln φ`, so it's a modified version of Binet's formula that rounds down instead of using the `(1/φ)^n` correction term. The `round(` (round to 9 decimal places) is needed to prevent rounding errors. [Answer] ## K - 12 Calculates the `n` and `n-1` Fibonacci number. ``` {x(|+\)/0 1} ``` Just the `nth` Fibonacci number. ``` {*x(|+\)/0 1} ``` [Answer] # Julia, 18 bytes ``` n->([1 1;1 0]^n)[] ``` [Answer] ## Java, 55 I can't compete with the conciseness of most languages here, but I can offer a substantially different and possibly much faster (constant time) way to calculate the n-th number: ``` Math.floor(Math.pow((Math.sqrt(5)+1)/2,n)/Math.sqrt(5)) ``` `n` is the input (int or long), starting with n=1. It uses [Binet's formula](https://en.wikipedia.org/wiki/Fibonacci_number#Closed-form_expression) and rounds instead of the subtraction. [Answer] # [Dodos](https://github.com/DennisMitchell/dodos), 26 bytes ``` dot F F F dip F dip dip ``` [Try it online!](https://tio.run/##S8lPyS/@/58zJb9EwY3LjYvTTSElswBKgfD///8NDQA "Dodos – Try It Online") ### How it works The function **F** does all the heavy lifting; it is defined recursively as follows. ``` F(n) = ( F(|n - 1|), F(||n - 1| - 1|) ) ``` Whenever **n > 1**, we have **|n - 1| = n - 1 < n** and **||n - 1| - 1| = |n - 1 - 1| = n - 2 < n**, so the function returns **( F(n - 1), F(n - 2) )**. If **n = 0**, then **|n - 1| = 1 > 0**; if **n = 1**, then **||n - 1| - 1| = |0 - 1| = 1 = 1**. In both cases, the attempted recursive calls **F(1)** raise a *Surrender* exception, so **F(0)** returns **0** and **F(1)** returns **1**. For example, **F(3) = ( F(1), F(2) ) = ( 1, F(0), F(1) ) = ( 1, 0, 1 )**. Finally, the **main** function is defined as ``` main(n) = sum(F(n)) ``` so it adds up all coordinates of the vector returned by **F**. For example, **main(3) = sum(F(3)) = sum(1, 0, 1) = 2**. [Answer] # [TypeScript's type system](https://www.typescriptlang.org), 193 188 186 bytes ``` type L='length' type T<N,U extends 0[]=[]>=U[L]extends N?U:T<N,[...U,0]> type S<A,B>=T<A>extends[...infer U,...T<B>]?U[L]:0 type F<N>=N extends 0|1?N:[...T<F<S<N,1>>>,...T<F<S<N,2>>>][L] ``` There's no way to do I/O here, but we can use hovering to view the value (also note that the generated JS is empty): [![Fibonacci(10)](https://i.stack.imgur.com/fxJ2p.png)](https://i.stack.imgur.com/fxJ2p.png) Unfortunately, TypeScript has strict recursion limits and on F18 we get a `Type instantiation is excessively deep and possibly infinite.` error: [![Fibonacci(11)](https://i.stack.imgur.com/33Bqv.png)](https://i.stack.imgur.com/33Bqv.png) [**Demo on TypeScript Playground**](https://www.typescriptlang.org/play?ts=4.5.4#code/C4TwDgpgBAMgvAcgDYQHYHNgAsEChSRQAqAPAHIA0AqlBAB7BoAmAzlAAwDaAunDwHxwqnGN3qNUrKGQD8VAFylKnAHRqqFdt375w0AMokAghQBCg0kf7jmLVWoCWqAGYQATlA1qVpc9zki3PLsuoQAYuSCZLQMthwAPgCMMmTy9j4kEYaUifx5FN6kWeQUAEx5-NyBuDUowFDOiQDs8lARzfwA3Lh1DYkAHK3t-V1AA) --- Ungolfed version: ``` type NTuple<N extends number, Tup extends unknown[] = []> = Tup['length'] extends N ? Tup : NTuple<N, [...Tup, unknown]>; type Add<A extends number, B extends number> = [...NTuple<A>, ...NTuple<B>]['length']; type Sub<A extends number, B extends number> = NTuple<A> extends [...(infer Tup), ...NTuple<B>] ? Tup['length'] : never; type Fibonacci<N extends number> = N extends 0 | 1 ? N : Add<Fibonacci<Sub<N, 1>>, Fibonacci<Sub<N, 2>>>; ``` [Answer] ## 05AB1E, 7 bytes Code: ``` 1$<FDr+ ``` [Try it online!](http://05ab1e.tryitonline.net/#code=MSQ8RkRyKw) [Answer] # [Whispers v3](https://github.com/cairdcoinheringaahing/Whispers), 35 bytes ``` > Input > fₙ >> 2ᶠ1 >> Output 3 ``` [Try it online!](https://tio.run/##K8/ILC5ILSo2@v/fTsEzr6C0hMtOIe1R00wuOzsFo4fbFhiCGP6lJUAZBeP//wE "Whispers v2 – Try It Online") (or don't, as this uses features exclusive to v3) Simply takes the first \$n\$ elements of the infinite list of Fibonacci numbers. [Answer] # [Trianguish](https://github.com/Radvylf/trianguish), ~~152~~ 135 bytes ``` 00000000: 0c05 10d8 0201 40d7 0401 4110 4102 a060 00000010: 2c02 b080 2c02 8050 20e4 0211 0710 e209 00000020: 1110 4028 0d00 6020 2902 10c3 0802 a107 00000030: 02a1 0502 8027 0910 290b 1110 403b 0890 00000040: 204d 03d0 503c 0790 602a 1071 02a0 9027 00000050: 0280 b110 8111 0402 70e2 0501 402a 0202 00000060: 9106 1107 0291 0b11 0902 702b 1040 2a10 00000070: 6110 2102 9050 2802 70b1 1071 1104 1102 00000080: 02a1 0502 802c 05 ``` [![Two loop? Too many loop!](https://i.stack.imgur.com/W3v8e.png)](https://i.stack.imgur.com/W3v8e.png) [Try it online!](https://radvylf.github.io/trianguish/#bRpe5WBWEKfq54fcmvocykcKIEW_rK16GoV0e6r4lucnIdyGjbqJf3c9repFoZbw_neIAf.TpzYLM_49nZVTcuaHAboCGhtT0aTOf5j23UhN0GP.S0Qh2nYlxQT2rGokPwlJ_bsoF6-iPeFkRxL%7EJvlaoxY%7E-Cu47GiimG5Ib0E.HGAeRg69H) --- Trianguish is my newest language, a cellular automaton sort of thing which uses a triangular grid of "ops" (short for "operators"). It features self-modification, a default max int size of 216, and an interpreter which, in my opinion, is the coolest thing I've ever created (taking over forty hours and 2k SLOC so far). This program consists of two precisely timed loops, each taking exactly ~~17~~ 11 ticks. The first, in the top right is what actually does the fibonacci part; two S-builders are placed in exactly the right position such that two things occur in exactly the same number of ticks: 1. The left S-builder, `x`, copies its contents to `y` 2. The sum of `x` and `y` is copied to `x` Precise timing is required, as if either of these occurred with an offset from the other, non-fibonacci numbers would appear in brief pulses, just long enough to desync everything. Another way this could have been done is with T-switches allowing only a single tick pulse from one of the S-builders, which would make precise timing unneeded, but this is more elegant and likely smaller. The second loop, which is also 11 ticks, is pretty simple. It starts off with a 1-tick pulse of `1n`, and otherwise is `0n`, allowing an n-switch and t-switch to allow the contents of `x` to be outputted once per cycle. Two S-switches are required to make the clock use an odd number of ticks, but otherwise it's just a loop of the correct number of wires. This program prints infinitely many fibonacci numbers, though if run with Mod 216 on, it will print them, as you might guess, modulo'd by 216 (so don't do that :p). [Answer] # [Perl 5](https://www.perl.org/), ~~36~~ ~~35~~ ~~33~~ 32 bytes *-2 bytes thanks to dingledooper* ``` 1x<>~~/^(..?)*$(??{++$i})/;say$i ``` [Try it online!](https://tio.run/##K0gtyjH9n5evUJ5YlJeZl16soJ5aUZBalJmbmleSmGNlVZybWFSSm1iSnKFu/d@wwsaurk4/TkNPz15TS0XD3r5aW1sls1ZT37o4sVIl8/9/I9N/@QUlmfl5xf91fU31DAwNAA "Perl 5 – Try It Online") This works by using the regex `^(..?)*$` to count [how many distinct partitions](https://en.wikipedia.org/wiki/Fibonacci_number#Symbolic_method) \$n\$ has as a sum of the numbers \$1\$ and \$2\$. For example, \$5\$ can be represented in the following \$8\$ ways: ``` 1+1+1+1+1 1+1+1+2 1+1+2+1 1+2+1+1 1+2+2 2+1+1+1 2+1+2 2+2+1 ``` This tells us that the \$F\_5=8\$. I had this basic idea on [2014-03-05](https://gist.github.com/Davidebyzero/9090628#gistcomment-1185486) but it didn't occur to me until today to try coding it into a program. *The following two paragraphs explain the **33 byte** version:* To count the number of distinct matches `^(..?)*$` can make in a string \$n\$ characters long, we must force Perl's regex engine to backtrack after every time the regex completes a successful match. Expressions like `^(..?)*$.` fail to do what we want, because Perl optimizes away the non-match, not attempting to evaluate the regex even once. But it so happens that it does *not* optimize away an attempt to match a backreference. So we make it try to match `\1`. This will always fail, but the regex engine isn't "smart" enough to know this, so it tries each time. (It's actually possible for a backreference to match after `$` with the multiline flag disabled, if it captured a zero-length substring. But in this particular regex, that can never happen.) Embedded code is used to count the number of times the regex engine completes a match. This is the `(?{++$i})`, which increments the variable `$i`. We then turn it into a non-match after the code block executes. To get this down to **32 bytes**, a "postponed" regular subexpression embedded code block is used, `$(??{`...`})` instead of `$(?{`...`})`. This not only executes the code, but then compiles that code's return value as a regex subexpression to be matched. Since the return value of `++$i` is the new value of `$i`, this will cause the match to fail and backtrack, since a decimal number (or any non-empty string) will never match at the end of a string. This does make the 32 byte version about 7 times slower than the 33 byte version, because it has to recompile a different decimal number as a regex after each failed match (i.e. the same number of times as the Fibonacci number that the program will output). Using `(??{++$i,0})` is almost as fast as `(?{++$i})\1`, as Perl optimizes the case in which the return value has not changed last time. But that would defeat the purpose of using `$(??{`...`})` in the first place, because it would be 1 byte longer instead of 1 byte shorter. As to the sequence itself – for golf reasons, the program presented above defines \$F\_0=1,\ F\_1=1\$. To define \$F\_0=0,\ F\_1=1\$ we would need an extra byte: ``` 1x<>~~/^.(..?)*$(??{++$i})/;say$i ``` [Try it online!](https://tio.run/##K0gtyjH9n5evUJ5YlJeZl16soJ5aUZBalJmbmleSmGNlVZybWFSSm1iSnKFu/d@wwsaurk4/Tk9DT89eU0tFw96@WltbJbNWU9@6OLFSJfP/fyOzf/kFJZn5ecX/dX1N9QwMDQA "Perl 5 – Try It Online") In the versions below, `(?{++$i})\1` is used for speed (at the golf cost of 1 extra byte), to make running the test suite more convenient. Here it is as a (reasonably) well-behaved anonymous function (**~~47~~ ~~46~~ 44 bytes**): ``` sub{my$i;1x pop~~/^.(..?)*$(?{--$i})\1/;-$i} ``` [Try it online!](https://tio.run/##VY5NCsIwFISv8pBAErXRIm6M1YuIEDXVB00aktS/UpcewCN6kdq6EFzNN/ANjNO@mLdV0BCix32U0PNFeYv2GCTY8leA6qvTHo22URWLRTDKR6Pi/kTH9FzioYuqMzGiKvCuD1SCuQHJszZUu9rcCMr0Cq50j8dkK5gQaz4kbF0nCcGGb9KJ7KGVfw/y0rN@mk0lwWU2S7sYjXgNmDOCvHYebRxs7KCBLwJBQeH9fAEVjOTJqre4bNoP "Perl 5 – Try It Online") - Displays \$F\_0\$ through \$F\_{31}\$ The above actually runs faster than the standard recursive approach (**39 bytes**): ``` sub f{my$n=pop;$n<2?$n:f($n-2)+f($n-1)} ``` [Try it online!](https://tio.run/##HcpBCsIwEEDRqwwl0IRgsRU3ToMXcaPSyIBOQ5IiErL1AB7Ri8Sa1f@L5yZ/35clTBCip2tE@P/z7Jn4FrCE5QI2PV6CjZsdCh6Ho@CDlYI3g9K1vcoF7ezlyshsUdBodv0arVUCWg2p5DxxbE7cZKgLgroWvu8PtJ2sRGEuPw "Perl 5 – Try It Online") - Displays \$F\_0\$ through \$F\_{31}\$ If that is golfed down using [Xcali's technique](https://codegolf.stackexchange.com/a/182864/17216) it becomes even slower, at **38 bytes**: ``` sub f{"@_"<2?"@_":f("@_"-2)+f("@_"-1)} ``` [Try it online!](https://tio.run/##K0gtyjH9X1qcqlBcUpSZXGKtAGKXJxblZealF1v/Ly5NUkirVnKIV7IxsgdRVmkaIErXSFMbyjLUrP1vnZZfpJFbqZJpa2Ctkmlja2wIpLS1NasVMtM0VDI1qwuKMvNKlGLylGoVwEwFlUw9dYVHbZMU1PU0wEo0FWr/AwA "Perl 5 – Try It Online") - Displays \$F\_0\$ through \$F\_{31}\$ or with the same indexing as my main answer here, **34 bytes**: ``` sub f{"@_"<2||f("@_"-2)+f("@_"-1)} ``` [Try it online!](https://tio.run/##K0gtyjH9X1qcqlBcUpSZXGKtAGKXJxblZealF1v/Ly5NUkirVnKIV7IxqqlJ0wCxdI00taEsQ83a/9Zp@UUauZUqmbYG1iqZNrbGIEpbW7NaITNNQyVTs7qgKDOvRCkmT6lWAcxUUMnUU1d41DZJQV1PA6xEU6H2PwA "Perl 5 – Try It Online") - Displays terms \$0\$ through \$30\$ See [Patience, young "Padovan"](https://codegolf.stackexchange.com/questions/182797/patience-young-padovan/223250#223250) for more variations and comparisons. # [Perl 5](https://www.perl.org/) `-p`, 28 bytes ``` 1x$_~~/^(..?)*$(??{++$\})/}{ ``` [Try it online!](https://tio.run/##K0gtyjH9n5evUJ5YlJeZl16soJ5aUZBalJmbmleSmGNlVZybWFSSm1iSnKFu/d@wQiW@rk4/TkNPz15TS0XD3r5aW1slplZTv7b6/38j03/5BSWZ@XnF/3ULAA "Perl 5 – Try It Online") I've just learned now, 16 months after posting the main answer above, that [Ton Hospel's Sum of combinations with repetition](https://codegolf.stackexchange.com/questions/155938/sum-of-combinations-with-repetition/155955#155955) answer used this same basic technique, predating my post by 3 years. By combining the tricks used in that answer with those already used here, the program length can be reduced even further. Perl actually literally wraps the program in a loop using string concatenation when called with `-p`, which I was surprised to learn (I would have implemented it in Perl as an emulated loop). So when this program is wrapped in `while (<>) {` ... `; print $_}` by the `-p` flag, it becomes: ``` while (<>) {1x$_~~/^(..?)*$(??{++$\})/}{; print $_} ``` `while (<>)` implicitly assigns the input from stdin, `<>`, to `$_` (which isn't done when using `<>` normally) at the beginning of each iteration of its loop. `$\` is the `print` output terminator. By default it is empty, but the above program turns it into an integer by incrementing it on every possible match found by the regex. If only one number \$n\$ is sent to the program via stdin, followed by EOF, then upon exiting the loop `$\` will actually represent the \$n\$th Fibonacci number. The `while (<>)` exits when it encounters EOF, giving `$_` an empty value. So then `print $_` will print that empty value, followed by the value of `$\`. As such, it defeats the intended purpose of the `-p` flag, as this program works properly when given a single value followed by EOF; if given multiple newline delimited values, it will output the sum of those Fibonacci numbers after finally being sent EOF (if running the program interactively, this would be done by pressing Ctrl+D at the beginning of a line). Contrast this with an actually loopable Perl `-p` program at **37 bytes**: ``` 1x$_~~/^(..?)*$(?{++$i})\1/;$i%=$_=$i ``` [Try it online!](https://tio.run/##DcvNCoJAFAbQ/fcULibUJPVe/xXxTZIhhhrQUVRIiHz0JrcHzqyWIbNmct5yMdo8V8dV@6wWPSqzyaGu11Eu2yi3x8ttLO2iP47o7oVh51@F13WfIBD660eN0JdW9K3Q1sYgMBKkyJCjQIkKdCKBGJSAUlAGykEFqARV4Bh8HgYn4BSc/aZ505NZ7W0e/g "Perl 5 – Try It Online") If the same multiline input is given to the 28 byte program, this happens: [Try it online!](https://tio.run/##DctLCoMwFAXQ@V2FA0GtVH1P468DN1JaQpFW0BhioILo0ps6PXB0b0bh1Ox9pVGDei9e0K@6N8PUKyvHtl0maewk7esT3Byt/vM40keYJF108cOu2@LYv@9Rum/OZSAwchQQKFGhRgM6kUAMykEFSIBKUAWqQQ04A5@HwTm4AIvfrO0wq8Vd9fgH "Perl 5 – Try It Online") Sadly, the `$\` trick can't be used with `say`; it only applies to `print`. The `$,` variable applies to both `print` and `say`, but only comes into play if at least two items are printed, e.g. `say"",""`. [Answer] # K - 8 bytes ``` +/[;1;0] ``` ## Explanation It makes use of ngn/k's recurrence builtin. ## How to use Calculates the `n`th fibonacci number. To calculate the `n`th put the number at the end of the program: ``` +/[;1;0]40 ``` [Answer] ## Ruby, 25 chars st0le's answer shortened. ``` p 1,a=b=1;loop{p b=a+a=b} ``` [Answer] ### FAC: Functional APL, 4 characters (!!) Not mine, therefore posted as community wiki. FAC is a dialect of APL that Hai-Chen Tu apparently suggested as his PhD dissertation in 1985. He later wrote an article together with Alan J. Perlis called "[FAC: A Functional APL Language](http://dl.acm.org/citation.cfm?id=1308785)". This dialect of APL uses "lazy arrays" and allow for arrays of infinite length. It defines an operator "iter" (`⌼`) to allow for compact definition of some recursive sequences. The monadic ("unary") case of `⌼` is basically Haskell's `iterate`, and is defined as `(F⌼) A ≡ A, (F A), (F (F A)), …`. The dyadic ("binary") case is defined somewhat analogously for two variables: `A (F⌼) B ≡ A, B, (A F B), (B F (A F B)), …`. Why is this useful? Well, as it turns out this is precisely the kind of recurrence the Fibonacci sequence has. In fact, one of the examples given of it is ``` 1+⌼1 ``` producing the familiar sequence `1 1 2 3 5 8 …`. So, there you go, quite possibly the shortest possible Fibonacci implementation in a non-novelty programming language. :D ]
[Question] [ Every integer can be expressed in powers of 2. You know this as the binary system Assume you are given a set of `k` numbers (`0 < k < 2^n`). You want to decide for this set whether every integer power of 2 up to `2^(n-1)` occurs at least `m` times One example: ``` n = 7 (2^n = 128, ) k = 5 set = {100, 91, 88, 63, 44} m = 3 Solution: Consider the binary representation of the set for up to n(=7) digits: set = { 1100100 1011011 1011000 0111111 0101100 } sum up the columns {3,3,3,4,3,2,2} -> result the set failed, because 2 < m ``` This is so far my best(fastest) algorithm(, written for vb.net): ``` Private Function Check(arr As Integer(), n As Integer, m as Integer) As Boolean For i = n - 1 To 0 Step -1 Dim columnCheck = 0 For j = 0 To arr.Length - 1 If (arr(j) And (1 << i)) <> 0 Then columnCheck += 1 Next If columnCheck < m Then Return False Next Return True End Function ``` maximum size of the elements of arr need to checked before entering. Do you have better ideas? ]
[Question] [ # Create a Sudoku solution CHECKER There are oodles of Sudoku SOLVERS here, but I want you to create a solution CHECKER as small as humanly possible (code-golf). * A valid entry will be able to either take a 9x9 array as an argument (passed by reference, serialized on the command line, or however you want to take it) or accept an input file that is nine lines of nine numbers for the final grid. See examples of input below. * Valid input should be base-10 numbers (1-9) * Missing, empty, extra, non-numeric positions, or positions with numbers outside of 1-9 should be rejected as invalid input by returning a non-zero result, printing an error, or both. * Your program needs to test whether each number appears once per column, once per line, and once per 3x3 sub-grid. If it passes, return "0" and if not, return a non-zero result. * Use of external resources (websites, etc.) is to be avoided. * If your solution is a stand-alone program, exiting with a exit status of, or printing, "0" or non-zero for "Pass" or "Fail", respectively, is ok. Let the smallest answer win! # Input Examples: c array: ``` int input[9][9]={{1,2,3,4,5,6,7,8,9}, {4,5,6,7,8,9,1,2,3}, {7,8,9,1,2,3,4,5,6}, {2,3,1,5,6,4,8,9,7}, {5,6,4,8,9,7,2,3,1}, {8,9,7,2,3,1,5,6,4}, {3,1,2,6,4,5,9,7,8}, {6,4,5,9,7,8,3,1,2}, {9,7,8,3,1,2,6,4,5} }; ``` file: ``` 123456789 456789123 789123456 231564897 564897231 897231564 312645978 645978312 978312645 ``` The 9 sub-grids: ``` +---+---+---+ |123|456|789| |456|789|123| |789|123|456| +---+---+---+ |231|564|897| |564|897|231| |897|231|564| +---+---+---+ |312|645|978| |645|978|312| |978|312|645| +---+---+---+ ``` [Answer] ## Python, 103 I hate sudoku. ``` b = [[1,2,3,4,5,6,7,8,9], [4,5,6,7,8,9,1,2,3], [7,8,9,1,2,3,4,5,6], [2,3,1,5,6,4,8,9,7], [5,6,4,8,9,7,2,3,1], [8,9,7,2,3,1,5,6,4], [3,1,2,6,4,5,9,7,8], [6,4,5,9,7,8,3,1,2], [9,7,8,3,1,2,6,4,5]] e=enumerate;print 243-len(set((a,t)for(i,r)in e(b)for(j,t)in e(r)for a in e([i,j,i/3*3+j/3]*(0<t<10)))) ``` How it works: each row, column, and block must have each number from 1 to 9. So for each `0 <= i, j < 9`, the cell `i,j` is in block `3*floor(i/3) + floor(j/3)`. Thus, there are 243 requirements to satisfy. I make each requirement a tuple `((item index,item type number),symbol)` where `item index` is a number between 0 and 8 (inclusive), `item type number` is 0,1, or 2 to denote row, column or block respectively, and `symbol` is the entry `b[i][j]`. Edit: I mistakenly didn't check for valid entries. Now I do. [Answer] ## APL (46) ``` {∧/,↑∊∘Z¨(/∘(,⍵)¨↓Z∘.=,3/3⌿3 3⍴Z←⍳9),(↓⍵),↓⍉⍵} ``` This takes a 9-by-9 matrix. The example one can be entered on TryAPL like so: ``` sudoku ← ↑(1 2 3 4 5 6 7 8 9)(4 5 6 7 8 9 1 2 3)(7 8 9 1 2 3 4 5 6)(2 3 1 5 6 4 8 9 7)(5 6 4 8 9 7 2 3 1)(8 9 7 2 3 1 5 6 4)(3 1 2 6 4 5 9 7 8)(6 4 5 9 7 8 3 1 2)(9 7 8 3 1 2 6 4 5) {∧/,↑∊∘Z¨(/∘(,⍵)¨↓Z∘.=,3/3⌿3 3⍴Z←⍳9),(↓⍵),↓⍉⍵} sudoku 1 ``` Explanation: * `↓⍉⍵`: get the columns of `⍵`, * `↓⍵`: get the rows of `⍵`, * `3/3⌿3 3⍴Z←⍳9`: make a 3-by-3 matrix containing the numbers `1` to `9`, then triplicate each number in both directions, giving a 9-by-9 matrix with the numbers `1` to `9` indicating each group, * `Z∘.=`: for each number `1` to `9`, make a bitmask for the given group, * `/∘(,⍵)¨`: and mask `⍵` with each, giving the groups of `⍵`. * `∊∘Z¨`: for each sub-array, see if it contains the numbers `1` to `9`, * `∧/,↑`: take the logical `and` of all of these numbers together. [Answer] ### GolfScript, 39 characters ``` .zip.{3/}%zip{~}%3/{[]*}%++{$10,1>=!},, ``` It takes an array of arrays as input (see [online example](http://golfscript.apphb.com/?c=WwogIFsxIDIgMyA0IDUgNiA3IDggOV0KICBbNCA1IDYgNyA4IDkgMSAyIDNdCiAgWzcgOCA5IDEgMiAzIDQgNSA2XQogIFsyIDMgMSA1IDYgNCA4IDkgN10KICBbNSA2IDQgOCA5IDcgMiAzIDFdCiAgWzggOSA3IDIgMyAxIDUgNiA0XQogIFszIDEgMiA2IDQgNSA5IDcgOF0KICBbNiA0IDUgOSA3IDggMyAxIDJdCiAgWzkgNyA4IDMgMSAyIDYgNCA1XQpdCgouemlwLnszL30lemlwe359JTMve1tdKn0lKyt7JDEwLDE%2BPSF9LCwK&run=true)) and outputs `0` if it is a valid grid. *Short explanation of the code* ``` .zip # Copy the input array and transpose it .{3/}% # Split each line into 3 blocks zip{~}% # Transpose these blocks 3/{[]*}% # Do the same for the lines themselves and join again ++ # Make one large list of 27 9-element arrays # (9 for rows, 9 for columns, 9 for blocks) {$10,1>=!}, # From those 27 select the ones which are not a permutation of [1 2 3 ... 9] # $ -> sort # 10,1> -> [1 2 3 ... 9] # =! -> not equal , # Count after filtering ``` [Answer] ## Java/C# - 183/180 181/178 173/170 bytes ``` boolean s(int[][]a){int x=0,y,j;int[]u=new int[27];for(;x<(y=9);x++)while(y>0){j=1<<a[x][--y];u[x]|=j;u[y+9]|=j;u[x/3+y/3*3+18]|=j;}for(x=0;x<27;)y+=u[x++];return y==27603;} ``` (Change `boolean` to `bool` for C#) Formatted: ``` boolean s(int[][] a){ int x=0, y, j; int[] u=new int[27]; for(;x<(y=9);x++) while(y>0){ j=1<<a[x][--y]; u[x]|=j; u[y+9]|=j; u[x/3+y/3*3+18]|=j; } for(x=0;x<27;) y+=u[x++]; return y==27603; } ``` The method creates an array `u` with 27 bitmasks, representing the digits found in the nine rows, columns and squares. It then iterates over all cells, performing the operation `1 << a[x][y]` to create a bitmask representing the digit and ORs its column, row and square bitmask with it. It then iterates over all 27 bitmasks, ensuring that they all add up to 27594 (1022\*9, 1022 being the bitmask for all digits 1-9 being present). (Note that `y` ends up as 27603 due to it already containing 9 following the double loop.) Edit: Accidentally left in a `%3` that's no longer necessary. Edit 2: Inspired by Bryce Wagner's comment, the code has been compressed a bit more. [Answer] # python = 196 Not the most golfed, but the idea is there. Sets are pretty useful. Board: ``` b = [[1,2,3,4,5,6,7,8,9], [4,5,6,7,8,9,1,2,3], [7,8,9,1,2,3,4,5,6], [2,3,1,5,6,4,8,9,7], [5,6,4,8,9,7,2,3,1], [8,9,7,2,3,1,5,6,4], [3,1,2,6,4,5,9,7,8], [6,4,5,9,7,8,3,1,2], [9,7,8,3,1,2,6,4,5]] ``` Program: ``` n={1,2,3,4,5,6,7,8,9};z=0 for r in b: if set(r)!=n:z=1 for i in zip(*b): if set(i)!=n:z=1 for i in (0,3,6): for j in (0,3,6): k=j+3 if set(b[i][j:k]+b[i+1][j:k]+b[i+2][j:k])!=n:z=1 print(z) ``` [Answer] # Java - 385 306 328 260 characters **Edit:** I foolishly misread the instructions that the answer *had* to be a complete program. Since it can be just a valid function, I've rewritten and minimized to be a function, and rewritten my solution introduction with that in mind. So, as a challenge to myself I thought I'd try to make the smallest Java solution checker. To achieve this I assume that the sudoku puzzle will be passed in as a java multidimensional array, like so: ``` s(new int[][] { {1,2,3,4,5,6,7,8,9}, {4,5,6,7,8,9,1,2,3}, {7,8,9,1,2,3,4,5,6}, {2,3,1,5,6,4,8,9,7}, {5,6,4,8,9,7,2,3,1}, {8,9,7,2,3,1,5,6,4}, {3,1,2,6,4,5,9,7,8}, {6,4,5,9,7,8,3,1,2}, {9,7,8,3,1,2,6,4,5}}); ``` Then, we have the actual solver, which returns "0" if valid solution, "1" if not. Fully golfed: ``` int s(int[][] s){int i=0,j,k=1;long[] f=new long[9];long r=0L,c=r,g=r,z=45L,q=r;for(f[0]=1L;k<9;){f[k]=f[k-1]*49;z+=f[k++]*45;}for(;i<9;i++){for(j=0;j<9;){k=s[i][j];r+=k*f[i];c+=k*f[j];g+=k*f[j++/3+3*(i/3)];q+=5*f[k-1];}}return (r==z&&c==z&&g==z&&q==z)?0:1;} ``` Readable: ``` int s(int[][] s) { int i=0,j,k=1; long[] f=new long[9]; long r=0L,c=r,g=r,z=45L,q=r; for(f[0]=1L;k<9;){f[k]=f[k-1]*49;z+=f[k++]*45;} for(;i<9;i++) { for (j=0;j<9;) { k=s[i][j]; r+=k*f[i]; c+=k*f[j]; g+=k*f[j++/3+3*(i/3)]; q+=5*f[k-1]; } } return (r==z&&c==z&&g==z&&q==z)?0:1; } ``` So how does this work? I basically just create my own number base with sufficient resolution in each digit that I only have to do three numeric comparisons after passing through the puzzle once to know if it's valid. I chose base 49 for this problem, but any base larger than 45 would be sufficient. A (hopefully) clear example: imagine that every "row" in the sudoku puzzle is a single digit in a base-49 number. We'll represent each digit in the base-49 number as a base-10 number in a vector for simplicity. So, if all rows are "correct" we expect the following base-49 number (as a base-10 vector): ``` (45,45,45,45,45,45,45,45,45) ``` or converted to a single base-10 number: `1526637748041045` Follow similar logic for all the columns, and same for the "sub-grids". Any value encountered in the final analysis that doesn't equal this "ideal number" means the puzzle solution is invalid. Edit to solve all-5s vulnerability and other related issues: I add a fourth base-49 number, based on the idea that there should be 9 of each number in every puzzle. So, I add 5 to each digit in the base-49 number for each occurrence of the base-10 number that represents the digit's index. An example, if there are 10 9's and 9 8's, 9 7's, 8 6's, and 9 of all others, you'd get a base-49 number (as a base-10 vector of size 10 to deal with overflow): ``` (1, 1, 45, 45, 40, 45, 45, 45, 45, 45) ``` Which will fail when compared against our "ideal" base-49 number. My solution takes advantage of this mathematical solution, to avoid as much as possible looping and comparison. I simply use a `long` value to store each base-49 number as a base-10 number and use a lookup array to get the "factors" for each base-49 digit during column/row/subgrid check value computation. As Java isn't designed to be concise, being careful in the mathematical construction was the only way I figured I could construct a concise checker. Let me know what you think. [Answer] ## R 145 ``` function(x)colSums(do.call(rbind,lapply(list(R<-row(b<-matrix(1,9,9)),C<-col(b),(R-1)%/%3+1+3*(C-1)%/%3),sapply,`==`,1:9))%*%c(2^(x-1))==511)==27 ``` The de-golfed code (more or less) can be found here <https://stackoverflow.com/a/21691541/1201032>. [Answer] ## J 52 54 ``` -.*/,(9=#)@~.@,"2(0 3 16 A.i.4)&|:(4#3)($,)".;._2]0 :0 ``` Takes it's argument pasted on the command line, ended with a ) as: ``` 1 2 3 4 5 6 7 8 9 4 5 6 7 8 9 1 2 3 7 8 9 1 2 3 4 5 6 2 3 1 5 6 4 8 9 7 5 6 4 8 9 7 2 3 1 8 9 7 2 3 1 5 6 4 3 1 2 6 4 5 9 7 8 6 4 5 9 7 8 3 1 2 9 7 8 3 1 2 6 4 5 ) ``` Returns 1 if passed, 0 if not. Internally, it converts the 9x9 grid to a 3x3x3x3 grid, and does some permutations on the axes to get the wanted unit (rows, lines and boxes) in the last 2 dimensions. After doing that, it is checked that each unit has has 9 unique values. Probably far from perfect, but beats the majority already ;-) [Answer] # Haskell (Lambdabot), 65 bytes ``` k x=and$(all$([1..9]==).sort)<$>[x,transpose x,join$chunksOf 3 x] ``` [Answer] ## Perl, 193 bytes ``` for(@x=1..9){$i=$_-1;@y=();push@y,$a[$i][$_-1]for@x;@y=sort@y;$r+=@y~~@x;@y=();push@y,$a[3*int($i/3)+$_/3][3*($i%3)+$_%3]for 0..8;@y=sort@y;$r+=@y~~@x}for(@a){@y=sort@$_;$r+=@y~~@x}exit($r!=27) ``` Input is expected in array form: ``` @a=( [1,2,3,4,5,6,7,8,9], [4,5,6,7,8,9,1,2,3], [7,8,9,1,2,3,4,5,6], [2,3,1,5,6,4,8,9,7], [5,6,4,8,9,7,2,3,1], [8,9,7,2,3,1,5,6,4], [3,1,2,6,4,5,9,7,8], [6,4,5,9,7,8,3,1,2], [9,7,8,3,1,2,6,4,5] ); ``` Exit code is 0, if `@a` is a solution, otherwise `1` is returned. **Ungolfed version:** ``` @x = (1..9); for (@x) { $i = $_ - 1; # columns @y = (); for (@x) { push @y, $a[$i][$_-1]; } @y = sort @y; $r += @y ~~ @x; # sub arrays @y = (); for (0..8) { push @y, $a[ 3 * int($i / 3) + $_ / 3 ][ 3 * ($i % 3) + $_ % 3 ]; } @y = sort @y; $r += @y ~~ @x } # rows for (@a) { @y = sort @$_; $r += @y ~~ @x } exit ($r != 27); ``` Each of the 9 rows, 9 columns and 9 sub arrays are put into a sorted array and checked, whether it matches the array `(1..9)`. The number `$r` is incremented for each successful match that must sum up to 27 for a valid solution. [Answer] # Mathematica, ~~84~~ 79 chars ``` f=Tr[Norm[Sort@#-Range@9]&/@Join[#,Thread@#,Flatten/@Join@@#~Partition~{3,3}]]& ``` **Examples:** ``` f[{{1,2,3,4,5,6,7,8,9}, {4,5,6,7,8,9,1,2,3}, {7,8,9,1,2,3,4,5,6}, {2,3,1,5,6,4,8,9,7}, {5,6,4,8,9,7,2,3,1}, {8,9,7,2,3,1,5,6,4}, {3,1,2,6,4,5,9,7,8}, {6,4,5,9,7,8,3,1,2}, {9,7,8,3,1,2,6,4,5}}] ``` > > 0 > > > ``` f[{{2,1,3,4,5,6,7,8,9}, {4,5,6,7,8,9,1,2,3}, {7,8,9,1,2,3,4,5,6}, {2,3,1,5,6,4,8,9,7}, {5,6,4,8,9,7,2,3,1}, {8,9,7,2,3,1,5,6,4}, {3,1,2,6,4,5,9,7,8}, {6,4,5,9,7,8,3,1,2}, {9,7,8,3,1,2,6,4,5}}] ``` > > 2 > > > ``` f[{{0,2,3,4,5,6,7,8,9}, {4,5,6,7,8,9,1,2,3}, {7,8,9,1,2,3,4,5,6}, {2,3,1,5,6,4,8,9,7}, {5,6,4,8,9,7,2,3,1}, {8,9,7,2,3,1,5,6,4}, {3,1,2,6,4,5,9,7,8}, {6,4,5,9,7,8,3,1,2}, {9,7,8,3,1,2,6,4,5}}] ``` > > 3 > > > [Answer] # Javascript ES6, 150 chars Takes input as a 81-char string without any delimeters. ``` s=>s.match("^(?=(#.{0,8}#.{9})+$)(?=(#(.{9}){0,8}#.){9})((#.?.?(.{9}){0,2}#...){3}.{18})+$".replace(/#(.*?)#/g,"123456789".replace(/./g,"(?=$$1$&)"))) ``` Function returns `null` as negative answer and an array with original string in first element as a positive one. Can change to bool by adding `!!` to the function begining. Test (see [related challenge](/q/78210/32091) for more detais): ``` f=s=>s.match("^(?=(#.{0,8}#.{9})+$)(?=(#(.{9}){0,8}#.){9})((#.?.?(.{9}){0,2}#...){3}.{18})+$".replace(/#(.*?)#/g,"123456789".replace(/./g,"(?=$$1$&)"))) ;`123456789456789123789123456231564897564897231897231564312645978645978312978312645 725893461841657392396142758473516829168429537952378146234761985687935214519284673 395412678824376591671589243156928437249735186738641925983164752412857369567293814 679543182158926473432817659567381294914265738283479561345792816896154327721638945 867539142324167859159482736275398614936241587481756923592873461743615298618924375 954217683861453729372968145516832497249675318783149256437581962695324871128796534 271459386435168927986273541518734269769821435342596178194387652657942813823615794 237541896186927345495386721743269158569178432812435679378652914924813567651794283 168279435459863271273415986821354769734692518596781342615947823387526194942138657 863459712415273869279168354526387941947615238138942576781596423354821697692734185 768593142423176859951428736184765923572389614639214587816942375295837461347651298` .split` `.every(f) && `519284673725893461841657392396142758473516829168429537952378146234761985687935214 839541267182437659367158924715692843624973518573864192298316475941285736456729381 679543182158926473432817659567381294914256738283479561345792816896154327721638945 867539142324167859159482736275398684936241517481756923592873461743615298618924375 754219683861453729372968145516832497249675318983147256437581962695324871128796534 271459386435168927986273541518734269769828435342596178194387652657942813823615794 237541896186927345378652914743269158569178432812435679495386721924813567651794283 168759432459613278273165984821594763734982516596821347615437829387246195942378651 869887283619214453457338664548525781275424668379969727517385163319223917621449519 894158578962859187461322315913849812241742157275462973384219294849882291119423759 123456789456789123564897231231564897789123456897231564312645978645978312978312645 145278369256389147364197258478512693589623471697431582712845936823956714931764825` .split` `.every(s => !f(s)) ``` [Answer] # R, ~~63~~ 50 bytes Assumes the input `m` is a 9x9 matrix of numbers. ``` all(apply(m,1,match,x=1:9),apply(m,2,match,x=1:9)) ``` I was right that further golfing was possible. ### Explanation: ``` apply(m,1,match,x=1:9), ``` Take `m`, and for each row, apply the `match` function. We specify a further argument `x=1:9` to be passed to `match`. `x` is the default first position argument, and therefore each row is placed in the second argument position, which is `table`. The function `match` looks for instances of `x` in `table`. In this case, then, it's looking for `1:9` (the numbers 1 through 9) in each row. For each of `1:9`, it will return `TRUE` (or `FALSE`) if that number is found (or not). So, this yields a series of 81 boolean values. ``` apply(m,2,match,x=1:9) ``` Repeat the above for each column of the input. ``` all( ) ``` Finally, `all` checks if every element of the list of booleans is `TRUE`. This will be the case if and only if the solution is correct (i.e. each number `1:9` is present only once in each column and each row). ### ~~Old approach:~~ ``` for(i in 1:2)F=F+apply(m,i,function(x)sort(x)==1:9);sum(F)==162 ``` It takes each row, sorts it, and then compares it to `[1, 2, ... 9]`. A correct row should match exactly. Then it does the same for each column. In total, we should have 162 exact matches, which is what the final portion checks for. There is likely some scope for further golfing here... [Answer] ## Haskell - 175 ``` import Data.List c=concat m=map q=[1..9] w=length.c.m (\x->(x\\q)++(q\\x)) b x=c.m(take 3.drop(3*mod x 3)).take 3.drop(3*div x 3) v i=sum$m(w)[i,transpose i,[b x i|x<-[0..8]]] ``` The function `v` is the one to call. It works by getting the difference of each rows, column and block against the list `[1..9]` and summing up the lengths of those difference lists. Demo using the example Sudoku: ``` *Main> :l so-22443.hs [1 of 1] Compiling Main ( so-22443.hs, interpreted ) Ok, modules loaded: Main. *Main> v [[1,2,3,4,5,6,7,8,9],[4,5,6,7,8,9,1,2,3],[7,8,9,1,2,3,4,5,6],[2,3,1,5,6,4,8,9,7],[5,6,4,8,9,7,2,3,1],[8,9,7,2,3,1,5,6,4],[3,1,2,6,4,5,9,7,8],[6,4,5,9,7,8,3,1,2],[9,7,8,3,1,2,6,4,5]] 0 ``` [Answer] # Javascript - 149 Characters ``` r=[];c=[];g=[];for(i=9;i;)r[o=--i]=c[i]=g[i]=36;for(x in a)for(y in z=a[x]){r[v=z[y]-1]-=y;c[v]-=x;g[v]-=3*(x/3|0)+y/3|0}for(i in r)o|=r[i]|c[i]|g[i] ``` Expects an array `a` to exist and creates a variable `o` for output which is `0` on success and non-zero otherwise. Works by checking that the sum of the position at which each value occurs for each row, column and 3\*3 grid equals 36 (0+1+2+3+4+5+6+7+8). **Testing** ``` a=[ [1,2,3, 4,5,6, 7,8,9], [4,5,6, 7,8,9, 1,2,3], [7,8,9, 1,2,3, 4,5,6], [2,3,1, 5,6,4, 8,9,7], [5,6,4, 8,9,7, 2,3,1], [8,9,7, 2,3,1, 5,6,4], [3,1,2, 6,4,5, 9,7,8], [6,4,5, 9,7,8, 3,1,2], [9,7,8, 3,1,2, 6,4,5] ]; ``` Gives 'o=0' ``` a=[ [1,2,3, 4,5,6, 7,8,9], [4,5,6, 7,8,9, 1,2,3], [7,8,9, 1,2,3, 4,5,6], [2,3,1, 5,6,4, 8,9,7], [5,6,4, 8,9,7, 2,3,1], [8,9,7, 2,3,1, 5,6,4], [3,1,2, 6,4,5, 9,7,8], [6,4,5, 9,7,8, 3,1,2], [9,7,8, 3,1,2, 6,5,4] ]; ``` (Last 2 digits swapped) Gives `o=-1` ``` a=[ [5,5,5, 5,5,5, 5,5,5], [5,5,5, 5,5,5, 5,5,5], [5,5,5, 5,5,5, 5,5,5], [5,5,5, 5,5,5, 5,5,5], [5,5,5, 5,5,5, 5,5,5], [5,5,5, 5,5,5, 5,5,5], [5,5,5, 5,5,5, 5,5,5], [5,5,5, 5,5,5, 5,5,5], [5,5,5, 5,5,5, 5,5,5] ]; ``` Gives `o=-284` [Answer] # Haskell, ~~121~~ ~~130~~ 127 bytes (87 Lambdabot) ``` import Data.List import Data.List.Split c=concat t=transpose k=chunksOf p x=all(==[1..9])$(sort<$>)=<<[x,t x,k 9.c.c.t$k 3<$>x] ``` uses: ``` -- k 9.c.c.t$k 3<$> x = chunksOf 9 $ concat $ concat $ transpose $ map chunksOf 3 x let ts = k 9$[10*a+b|a<-[1..9],b<-[1..9]] --yep, this is ugly in k 9.c.c.t$k 3<$>ts -- prints: --[[11,12,13,21,22,23,31,32,33],[41,42,43,51,52,53,61,62,63],[71,72,73,81,82,83,91,92,93],[14,15,16,24,25,26,34,35,36],[44,45,46,54,55,56,64,65,66],[74,75,76,84,85,86,94,95,96],[17,18,19,27,28,29,37,38,39],[47,48,49,57,58,59,67,68,69],[77,78,79,87,88,89,97,98,99]] ``` Lambdabot loads Data.List and Data.List.Split by default (I don't think BlackCap's solution checks the boxes). Ideas for improvement welcome //Edit: I messed up :) //Edit: 3 bytes saved by BlackCap [Answer] # [JavaScript (Node.js)](https://nodejs.org), 143 bytes ``` A=>A.map((_,i)=>(c=d=>new Set(d).size==9)(A[i])&&c(A.map(b=>b[i]))&&c([0,0,0].reduce((a,_,O)=>a.concat(A[~~(i/3)*3+O].slice(l=i%3*3,l+3)),[]))) ``` [Try it online!](https://tio.run/##XZA9T8MwEED3/IpbqM7tYUhd@jE4Un5BB8bIqlzHRUYhqZoAEkP/ejBEl8G67endO@ne7Zft3S1ch8e2q/140WOpi1J@2CviiYLQBTpd66L13/DqB6yF7MOP1/ogsKyCEYuFw8k/6@L8R/5R9UxxjLz5@tN5REsnOsaala5rnR3i8v2O4UmJpVodjeybELVGhwe1VNSslBBUxZYYo993jZdN94YXzCqoICdYEyiCDcELwZZgR7AnOIChDKKQcuIVFlI@p1iYYM6dDfs7FlLOnZyFlM8pFhRf3/L1yd@zkHLurFlI@ZwCAybL4vN@AQ "JavaScript (Node.js) – Try It Online") [Answer] # J, 56 chars Reads 9 lines of digits from ARGV and does magic: ``` echo-.*/,(b~:0),,(2 2$3)(-:~.)&,;.3 b=:"."0>cutLF{:>ARGV ``` Part of this is infused with an older script I wrote for a similar challenge elsewhere, so I don't remember what everything does. What I *do* remember is that `;.3` is really the funny magic here, because it "divides" the matrix of numbers into smaller "squares" according to the value `2 2$3` (I don't remember what it means, but pretend it's important). [Try it online!](https://tio.run/##DYsxCsJAEEX7OUUIIols1uzM7MzOigEbbawsPECCIDY2Wgm5@rrV47/Pe5XyWJ7vwe/2rpvXPPbOddjghvpuyKvvt@7gqZmPufXtOC3fz/X8y9PpdrmXUpIwacBoQBgTm0oAq0LqIGCSYNUrBEsSlQkBKxJZEJBkSlxj0EARkxhDZKwXafoD) [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 36 bytes ``` |©vy3ô})3ôøvyJvyê}}®øvyê}®vyê})êžh¦Q ``` [Try it online!](http://05ab1e.tryitonline.net/#code=fMKpdnkzw7R9KTPDtMO4dnlKdnnDqn19wq7DuHZ5w6p9wq52ecOqfSnDqsW-aMKmUQ&input=MTIzNDU2Nzg5CjQ1Njc4OTEyMwo3ODkxMjM0NTYKMjMxNTY0ODk3CjU2NDg5NzIzMQo4OTcyMzE1NjQKMzEyNjQ1OTc4CjY0NTk3ODMxMgo5NzgzMTI2NDU) 1 is true, anything else is false. [Answer] **Clojure, 151 bytes** Quite long, but others seem to be as well. Also annoying that union of sets requires a `require`, so I used a concat of vectors instead. Iterates over each row and column and if the value is between 1 and 9 it emits three vectors, one for row, col and 3x3 cell. Returns 0 on success and `nil` otherwise, with two extra characters could return 1 on fail. Handles numbers outside of 1 - 9 by returning `nil` but will crash on other anomalies such as non-integer values. Quotients are 0 - 2 so it is safe to use values `8` and `9` to differentiate cell values from rows and columns. ``` (fn[s](if(= 243(count(set(apply concat(for[i(range 9)j(range 9)](let[v(nth(nth s i)j)q #(quot % 3)](if(<= 1 v 9)[[8 v i][9 v j][(q i)(q j)v]])))))))0)) ``` Input is a nested vector of vectors (so that `nth` works): ``` (def sudoku [[1 2 3 4 5 6 7 8 9] [4 5 6 7 8 9 1 2 3] [7 8 9 1 2 3 4 5 6] [2 3 1 5 6 4 8 9 7] [5 6 4 8 9 7 2 3 1] [8 9 7 2 3 1 5 6 4] [3 1 2 6 4 5 9 7 8] [6 4 5 9 7 8 3 1 2] [9 7 8 3 1 2 6 4 5]]) ``` Ungolfed: ``` (defn f [s] (->> (for [i (range 9) j (range 9)] (let [v (-> s (nth i) (nth j)) q #(quot % 3)] (if (<= 1 v 9) [[:row v i] [:col v j] [:cell [(q i) (q j)] v]]))) (apply concat) set count (#(if (= 243 %) :pass :fail)))) ``` [Answer] # PHP, ~~196~~ 190 bytes ``` while($i<9){for($b=$c=$k=$y="";$y++<9;)$b.=($a=$argv)[$y][$i];for(;$k<3;)$c.=substr($a[++$k+$i-$i%3],$i%3*3,3);if(($u=count_chars)($a[++$i],3)<($d=123456789)|$u($b,3)<$d|$u($c,3)<$d)die(1);} ``` Program takes 9 separate command line arguments (one string of digits for each line of the grid); exits with `1` (error) for invalid, `0` (ok) for valid. Run with `php -nr '<code>' <row1> <row2> ...`. **breakdown** ``` while($i<9) { for($b=$c=$k=$y="";$y++<9;)$b.=($a=$argv)[$y][$i]; // column to string for(;$k++<3;)$c.=substr($a[$i-$i%3+$k],$i%3*3,3); // sub-grid to string if(($u=count_chars)($a[++$i],3)<($d=123456789) // check row |$u($b,3)<$d // check column |$u($c,3)<$d // check sub-grid )die(1); // test failed: exit with 1 } ``` **explanation** `count_chars` counts characters in a string and usually creates an array with ascii codes as keys and character count as values; but with `3` as mode parameter, it creates a sorted string from the characters; and that can easily be compared to the number with the wanted digits. The comparison does not only check for duplicates, but also includes the check for invalid characters. And it only requires `<`, not `!=`, because this is numeric comparison: PHP will interpret the string as a number as far as it can. `123e56789`, `0x3456789` or similar cannot appear, because the characters are sorted; and any pure integer with a digit missing is smaller than `123456789` ... and `.23456789` too, of course. `$a=$argv` saves one byte, `$d=123456789` saves nine and `$u=count_chars` saves 13. [Answer] # C# - 306 298 288 characters The following Console program was used to call the checking function; ``` static void Main(string[] args) { int[,] i={{1,2,3,4,5,6,7,8,9}, {4,5,6,7,8,9,1,2,3}, {7,8,9,1,2,3,4,5,6}, {2,3,1,5,6,4,8,9,7}, {5,6,4,8,9,7,2,3,1}, {8,9,7,2,3,1,5,6,4}, {3,1,2,6,4,5,9,7,8}, {6,4,5,9,7,8,3,1,2}, {9,7,8,3,1,2,6,4,5} }; Console.Write(P(i).ToString()); } ``` All this does is initialise the array and pass it into the checking function P. The checking function is as below (in Golfed form); ``` private static int P(int[,]i){int[]r=new int[9],c=new int[9],g=new int[9];for(int p=0;p<9;p++){r[p]=45;c[p]=45;g[p]=45;}for(int y=0;y<9;y++){for(int x=0;x<9;x++){r[y]-=i[x,y];c[x]-=i[x,y];int k=(x/3)+((y/3)*3);g[k]-=i[x,y];}}for(int p=0;p<9;p++)if(r[p]>0|c[p]>0|g[p]>0)return 1;return 0;} ``` Or in fully laid out form; ``` private static int P(int[,] i) { int[] r = new int[9],c = new int[9],g = new int[9]; for (int p = 0; p < 9; p++) { r[p] = 45; c[p] = 45; g[p] = 45; } for (int y = 0; y < 9; y++) { for (int x = 0; x < 9; x++) { r[y] -= i[x, y]; c[x] -= i[x, y]; int k = (x / 3) + ((y / 3) * 3); g[k] -= i[x, y]; } } for (int p = 0; p < 9; p++) if (r[p] > 0 | c[p] > 0 | g[p] > 0) return 1; return 0; } ``` This uses the idea that all columns, rows and sub-grids should add up to 45. It works through the input array and subtracts the value of each position from it's row, column and sub-grid. Once complete it then checks that none of the rows, columns or sub-grids still have a value. As requested returns a 0 if the array is a valid Sudoku solution and non-zero (1) where it's not. ]
[Question] [ I would like to generate (as a return result of a function, or simply as the output of a program) the [ordinal](http://en.wikipedia.org/wiki/Ordinal_number_%28linguistics%29) suffix of a positive integer concatenated to the number. Samples: ``` 1st 2nd 3rd 4th ... 11th 12th 13th ... 20th 21st 22nd 23rd 24th ``` And so on, with the suffix repeating the initial 1-10 subpattern every 10 until 100, where the pattern ultimately starts over. The input would be the number and the output the ordinal string as shown above. What is the smallest algorithm for this? [Answer] # Python 2, 49 bytes ``` lambda n:`n`+'tsnrhtdd'[n%5*(n%100^15>4>n%10)::4] ``` An anonymous function. A [full program](http://golf.shinh.org/reveal.rb?1st%202nd%203rd%204th/xsot_1456205408&py) would be counted at 55 bytes. `'tsnrhtdd'[i::4]` encodes the suffixes `th st nd rd` for values of `i` from 0 to 3. Given this, all we need is a way to map the values of `n` to the index of the corresponding suffix, `i`. A straightforward expression that works is `(n%10)*(n%10<4 and not 10<n%100<14)`. We can easily shorten this by dropping the first set of parentheses and observing that `n%5` gives the same results as `n%10` for the values of `n` with the special suffixes. With a bit of trial and error, one may also shorten `not 10<n%100<14` to `n%100^15>4`, which can be chained with the other conditional to save even more bytes. [Answer] ## Perl, 37 + 1 characters ``` s/1?\d\b/$&.((0,st,nd,rd)[$&]||th)/eg ``` This is a regexp substitution that appends the appropriate ordinal suffix to any numbers in `$_` that are not already followed by a letter. To apply it to file input, use the `p` command line switch, like this: ``` perl -pe 's/1?\d\b/$&.((0,st,nd,rd)[$&]||th)/eg' ``` This is a complete Perl program that reads input from stdin and writes the processed output to stdout. The actual code is 37 chars long, but the `p` switch [counts as one extra character](https://codegolf.meta.stackexchange.com/questions/273/on-interactive-answers-and-other-special-conditions). ### Sample input: ``` This is the 1 line of the sample input... ...and this is the 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 101 102 103 104 105 106 107 108 109 110 ``` ### Output: ``` This is the 1st line of the sample input... ...and this is the 2nd. 1st 2nd 3rd 4th 5th 6th 7th 8th 9th 10th 11th 12th 13th 14th 15th 16th 17th 18th 19th 20th 21st 22nd 23rd 24th 25th 26th 27th 28th 29th 30th 101st 102nd 103rd 104th 105th 106th 107th 108th 109th 110th ``` Numbers already followed by letters will be ignored, so feeding the output again through the filter won't change it. Spaces, commas and periods between numbers are not treated specially, so they're assumed to separate numbers like any other punctuation. Thus, e.g. `3.14159` becomes `3rd.14159th`. ### How does it work? * First, this is a global regexp replacement (`s///g`). The regexp being matched is `1?\d\b`, where `\d` matches any digit and `\b` is a zero-width assertion matching the boundary between an alphanumeric and a non-alphanumeric character. Thus, `1?\d\b` matches the last digit of any number, plus the previous digit if it happens to be `1`. * In the substitution, which is evaluated as Perl code due to the `/e` switch, we take the matched string segment (`$&`) and append (`.`) to it the suffix obtained by using `$&` itself as an integer index to the list `(0,st,nd,rd)`; if this suffix is zero or undefined (i.e. when `$&` is zero or greater than three), the `||` operator replaces it with `th`. --- **Edit:** If the input is restricted to a single integer, then this 35 character solution will suffice: ``` s/1?\d$/$&.((0,st,nd,rd)[$&]||th)/e ``` [Answer] ## Python, 68 characters ``` i=input() k=i%10 print"%d%s"%(i,"tsnrhtdd"[(i/10%10!=1)*(k<4)*k::4]) ``` [Answer] # Mathematica ~~39~~ 45 bytes Note: In recent versions of Mathematica, asking for the `nth` part of `p`, where `p` is undefined, generates an error message, but returns the correct answer anyway. I've added `Quiet` to prevent the error message from printing. ``` Quiet@StringSplit[SpokenString[p[[#]]]][[2]]& ``` **Usage** ``` Quiet@StringSplit[SpokenString[p[[#]]]][[2]] &[31] ``` > > 31st > > > ``` Quiet@StringSplit[SpokenString[p[[#]]]][[2]] &/@Range[21] ``` > > {"1st", "2nd", "3rd", "4th", "5th", "6th", "7th", "8th", "9th", > "10th", "11th", "12th", "13th", "14th", "15th", "16th", "17th", > "18th", "19th", "20th", "21st"} > > > --- **How it works** `SpokenString` writes out an any valid Mathematica expression as it might be spoken. Below are two examples from the documentation for [SpokenString](http://reference.wolfram.com/mathematica/ref/SpokenString.html), ``` SpokenString[Sqrt[x/(y + z)]] ``` > > "square root of the quantity x over the quantity y plus z" \*) > > > ``` SpokenString[Graphics3D[Sphere[{{0, 0, 0}, {1, 1, 1}}]], "DetailedGraphics" -> True] ``` > > "a three-dimensional graphic consisting of unit spheres centered at 0, 0, 0 and 1, 1, 1" > > > --- Now, for the example at hand, ``` Quiet@SpokenString[p[[#]]] &[31] ``` > > "the 31st element of p" > > > Let's represent the above string as a list of words: ``` StringSplit[%] ``` > > {"the", "31st", "element", "of", "p"} > > > and take the second element... ``` %[[2]] ``` > > 31st > > > [Answer] # Javascript (ES6) ~~50~~ 44 Bytes ``` a=>a+=[,"st","nd","rd"][a.match`1?.$`]||"th" ``` ### Notes * takes imput as a string * Removed 6 bytes, thanks @user81655 [Answer] ## Ruby, 60 It's not as good as the Perl entry, but I figured I'd work on my Ruby skills. ``` def o(n)n.to_s+%w{th st nd rd}[n/10%10==1||n%10>3?0:n%10]end ``` Function takes one integer argument, `n`, and returns a string as the ordinal form. Works according to the following logic: If the tens digit is a 1 or the ones digit is greater than 3 use the suffix 'th'; otherwise find the suffix from the array ['th', 'st', 'nd', 'rd'] using the final digit as the index. [Answer] ## Javascript, ~~68~~ 71 ``` function o(n){return n+([,'st','nd','rd'][~~(n/10%10)-1?n%10:0]||'th')} ``` Joint effort with ItsCosmo. EDIT: Wasn't working properly with numbers > 100 [Answer] # JavaScript, 64 characters (ES3) or 47 characters (ES6) ### ES3 (64 characters): `function(n){return n+=[,'st','nd','rd'][n%100>>3^1&&n%10]||'th'}` ### ES6 (47 characters): `n=>n+=[,'st','nd','rd'][n%100>>3^1&&n%10]||'th'` ### Explanation The expression `n % 100 >> 3 ^ 1` evaluates to 0 for any positive `n` ending with digits `08`–`15`. Thus, for any `n mod 100` ending in `11`, `12`, or `13`, the array lookup returns `undefined`, leading to a suffix of `th`. For any positive `n` ending in other digits than `08`–`15`, the expression `n % 100 >> 3 ^ 1` evaluates to a positive integer, invoking the expression `n % 10` for array lookup, returning `st`,`nd`, or `rd` for `n` which ends with `1`, `2`, or `3`. Otherwise, `th`. [Answer] ## Haskell, ~~95~~ 100 chars ``` h=foldr g"th".show g '1'"th"="1st" g '2'"th"="2nd" g '3'"th"="3rd" g '1'[x,_,_]='1':x:"th" g a s=a:s ``` Testing: ``` *Main> map h [1..40] ["1st","2nd","3rd","4th","5th","6th","7th","8th","9th","10th","11th","12th","13t h","14th","15th","16th","17th","18th","19th","20th","21st","22nd","23rd","24th", "25th","26th","27th","28th","29th","30th","31st","32nd","33rd","34th","35th","36 th","37th","38th","39th","40th"] ``` Must be loaded with -XNoMonomorphismRestriction. [Answer] # J - ~~44~~ 41 char Nothing in J? This is an outrage! ``` (":,th`st`nd`rd{::~4|4<.10(|*|~:-~)100&|) ``` Explained (note that `1` is boolean true in J and `0` is false): * `100&|` - First, reduce the input modulo 100. * `10(|*|~:-~)` - In this subexpression, `|` is the input mod 10 and `-~` is the input (mod 100) minus 10. You don't get many trains as clean as this one in J, so it's a treat to see here! + `~:` is not-equals, so `|~:-~` is false if the tens digit is 1 and true otherwise. + `*` is just multiplication, so we're taking the input mod 10 and multiplying by a boolean, which will zero it out if false. The result of this is "input mod 10, except 0 on the tens". * `4|4<.` - Min (`<.`) the above with 4, to clamp down larger values, and then reduce modulo 4 so that they all go to zero. * `th`st`nd`rd{::~` - Use that as an index into the list of suiffixes. Numbers ending in X1 or X2 or X3, but not in 1X, will find their suffix, and everything else will take the 0th suffix `th`. * `":,` - Finally, take the original input, convert it to a string (`":`), and append the suffix. Usage is obvious, though as-is the verb can only take one ordinal, not a list. ``` (":,th`st`nd`rd{::~4|4<.10(|*|~:-~)100&|) 112 NB. single use 112th (":,th`st`nd`rd{::~4|4<.10(|*|~:-~)100&|) 1 2 3 4 5 NB. doing it wrong |length error | (":,th`st`nd`rd{::~4|4<.10(|*|~:-~)100&|)1 2 3 4 5 NB. i.5 10 makes a 5x10 grid of increasing integers NB. &.> to operate on each integer separately, and box the result after (":,th`st`nd`rd{::~4|4<.10(|*|~:-~)100&|)&.> i.5 10 NB. all better +----+----+----+----+----+----+----+----+----+----+ |0th |1st |2nd |3rd |4th |5th |6th |7th |8th |9th | +----+----+----+----+----+----+----+----+----+----+ |10th|11th|12th|13th|14th|15th|16th|17th|18th|19th| +----+----+----+----+----+----+----+----+----+----+ |20th|21st|22nd|23rd|24th|25th|26th|27th|28th|29th| +----+----+----+----+----+----+----+----+----+----+ |30th|31st|32nd|33rd|34th|35th|36th|37th|38th|39th| +----+----+----+----+----+----+----+----+----+----+ |40th|41st|42nd|43rd|44th|45th|46th|47th|48th|49th| +----+----+----+----+----+----+----+----+----+----+ ``` Alternative 41 char solution showing off a couple logical variants: ``` (":;@;st`nd`rd`th{~3<.10(|+3*|=-~)100|<:) ``` Previously I had an overlong explanation of this 44 char hunk of junk. `10 10#:` takes the last two decimal digits and `/@` puts logic between them. ``` (":,th`st`nd`rd{::~10 10(]*[(~:*])4>])/@#:]) ``` [Answer] ## Golfscript, 34 characters ``` ~.10/10%1=!1$10%*.4<*'thstndrd'2/= ``` [Answer] # [R](https://www.r-project.org/), ~~79~~ 76 bytes Since there is no R solution yet... no tricks here, basic vector indexing, golfed down 3 chars thanks to Giuseppe. Previously tried index: `[1+(x%%10)-(x%%100==11)]` and `[1+(x%%10)*(x%%100!=11)]`. ``` function(x)paste0(x,c("th","st","nd","rd",rep("th",6))[1+x%%10*!x%%100==11]) ``` [Try it online!](https://tio.run/##K/qfbqP7P600L7kkMz9Po0KzILG4JNVAo0InWUOpJENJR6m4BEjkpQCJIiBRlFoAETfT1Iw21K5QVTU00FIEUwa2toaGsZr/ixMLCnIqNQytDA0NddI1uf4DAA "R – Try It Online") With `substr`, 79 bytes: ``` function(x,y=1+2*min(x%%10-(x%%100==11),4))paste0(x,substr("thstndrdth",y,y+1)) ``` [Try it online!](https://tio.run/##JcrLCoMwEEbhvY8hCJk6Qn7pqpiHSb1Dm4bMCM3TR8HV@RYnlXXoynKEUfdfMH/ODm3/@O6Xmwa2u2OdA4ifRNGLzvYa5XiLJlPrJhqmNOlWc@bcgqiIj/GTDV4AeKWqnA "R – Try It Online") [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~38~~ 36 bytes Thanks to ngn for fixing a bug while maintaining byte count. Anonymous tacit prefix function. Requires `⎕IO` (**I**ndex **O**rigin) set to `0`, which is default on many systems. Even works for 0! ``` ⍕,{2↑'thstndrd'↓⍨2×⊃⍵⌽∊1 0 8\⊂10↑⍳4} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG9qZv6jtgkG/9OA5KPeqTrVRo/aJqqXZBSX5KUUpag/apv8qHeF0eHpj7qaH/VufdSz91FHl6GCgYJFzKOuJkMDoOJHvZtNav//T1Mw4EpTMARiIwUFIGkMJk2ApLqenp46SM4QLGQIkTc0RpIyMgCLGYG1G4EIYxBhAgA "APL (Dyalog Unicode) – Try It Online") `{`…`}` anonymous lambda; `⍵` is argument:  `⍳4` first four **ɩ**ndices; `[0,1,2,3]`  `10↑` take first ten elements from that, padding with zeros: `[0,1,2,3,0,0,0,0,0,0]`  `⊂` enclose to treat as single element; `[[0,1,2,3,0,0,0,0,0,0]]`  `1 0 8\` expand to one copy, a prototypical copy (all-zero), eight copies;   `[[0,1,2,3,0,0,0,0,0,0],`    `[0,0,0,0,0,0,0,0,0,0],`    `[0,1,2,3,0,0,0,0,0,0],`    `[0,1,2,3,0,0,0,0,0,0],`    ⋮ (5 more)    `[0,1,2,3,0,0,0,0,0,0]]`  `∊` **ϵ**nlist (flatten);   `[0,1,2,3,0,0,0,0,0,0,`    `0,0,0,0,0,0,0,0,0,0,`    `0,1,2,3,0,0,0,0,0,0,`    `0,1,2,3,0,0,0,0,0,0,`    ⋮ (50 more)    `0,1,2,3,0,0,0,0,0,0]`  `⍵⌽` cyclically rotate left as many steps as indicated by the argument  `⊃` pick the first number (i.e. the argument-mod-100'th number)  `2×` multiply two by that (gives `0`, `2`, `4`, or `6`)  `'thstndrd'↓⍨`drop that many characters from this string  `2↑` take the first two of the remaining characters `⍕,` concatenate the stringified argument to that [Answer] # Javascript, ~~75~~ 60 With the new arrow notation: ``` o=(s)=>s+((0|s/10%10)==1?"th":[,"st","nd","rd"][s%10]||"th") ``` *Old version, without arrow notation (75 chars):* ``` function o(s){return s+((0|s/10%10)==1?"th":[,"st","nd","rd"][s%10]||"th")} ``` [Answer] Bash (Cardinal to ordinal) **91** Bytes: ``` function c(){ case "$1" in *1[0-9]|*[04-9])"$1"th;;*1)"$1"st;;*2)"$1"nd;;*3)"$1"rd;;esac } ``` [Answer] ## PowerShell, 92 ``` process{"$_$(switch -r($_){"(?<!1)1$"{'st'}"(?<!1)2$"{'nd'}"(?<!1)3$"{'rd'}default{'th'}})"} ``` Works with one number per line of input. Input is given through the pipeline. Making it work for only a single number doesn't reduce the size. [Answer] ## PHP, 151 I know that this program is not comparable to the others. Just felt like giving a solution. ``` <?$s=explode(' ',trim(fgets(STDIN)));foreach($s as$n){echo$n;echo(int)(($n%100)/10)==1?'th':($n%10==1?'st':($n%10==2?'nd':($n%10==3?'rd':'th')))."\n";} ``` [Answer] # K - 44 char It so happens that this is exactly as long as the J, and works in almost the same way. ``` {x,$`th`st`nd`rd@{y*(y<4)*~1=x}.-2#0,.:'x$:} ``` Explained: * `x$:` - First, we convert the operand `x` into a string, and then assign that back to `x`. We will need its string rep again later, so doing it now saves characters. * `.:'` - Convert (`.:`) each (`'`) digit back into a number. * `-2#0,` - Append a 0 to the front of the list of digits (in case of single-digit numbers), and then take the last two. * `{y*(y<4)*~1=x}.` - Use the two digits as arguments `x` and `y` to this inner function, which returns `y` if `y` is less than 4 and `x` is not equal to 1, otherwise 0. * ``th`st`nd`rd@` - Index the list of suffixes by this result. * `x,$` - Convert the suffix from symbol to string, and append it to the original number. Usage: ``` {x,$`th`st`nd`rd@{y*(y<4)*~1=x}.-2#0,.:'x$:} 3021 "3021st" {x,$`th`st`nd`rd@{y*(y<4)*~1=x}.-2#0,.:'x$:}' 1 2 3 4 11 12 13 14 /for each in list ("1st" "2nd" "3rd" "4th" "11th" "12th" "13th" "14th") ``` [Answer] # PHP, 98 bytes ``` function c($n){$c=$n%100;$s=['','st','nd','rd'];echo$c>9&&$c<14||!$s[$c%10]?$n.'th':$n.$s[$c%10];} ``` The 11-13 bit is killing me here. Works for any integer `$n >= 0`. For any integer `$n`: # PHP, 103 bytes ``` function c($n){$c=abs($n%100);$s=['','st','nd','rd'];echo$c>9&&$c<14||!$s[$c%10]?$n.'th':$n.$s[$c%10];} ``` [Answer] # Javascript ES6, 52 chars ``` n=>n+(!/1.$/.test(--n)&&'snr'[n%=10]+'tdd'[n]||'th') ``` [Answer] # C#, 62 bytes ``` n=>n+(n/10%10==1||(n%=10)<1||n>3?"th":n<2?"st":n<3?"nd":"rd"); ``` Full program and verification: ``` using System; namespace OutputOrdinalNumbers { class Program { static void Main(string[] args) { Func<int,string>f= n=>n+(n/10%10==1||(n%=10)<1||n>3?"th":n<2?"st":n<3?"nd":"rd"); for (int i=1; i<=124; i++) Console.WriteLine(f(i)); } } } ``` [Answer] # Mathematica 29 + 5 = 34 bytes ``` SpokenStringDump`SpeakOrdinal ``` +5 bytes because `Speak` function must be called before using this built-in. **Usage** ``` SpokenStringDump`SpeakOrdinal[1] ``` > > `"1st "` > > > ``` SpokenStringDump`SpeakOrdinal[4707] ``` > > `"4,707th "` > > > [Answer] # Java 7, ~~91~~ 81 bytes ``` String d(int n){return n+(n/10%10==1|(n%=10)<1|n>3?"th":n<2?"st":n<3?"nd":"rd");} ``` Port from [*@adrianmp*'s C# answer](https://codegolf.stackexchange.com/a/94774/52210). Old answer (**91 bytes**): ``` String c(int n){return n+((n%=100)>10&n<14?"th":(n%=10)==1?"st":n==2?"nd":n==3?"rd":"th");} ``` **Ungolfed & test code:** [Try it here.](https://ideone.com/pA66N2) ``` class M{ static String c(int n){ return n + ((n%=100) > 10 & n < 14 ?"th" : (n%=10) == 1 ? "st" : n == 2 ? "nd" : n == 3 ? "rd" :"th"); } static String d(int n){ return n + (n/10%10 == 1 | (n%=10) < 1 | n > 3 ? "th" : n < 2 ? "st" : n < 3 ? "nd" :"rd"); } public static void main(String[] a){ for(int i = 1; i < 201; i++){ System.out.print(c(i) + ", "); } System.out.println(); for(int i = 1; i < 201; i++){ System.out.print(d(i) + ", "); } } } ``` **Output:** ``` 1st, 2nd, 3rd, 4th, 5th, 6th, 7th, 8th, 9th, 10th, 11th, 12th, 13th, 14th, 15th, 16th, 17th, 18th, 19th, 20th, 21st, 22nd, 23rd, 24th, 25th, 26th, 27th, 28th, 29th, 30th, 31st, 32nd, 33rd, 34th, 35th, 36th, 37th, 38th, 39th, 40th, 41st, 42nd, 43rd, 44th, 45th, 46th, 47th, 48th, 49th, 50th, 51st, 52nd, 53rd, 54th, 55th, 56th, 57th, 58th, 59th, 60th, 61st, 62nd, 63rd, 64th, 65th, 66th, 67th, 68th, 69th, 70th, 71st, 72nd, 73rd, 74th, 75th, 76th, 77th, 78th, 79th, 80th, 81st, 82nd, 83rd, 84th, 85th, 86th, 87th, 88th, 89th, 90th, 91st, 92nd, 93rd, 94th, 95th, 96th, 97th, 98th, 99th, 100th, 101st, 102nd, 103rd, 104th, 105th, 106th, 107th, 108th, 109th, 110th, 111th, 112th, 113th, 114th, 115th, 116th, 117th, 118th, 119th, 120th, 121st, 122nd, 123rd, 124th, 125th, 126th, 127th, 128th, 129th, 130th, 131st, 132nd, 133rd, 134th, 135th, 136th, 137th, 138th, 139th, 140th, 141st, 142nd, 143rd, 144th, 145th, 146th, 147th, 148th, 149th, 150th, 151st, 152nd, 153rd, 154th, 155th, 156th, 157th, 158th, 159th, 160th, 161st, 162nd, 163rd, 164th, 165th, 166th, 167th, 168th, 169th, 170th, 171st, 172nd, 173rd, 174th, 175th, 176th, 177th, 178th, 179th, 180th, 181st, 182nd, 183rd, 184th, 185th, 186th, 187th, 188th, 189th, 190th, 191st, 192nd, 193rd, 194th, 195th, 196th, 197th, 198th, 199th, 200th, 1st, 2nd, 3rd, 4th, 5th, 6th, 7th, 8th, 9th, 10th, 11th, 12th, 13th, 14th, 15th, 16th, 17th, 18th, 19th, 20th, 21st, 22nd, 23rd, 24th, 25th, 26th, 27th, 28th, 29th, 30th, 31st, 32nd, 33rd, 34th, 35th, 36th, 37th, 38th, 39th, 40th, 41st, 42nd, 43rd, 44th, 45th, 46th, 47th, 48th, 49th, 50th, 51st, 52nd, 53rd, 54th, 55th, 56th, 57th, 58th, 59th, 60th, 61st, 62nd, 63rd, 64th, 65th, 66th, 67th, 68th, 69th, 70th, 71st, 72nd, 73rd, 74th, 75th, 76th, 77th, 78th, 79th, 80th, 81st, 82nd, 83rd, 84th, 85th, 86th, 87th, 88th, 89th, 90th, 91st, 92nd, 93rd, 94th, 95th, 96th, 97th, 98th, 99th, 100th, 101st, 102nd, 103rd, 104th, 105th, 106th, 107th, 108th, 109th, 110th, 111th, 112th, 113th, 114th, 115th, 116th, 117th, 118th, 119th, 120th, 121st, 122nd, 123rd, 124th, 125th, 126th, 127th, 128th, 129th, 130th, 131st, 132nd, 133rd, 134th, 135th, 136th, 137th, 138th, 139th, 140th, 141st, 142nd, 143rd, 144th, 145th, 146th, 147th, 148th, 149th, 150th, 151st, 152nd, 153rd, 154th, 155th, 156th, 157th, 158th, 159th, 160th, 161st, 162nd, 163rd, 164th, 165th, 166th, 167th, 168th, 169th, 170th, 171st, 172nd, 173rd, 174th, 175th, 176th, 177th, 178th, 179th, 180th, 181st, 182nd, 183rd, 184th, 185th, 186th, 187th, 188th, 189th, 190th, 191st, 192nd, 193rd, 194th, 195th, 196th, 197th, 198th, 199th, 200th, ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 6 bytes ``` ∆o2NȯJ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLiiIZvMk7Ir0oiLCIiLCIyMyJd) [Answer] Python 2.7, 137 chars ``` def b(n): for e,o in[[i,'th']for i in['11','12','13']+list('4567890')]+[['2','nd'],['1','st'],['3','rd']]: if n.endswith(e):return n+o ``` `n` should be a string I know I'm beaten by the competition here already, but I thought I'd provide my idea anyways this just basically generates a list of key, value pairs with number (as a string) ending `e` and the ordinal `o`. It attempts to match 'th' first (hence why I didn't use a dictionary), so that it won't accidentally return 'st', for example, when it should be 'th'. This will work for any positive integer [Answer] ### Scala 86 ``` def x(n:Int)=n+{if(n%100/10==1)"th"else(("thstndrd"+"th"*6).sliding(2,2).toSeq(n%10))} ``` Scala 102: ``` def x(n:Int)=if((n%100)/10==1)n+"th"else if(n%10<4)n+("thstndrd".take(n+1)%5*2.drop(n%5*2))else n+"th" ``` 102 as well: ``` def x(n:Int)=if((n%100)/10==1)n+"th"else if(n%10<4)n+("thstndrd".sliding(2,2).toSeq(n%10))else n+"th" ``` ungolfed: ``` def x (n: Int) = n + { if (((n % 100) / 10) == 1) "th" else (("thstndrd" + ("th" * 6)).sliding (2, 2).toSeq (n % 10)) } ``` [Answer] # C: 95 characters A ridiculously long solution: ``` n;main(){scanf("%d",&n);printf("%d%s",n,n/10%10-1&&(n=n%10)<4&&n?n>2?"rd":n<2?"st":"nd":"th");} ``` It needs to be mangled more. [Answer] # OCaml I'm pretty new to OCaml, but this is the shortest i could get. ``` let n x = let v = x mod 100 and string_v = string_of_int x in let z = v mod 10 in if v=11 || v=12 || v=13 then string_v^"th" else if v = 1 || z = 1 then string_v^"st" else if v = 2 || z = 2 then string_v^"nd" else if v = 3 || z = 3 then string_v^"rd" else string_v^"th";; ``` I created a function n that takes a number as a parameter and does the work. Its long but thought it'd be great to have a functional example. [Answer] # C - 95 83 characters ``` main(n,k){scanf("%d",&n);k=(n+9)%10;printf("%d%s\n",n,k<3?"st\0nd\0rd"+3*k:"th");} ``` Degolfed: ``` main(n,k) { scanf("%d",&n); k=(n+9)%10; // xx1->0, xx2->1, xx3->2 printf("%d%s\n",n,k<3?"st\0nd\0rd"+3*k:"th"); } ``` We could do `k=(n-1)%10` instead of adding 9, but for n=0 we would get an incorrect behaviour, because in C `(-1)%10` evaluates to -1, not 9. [Answer] # Javascript, 75 ``` function s(i){return i+'thstndrd'.substr(~~(i/10%10)-1&&i%10<4?i%10*2:0,2)} ``` ]
[Question] [ **This question already has answers here**: [Find the temperature closest to 0](/questions/112021/find-the-temperature-closest-to-0) (36 answers) Closed 5 years ago. # Description : You are given a string of numbers (positive and negative but not decimals) along with the number of entries like so. Like so `8 '1 2 5 0 7 -9 12 -8'` # Task : Your job is to return the number closest to zero be it +ve or -ve. Your input will be separated by spaces only. You are free to return the answer in any way you like namely : 1. A string - A float (Why would you though) - An array (One digit array I guess) - A number (preferred) Since this is code golf the answer with the shortest will be the winner. I guess? Have fun. ### code snippets : ``` console.log(`6 '1 -2 -8 4 3 5'`) // should return 1 console.log(`3 '-12 -5 -137'`) // should return -3 console.log(`8 '1 2 5 0 7 -9 12 -8'`) // should return 0 ``` ### Note : This is my first attempt at this. Apologies in advance for any mistakes, do tell so I can correct them. Thanks [Answer] # [Python 2](https://docs.python.org/2/), 41 bytes ``` lambda n:min(map(abs,map(int,n.split()))) ``` [Try it online!](https://tio.run/##K6gsycjPM/qfbhvzPycxNyklUSHPKjczTyM3sUAjMalYB0Rn5pXo5OkVF@RklmhoAsH/giKgkEK6hpKhgpGCqYKBgrmCrqWCoZGCroWS5n8A "Python 2 – Try It Online") ]
[Question] [ # Challenge Implement binary search on a list of length 256 with no branches. # Specification * Input an integer `X` and a strictly increasing list of integers * Output is the greatest element of the list that is less than or equal to `X` * The output will always exist * List will always have exactly 256 elements and be strictly increasing * The algorithm must be a binary search on the list # Example code (with branches) Without branches, these examples would be valid entries. First a functional example (actually valid Haskell code): ``` b value list = b' 0 7 where b' pos bitpos | bitpos < 0 = list !! pos | (list !! (pos + 2^bitpos)) < value = b' (pos + 2^bitpos) (bitpos - 1) | (list !! (pos + 2^bitpos)) == value = list !! (pos + 2^bitpos) | otherwise = b' pos (bitpos - 1) ``` Now a pseudocode iterative example: ``` b(value, list): pos = 0 bitpos = 7 while bitpos >= 0: if list[pos + 2^bitpos] < value pos += 2^bitpos elseif list[pos + 2^bitpos] == value return list[pos + 2^bitpos] bitpos -= 1 return list[pos] ``` # Rules * Branches include: `if/then`, `switch`, `case`, `for`, `while`, `?:`, guards, and all other branches * Instead of a list, you may use a list-like object, so space separated string, vector, etc. * Entry may be a function or full program * If your language has a function that solves this challenge, it is not allowed * Score is in bytes, lowest score wins! # Example Input/Output (abbreviated) ``` Input: 50, [..21,34,55,89,144..] Output: 34 Input: 15, [..2,3,15,25,34,35..] Output: 15 Input: 144, [..37,50,65,82,101,122,145..] Output: 122 ``` [Answer] # C, 75 bytes Here's the code: ``` #define g p+=(x>=p[i/=2])*i b(x,p,i)int*p;{i=256;g;g;g;g;g;g;g;g;return*p;} ``` Less golfed: ``` int bin_search(int x, int * p){ int i = 256; i = i / 2; p += (p[i] <= x) * i; \\ above two lines repeated 8 times return *p; } ``` ]
[Question] [ **Challenge** You will create a function which takes a matrix filled with letters from the alphabet and determine if a `2x2` square composed of vowels exists. * If a 2x2 square of vowels is found, your function should return the top-left position (row-column) of the square. * If no 2x2 square of vowels exists, then return the string `"not found"`. * If there are multiple squares of vowels, return the one that is at the most top-left position in the whole matrix. **Rules** * Matrix must be at least `2x2` * Matrix can only contain letters from the alphabet * Input can be a String, where each line is separated by `\n`, `,`, `.`, `\t` (`\n` means `line break` and `\t` TAB) or an array of strings. * Vowels are `a e i o u`. **Example** Given `["abcd", "eikr", "oufj"]` ``` a b c d e i k r o u f j ``` Output: `1-0` --- Given `["gg", "ff"]` ``` g g f f ``` Output `not found` --- **Test Cases** **Given `["asd", "qie", "euo"]`** ``` a s d q i e e u o ``` Output: `1-1` **Given `["aqrst", "ukaei", "ffooo"]`** ``` a q r s t u k a e i f f o o o ``` Output: `1-2` **Given `["ghsdfhsd", "sdfgsdff", "sdfgsdfg"]`** ``` g h s d f h s d s d f g s d f f s d f g s d f g ``` Output: `"not found"` * Consider the examples as test cases as well ## Update * If you are going to use 1-based index, please clarify it in your answer. --- This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes win. [Answer] # [Python 2](https://docs.python.org/2/), 121 bytes ``` import re s=input() w=s.find(',') v='[aeiou]'*2 m=re.search(v+'.'*~-w+v,s) print m and divmod(m.start(),-~w)or'not found' ``` [Try it online!](https://tio.run/##Dcy7DcMgEADQnimQm4MYU7hnkigFCiCjCI4cHyuNVyd@A7zyawfmfc6YClLj5Fk1MZfehGSnqTrE7AQokGwYeFofsb/gsbNkyOvqLb0PMVbQ8Li2cx2qSlYo5sYTt9lxF0dCJ5KuzdJ9qu06JRJkbDxgzw7mXOyXalP9c@8qBERc/g "Python 2 – Try It Online") I feel like I don't get to use `divmod` often in Python, haha. Takes input like `"aqrst,ukaei,ffooo"`. ## Explanation We compute the width **w** of the matrix by finding the position of the first `,`: in this case, that's 5. Then, we build the regex `[aeiou][aeiou]....[aeiou][aeiou]` with **(w − 1)** dots: to match vowels on the next row, we skip (one row − 2 letters + 1 comma) = **(w − 1)** characters we don't care about. To turn `m.start()` back into coordinates, we `divmod` by **(w + 1)** (minding the comma). [Answer] # JavaScript (ES6), ~~89~~ 88 bytes *Saved 1 byte thanks to @RickHitchcock* Takes input as a comma-separated string. ``` s=>~(k=s.search((v='[aeiou]{2}')+`.{${(w=s.search`,`+1)-2}}`+v))?[k/w|0,k%w]:'not found' ``` [Try it online!](https://tio.run/##bY1NDoIwGET3nsIQTdtQUFmaVA9CSGjoj1jSTyiFBeLVaze6MC5eZpJ5ydz5xF0ztI8xsyBkUCw4dnlhw1zuJB@aG8YTQyWXLfhqKVZE0jpfdguev0ZN6/REsmJd63Qi5Fqaw/w8UrOfqzOyMG4VeCtQaMA66GTegcYKJ9wJ2reSSg8JIZvftR/cSL2Jx1QpgH@OvjmhIjSGjqhP0VEObw "JavaScript (Node.js) – Try It Online") [Answer] # Java 8, 156 bytes ``` m->{for(int i=0,j;++i<m.length;)for(j=0;++j<m[i].length;)if((m[i][j]+m[i][j-1]+m[i-1][j]+m[i-1][j-1]).matches("[aeiou]+"))return i+"-"+j;return"not found";} ``` 1-indexed output. [Try it online.](https://tio.run/##rVFBbsMgELz3FStOIMdWenbSHzSXHi0fCAYMMZAYSFVFfrtL7DTtwa1UKRKwuzOI2Vk0PdNcN4eRddR7eKXKXp4AlA28F5Rx2F1LgLfQKyuB4Tmp6qoGQ8rEDWmn5QMNisEOLGxhNPnLRbgep3dAbdcrXWaZ2pii41aGtiRXTm/XCdUbU6n6TiiB8RWodJ3NMX@eshRu2JSlgxSGBtZyj1FFuXKxzhAhPQ@xt6AylKNMl3OJrAsgXLQNKoexnDs@xn2XOr41fnaqAZPs3x1ScrP@4QM3hYuhOCYmdBbbgmHL3@F7GPNVAET3rEGFP3YqYITI6gvn6tAv4S4K/QOf4IFMk/2vtJRLAkI86HnqF42dFF/0G92jdE@9D0sS8ZC@fdmyc49Sl61vRLtsPTEybfEHJ39pY3gaxk8) ``` m->{ // Method with String-matrix input and String return-type for(int i=0,j;++i<m.length;) // Loop over the rows, skipping the first for(j=0;++j<m[i].length;) // Inner loop over the columns, skipping the first if((m[i][j]+m[i][j-1]+m[i-1][j]+m[i-1][j-1]) // If four characters in a square appended to each other, .matches("[aeiou]+")) // are only vowels return i+"-"+j; // Return the 1-indexed output return"not found";} // Return "not found" ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~143~~ ~~132~~ ~~130~~ 129 bytes * Thanks to [musicman523](https://codegolf.stackexchange.com/users/69054/musicman523) for golfing eleven bytes; golfed `{m[y][x],m[y][x+1],m[y+1][x],m[y+1][x+1]}` to `{*(m[y][x:x+2]+m[y+1][x:x+2])}`. * Thanks to [ovs](https://codegolf.stackexchange.com/users/64121/ovs), golfed `{...}<={*"aeiou"}` to `{...}<{*"aeiou"}`; using the fact that five vowels do not fit into four cells. ``` lambda m:([(y,x)for y in range(len(m)-1)for x in range(len(m[y])-1)if{*(m[y][x:x+2]+m[y+1][x:x+2])}<{*"aeiou"}]+["not found"])[0] ``` [Try it online!](https://tio.run/##XU5LDsIgEN17CsIKrCZWd0ZPgizQMhTbMkpL0sZ49gptjKaLybx5v8xj6Ep0hxHOl7FWzbVQpDkywYZNzwE9GYh1xCtnNKu1Yw3f5hPfL3gxyCRZeK2nQ/THPtvLLOIs/178fXqtqdIWA33LTFCHHQEMrqCSi50cH966jgETVF1vBd0Qqm3l08YA92jiq5/FmCQALGjVTsGn1VM@4FJ/@rZLUqjiJ3MF4tJlyraAcq6KyMSBP2ySffwA "Python 3 – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 26 bytes ``` e€€ØcaƝ⁺€T€µT,FZḢȯ“¤Ø#"ȯ"» ``` Indexing is 1-based. [Try it online!](https://tio.run/##y0rNyan8/z/1UdMaIDo8Iznx2NxHjbuA7BAgPrQ1RMct6uGORSfWP2qYc2jJ4RnKSifWKx3a/f9wO1D6//9oLoVopcSk5BQlHQWl1MzsIhCdX5qWpRSrA5JKTwcJpKVBuYnFYIWFmalg9aX5MPHCouISkFBpdmJqJkRLfj5MNj2jOCUtA6IVyEoH4jQkdjpUWUFKaj5IuLwsMRNifF4ymE4tLwMpiQUA "Jelly – Try It Online") [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 82 bytes ``` (.*¶)*?(.)*?[aeiou]{2}.*¶(?>(?<-2>(.))*)[aeiou]{2}(.|¶)* $#1-$#3 ^[^-]*$ not found ``` [Try it online!](https://tio.run/##K0otycxL/P9fQ0/r0DZNLXsNPSARnZiamV8aW21UCxLVsLfTsLfRNbIDymlqaSIkNfRqQHq4VJQNdVWUjbniouN0Y7VUuPLySxTS8kvzUv7/rwAA "Retina 0.8.2 – Try It Online") Explanation: ``` (.*¶)*? ``` Match an optional number of rows which are stacked into capture group 1. ``` (.)*? ``` Match an optional number of columns which are stacked into capture group 2. ``` [aeiou]{2} ``` Match two vowels. ``` .*¶ ``` Match the rest of the line. ``` (?>(?<-2>(.))*) ``` Match an equal number of columns on the next line, which are stacked into capture group 3, as the matching empties the capture group 2 stack. ``` [aeiou]{2} ``` Match two more vowels. ``` (.|¶)* ``` Match the rest of the input. ``` $#1-$#3 ``` If there's a match, replace the entire input with the number of rows and columns matched. ``` ^[^-]*$ not found ``` If the input doesn't yet contain a `-` then the match must have failed. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 35 bytes ``` FḟØcṆ ZÇ€T,€ ṡ€2ṡ2ç"JṖFḣ2Uȯ“¤Ø#"ȯ"» ``` [Try it online!](https://tio.run/##y0rNyan8/9/t4Y75h2ckP9zZxhV1uP1R05oQHSDB9XDnQiBlBKSMDi9X8nq4cxpQ4WKj0BPrHzXMObTk8AxlpRPrlQ7t/g/kJiYlpwCp1MzsIiCVX5qW9ahhrg6QmZ4OJNLSoLzEYpCqwsxUkNrSfJhoYVFxCZAuzU5MzQQrz8@HyaVnFKekZYC1ARnpQJyGYKZDFRWkpALVzykvS8wEG5yXDKJSy8uA8mAP/QcA "Jelly – Try It Online") (comes with test-suite) Way too long, but I guess it'll improve. Uses 1-based indexing. [Answer] # APL+WIN, 73 bytes Prompts for character matrix input: ``` z←,(,r)/(⍴r)⊤(⍳⍴,r←<⍀<\(2^/m,0)×2^⌿(m←⎕∊'aeiou')⍪0)⋄z,(~×⍴z)↑⊂'not found' ``` [Answer] # [Python 2](https://docs.python.org/2/), 134 bytes ``` f=lambda m,i=0,y=0:m[i+1:]and(m[i][y+1:]and(set(m[i][y:y+2]+m[i+1][y:y+2])<set('aeiou')and(i,y)or f(m,i,y+1))or f(m,i+1))or'not found' ``` [Try it online!](https://tio.run/##XU/LboQgFN3PV9yQGCAyjdqkC1Ob9DuMC6aIMqPgAC78egs6mqYL4BzO48K0@N7oYl1lNfDxJjiMTFUZW6qsHGuV5mXDtSABNvVyMNf61025pEWTbsaD0c8oY94qM2Ma7Yot1FiQJFSzUEJPtmOsjQdpZi3wKoPkGVhQGkiN@O1HIAaoVQ8bTzPLO2oYkJxBRimLnq6LipTxHp1VaBe52/JP1W41sznS@SvNn9b5qM2P8OS9yZjTVhxDeidkv5cF1IUl/@Du//DyAjBZpT3g5Pr@4eD6BYnFkAAJ35PEUxoc3LnW@o1CVYG9XLbMvgP6HgbwrfMOpugUb2j9BQ "Python 2 – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), ~~146~~ 140 bytes ``` l x=[0..length x-2] h x|p<-(!!).(x!!)=([show(i,j)|i<-l x,j<-l(x!!0),all(`elem`"aeiou")[p i j,p(i+1)j,p i$j+1,p(i+1)$j+1]]++["not found"])!!0 ``` [Try it online!](https://tio.run/##RU/LTsMwELz3K7ZWJWzloRYkTgkXrnDiGCJqmo3j1LXdxGlz6L@HTQpC1npmd2ZWdiP7IxozTQbGvNimqUGrQgNj8liuCG4@S/h6LVI@0p3zom/cleu4FTedJRSKW4JZ3IpYGsP3aPC0ZxK1G5goPGhoY891tBOEoDdttPvtZ1qWUVQw6wLUbrAVKwVtmk5SW8jhJP37F/DPMXkBP4SP0L1Z2MAIUQQdeqMPMiDwp2dI4O/dAh7okIEBpdjMGuAdyoo0ASkYbbGHPMtAYXh1NqAN/VQw@X2oWMxQHzsCN9QtK1cFU4q6ul647GfHWePsG9x9du76QP1wpC8vVufuimr6qm6WCBFFVf9TtVh8hY5m14vUy0p7mAGvF1b@AA "Haskell – Try It Online") ### Explanation This just generates a list of possible indices, nothing special: ``` l x=[0..length x-2] ``` This is just a little helper, that allows quickly accessing the element at `(i,j)` with `p i j` (due to operator precedence it's shorter not to use an operator): ``` p<-(!!).(x!!) ``` This generates a list with all the indices (as strings...) of 2x2 sub-matrices that consist of vowels in order: ``` h x| = [show(i,j)|i<-l x,j<-l(x!!0),all(`elem`"aeiou")[p i j,p(i+1)j,p i$j+1,p(i+1)$j+1]] ``` Now we just need to append the `"not found"` string: ``` ( ++["not found"]) ``` This way we can simply retrieve the first element in this list (since it's generated in order and in case of no such indices, there's always the `"not found"` string): ``` !!0 ``` [Answer] # [J](http://jsoftware.com/), 61 bytes ``` [:'not found'"_`($#:t)@.(#@,~:t=.4:i.~,)2 2+/@,;.3'aoeiu'e.~] ``` [Try it online!](https://tio.run/##TYwxC8IwFIT3/opHKzyL8SnVKVIoCE5OriIabJJGoaE2WfvXY1oEOxwc993dK6SECkoOCAy2wKPWBMfL@RSuHFvrQFnf1pjeH8tFxl1e0TKr2MBdSXtuaGB5AcVqU7ED7VBYaTxKGm4hTyCRz8aCAhR9jQw7I5FxlN7in3Sf3kXm30KakSpl7YxrPU3ELGn6WjXTYTQ6So2Vn9cYvg "J – Try It Online") ## Explanation: ``` ] a =. 'asd','qie',:'euo' Let `a` be the first test case asd qie euo 'aoeiu'e.~] a creates an equality table between the input and the vowels 1 0 0 0 1 1 1 1 1 2 2<;.3'aoeiu'e.~] a 2 2 u ,. 3 x splits the table into 2x2 overlapping windows ┌───┬───┬─┐ │1 0│0 0│0│ │0 1│1 1│1│ ├───┼───┼─┤ │0 1│1 1│1│ │1 1│1 1│1│ ├───┼───┼─┤ │1 1│1 1│1│ └───┴───┴─┘ ``` I need to check if all the 4 chars are vowels, so I add the numbers (reduce with addition `+/` the flattened list): ``` 2 2+/@,;.3'aoeiu'e.~] a 2 2 1 3 4 2 2 2 1 (t=.4:i.~,)2 2+/@,;.3'aoeiu'e.~] a flattens the list, finds the first 4 occurence of 4 in it and saves it in `t` ``` If 4 is not found J returns the length of the list. That's why I compare the result with the length of the flattened list: ``` (#@,~:t=.4:i.~,)2 2+/@,;.3'aoeiu'e.~] a (0 means not found; 1 - found) 0 u`[[email protected]](/cdn-cgi/l/email-protection) '@.' is 'agenda' - checks the value of y and uses it as an index to the train of verbs on the left. 0 > u; 1 -> v and so on. ``` If `0`, it simply returns 'not found' If `1`, finds the position by converting the index to a pair of numbers in a number system denoted by the size of the input `$#:t`: ``` 3 3#:4 (t is the index of 4, #: convert to antibase, the base is 1 1 the shape of the table, $) ``` ]
[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/25890/edit). Closed 9 years ago. [Improve this question](/posts/25890/edit) I challenge you to generate the following sequence till 100 terms through any programming language in shortest characters possible. The sequence is like this :- ``` 1 2 3 4 5 10 20 30 40 50 100 200 300 400 500 ........ ``` The output needs to be like this (above) only, nothing extra. Remember, You can use `+` and `-` **only** and for mathematical calculations **only** (`++` and `--` are also allowed) and no other mathematical function like `tan()`, `log()`, `pow()`, ......etc. Also, You cannot use any character variables in your code. [Answer] ## GolfScript (21 chars) If > > You can use + and - only for mathematical calculations > > > means what it says then: ``` [6,1>~{4$10*}95*]' '* ``` If it is intended to say > > The only mathematical operators you can use are + and - > > > then the multiplications can be replaced with string manipulation at the same character count: ``` [6,1>~{4$0`+}95*]' '* ``` Dissection: ``` [ # Start gathering values into an array 6,1>~ # Dump the numbers 1 to 5 onto the stack { # Beginning of loop body 4$ # Copy the 5th item on the stack ``` Here the variants differ ``` 10* # Multiply it by 10 ``` or ``` 0`+ # Postpend '0' ``` And then merge again ``` }95* # Loop 95 times, so we end up with 100 items on the stack ] # Gather those 100 items into an array ' '* # Space-separate them ``` [Answer] ## Perl, 38 bytes Disclaimer: The restrictions of the changed question are not too clear to me. ``` for$i(0..19){print$_.0 x$i.$"for 1..5} ``` The code uses variables with integer values except for `$"` which is used for the separation space. It can be easily replaced by `' '` (+1 byte). Mathematical operations are not used, the code only contains string concatenations and the repetition operator. The result are 100 numbers: ``` 1 2 3 4 5 10 20 30 40 50 100 200 300 400 500 1000 2000 3000 4000 5000 10000 20000 30000 40000 50000 100000 200000 300000 400000 500000 1000000 2000000 3000000 4000000 5000000 10000000 20000000 30000000 40000000 50000000 100000000 200000000 300000000 400000000 500000000 1000000000 2000000000 3000000000 4000000000 5000000000 10000000000 20000000000 30000000000 40000000000 50000000000 100000000000 200000000000 300000000000 400000000000 500000000000 1000000000000 2000000000000 3000000000000 4000000000000 5000000000000 10000000000000 20000000000000 30000000000000 40000000000000 50000000000000 100000000000000 200000000000000 300000000000000 400000000000000 500000000000000 1000000000000000 2000000000000000 3000000000000000 4000000000000000 5000000000000000 10000000000000000 20000000000000000 30000000000000000 40000000000000000 50000000000000000 100000000000000000 200000000000000000 300000000000000000 400000000000000000 500000000000000000 1000000000000000000 2000000000000000000 3000000000000000000 4000000000000000000 5000000000000000000 10000000000000000000 20000000000000000000 30000000000000000000 40000000000000000000 50000000000000000000 ``` **Ungolfed:** ``` for $i (0..19) { # 20 * 5 = 100 numbers for $_ (1..5) { print $_ # first digit . 0 x $i # zeros . $" # separator (space) } } ``` [Answer] ## Python 60 ``` r=range for i in r(20): for j in r(1,6):print str(j)+'0'*i, ``` --- Thanks to @ace for pointing out that this was way too long. ## Python 113 ``` from itertools import* i=j=0 for x in cycle(range(1,6)): i+=1;print str(x)+'0'*j, if i%5==0:j+=1 if i>99:break ``` [Answer] # GolfScript, ~~30~~ 25 characters (~~26~~ 23 newline separated) ``` ;6,1>{.{10*}%}20*][]*' '* ``` Commented: ``` ; # pop the input string (empty) 6,1> # generate [1 2 3 4 5] {.{10*}%} # duplicate the array and multiply everything by 10 20* # do this 20 times (5 * 20 = 100) ] # wrap the whole stack in an array []* # flatten ' '* # join by space ``` ~~I really don't like the repetition at the end, but GS doesn't provide a `flat_map` or `flatten` of any sort.~~ Thanks @PeterTaylor for providing a way to flatten! If we can separate by newlines instead of spaces, then **23 characters**: ``` ;6,1>{.{10*}%}20*][]*n* ``` [Answer] ## APL (~~17~~ 24) ``` ,⍉10⊥¨(⍳5)∘.{⍺,1↓⍵/0}⍳20 ``` [Answer] # Java,185 ``` class g {public static void main(String[] args){for(int x=0;x<20;x++){for(int i=1;i<6;i++){System.out.print(""+i); for(int j=0;j<x;j++){System.out.print("0");}System.out.print(" ");}}}} ``` [Answer] # Julia - 38 ``` [print(i,"0"^j," ") for i=1:5,j=0:19]; ``` ### Output: ``` 1 2 3 4 5 10 20 30 40 50 100 200 300 400 500 1000 2000 3000 4000 5000 10000 20000 30000 40000 50000 100000 ... ``` [Answer] # C, 93 ``` i;main(j,k){for(;++i;)for(j=0;++j<6;){for(putchar(48+j),k=0;++k<i;putchar(48));putchar(32);}} ``` // it draws nice patterns on the terminal... [Answer] # PHP - 61 ``` for($i=0;$i++<21;)for($j=0;$j++<5;)echo str_pad($j,$i,0).' '; ``` ]
[Question] [ ## Assumption A cigarette can be made by combining four cigarette butts. Cigarette butts last infinitely until smoked. ## Explanation Say you have 31 butts. That means, you can make 7 cigarettes from 28 butts and have 3 left over. Now, these 7 cigarettes will yield 7 butts when you're done smoking them. That means you have 3 + 7 = 10 butts. These 10 butts make 2 new cigarettes and 2 butts are left over, but the two new cigarettes yield 2 more butts, for a total of 4 butts remaining. Therefore, 31 butts means you can smoke 10 cigarettes in total. ## The question Given a number of butts `N`, where `0 <= N < 1000000`, find out how many cigarettes can be made from those `N` butts. ### Input format A single line containing the integer N. ### Output format Print the number of cigarettes that can be made from N butts. ## Test cases 1. Input: ``` 31 ``` Output: ``` 10 ``` 2. Input: ``` 7 ``` Output: ``` 2 ``` 3. Input: ``` 4 ``` Output: ``` 1 ``` For `N <= 3`, the output should be 0. My personal best C solution is 66 bytes. A friend helped reduce it to 63 bytes, and someone else I know was able to come up with a 43-byte solution (also in C). [Answer] # JavaScript (ES6), 10 bytes Unless I'm missing something, this boils down to: ``` n=>~-n/3|0 ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/P1q5ON0/fuMbgf3J@XnF@TqpeTn66RpqGsaGmpoK@voKhAReqhII5RMIIXdwEquE/AA "JavaScript (Node.js) – Try It Online") Or **[9 bytes](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/P1q5ON0/fOO9/cn5ecX5Oql5OfrpGmoaxYZ6mpoK@voKhAReqjII5VMYIXcIEpuU/AA)** with BigInts. [Answer] # [C (gcc)](https://gcc.gnu.org/), 14 bytes ``` f(n){n=~-n/3;} ``` [Try it online!](https://tio.run/##XU/dSsMwGL3fUxwKg3RL2boqQ@K8EZ/C9qKkySzTdDQBi6U@uvFb1wZnIB/J@fs4MjlK6b1mJu7N4Tsxm0wMvjYOH2VtWIx@AToXwCnrXgsc0Gcpx57jbhCBVN1ZSaeqqyDdcuw40kkgG2Md5FvZrmgqeVLtVRfl3csu7x6e6d5HHH//WTS5ddOCXXbUplId2bZiej7C1l@q0WzeHmMzQ6uACazXo34uEwpR1lhqZAtxQ1oiNXPxLaoIDVX/284tSTSLlhWSJ9Bc2txQK8dheShOwZRRTMHDYvA/Ur@XR@uTz18 "C (gcc) – Try It Online") *Port of [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)'s [JavaScript answer](https://codegolf.stackexchange.com/a/269783/9481)* [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 6 bytes ``` I÷↔⊖N³ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEwzOvxCWzLDMlVcMxqTg/p7QkVcMlNbkoNTc1ryQ1BShdUFriV5qblFqkoampqaNgDCSt//83@K9blgMA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` N Input as a number ⊖ Decremented ↔ Absolute value ÷ Integer divided by ³ Literal integer `3` I Cast to string Implicitly print ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 4 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` s3ṖL ``` A monadic Link that accepts the number of butts and yields the number of cigarettes. **[Try it online!](https://tio.run/##y0rNyan8/7/Y@OHOaT7///83NgQA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8/7/Y@OHOaT7/jY0e7timc7hd5VHTGvf/AA "Jelly – Try It Online"). ##### How? Group the butts into threes, and consider the last up to three butts your "Pile". Take each of the other groups of three butts in turn and combine with one of your Pile, replenishing your Pile with the generated butt. ``` s3ṖL - Link: integer, Butts s3 - split into threes (rightmost lacking if necessary) Ṗ - pop (remove your Pile from the right side) L - length ``` [Answer] # [Funge-98](https://esolangs.org/wiki/Funge-98), 12 bytes ``` &:1-3/\!!*.@ ``` [Try it online!](https://tio.run/##S0pNK81LT9W1tNAtqAQz//9XszLUNdaPUVTU0nP4/9/YkAsA "Befunge-98 (PyFunge) – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 3 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` <3÷ ``` [Try it online](https://tio.run/##yy9OTMpM/f/fxvjw9v//DQA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeV/G@PD2//r/I82NtQx1zHRMdYxiAUA). **Explanation:** ``` < # Decrease the (implicit) input-integer by 1 3÷ # Then integer-divide it by 3 # (after which the result is output implicitly) ``` Note: Integer-division in 05AB1E (built in Elixir) will round towards 0 for negative values, so this works even for \$n=0\$. [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 11 bytes ``` .+ $* ...\B ``` [Try it online!](https://tio.run/##K0otycxL/K@q4Z7wX0@bS0WLS09PL8bp/39jQy5zLhMA "Retina 0.8.2 – Try It Online") Link is to verbose version of code. Explanation: ``` .+ $* ``` Convert to unary. ``` ...\B ``` For every three butts, if there is at least one other butt left over, you can smoke another cigarette, which will leave a butt, which therefore replenishes the butt left over. So this just counts the number of groups of three butts while still leaving at least one butt left over. [Answer] # [Rattle](https://github.com/DRH001/Rattle), 6 bytes ``` |-/3R1 ``` [Try it Online!](https://www.drh001.com/rattle/?flags=&code=%7C-%2F3R1&inputs=31) # Explanation ``` | take input - decrement /3 divide by 3 R1 reformat as int, implicit output ``` Alternatively, the code could be `|!-/3i` ]
[Question] [ Given string `S` representing a dollar amount, make change for that amount of money use the least number of coins to make the change and record the amount of each coin in a list. Here are the coins available to use and their value. ``` Coin : Value Dollar Coins : $1.00 Quarters: $0.25 Dimes: $0.10 Nickels: $0.05 Pennies: $0.01 ``` ## Input String `S` that contains the dollar symbol `$` and the dollar amount. ## Output List of coin numbers separated by a space character `" "`. The list must be in this order: Dollar coins, quarters, dimes, nickels, pennies. ## Constraints * `$0.00 < S < $10.00` * `S` is given to two decimal places. * make change for that amount of money use the least number of coins ## Example Input `$4.58` `$9.99` ## Output `4 2 0 1 3` `9 3 2 0 4` ## Win Condition shortest bytes win. [Answer] # [Hexagony](https://github.com/m-ender/hexagony), ~~35~~ ~~32~~ ~~28~~ 27 bytes ``` ]{=?2'?!/@[1[5/P0;:!%'[01[5 ``` [Try it online!](https://tio.run/##y0itSEzPz6v8/z@22tbeSN1eUd8h2jDaVD/AwNpKUVU92gDI@f9fxVLP0hIA "Hexagony – Try It Online") There are no no-ops `.` now, ~~so it must be optimal~~. [![Colored.](https://i.stack.imgur.com/BJ78Q.png)](https://i.stack.imgur.com/BJ78Q.png) [Answer] # [Python 2](https://docs.python.org/2/), ~~79~~ ~~72~~ 71 bytes ``` s=input() d=int(s[1]+s[3:]) for c in(100,25,10,5,1):print d/c,;d-=d/c*c ``` [Try it online!](https://tio.run/##HYxBCsMgFET3/xTyyUJTm6ppoKZ4kpCVWpqNSjSQnt7abmaGx/DSp7xjUNVG5w0i1my2kI5CGbi2Cs2LXC95GeeVwSvuxJItUCkEVxOXgrdgc9rbk7ib5U93Na17W/8MmhH86S35@XtVsbsP0wMBOz1ojV8 "Python 2 – Try It Online") Saved 7 bytes thanks, in part, to [Chas Brown](https://codegolf.stackexchange.com/users/69880/chas-brown) Saved a byte thanks to [Jo King](https://codegolf.stackexchange.com/users/76162/jo-king) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~24~~ 17 bytes ~~¦'.¡`25‰`10‰`5‰`r5F?' ?}~~ ``` ¦'.¡`25‰`T‰`5‰`ðý ``` [Try it online!](https://tio.run/##MzBNTDJM/f//0DJ1vUMLE4xMHzVsSAgBEWDW4Q2H9/7/r2KiZ2oBAA "05AB1E – Try It Online") My first attempt at it. It's very verbose in my opinion and I'll look at further revising this answer. Maybe somebody better than me will figure it out. **Explanation** ``` ¦ # Remove '$' from input '.¡ # Push '.' and split string on that. (dollar),(cents) is result `25‰ # Push all items onto stack and mod top by 25 `T‰ # Push all items onto stack and mod top by 10 `5‰ # Push all items onto stack and mod top by 5 `r # Push all items onto stack and reverse stack ðý # Loop through stack and print each element with space ``` -7 bytes thanks to Emigna [Answer] # [Octave](https://www.gnu.org/software/octave/), 106 bytes ``` @(n)[k=(f=@fix)(x=str2num(n(2:5))),m=f(4*(x-k)),t=f(10*(s=x-k-.25*m)),p=f(20*(s-.1*t)),100*(s-.1*t-.05*p)] ``` [Try it online!](https://tio.run/##PchBCsMgEEDRfc9RcEbqoBKhFgZyj9JFKRVK0IbEBm9vJpvu/vvfV31u756YiPoIBe8TQ@IxfRpC47UuvvwyFPC3gIiXzAkGDc1MgipwVsPKYkM@6Cx3luuPa8jpKsPZvwzZoGd89ATqPFC4KjwdGSlGhX0H "Octave – Try It Online") 16 bytes is used simply to get rid of `$` and convert the string to a number. The rest is simply removing the as many coins as possible, one value at a time. [Answer] # [R](https://www.r-project.org/), 81 bytes ``` x=as.double(substr(scan(,""),2,6));for(i in 1/c(1,4,10,20,100))x=x-i*print(x%/%i) ``` [Try it online!](https://tio.run/##DcRbCoAgEADAq0gU7MZmGhZBeBjtAQthoQXe3pqPiaVk65LcrtefO6TXpydCWl0AqiqkgSbE5bgisOAgdL@CJkNa0aD@FWK2ueP2jhweyE3fMJbayHEuHw "R – Try It Online") 26 bytes ensuring the data are a `double` rather than a string, very nearly a third of the program! That's lame, to say the least. [Answer] # [Stax](https://github.com/tomtheisen/stax), ~~18~~ 17 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ä┐¢6ⁿ≡♠₧ç7╦Δ╛XÄR│ ``` [Run and debug it](https://staxlang.xyz/#p=84bf9b36fcf0069e8737cbffbe588e52b3&i=%244.58%0A%249.99&a=1&m=2) [Answer] # [Ruby](https://www.ruby-lang.org/), 74 bytes ``` ->s{n=s.delete("$.").to_i;["%s"]*5*" "%[n/100,n/25%4,(m=n/5%5)/2,m%2,n%5]} ``` [Try it online!](https://tio.run/##LczdCoMgGIDhW4mPhAqnTvpqMtyNiIyNFQjpYtbBqF17@/Po5Tl5H/P1ufV6253iEnRkt27opq6AnEHJpvvZHQ2QCLbCCjIgJvC9EDRwiaSmhdeBI8GSS@qJpIGgfW3jPMXMQF4zFEB/xX@b5Ca5TW6T8fCtYkqBZf4yLqtbe@M@zzc "Ruby – Try It Online") Converts input to an integer containing number of pennies, then applies formulas in the `[]` at the end. ``` 5 bytes standard Ruby boilerplate ->s{} 34 bytes on solving the problem 35 bytes on formatting ``` [Answer] # [Julia](https://julialang.org), ~~72~~ 71 bytes ``` !s=(x=parse(Int,filter(>('.'),s));[100,25,10,5,1].|>u->(t=x÷u;x%=u;t)) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=ldBLCsIwEADQfU9R_wmMIakVLCXFnXiG2kWgqUREJR_owpu46cYzCG49hbextX5WLmTCDOSFITOn88Ztlaju11xYwVPP97urfkimsy5P0hACoMBgkkELEYmiBiKYPCl8AyWUNUChDfYF9gH2gszr-fXpGI5KfhDaSLTcWSjU1kqNlMnVWlkwGMcpoxSCKTAKdcrIMXHjBFle3i4uLgfcxRbjs7PFeHZf_OiXoBEZ4b_bDYu99pEBLQ3mzXLqeebCGKlt83Ne33tyl7evq6qtDw) * -1 byte: `x=x%u` -> `x*=u` - thanks to @MarcMush [Answer] # Java 8, 138 bytes ``` s->{long p=new Long(s.replaceAll("\\D","")),c,i=100;for(s="";i>0;s+=c+" ",i=i>25?25:i>10?10:i>5?5:i>1?1:0)for(c=0;p>=i;p-=i)c++;return s;} ``` **Explanation:** [Try it online.](https://tio.run/##hU/BTsMwDL3vK6yIQ6q2UVpWiS5KKySOsAtHxiFkGcrI0ihJh9DUby8Z9AySLT/bz9Z7R3EW5XH/MUsjQoAnoe1lBaBtVP4gpILttQV4jl7bd5B4ASFjaT6lTBGiiFrCFixwmEPZXcyQOI5b9QmPCeJAvHIm/bs3BqPd7gEVCGVZIQvNK0rZYfA4cISY7igLOZc5ApR2uqubvm42uqtoX9FUm/6n66sNza5XklPmOq6ZK7nOZJ4zr@LoLQQ2zexXnxvfTNK3yDwPeg@nZHTx8vIqssXkV4jqRIYxEpc20VhsicToZk2auySX/c1qSdv@z6rqW7JuFt60muZv) ``` s->{ // Method with String as both parameter and return-type long p=new Long(s.replaceAll("\\D","")), // Remove all non-digits, and convert it to a number c, // Count-integer i=100; // Amount integer, starting at 100 for(s=""; // Set the input to an empty String, because we no longer need it i>0 // Loop as long as `i` is not 0 ; // After every iteration: s+=c+" ", // Append the count and a space to `s` i=i>25? // If `i` is 100: 25 // Change it to 25 :i>10? // Else-if `i` is 25: 10 // Change it to 10 :i>5? // Else-if `i` is 10: 5 // Change it to 5 :i>1? // Else-if `i` is 5: 1 // Change it to 1 : // Else (`i` is 1) 0) // Change it to 0 for(c=0; // Reset the count `c` to 0 p>=i; // Inner loop as long as `p` is larger than or equal to `i` p-=i) // After every iteration: subtract `i` from `p` c++; // Increase the count `c` by 1 return s;} // Return the result ``` ]
[Question] [ I want format a JSON string into human-readable form. A string like this: ``` '{"foo":"hello","bar":"world","c":[1,55,"bye"]}' ``` would be formatted as: ``` { "foo": "hello", "bar": "world", "c": [ 1, 55, "bye" ] } ``` **Rules:** 1. For objects and arrays properties and items should be starting in new line with indent of +2 as you see in the above mentioned example. 2. Space after colon is mandatory 3. This is `code-golf`. Shortest code in bytes wins! please be aware that json string should be part of the answer (but we will omit that from number of bytes, example: ``` echo '{"foo":"hello","bar":"world","c":[1,55,"bye"]}'|npx json ``` will be counted as 14 bytes => `echo |npx json` after omitting the string [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 18 [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 prefix function. ``` ⎕JSON⍠'Compact'0⍣2 ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT////1HfVK9gf79HvQvUnfNzCxKTS9QNHvUuNvqf9qhtwqPevkddzY961zzq3XJovfGjtolA5cFBzkAyxMMz@H@agnq1Ulp@vpKVUkZqTk6@ko5SUmIRkFeeX5STAuQlK1lFG@qYmgLFK1OVYmvVAQ "APL (Dyalog Unicode) – Try It Online") `⎕JSON` is the built-in to/from JSON converter `⍠` sets options, here:  `'Compact'` is switched off (`0`) `⍣2` does the conversion twice (JSON string to APL array, from APL array to JSON string) [Answer] # [Python 3](https://docs.python.org/3/), 11 bytes ``` -mjson.tool ``` [Try it online!](https://tio.run/##K6gsycjPM/7/v1opLT9fyUopIzUnJ19JRykpsQjIK88vykkB8pKVrKINdUxNgeKVqUqxtf///8svKMnMzyv@r5ubVZyfp1eSn58DAA "Python 3 – Try It Online") Note that due to the way TIO works, the code goes in the command line options area and the input goes in the code area. [Answer] # JavaScript, 24 bytes ``` o=>JSON.stringify(o,0,2) ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/f1s4r2N9Pr7ikKDMvPTOtUiNfx0DHSPN/cn5ecX5Oql5OfrpGmka1Ulp@vpKVUkZqTk6@ko5SUmIRkFeeX5STAuQlK1lFG@qYmgLFK1OVYms1Nf8DAA) [Answer] # JavaScript, ~~39~~ 35 bytes ``` s=>JSON.stringify(eval('_='+s),0,2) ``` *Saved 4 bytes thanks to [Arnauld](https://codegolf.stackexchange.com/users/58563).* ``` f= s=>JSON.stringify(eval('_='+s),0,2) console.log(f('{"foo":"hello","bar":"world","c":[1,55,"bye"]}')) ``` [Answer] # Java + Android, 41 bytes ``` s->new org.json.JSONObject(s).toString(2) ``` ]
[Question] [ **This question already has answers here**: [Return 1 - Popularity Contest [closed]](/questions/12141/return-1-popularity-contest) (70 answers) Closed 10 years ago. Today, [Numberphile](https://www.youtube.com/user/numberphile) posted [this video](https://www.youtube.com/watch?v=w-I6XTVZXww) where it's stated that `1+2+3+4+...+n = -1/12`. While this isn't really new (several ways to prove that have been found, you can look [here](https://math.stackexchange.com/questions/39802/why-does-123-dots-1-over-12/39811#39811) for further informations), this leads us to our question! Your goal is to write a function that returns **-0.083333** (feel free to stop at **-0.083** if you wish), which is -1/12. Be original, since this is a [popularity-contest](/questions/tagged/popularity-contest "show questions tagged 'popularity-contest'")! Most upvoted answer in 2 weeks wins this. [Answer] The [Riemann Zeta function](http://en.wikipedia.org/wiki/Riemann_zeta_function) is defined as ζ(s) = Sum(n-s) where you sum from n=1 to n=infinity. Hence ζ(-1) = Sum(n) = 1 + 2 + 3 + 4 + ... to infinity. Now [scipy defines zetac](http://docs.scipy.org/doc/scipy/reference/generated/scipy.special.zetac.html) to be `sum(k**(-x), k=2..inf)` (that is the zeta function with the first term removed). Hence in python ``` >>> import scipy.special >>> print 1+scipy.special.zetac(-1) -0.0833333333333 ``` essentially calculates the infinite sum 1+2+3+4+... to give -1/12. [Answer] ## J This is quite short, but I hope you think it's sweet: ``` (%&13@<:^:_)0 ``` I'm relying on the fact that a negative twelfth is -0.1111111... in base thirteen. This function takes its argument, decrements it, and divides by 13 (a right-shift in base 13). It does this until the value converges to -1/12. To see how the base 13 stuff fits in, you might want to imagine the 13 being changed to a 10. The function would then converge at decimal -0.111111... = -1/9. [Answer] # PowerShell (and probably a polyglot) I know this isn't code-golf, but since no other parameters are really defined for the challenge except: > > Your goal is to write a function that returns -0.083333 (feel free to stop at -0.083 if you wish), which is -1/12. > > > I have a really hard time justifying doing anything other than: ``` -1/12 ``` This outputs: ``` -0.0833333333333333 ``` ]
[Question] [ Hehe, see what I did with the title? Anyways... Your job is to create a sudoku solver that accepts input in Morse code and creates output in Morse code. Here's the Morse code numbers for reference: ``` 0: ----- 1: .---- 2: ..--- 3: ...-- 4: ....- 5: ..... 6: -.... 7: --... 8: ---.. 9: ----. ``` # Rules: * The code must define a function `s(x)` which returns the answer. * The function must accept a string or character array (whichever is the "string of characters" type of your relevant language) with 81 Morse code numbers (see above) separated by spaces. Each 9 Morse code numbers is one row of the sudoku puzzle. Known numbers should be represented by their appropriate Morse code number, while unknown numbers should be `0` in Morse code. * The function must perform calculations and then return a string of Morse code numbers similar to the input but as a solved board (separated by spaces). * Be mindful of the [standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) Here's an example. I have the following input string: ``` ----- -.... ----- ...-- ----- ----- ---.. ----- ....- ..... ...-- --... ----- ----. ----- ----- ----- ----- ----- ....- ----- ----- ----- -.... ...-- ----- --... ----- ----. ----- ----- ..... .---- ..--- ...-- ---.. ----- ----- ----- ----- ----- ----- ----- ----- ----- --... .---- ...-- -.... ..--- ----- ----- ....- ----- ...-- ----- -.... ....- ----- ----- ----- .---- ----- ----- ----- ----- ----- -.... ----- ..... ..--- ...-- .---- ----- ..--- ----- ----- ----. ----- ---.. ----- ``` ...which in regular numbers, is this: ``` 0 6 0 3 0 0 8 0 4 5 3 7 0 9 0 0 0 0 0 4 0 0 0 6 3 0 7 0 9 0 0 5 1 2 3 8 0 0 0 0 0 0 0 0 0 7 1 3 6 2 0 0 4 0 3 0 6 4 0 0 0 1 0 0 0 0 0 6 0 5 2 3 1 0 2 0 0 9 0 8 0 ``` And when I put the Morse code string through a correct function, it should then look like this (a solved sudoku board): ``` ..--- -.... .---- ...-- --... ..... ---.. ----. ....- ..... ...-- --... ---.. ----. ....- .---- -.... ..--- ----. ....- ---.. ..--- .---- -.... ...-- ..... --... -.... ----. ....- --... ..... .---- ..--- ...-- ---.. ---.. ..--- ..... ----. ....- ...-- -.... --... .---- --... .---- ...-- -.... ..--- ---.. ----. ....- ..... ...-- ..... -.... ....- ---.. ..--- --... .---- ----. ....- ---.. ----. .---- -.... --... ..... ..--- ...-- .---- --... ..--- ..... ...-- ----. ....- ---.. -.... ``` ...which is this in regular numbers: ``` 2 6 1 3 7 5 8 9 4 5 3 7 8 9 4 1 6 2 9 4 8 2 1 6 3 5 7 6 9 4 7 5 1 2 3 8 8 2 5 9 4 3 6 7 1 7 1 3 6 2 8 9 4 5 3 5 6 4 8 2 7 1 9 4 8 9 1 6 7 5 2 3 1 7 2 5 3 9 4 8 6 ``` Any language allowed. Have fun, and golf away! [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 42 [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 prefix function. ``` ⌂morse{1↓∊' ',¨⍺⍺∊⍕¨⊃⌂sudoku⍎¨9 9⍴⍺⍺⍵⊆⍨≠⍵} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn//1FPU25@UXFqteGjtsmPOrrUFdR1Dq141LsLhDq6HvVOBfK6moHKiktT8rNLH/X2HVphqWD5qHcLVFHv1kddbY96VzzqXABk1/5Pe9Q2AajqUd9UT3@gzkPrjR@1TQTygoOcgWSIh2fw/zQFdV0QUNDVAwIFCBvIAolAxGEksqwehNSDq0ToBRF66HrRSIgJWGRRzNQlaDLUDVA2isv1CLkBN4lsph6Sq/D5AsXNMF9g9aMeMW5AjQu47RBb9FDcgM0EPcxYUwcA "APL (Dyalog Extended) – Try It Online") `⌂morse{`…`}` derive a function where `⍺⍺` is shorthand for the to/from-Morse function  `⍵` the argument string  `≠` Boolean mask where not a space  `⍵⊆⍨` cut where false (this gives us a list of Morse digit strings)  `⍺⍺` convert Morse digits strings to string of digits  `9 9⍴` **r**eshape to 9 rows and 9 columns  `⍎¨` evaluate each character (turns them into integers)  `⌂sudoku` find all solutions  `⊃` pick the first solution  `⍕¨` stringify each integer  `∊` **ϵ**nlist (flatten)  `⍺⍺` convert string of digits to list of Morse digit strings  `' ',¨` prepend a space to each Morse digit string  `∊` **ϵ**nlist (flatten)  `1↓` drop the first character (the leading space) ]
[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/180724/edit). Closed 4 years ago. [Improve this question](/posts/180724/edit) A very simple golf this time, but should be fun to do. # Challenge Output your code, but rotated 45 (or -45) degrees. E.g: `lorem ipsum dolor sit amet` becomes ``` t e m a t i s r o l o d m u s p i m e r o l ``` This logic follows for newlines, too: `lorem ipsum dolor sit amet consectetur adipiscing` becomes ``` t e m a g t n i i s c s r i o p l i o d d a m r u u s t p e i t c m e e s r n o o l c ``` Of course, the difficulty is that you have to output your own code in this format. # Scoring Find position *b* (the amount of bytes in your code). on the X-axis of the formula \$y=\left(\frac{b}{8}-15\right)^2-n\$ (given *n* is the number of newlines). The lower the score, the better. Newlines are encouraged, as they made rendering it harder. Also, -15 bonus points for doing -45 degrees, as opposed to 45. My examples were -45 degrees. # Rules * Standard loopholes apply. * No reading your own source. * There must be a space between one line of code and the next, if you choose to do so * Every line must be at least 5 characters long. * Newlines cannot be replaced with '\n'. Tabs should be replaced with two spaces. * Every line must do something; when removed, the program must not work * No trailing newlines (unless for an implicit return) or no-ops. * Blank newlines should be rendered with a space in its place (you can assume its a line of contents ' ') [Answer] # [Gol><>](https://github.com/Sp3000/Golfish), 120 bytes, score 0 ``` sP#|oao|o `FLFl " ``` Adding a ton of no-ops makes my score really low, so I'm just going to go with it even though it hurts my heart to see so many no-ops doing absolutely nothing :( [Try it online!](https://tio.run/##S8/PScsszvj/vzhAuSY/Mb8mXyHBzcctR4FOQOn/fwA "Gol><> – Try It Online") **golfed answer**, 16 bytes, Score : 152?! ``` sP#|oao|o `FLFl" ``` Wow, that is much smaller and more correct than my previous answer!!! (my other ones were backwards!) [Try it online!](https://tio.run/##S8/PScsszvj/vzhAuSY/Mb8mXyHBzcctR@n/fwA "Gol><> – Try It Online") [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), Score 50.765625 ``` var s="var s={0}{1}{0};for(int i=0;;)WriteLine(new String(' ',i)+string.Format(s,(char)34,s)[i++]);";for(int i=0;;)WriteLine(new String(' ',i)+string.Format(s,(char)34,s)[i++]); ``` [Try it online!](https://tio.run/##Sy7WTS7O/P@/LLFIodhWCUJVG9RWG9YCSeu0/CKNzLwShUxbA2trzfCizJJUn8y8VI281HKF4JKizLx0DXUFdZ1MTe1iME/PLb8oN7FEo1hHIzkjsUjT2ESnWDM6U1s7VtNaiaqm/f8PAA "C# (Visual C# Interactive Compiler) – Try It Online") Also prints to STDERR, if this is invalid I will change it. [Answer] # Japt `-S`, 25 bytes, Score: 116 ``` 25Çî iRiZgQi"25Çî iRiZgQi ``` [Run it online](https://ethproductions.github.io/japt/?v=1.4.6&code=MjXH7iBpUmlaZ1FpIjI1x+4gaVJpWmdRaQ==&input=LVM=) [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), Score -14 ``` <+map {say( ~($_,) .indent( $++)) },[Z] "<$_>[]~~ .EVAL#1234567" .words .map:{ .fmt( "%-14s" ).comb }>[]~~ .EVAL#1234567 ``` [Try it online!](https://tio.run/##K0gtyjH7/99GOzexgKu6OLFSg6tOQyVeR5NLLzMvJTWvRINLRVtbU5OrVic6KpZLyUYl3i46tq6OS881zNFH2dDI2MTUzFyJS688vyilmEsPaIxVNZdeWi5Qo5KqrqFJsRKXpl5yfm4SVy0Wjf//AwA "Perl 6 – Try It Online") New solution since my old one (below) might (?) be invalidated by the new rules. The output looks like: ``` < { ~ . $ } " . . . . " ) } . + s ( i + , < E w m f % . > E m a $ n + [ $ V o a m - c [ V a y _ d ) Z _ A r p t 1 o ] A p ( , e ) ] > L d : ( 4 m ~ L ) n [ # s { s b ~ # t ] 1 " 1 ( ~ 2 2 ~ 3 3 4 4 5 5 6 6 7 7 " ``` I'm not sure if this is valid output since there's no example of a normal 45 degree quine in the question itself (this one is mirrored as well as rotated). # [Perl 6](https://github.com/nxadm/rakudo-pkg), Score: -8 ``` <+map {say .indent($++),' 'x($++ <5)*16},"<$_>~~.EVAL".comb#123>>~~.EVAL ``` [Try it online!](https://tio.run/##K0gtyjH7/99GOzexQKG6OLFSQS8zLyU1r0RDRVtbU0ddQb0CxFKwMdXUMjSr1VGyUYm3q6vTcw1z9FHSS87PTVI2NDK2gwlxKYAA8eT//wA "Perl 6 – Try It Online") Pads the code by 8 lines of 5 space characters, and then adds trailing spaces to the first 5 lines. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 40 bytes, score 100 ``` ≔´α´↗´´´≔´F´α´↗´⁺´´´´´ι´↗´αα↗´≔Fα↗⁺´´ι↗α ``` [Try it online!](https://tio.run/##S85ILErOT8z5//9R55RDW85tPLTlUdv0Q1tAECzyfs8yJOFHjbsgciB4bidU9NzGcxsh0p1TgOrBHKjKczuB7HMb////r5sIAA "Charcoal – Try It Online") Based off the [standard Charcoal quine](https://codegolf.stackexchange.com/a/121529/39244) ]
[Question] [ # Task: Take a string as input and if it meets the requirements, accept the password. **Input**: a string, e.g. `someString`, `asjk23t89h`, `123456789abcdef`. **Output**: two distinct values representing "secure" and "insecure", e.g. `0`/`1`, `true`/`false`, `secure`/`insecure`. # Password requirements: In order for a password to be determined as secure, it must: * Be at least 8 characters in length. * Contain at least one character each from the four groups `a-z`, `A-Z`, `0-9` and `!"£$%^&*()_+-={}[]:@~;'#<>?,./` # Examples: * `password` -> insecure * `password123` -> insecure * `L0h~[/1s7C` -> secure * `h&fn3*#` -> insecure * `C#de g07F` -> secure # Winning: This is code golf, the shortest answer wins. [Answer] # Java 8, ~~93~~ ~~62~~ ~~65~~ 60 bytes ``` s->s.matches("([a-z]()|[A-Z]()|\\d()|.()){8,}+\\2\\3\\4\\5") ``` +3 bytes due to a bugfix, pointed out by *@MartinEnder♦*. -5 bytes thanks to *@jaytea* by using capture groups instead of lookaheads, since the matches are not overlapping. Old answer with (redundant) dictionary (**~~93~~ 96 bytes**): ``` d->s->!d.contains(s.toLowerCase())&s.matches("(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[\\W_]).{8,}") ``` ~~Because I can't think of a single word in the dictionary that contains at least one uppercase, lowercase, digit and other ASCII character.. So the dictionary-check is kinda redundant in that case.~~ **Explanation:** [Try it here.](https://tio.run/##jY/BTsMwEETv@YpVKiEbiGkbUJEikFAlTtBLb2R7cG23cUnsKHaLoIRfT13IPVxmtdqnmdkdP/DE1srs5HsnSu4cvHJtjhGANl41Gy4ULM4rwNraUnEDgix9o80WHM3CoY2COM@9FrAAAw/QueTRsYp7UShHYpLz5GtF6Hf@lLydJ6IMygilx/vr9gpxipgi3iLexbTLfsMAwqj36zK49uYHqyVUoV2fn6@A079qy0/nVcXs3rM6nHxpiGGCxHV46MM2MqY0@xc4maaD7Mu4@MlvJm42H0SLi41JL0eD3HwkFWzHs@eebKO2OwE) ``` s-> // Method with String parameter and boolean return-type s.matches("([a-z]() // Checks if the String contains at least one lowercase letter |[A-Z]() // and at least one uppercase letter |\\d() // and at least one digit .() // and at least one other ASCII character ){8,}+\\2\\3\\4\\5") // And has a length of at least 8 // End of method (implicit / single-line return-statement) ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~112~~ ~~107~~ ~~83~~ 86 bytes ``` lambda s:re.match(r'(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[\W_]).{8,}',s)!=None import re ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUaHYqihVLzexJDlDo0hdw95WTys6UbcqVhPCdNSNgjJjUqBCMeHxsZp61RY6teo6xZqKtn75ealcmbkF@UUlCkWp/wuKMvNKFNI01AsSi4vL84tS1DW5MMQMjYyRhX0MMuqi9Q2LzZ2RRTPU0vKMtZSRhZyVU1IV0g3M3dQ1/wMA "Python 2 – Try It Online") ]
[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/6634/edit) # Triangle Puzzle Consider the triangle below. This triangle would be represented by the following input file. ```    **5**   **9** 6  4 **6** 8 0 **7** 1 5 ``` By starting at the top and moving to adjacent numbers on the row below, one creates a path to the bottom of the triangle. There are many such paths in a triangle, which may have different weights. The weight of a path is the sum of all numbers encountered along the way. Write a program to find the weight of the path with the highest weight for a given triangle. In above example, the maximum sum from top to bottom is 27, and is found by following the bold text above path. 5 + 9 + 6 + 7 = 27. (More formally: The triangle is an acyclic digraph, and each number represents the value of a node. Each node has either two or zero direct successors, as shown by the arrows above. A complete path is a path which begins at the root node—the one with no immediate predecessors—and ends at a node with no immediate successors. The weight of a complete path is the sum of the values of all nodes in the path graph. Write a program which finds the weight of the complete path with the largest weight for a given triangle.) Bigger test sample data : ``` 9235 9096 637 973 3269 7039 3399 3350 4788 7546 1739 8032 9427 976 2476 703 9642 4232 1890 704 6463 9601 1921 5655 1119 3115 5920 1808 645 3674 246 2023 4440 9607 4112 3215 660 6345 323 1664 2331 7452 3794 7679 3102 1383 3058 755 1677 8032 2408 2592 2138 2373 8718 8117 4602 7324 7545 4014 6970 4342 7682 150 3856 8177 1966 1782 3248 1745 4864 9443 4900 8115 4120 9015 7040 9258 4572 6637 9558 5366 7156 1848 2524 4337 5049 7608 8639 8301 1939 7714 6996 2968 4473 541 3388 5992 2092 2973 9367 2573 2658 9965 8168 67 1546 3243 752 8497 5215 7319 9245 574 7634 2223 8296 3044 9445 120 7064 1045 5210 7347 5870 8487 3701 4301 1899 441 9828 3076 7769 8008 4496 6796 ``` [Answer] > > (More formally: The triangle is an acyclic digraph, and each number represents the value of a node. <snip /> A complete path is a path which begins at the root node—the one with no immediate predecessors—and ends at a node with no immediate successors. The weight of a complete path is the sum of the values of all nodes in the path graph. Write a program which finds the weight of the complete path with the largest weight for a given triangle.) > > > This easily generalises to any dag `G(V,E)` with weighted nodes. Perform a topological sort, and then iterate through the nodes in that order setting `weight[v] += max {weight[v'] : v' in predecessors(v)}`. Assuming a suitable representation, this is `O(E)`. As an implementation note, it may be convenient to add a dummy "sink" node with weight 0 to which all the successor-less nodes of the original graph gain an edge. Alternatively it might be convenient to iterate through the topologically sorted nodes in reverse order using successors instead of predecessors. The latter is the case given the special structure of the triangle, for which in addition it's possible to do an implicit topological sort and to use only `O(sqrt(V))` extra space (assuming that we mustn't alter the original graph and hence require extra space). ``` input: a triangular array T of n rows increasing in length from 1 to n scratch = clone T[n-1] for y = n-2 downto 0 for x = 0 to y-1 scratch[x] = T[y][x] + max(scratch[x], scratch[x+1]) output: scratch[0] ``` [Answer] # Groovy Here's a groovy script with two solutions, one using recursion and one using a "bottom-up" approach. The file "test\_sample\_data.txt" is assumed to be in the classpath. ``` // Read the sample data file, store as List<List<int>> def triangle = getClass(). getResource('test_sample_data.txt'). // get the file resource text. // contents as string split('\n'). // split into lines collect { line -> // collect rows line.split().collect { it as int } // collect columns } println "Recursive: ${findLargestWeightRecursively(triangle)}" println "Bottom up: ${findLargestWeightBottomUp(triangle)}" def findLargestWeightRecursively(List triangle, row = 0, col = 0) { def current = triangle[row][col] if (row < triangle.size() - 1) { def w1 = findLargestWeightRecursively(triangle, row + 1, col) def w2 = findLargestWeightRecursively(triangle, row + 1, col + 1) return Math.max(w1, w2) + current } else { return current } } def findLargestWeightBottomUp(List triangle) { def weights = triangle[triangle.size() - 1].clone() for (int row = triangle.size() - 2; row >= 0; row--) { def nextRow = triangle[row] for (int col = 0; col < nextRow.size(); col++) { def largest = Math.max(weights[col], weights[col + 1]) weights[col] = nextRow[col] + largest } weights.remove(weights.size() - 1) } return weights[0] } ``` **Output:** ``` Recursive: 108146 Bottom up: 108146 ``` [Answer] # My Perl Solution ## input file is named as input.txt ``` $refarray; open TRIG, "input.txt"; while(<TRIG>){ $i++; $_ =~ s/^\s+//g; $_ =~ s/\s+$//g; @num=split(/\s+/); for $j (0...$#num) { $refarray[$i]->[$j]=$num[$j]; } } close TRIG; while($i>0){ for $j (0...$i-2){ if($refarray[$i]->[$j]>$refarray[$i]->[$j+1]) { $refarray[$i-1]->[$j]+=$refarray[$i]->[$j]; } else{ $refarray[$i-1]->[$j]+=$refarray[$i]->[$j+1]; } $total=$refarray[$i-1]->[$j]."\t"; } $i-=1; } print $total; ``` [Answer] I solved this problem many years ago in a training for programming contest. Now I just translated to a modern language as C#. ``` int MaximumSum(List<List<int>> values) { // Making a copy by values of all list and validating the data at same time. var numbers = new List<List<int>>(); int index = 0; while ((index < values.Count) && (values[index] != null) && (values[index].Count == index + 1)) { numbers.Add(new List<int>()); for (int j = 0; j <= index; j++) numbers[index].Add(values[index][j]); index++; } if (index == values.Count) { /* Applying dinamic programming principles we can obtain the maximum value starting from the last row until the first one. * Storing only the optimum result until the specific value being analized. * At the end the value on the top of the triangle will be the maximum needed. */ for (int row = numbers.Count - 2; row >= 0; row--) for (int col = 0; col <= row; col++) numbers[row][col] += (numbers[row + 1][col] > numbers[row + 1][col + 1]) ? numbers[row + 1][col] : numbers[row + 1][col + 1]; return numbers[0][0]; } else { throw new Exception("Invalid data"); } } ``` [Answer] Ruby, 2nd version ``` t=%w{ 1 2 1 3 2 1 4 3 2 1 5 4 3 2 1 1 2 3 4 5 10000 }.map &:to_i l = [] i=1 loop do l.push t.slice!(0,i) i += 1 break if t == [] end trees = [0, 1].repeated_permutation(l.length-1).to_a.map! do |tree| [0].concat tree end trees.map! do |tree| newt = [] tree.each_with_index do |e, i| newt.push tree.slice(0, i+1).inject :+ end newt end rr = [] trees.each do |t| r = 0 t.each_with_index do |v, i| r += l[i][v] end rr.push r end p rr.max ``` Code above outputs: `10005` Sample of data in the question results to `108146` [Answer] Python Put the triangle in a file called "triangle.txt", with whitespace only between the numbers. ``` f=open("triangle.txt", "r") triangle=eval("[["+f.read().replace(" ", ",").replace("\n", "],[")[:-4]+"]]") f.close() for i in range(len(triangle)-2, -1, -1): for j in range(len(triangle[i])): triangle[i][j]+=max(triangle[i+1][j+1],triangle[i+1][j]) del triangle[i+1] print triangle[0][0] ``` Example Triangle: ``` 1 ( 1 ) 2 3 ( 2 3 ) 4 5 6 ( 4 5 6 ) ``` The 2 has 4, 5 below it. 5>4, so replace the 2 with 2+5=7. The 3 has 5, 6 below it. 6>5, so replace the 3 with 3+6=9. ``` 1 ( 1 ) 7 9 ( 7 9 ) ``` The 1 has 7, 9 below it. 9>7, so replace the 1 with 1+9=10. There are no more rows to process, so the maximal sum is 10. [Answer] # Q ``` t:"I"$'/:" "vs'read0`t; {(-2_x),enlist (1_mmax[2;last x])+last -1_x}/[count[t]-1;t] exit 0 ``` It assumes the triangle is a space separated triangle of integers stored in a file called t. On the second test case: ``` $ time q tri.q -q 108146 real 0m0.018s user 0m0.010s sys 0m0.010s ``` [Answer] Here is my solution implementation in java. I got idea from this <https://stackoverflow.com/a/8002423/205585> ``` package com.euler.problems; import java.util.*; public class Problem18 { private static Map<Integer,List<Integer>> triangle = new HashMap<Integer,List<Integer>>(); public static void main(String args[]) { _init(); int res = maxSum(triangle); System.out.println("Sum = "+res); } //max sum from top to bottom of right angled triangle public static int maxSum(Map<Integer,List<Integer>> triangle) { int sum = 0; if(triangle == null || triangle.isEmpty()) return 0; int size = triangle.size(); if(size == 1) return triangle.get(0).get(0); int i=size-2,tmp,tmp_max,max_value; while(i>=0) { List<Integer> current_row = new ArrayList<Integer>(); current_row = triangle.get(i); for(int index=0; index<current_row.size(); index++) { tmp = current_row.get(index); tmp_max = tmp+triangle.get(i+1).get(index); max_value = tmp+triangle.get(i+1).get(index+1); if(tmp_max > max_value) max_value = tmp_max; current_row.set(index,max_value); } triangle.put(i,current_row); current_row = null; i--; } return triangle.get(0).get(0); } private static void _init() { List<List<Integer>> tuples = new ArrayList<List<Integer>>(); tuples.add(Arrays.asList(75)); tuples.add(Arrays.asList(95,64)); tuples.add(Arrays.asList(17,47,82)); tuples.add(Arrays.asList(18,35,87,10)); tuples.add(Arrays.asList(20,4,82,47,65)); tuples.add(Arrays.asList(19,1,23,75,3,34)); tuples.add(Arrays.asList(88,2,77,73,7,63,67)); tuples.add(Arrays.asList(99,65,4,28,6,16,70,92)); tuples.add(Arrays.asList(41,41,26,56,83,40,80,70,33)); tuples.add(Arrays.asList(41,48,72,33,47,32,37,16,94,29)); tuples.add(Arrays.asList(53,71,44,65,25,43,91,52,97,51,14)); tuples.add(Arrays.asList(70,11,33,28,77,73,17,78,39,68,17,57)); tuples.add(Arrays.asList(91,71,52,38,17,14,91,43,58,50,27,29,48)); tuples.add(Arrays.asList(63,66,4,68,89,53,67,30,73,16,69,87,40,31)); tuples.add(Arrays.asList(4,62,98,27,23,9,70,98,73,93,38,53,60,4,23)); int i=0; for(List<Integer> tuple : tuples) { triangle.put(i++,tuple); } //print for(Integer key : triangle.keySet()) { System.out.println(triangle.get(key)); } } } ``` [Answer] Haskell solution ``` maximizeTree tree | length tree == 1 = head . head $ tree | otherwise = maximizeTree (take (length tree - 2) tree ++ [zipWith (\a b -> maximum a + b) (pairUpList . last $ tree) (tree !! (length tree - 2))]) where pairUpList list = [[list !! n, list !! (n + 1)] | n <- [0 .. (length list - 2)]] maximizeTree [[5], [9, 6], [4, 6, 8], [0, 7, 1, 5]] ``` [Answer] Python solution where the file is read as list of lists and processed bottom up: ``` from io import open def parse_file(fpath): return [[int(i) for i in l.strip('\n').split()] for l in open(fpath, "r").readlines()] def process_row(lower, upper): results = [] for i in range(0,len(upper)): results.append(upper[i] + max(lower[i], lower[i+1])) return results def traverse_triangle_bottom_up(triangle): triangle.reverse() results = triangle.pop(0) for row in triangle: results = process_row(results, row) return results[0] triangle = parse_file("triangle.txt") max_weight = traverse_triangle_bottom_up(triangle) print(max_weight) ``` ]
[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/26910/edit). Closed 9 years ago. [Improve this question](/posts/26910/edit) **This is the goal:** count from 0 all the way to the current epoch time while the epoch time is still advancing in the fastest time possible. An example of how you'd do it could be as what is shown here in Python 2.7: ``` from time import time start, end, count = None, None, 0 while count <= time(): if start == None: start = time() count += 1 end = time() ``` The above code took 10 minutes and 8 seconds to run through on an 8-core AMD with 16 GB of RAM. You must do it faster than that without skipping numbers and starting from zero. # Scoring Achieving a lower time than what Python did is the goal in addition to using the least amount of code too, but special attention will be given to the following: * Code that takes the precise epoch time sourced from your counting to display something mentioning historical events or irrelevant ones that can be found on Wikipedia. (10 points) * Getting the current epoch time from a source other than your own. (5 points) * Your application continues to count alongside the epoch time after it catches up. (5 points) 50 points will be awarded to the person who achieves the lowest time and additional bonus points will be awarded from above if they're met. # Deadline The contest closes June 1st. [Answer] # C, about 5 seconds ``` #include <stdio.h> #include <time.h> int main(){ time_t t=0, margin=0x40000000; int i; while (margin) { for (i=0;i<margin;i++) t++; while (margin && time(NULL)-t < margin) margin /= 2; } printf("t=%ld, time=%ld\n",t,time(NULL)); return 0; } ``` [Answer] # Java : 140 **No bonuses, ~60ms runtime** Sets the start time in `j` and doesn't check time again until `j` is reached. Once it is, it keeps counting up to current time. Generally it only needs to check the time twice, since it runs in well under a second. ``` class N{public static void main(String[]a){for(int i=0,j=t();i++<j||i<t(););}static int t(){return (int)(System.currentTimeMillis()/1000);}} ``` Line breaks for clarity: ``` class N{ public static void main(String[]a){ for(int i=0,j=t();i++<j||i<t();); } static int t(){return (int)(System.currentTimeMillis()/1000);} } ``` ]
[Question] [ **This question already has answers here**: [How many syllables in that number?](/questions/177586/how-many-syllables-in-that-number) (13 answers) Closed 4 months ago. # Task Your boss is on another crusade for 'efficiency.' He wants to encourage the use of numbers with fewer syllables, so that they're easier to *discuss* in meetings. If you want to take some time off work, you're boss would prefer you take `9` days instead of `7`. You're boss would prefer a credit card expense of `$99,502` over `$77,601` ## Input You can chose your input format for the numbers, if you want to take in `7/9` or `seven/nine` it's completely up to you ## Output Output whichever number has the least syllables. ***CATCH!*** You must output the answer in the same format you chose for the input. So if your program takes in `7/9` as input, it must output `9`. And if your program takes in binary numbers as the input, such as `0000111/0001001`, then it must output the answer as `0001001` ## Examples I used [howmanysyllables.com](https://www.howmanysyllables.com/) to find the amount of syllables in each number: | `Input` | `Syllables` | `Output` | | --- | --- | --- | | `7\9` | `2 vs 1` | `9` | | `ninety nine\one hundred and five` | `3 vs 5` | `ninety nine` | | `0111101\1100011` | `3 vs 3` | `0111101 1100011` | | `seventy seven thousand six hundred and one\ninety one thousand five hundred and two` | `12 vs 10` | `ninety one thousand five hundred and two` | | `10011111111011\10111111111111` | `10 vs 11` | `10011111111011` | | `13\15` | `2 vs 2` | `13 15` | ## Additional rules 1. Numbers must include `and` where appropriate. For example, `105` should be calculated as `one hundred and five` instead of `one hundred five`. I know some people might include `and` more than others when pronouncing numbers, so this is open to change in future depending on feedback! 2. If both numbers have the same number of syllables, output both numbers in the format you took them in 3. The input will only ever be a positive integer ## Numbers/Syllables > > 1,2,3,4,5,6,8,9,10,12 = 1 syllables > > > > > 7,13,14,15,16,18,19,20 = 2 syllables > > > > > 11,17,21,22,23,24,25,26 = 3 syllables > > > > > 27 = 4 syllables > > > This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so **the shortest program wins!** [Answer] # [sed](https://www.gnu.org/software/sed/) `-E`, 120 bytes ``` h;s/n//g;s/[ls]e/##/g;s/ve/-/g;s/[aeiou]+/#/g;s/y/#/g;s/[^#,]//g;G;s/^(#*)#+,\1\n.*,//;s/^(#*),\1#+.(.*),.*/\2/;s/.*\n// ``` [Try it online!](https://tio.run/##lY3BDoIwEETv/kYvWEo3evVs/AgKCUlXaGK2hm0J/Ly1gN412WR23sxmGW3VU0xpuDAQQJ@lfnCDIMRmJoRqpx06H5sSdr58tG6Fata7WzZtIeRRlMqcDGmpAL4sE1HqQudNSzDnNdDS5IcphWFEHCLZEW1Hlt0clrubUDFOSGHZ5PBTK/jIOfyrnMcTvvwzOE@cqusb "sed – Try It Online") ]
[Question] [ **This question already has answers here**: [Sum of primes between given range](/questions/113/sum-of-primes-between-given-range) (61 answers) Closed 7 months ago. Given a number x, find the sum of all primes up to that number. The input will always be a positive number, bigger than 2. An upper limit isn't defined, so data types can be ignored. Use whichever you want. * This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins. Example for 5: `2 + 3 + 5 = 10` Test cases: | Input | Output | | --- | --- | | 2 | 2 | | 3 | 5 | | 17 | 58 | The input doesn't have to be parsed, so assume you get the "correct" data-type. (`int` in Java, for example) [Answer] # [Thunno 2](https://github.com/Thunno/Thunno2) `S`, 2 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md) ``` æP ``` [Try it online!](https://Not-Thonnu.github.io/run#aGVhZGVyPSZjb2RlPSVDMyVBNlAmZm9vdGVyPSZpbnB1dD0xNyZmbGFncz1T) #### Explanation ``` # Implicit input æ # Filter [1..input] by: P # Prime check # Sum the list # Implicit output ``` ]
[Question] [ **This question already has answers here**: [Build a typing speed test / measuring CPM](/questions/5763/build-a-typing-speed-test-measuring-cpm) (9 answers) Closed 11 months ago. # Description a typeracer is an apps where user could type and evaluate their typing speed and accuracy. # Criteria * User could type "A quick brown fox jumps over the lazy dog." * A visual indicator of each wrong character typed. * A visual indicator of what characters to type. * A visual indicator of what has been typed * A visual indicator of what hasn't been typed. * After the last character is typed, shows time it took, WPM, and accuracy. + Time it took: since first character typed till the last character typed + WPM: round(right character typed/5) + Accuracy: right characters / all characters [Answer] I'm quite new to code golf forum. I've written a type racer with criteria above. <https://ramsicandra.com/type-racer.html> <https://github.com/ramsicandra/simple-type-racer> ]
[Question] [ **This question already has answers here**: [Line ending conversion program](/questions/101374/line-ending-conversion-program) (3 answers) Closed 3 years ago. Inspired by what I'm doing at work right now. Your program should take one parameter, the path to the file It should convert all the windows style newlines (\r\n) to unix style (\n) and write the result back to the file [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~22~~ bytes Anonymous tacit prefix function. ``` 10@3∘⎕NGET⎕NPUT{⍵1} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///v1rjUVfzo76pfu6uIY96t2qqqxsagLgBoSCuYe3/tEdtEx719oFU9a551Lvl0HrjR20TgUqCg5yBZIiHZ/B/EM9DPTU5I19BN1VBKTEppigmLzklNQ1Ep2fEFCkp2CmUpBaXqHNBlFZUpED5aQrqWCUA "APL (Dyalog Unicode) – Try It Online") `⎕NGET` get content,encoding,line-ending from argument file `10@3∘` replace the third element (line ending) with 10, meaning \n `⎕NPUT` put that into… `{⍵1}` the file name followed by an overwrite flag ]
[Question] [ **This question already has answers here**: [Remove common leading spaces](/questions/53219/remove-common-leading-spaces) (30 answers) Closed 5 years ago. Write a program which removes any common leading spaces from the input string. For example, if the *least* indented line started with 3 spaces, and every other line has `>=` 3 leading spaces, then remove 3 spaces from the beginning of each line. The indentation consists solely of spaces, and the string will not contain any tabulation. This is the same as the `textwrap.dedent` function in python. Example (input, output): ### Input ``` 7aeiou 3b 555 ``` ### Output ``` 7aeiou 3b 555 ``` ### Input ``` this is a test ``` ### Output ``` this is a test ``` ### Input ``` Hello world ``` ### Output ``` Hello world ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 11 bytes ``` *.indent(*) ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPtfSy8zLyU1r0RDS/O/NVdxYqVCmoaSAgSYJ6Zm5pdyAVnGSVxgEVNTUyXN/wA "Perl 6 – Try It Online") ]
[Question] [ **This question already has answers here**: [Determine if an integer is a palindrome in a given radix (base)](/questions/22449/determine-if-an-integer-is-a-palindrome-in-a-given-radix-base) (22 answers) Closed 5 years ago. write a function to tell if a number is symmetric or not. for example: input: 151 output: True input: 142 output: False and so on: 1111 True, 2390 False, 1226221 True [Answer] # [Python 2](https://docs.python.org/2/), 23 bytes ``` lambda n:`n`==`n`[::-1] ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSHPKiEvwdYWSERbWekaxv4vKMrMK1FI0zA0NdRUVsgvLSkoLbFSCCkqTeXigsuZGCHJuSXmFCNLAgFQFqRDRwEuamRsaQAUBatFEjY0MjIzMoKp/w8A "Python 2 – Try It Online") ]
[Question] [ **This question already has answers here**: [AlTeRnAtE tHe CaSe](/questions/122783/alternate-the-case) (41 answers) Closed 5 years ago. Your goal is to alternate uppercase and lowercase letters, while ignoring non-alphaneumeric characters. ``` Input => Output abc => aBc OR AbC a c => A c OR a C abc123abc => AbC123aBc OR aBc123AbC ``` Shortest answer wins. [Answer] # JavaScript, 116 ``` s=>{x=!0;return s.split("").map(e=>{if(e.match(/[a-zA-Z]/))x=!x;return x?e.toUpperCase():e.toLowerCase()}).join("")} ``` Saved two bytes thanks to NTCG ]
[Question] [ **This question already has answers here**: [Mozilla/1.0 Mozilla/2.0 Mozilla/3.0 Mozilla/4.0 Mozilla/5.0](/questions/137816/mozilla-1-0-mozilla-2-0-mozilla-3-0-mozilla-4-0-mozilla-5-0) (5 answers) Closed 6 years ago. # Background Many people visit webpages, which require special browsers because of lack of compatibility. So you have to write a script (client sided or server sided), which just prints the name of the browser. Because not everyone has fast internet, the script has to be as short as possible. (This is a joke xD) # Rules 1. You have to print the name of the browser loading the page without any version number etc. to STDOUT or equivalent. Leading or trailing spaces are allowed. 2. You can assume the browser is Firefox, Chrome, Edge, Safari or Opera, so only those browsers will be tested. Don't print "Chromium", this does NOT count. 3. The script may be server sided with CGI (in any language), ruby on rails, jsp and similar. (Given server will be apache 2 on debian) Client sided scripts may be written in JavaScript, TypeScript, and any other versions of ECMAScript, it just has to run in all five browsers. 4. If your language has no offline interpreter for CGI, assume it's saved in /usr/bin/i, the shebang at the beginning does not add bytes to the count. 5. This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer wins! 6. Http requests are put through stdin. [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~55~~ 52 bytes *-3 bytes thanks to Shaggy* ``` Ox`nàÀÓ&.ÔÀAgt` `SafÂÈOpÀCËTFifoxnEdge`qn f!øU o ``` [Try it!](https://ethproductions.github.io/japt/?v=1.4.5&code=T3hgbuDA0yYu1MBBZ4F0YApgU2FmwshPcMAYQ8tUgUZpnGZveG5FZGdlYHFuIGYh+FUgbw==&input=) ]
[Question] [ **This question already has answers here**: [Print your code backwards - reverse quine](/questions/16021/print-your-code-backwards-reverse-quine) (72 answers) Closed 6 years ago. Well the title says it all. * Standard loopholes apply * Nothing to read from stdin, and output goes to stdout * 1-byte-long programs are... nonsense. They don't qualify * A program with a single byte repeated is also a nonsense (like `aaa`) * **Please mark it out if your program is a palindrome** Sample: > > A program with source code > > > > ``` > abcde > > ``` > > should output > > > > ``` > edcba > > ``` > > Because this is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest program wins! [Answer] # [RProgN 2](https://github.com/TehFlaminTaco/RProgN-2), 3 bytes ``` 1 0 ``` [Try it online!](https://tio.run/##Kyooyk/P0zX6/9@Qy@D/fwA "RProgN 2 – Try It Online") Pretty sure this has been submitted before, but here's one in RProgN 2. It outputs ``` 0 1 ``` ]
[Question] [ **This question already has answers here**: [Three-Three-Three!](/questions/108133/three-three-three) (94 answers) Closed 6 years ago. This is the sequel to one of my previous challenges, [Three-Three-Three!](https://codegolf.stackexchange.com/questions/108133/three-three-three) --- Write a program (or function, or snippet) that takes no input and produces an output according to the following four Conditions. > > Both the program and the output must be written such that: > > > 1. At least 16 distinct characters appear (since 16 = 4 × 4). > 2. The number of occurrences of each character is a multiple of 4. > > > Also: > > > 3. The program and the output must not be the same (because [programs consisting of a single literal like `1111222233334444` are quite boring](https://codegolf.stackexchange.com/a/108142/47097)). > > > Finally, the program: > > > 4. Cannot be written as a string repeated 4 times (e.g. `f();f();f();f();`, `1234123412341234`). > > > It's [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'")! In anticipation of a multi-way tie for 64 bytes, the first submission whose *output* also satisfies Condition 4 will be the winner. ## Notes * You are encouraged not to use comments to satisfy Conditions 1 and 2. * Feel free to [embed wild bananas in your variable names](https://codegolf.stackexchange.com/questions/108133/three-three-three#comment263154_108145) as you see fit. [Answer] # CJam, 16 bytes ``` 4,4,4,4,@@@@\\\\ ``` [Try it online!](https://tio.run/##S85KzP3/30QHAh2AIAYI/v8HAA) ]
[Question] [ **This question already has answers here**: [Program that creates larger versions of itself (quine-variant)](/questions/21831/program-that-creates-larger-versions-of-itself-quine-variant) (64 answers) [Generate Programs in Increasing size](/questions/69504/generate-programs-in-increasing-size) (7 answers) Closed 7 years ago. Your job is to write a program that rewrites and makes itself longer on each run of the program. # Challenge The program will print `Hello, World!\n` (`\n` denotes a newline). Then, it will modify its own file so that the new program length is exactly 2x the length at runtime. This modified file when run, will print `Hello, World!\nHello, World!\n`. When run a third time, the file will print `Hello, World!\nHello, World!\nHello, World!\nHello, World!\n`. More simply, on the `n`th run of the program, it will output `2^(n-1)` instances of `Hello, World!\n`, and have a program length of `2^(n-1)` the length of the original. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code (before first run) wins. Please comment if you need something is not clear. **Edit:** To get past the restriction of file-rewriting, your program may print the modified source along with the `Hello, World!\n`s at a **+40%** penalty. [Answer] # PHP, 100 ## More efficient, 101 ``` <?$a=$argv[0];$b=file_get_contents($a);file_put_contents($a,$b.substr($b,81,20));echo"Hello World\n"; ``` This script is appending an `echo"Hello World";`, but because you said the size should also vary, and because it's shorter, I'm also having this script: ## Shorter, 100 ``` <?$a=$argv[0];$b=file_get_contents($a);file_put_contents($a,$b.substr($b,2,98));echo"Hello World\n"; ``` This script is appending itself, in a way it adds one Hello World, but this version will overall take more space and takes longer to execute. ## Example But the scripts don't vary when it comes to the output: ``` root@raspberrypi:~/stack# php hello_expand.php Hello World root@raspberrypi:~/stack# php hello_expand.php Hello World Hello World root@raspberrypi:~/stack# php hello_expand.php Hello World Hello World Hello World ``` ]
[Question] [ **This question already has answers here**: [Converting integers to English words](/questions/12766/converting-integers-to-english-words) (14 answers) Closed 10 years ago. I took inspiration from a challenge I did some years ago in a programming competition. Your goal is to write a **function** that generates a random **integer** number between **0** and **150** (included), and then prints it in actual words. For example, *139* would be printed as *onehundredthirtynine*. **Rules:** * You cannot use any external resource, nor any library that will perform the conversion. * The shortest answer will win. Good luck! [Answer] # Lua ``` print"four" ``` Highly optimized and golfed [xkcd's random number generator](http://xkcd.com/221/) # An actual solution, 380 ``` x=math.random(0,150)m=math.floor print(x==0 and"zero"or((x>99 and"onehundred"or"")..(({"ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen"})[x%100-9]or({[0]="",nil,"twenty","thirty","fourty","fifty","sixty","seventy","eighty","ninety"})[m(x/10)%10]..({[0]="","one","two","three","four","five","six","seven","eight","nine"})[x%10]))) ``` ]
[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/10903/edit) so it's [on-topic](/help/on-topic) for Code Golf Stack Exchange. Closed 10 years ago. [Improve this question](/posts/10903/edit) I'm trying to come up with ways to write Sieve of Eratosthenes in Octave that vectorize as much as possible (ie minimizing the number of times iterating over the for-loop/while-loop/recursive call) I found one that requires only O(log(log(n))) iterations inside the for-loop, but the big-O running time (and also space) is O(n^(5/4)/log(n)) so it's arguably not the Sieve of Eratosthenes Now I think I have one with the usual running time O(nlog(log(n))) and only O(log(n)) iterations, but I want to see if someone else comes up with a better solution. [Answer] Here's my solution The loop clearly runs O(logn) times and it's easy to see that the number of operations is bounded above by the normal number of operations for SOE(2n) so it's within O(nlog(logn)) big-O running time ``` function [primes] = eratosieve(n) isprime = ones(n, 1); isprime(1) = false; m = 1; while(m ^ 2 < n) nprimes = find(isprime(m + 1 : m * 2)) + m; mult = (m + 1) : (n/(m + 1)); a = nprimes * mult; isprime(a(a<=n)) = false; m *= 2; end primes = find(isprime); endfunction ``` ]
[Question] [ **This question already has answers here**: [Day of the week of the next Feb 29th](/questions/1003/day-of-the-week-of-the-next-feb-29th) (12 answers) Closed 10 years ago. Knowing a given date (`11/28/1973`), and supposing I will die when I'm 99, what are the years when my birthday will be a thursday so that I will be able to party all week-end? [Answer] js ``` var y = 1973 + 99; while(y-- > 1973) 4!=new Date('11/23/'+y).getDay()||console.log(y); ``` [Answer] Something like this: **c#** ``` var birthdate = new DateTime(1973,11,28); for (int i = 0; i <= 99; i++) { var date = birthdate.AddYears(i); if (date.DayOfWeek.Equals(DayOfWeek.Thursday)) { Console.WriteLine(date.Year); } } ``` ]
[Question] [ ## Introduction The challenge itself was something I came across and had to try and figure out for a personal of project of mine. I ended up branching out and asking family members if they could provide an equation to meet the requirements. **Note:** I have (with the help of others) found a solution for this but now I'm just trying to see how others would approach this. ## Challenge Take the following scenario where the left hand side number is N (the input): ``` N Output 0 -> 9 1 -> 99 2 -> 999 3 -> 9999 4 -> 99,999 5 -> 999,999 ... 15 -> 9,999,999,999,999,999 ``` So, essentially, for an input number **N**, your program must provide the highest integer with **N + 1** decimal places. **Note:** Commas are not required to separate the numbers, I placed them above purely for readability. ## Criteria of Success The criteria of success is based on the following: * Shortest in terms of code size [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 3 bytes ### Code: ``` >°< ``` Uses the **05AB1E** encoding. [Try it online!](https://tio.run/##MzBNTDJM/f/f7tAGm///TQA "05AB1E – Try It Online") ### Explanation: ``` > # Increment the implicit input ° # Compute 10 ** (input + 1) < # Decrement the result ``` [Answer] # [Neim](https://github.com/okx-code/Neim), 3 bytes ``` >9𝕣 ``` Explanation: ``` > Increment input 9𝕣 Repeat 9 ``` [Try it online!](https://tio.run/##y0vNzP3/387yw9ypi///NwUA "Neim – Try It Online") [Answer] # [Proton](https://github.com/alexander-liao/proton), 11 bytes ``` (1+)+("9"*) ``` [Try it online!](https://tio.run/##KyjKL8nP@59m@1/DUFtTW0PJUklL839BUWZeiUaahomm5n8A "Proton – Try It Online") This is a function. # Explanation ``` (1+)+("9"*) Function 1+ Anonymous function; add the input to 1 "9"* Anonymous function; multiply "9" by the input + Function Composition; add the input to 1 then multiply "9" by this number ( ) ( ) Brackets for order of operations ``` :o proton beats python with its function composition for once :D [Answer] # [J](http://jsoftware.com/), 7 bytes Anonymous tacit prefix function ``` 9^&.>:] ``` [Try it online!](https://tio.run/##y/r/P83WyjJOTc/OKvZ/anJGvkKagoGCoYKRgrGCiYKpgqFpxX8A "J – Try It Online") `9^`…`]` nine raised to the power of the argument  `&.`… while both nine and the argument are under the influence of   `>:` increment I.e. increment nine and the argument, then power, then un-increment, i.e. decrement. Effectively `((9+1)^(n+1))-1`. [Answer] # APL+WIN, ~~9~~ 5 bytes Thanks to ngn for -3 bytes and Adám for -1 byte Prompts for integer input: ``` 1⎕/⍕9 ``` [Answer] # [99](https://github.com/TryItOnline/99), 90 bytes ``` 999 9999 9 9 99999 99 9 9999 9 999 999 9999 9 99999 999 999 9 999999 999 9 9999 ``` [Try it online!](https://tio.run/##s7T8/1/B0tKSC4gtFYAQzADSYA6YxQXhw7mcnJxcIABWiJDkAstDeFxQzf//mwAA "99 – Try It Online") Possibly not optimal, but it was fun to write. EDIT: looks like I was right, as [Jo King outgolfed me](https://codegolf.stackexchange.com/a/163816/67312) by not incrementing the input and being smarter about the gotos. ``` 999 assign input to tri-nine 9999 9 9 assign 0 to quad-nine 99999 99 9 9999 9 assign 81 to quint-nine for printing 999 999 9999 9 increment tri-nine 99999 print 81/nine (the numeral nine) 999 999 9 decrement tri-nine 999999 999 if tri-nine is zero exit program (goto outside program) 9 9999 else goto line nine ``` [Answer] # [*99*](https://github.com/TryItOnline/99), 69 bytes ``` 9999 9 9 99999 99 9 9999 9 999 99999 99 999 999 999 9 9 9999 ``` [Try it online!](https://tio.run/##s7T8/98SCBSAkMsSwgJzwCwuEM0FAWBJLrCsJVipAkwJWDHQGAA "99 – Try It Online") Appropriate (but it's a pity that this didn't end up at 99 bytes) ### Explanation ``` 9999 9 9 9999 = 9-9 99999 99 9 9999 9 99999 = 99-9+(9-9)-9 = 9*9 999 999 = input*9 Filler to get up to line 9 99999 Print (9*9)/9 as a number 99 999 Jump to line 99 if 999 is 9-9 999 999 9 999 = 999 - 9 9 9999 Jump unconditionally to line 9 ``` [Answer] # [Actually](https://github.com/Mego/Seriously), 3 bytes ``` u╤D ``` Explanation: ``` u Increment input ╤ 10 ** x D Decrement ``` [Try it online!](https://tio.run/##S0wuKU3Myan8/7/00dQlLv//mwIA "Actually – Try It Online") [Answer] # [MATL](https://github.com/lmendo/MATL), 6 bytes ``` Q10w^q ``` [Try it online!](https://tio.run/##y00syfn/P9DQoDyu8P9/YwA "MATL – Try It Online") ### Explanation: ``` Q % Grab input and increment by 1 10 % Push 10 w % Swap stack ^ % Raise 10 to the power of input+1 q % Decrement by 1 ``` [Answer] # Pyth, 4 ``` *\9h ``` [Online test](https://pyth.herokuapp.com/?code=%2A%5C9h&input=0%0A1%0A2%0A3%0A4%0A5%0A15&test_suite=1&test_suite_input=0%0A1%0A2%0A3%0A4%0A5%0A15&debug=0). ### Explanation ``` Q # Implicit input h # Increment *\9 # Repeat string "9" n+1 times ``` [Answer] # [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), 8 ``` A?1+^1-p ``` [Try it online!](https://tio.run/##S0n@/9/R3lA7zlC34P9/EwA "dc – Try It Online") ### Explanation ``` A # Push 10 ? # Push input 1+ # Increment input ^ # Raise 10 to the (input + 1)th power 1- # Decrement p # Print ``` [Answer] # [Haskell](https://www.haskell.org/), ~~14~~ 13 bytes ``` f n=10*10^n-1 ``` Or for string output 15 bytes, `f n='9'<$[0..n]` Thanks to @EsolangingFruit for a byte. [Try it online!](https://tio.run/##y0gszk7Nyfn/P00hz9bQIE4jT9tQU9fwf25iZp6CrUJBaUlwSZFPnoKSn4KCgn9pCVBAScHOTiE3scA3XkEjJlPXTkEDokqvOCO/XDMTJAsRUFBSeNQ2SQGsvqAoM69EQSNNIVNTUyHaQE/PNPY/AA "Haskell – Try It Online") [Answer] # [Zsh](https://www.zsh.org/), 19 bytes [Zsh](https://www.zsh.org/) does a better job than [Bash](https://www.gnu.org/software/bash/) ([needs eval](https://tio.run/##S0oszvj/P7UsMUehoCgzryRNwVJVr1ih2kBPT8Ww9v///4YA)): ``` printf 9%.s {0..$1} ``` [Try it online!](https://tio.run/##qyrO@P@/oCgzryRNwVJVr1ih2kBPT8Ww9v///4YA "Zsh – Try It Online") ### Alternative, 20 bytes This works for both [Zsh](https://www.zsh.org/) and [Bash](https://www.gnu.org/software/bash/) (due to [Digital Trauma](https://codegolf.stackexchange.com/users/11259/digital-trauma?tab=profile)): ``` echo $[10**($1+1)-1] ``` [Try it online!](https://tio.run/##qyrO@P8/NTkjX0El2tBAS0tDxVDbUFPXMPb////GAA "Zsh – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 16 bytes ``` lambda a:"9"*-~a ``` [Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSHRSslSSUu3LvF/QVFmXolGmoaJpuZ/AA "Python 3 – Try It Online") Just a simple anonymous function. [Answer] # [JavaScript (Node.js)](https://nodejs.org), 18 bytes ``` x=>"9".repeat(x+1) ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@7/C1k7JUkmvKLUgNbFEo0LbUPN/cn5ecX5Oql5OfrpGmoappibXfwA "JavaScript (Node.js) – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes ``` ‘⁵*’ ``` [Try it online!](https://tio.run/##y0rNyan8//9Rw4xHjVu1HjXM/P//vykA "Jelly – Try It Online") ``` ‘⁵*’ - Main link. Argument: n (integer) ‘ - n+1 ⁵* - 10 ** (n+1) ’ - (10 ** (n+1)) - 1 ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 4 bytes ``` R'9→ ``` [Try it online!](https://tio.run/##yygtzv7/P0jd8lHbpP///xsAAA "Husk – Try It Online") ``` R'9→ -- example input: 3 → -- increment: 4 R'9 -- replicate the character '9': ['9','9','9','9'] -- implicitly print "9999" ``` [Answer] # [Canvas](https://github.com/dzaima/Canvas), 3 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md) ``` ╵9× ``` [Try it here!](https://dzaima.github.io/Canvas/?u=JXUyNTc1OSVENw__,i=NQ__,v=2) ``` ╵ increment the input 9 push "9" × repeat the "9" input+1 times ``` [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 48 bytes ``` ({}()){({}<(((((()()()){}()){}){}){}())>[()])}{} ``` [Try it online!](https://tio.run/##SypKzMzTTctJzP7/X6O6VkNTsxpI2WiAgSYIakJEayEIyLSL1tCM1aytrv3/3/C/riMA "Brain-Flak – Try It Online") This uses the `-A` to enable ASCII output. Bonus round: A version without `-A`. # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 50 bytes ``` ({}(())){({}<((({})(({}){}){}){})>[()])}{}({}[()]) ``` [Try it online!](https://tio.run/##SypKzMzTTctJzP7/X6O6VkNDU1OzGsiw0dAAkppgAo7sojU0YzVrgcqqa8HM//8NAQ "Brain-Flak – Try It Online") [Answer] # [Momema](https://github.com/ScratchMan544/momema), 21 bytes ``` a00+1*0-8 9a=+*0-+1_A ``` [Try it online!](https://tio.run/##y83PTc1N/P8/0cBA21DLQNdCwTLRVhvI0DaMd/z/39LS8l9@QUlmfl7xf91MAA "Momema – Try It Online") Requires the `-i` interpreter flag. ## Explanation A brief rundown of Momema's features: * Its only data type is the unbounded integer. It has a double-ended tape (indexed by unbounded integers) where every number is initialized to zero. * Strings of digits are integer literals which evaluate to themselves. Leading zeroes are parsed as their own integers. * `+ab` evaluates to the sum of `a` and `b`. * `-a` evaluates to the negation of `a`. * `*a` evaluates to the value of cell `a` on the tape. * `=a` evaluates to 0 if `a` evaluates to 0, and `=` otherwise. * At the top level, `ab` stores `b` at cell `a` on the tape. Attempting to write a number to `-8` writes its decimal representation to STDOUT instead. * At the top level, `[w]a` (where `[w]` is any string of lowercase letters) acts like "relative jump forward by `a` jump instructions that share the label `[w]`." * The Momema reference implementation accepts a flag `-i`, which activates interactive mode. In interactive mode, `_[W]` (where `[W]` is any string of uppercase letters) is called a *hole* and evaluates to a number read from STDIN. However, it caches the number with its label, so if a hole with the same label is ever evaluated again it will be reused. Knowing this, here's how you expand this program: ``` a 0 # do { 0 (+ 1 (* 0)) # n = n + 1 -8 9 # print 9 a (= (+ (* 0) (- (+ 1 _A)))) # while (n != input) ``` (This still parses, by the way; the Momema parser treats parentheses the same way as whitespace.) --- ``` a 0 ``` Jumps forward by 0 `a` instructions (i.e. does nothing). This is only here to serve as a jump target later. ``` 0 (+ 1 (* 0)) ``` Increments the value of cell 0 (initially 0) and stores it back in cell 0. ``` -8 9 ``` `-8` is memory-mapped for numeric I/O, so this outputs `9` to STDOUT. ``` a (= (+ (* 0) (- (+ 1 _A)))) ``` Compute `tape[0] - (input + 1)`. If it is zero (i.e. both sides were equal), then `=` maps the result to 0, making it a no-op. Control runs off of the end of the program. However, if it is nonzero, this is a `1`. Since there are no `a` instructions after here, it wraps around to the beginning of the program. [Answer] # [brainfuck](https://github.com/TryItOnline/brainfuck), ~~24~~ 23 bytes thanks to [Jo King](https://codegolf.stackexchange.com/users/76162/jo-king) for -1 byte ``` -[++>+[+<]>]>+<,+[->.<] ``` [Try it online!](https://tio.run/##SypKzMxLK03O/v9fN1pb2047Wtsm1i7WTttGRzta107PJvb/f04A "brainfuck – Try It Online") Takes input as ASCII [Answer] # [Whitespace](https://web.archive.org/web/20150618184706/http://compsoc.dur.ac.uk/whitespace/tutorial.php), 79 bytes ``` [S S S T S T S N _Push_10][S N S _Duplicate_10][S N S _Duplicate_10][S N S _Duplicate_10][T N T T _Read_STDIN_as_integer][T T T _Retrieve_input][N S S N _Create_Label_LOOP][S S S T N _Push_1][T S S T _Subtract][S N S _Duplicate][N T T S N _If_negative_Jump_to_Label_EXIT][S N T _Swap][S T S S T S N _Copy_2st][T S S N _Multiply][S N T _Swap][N S N N _Jump_to_Label_LOOP][N S S S N _Create_Label_EXIT][T S S S _Add][T N S T _Print_as_integer] ``` Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only. `[..._some_action]` added as explanation only. [Try it online](https://tio.run/##K8/ILEktLkhMTv3/X0FBgRMIuYAQgji5OEEAwgXxFCDSnBBSAcLnVADzgJgLpAzEB6pV4Pz/3wQA) (with raw spaces, tabs and new-lines only). **Explanation in pseudo-code:** ``` Integer i = STDIN as integer Integer j = 10 Start LOOP: i = i - 1 If i is negative (-1): Go to function PRINT_AND_EXIT j = j * 10 Go to next iteration of LOOP function PRINT_AND_EXIT: j = j + i (Since i=-1 at this point, this is basically j = j - 1) Print j as integer Exit with error ``` **Example run (`n=4`):** ``` Command Explanation Stack HEAP STDIN STDOUT STDERR SSSTSTSN Push 10 [10] SNS Duplicate top (10) [10,10] SNS Duplicate top (10) [10,10,10] SNS Duplicate top (10) [10,10,10,10] TNTT Read STDIN as integer [10,10,10] {10:4} 4 TTT Retrieve [10,10,4] {10:4} NSSN Create Label_LOOP [10,10,4] {10:4} SSSTN Push 1 [10,10,4,1] {10:4} TSST Subtract (4-1) [10,10,3] {10:4} SNS Duplicate top (3) [10,10,3,3] {10:4} NTTSN If neg.: Jump to Label_EXIT [10,10,3] {10:4} SNT Swap top two [10,3,10] {10:4} STSSTSN Copy 2nd [10,3,10,10] {10:4} TSSN Multiply (10*10) [10,3,100] {10:4} SNT Swap top two [10,100,3] {10:4} NSNN Jump to Label_LOOP [10,100,3] {10:4} SSSTN Push 1 [10,100,3,1] {10:4} TSST Subtract (3-1) [10,100,2] {10:4} SNS Duplicate top (2) [10,100,2,2] {10:4} NTTSN If neg.: Jump to Label_EXIT [10,100,2] {10:4} SNT Swap top two [10,2,100] {10:4} STSSTSN Copy 2nd [10,2,100,10] {10:4} TSSN Multiply (100*10) [10,2,1000] {10:4} SNT Swap top two [10,1000,2] {10:4} NSNN Jump to Label_LOOP [10,1000,2] {10:4} SSSTN Push 1 [10,1000,2,1] {10:4} TSST Subtract (2-1) [10,1000,1] {10:4} SNS Duplicate top (1) [10,1000,1,1] {10:4} NTTSN If neg.: Jump to Label_EXIT [10,1000,1] {10:4} SNT Swap top two [10,1,1000] {10:4} STSSTSN Copy 2nd [10,1,1000,10] {10:4} TSSN Multiply (1000*10) [10,1,10000] {10:4} SNT Swap top two [10,10000,1] {10:4} NSNN Jump to Label_LOOP [10,10000,1] {10:4} SSSTN Push 1 [10,10000,1,1] {10:4} TSST Subtract (1-1) [10,10000,0] {10:4} SNS Duplicate top (0) [10,10000,0,0] {10:4} NTTSN If neg.: Jump to Label_EXIT [10,10000,0] {10:4} SNT Swap top two [10,0,10000] {10:4} STSSTSN Copy 2nd [10,0,10000,10] {10:4} TSSN Multiply (10000*10) [10,0,100000] {10:4} SNT Swap top two [10,100000,0] {10:4} NSNN Jump to Label_LOOP [10,100000,0] {10:4} SSSTN Push 1 [10,100000,0,1] {10:4} TSST Subtract (0-1) [10,100000,-1] {10:4} SNS Duplicate top (-1) [10,100000,-1,-1] {10:4} NTTSN If neg.: Jump to Label_EXIT [10,100000,-1] {10:4} NSSSN Create Label_EXIT [10,100000,-1] {10:4} TSSS Add (10000+-1) [10,99999] {10:4} TNST Print as integer [10] {10:4} 99999 error ``` Stops program with error: No exit defined. [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~5~~ 4 bytes ``` °Uî9 ``` [Try it online!](https://tio.run/##y0osKPn//9CG0MPrLP//NwYA) Shaved off that one byte thanks to [Shaggy](https://codegolf.stackexchange.com/users/58974/shaggy)'s clever eyes. You can see the edit history for a number of 5-byte solutions. [Answer] # [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), 26 bytes ``` {for(;a++<$1;){printf"9"}} ``` [Try it online!](https://tio.run/##SyzP/v@/Oi2/SMM6UVvbRsXQWrO6oCgzryRNyVKptvb/f0NTAA "AWK – Try It Online") [Answer] # Julia, 14 bytes `f(n)="9"^(n+1)` That's if the result can be a string. [Answer] # [SNOBOL4 (CSNOBOL4)](http://www.snobol4.org/csnobol4/), 30 bytes ``` OUTPUT =DUPL(9,INPUT + 1) END ``` [Try it online!](https://tio.run/##K87LT8rPMfn/n9M/NCQgNETB1iU0wEfDUsfTD8TTVjDU5HL1c/n/39AUAA "SNOBOL4 (CSNOBOL4) – Try It Online") [Answer] # [Gol><>](https://github.com/Sp3000/Golfish), 5 bytes ``` PR`9H ``` [Try it online!](https://tio.run/##S8/PScsszvhv6Ohu6f4/ICjB0uP/fwA "Gol><> – Try It Online") This is a Gol><> function which takes the stack content as input. ### Example full program & How it works ``` 1AG9G PR`9H 1AG Register row 1 as function G 9G Call G with stack [9] P Increment R`9 Push char '9' that many times H Print the stack content as chars and halt ``` [Answer] # TI-Basic, 7 bytes ``` 10^(Ans+1)-1 ``` Fairly straightforward... [Answer] # [CJam](https://sourceforge.net/p/cjam), 6 bytes ``` qi)'9* ``` [Try it online!](https://tio.run/##S85KzP3/vzBTU91S6/9/YwA "CJam – Try It Online") [Answer] # [Perl 5](https://www.perl.org/), 7 bytes ``` $_=9x$_ ``` [Try it online!](https://tio.run/##K0gtyjH9/18l3tayQiX@/3/Tf/kFJZn5ecX/dQsA "Perl 5 – Try It Online") ]
[Question] [ Print this text: ``` _________ | | | | | | |_________| ``` Shortest code wins. Notice the space at the start of the first line. [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~40~~ 37 bytes ``` " "+($x="_"*9) ,"|$(" "*9)|"*3 "|$x|" ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/X0lBSVtDpcJWKV5Jy1KTS0epRkUDKAZk1yhpGXMBuRU1Sv//AwA "PowerShell – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 12 bytes ``` ←×⁵_↑⁴ ×⁵_‖O ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMPKJzWtREchJDM3tVjDVEdBKV5JU9OaCyoZWqCjYALnKikowdnoGoJS03JSk0v8y1KLchILNDSt////r1uWAwA "Charcoal – Try It Online") Link is to verbose version of code. Sadly the vertical direction is insufficiently symmetric to make it worthwhile reflecting. Explanation: ``` ←×⁵_ ``` Print 5 `_`s, leaving the cursor to the left of the first `_`. This makes up half of the bottom of the square. ``` ↑⁴ ``` Print 4 `|`s upwards, making the left of the square. ``` ×⁵_ ``` Print a space and 5 `_`s, making half of the top of the square. ``` ‖O ``` Reflect to complete the square. [Answer] # [J](http://jsoftware.com/), 24 bytes ``` <3 9$LF[9!:7' |_'#~6 4 1 ``` [Try it online!](https://tio.run/##y/qfmpyRr6RXa2WgYGXw38ZYwVLFxy3aUtHKXF2hJl5duc5MwUTB8P9/AA "J – Try It Online") [Answer] # [Canvas](https://github.com/dzaima/Canvas), 9 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md) ``` I×⁹-x~‰‟│ ``` [Try it here!](https://dzaima.github.io/Canvas/?u=JXVGRjI5JUQ3JXUyMDc5LXglN0UldTIwMzAldTIwMUYldTI1MDI_,v=8) Compression. Less boring 12-byte answer: ``` 2|*5_×+⇵ ∔↕╪ 2|* repeat "|" vertically 2 times 5_× repeat "_" horizontally 5 times + add the two together horizontally ⇵ reverse the canvas vertically ∔ prepend a space (because otherwise it glitches out :|) ↕ reverse vertically, moving the underscores up ╪ quad-palindromize, moving underscores as needed ``` [Try it here!](https://dzaima.github.io/Canvas/?u=JXVGRjEyJTdDJXVGRjBBJXVGRjE1XyVENyV1RkYwQiV1MjFGNSUyMCV1MjIxNCV1MjE5NSV1MjU2QQ__,v=8) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~24~~ ~~22~~ 21 bytes ``` ð'_9׫ð9×'|.ø4и`ð'_:» ``` [Try it online!](https://tio.run/##yy9OTMpM/f//8Ab1eMvD0w@tPrwBSKnX6B3eYXJhRwJI2OrQ7v//AQ "05AB1E – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 41 bytes ``` a=' ' for b in'_ _':print a+9*b+a;a='|' ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P9FWXUGdKy2/SCFJITNPPV5BQSFe3aqgKDOvRCFR21IrSTvRGqimRv3/fwA "Python 2 – Try It Online") Changes the outer character from `' '` to `'|'` after the first line using an assignment, a simple trick I don't remember seeing in an ASCII art golf before. [Answer] # Java 11, 57 bytes ``` v->" _________\n"+"| |\n".repeat(3)+"|_________|" ``` [Try it online.](https://tio.run/##PU5BCsIwELz3FUtOCdJcPBb9gb0IXlRkTaOkpmlptgGxfXtMsXUOCzOzzEyNAfO6ekVl0Xs4oHGfDMA40v0DlYZypgBH6o17guKn1lQQRJHUKUvHE5JRUIKDHcSQ7xncVlwc27ARVoyJy153GolvRXL@jyOLxRzWDXebwpbMMFc1aRH/tZ@vgGKZ8/akG9kOJLtkkXXcScXdYK1Ytk3xCw) I don't think this requires an explanation.. >.> [Answer] # [Canvas](https://github.com/dzaima/Canvas), 19 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md) ``` “5+║³╵∑O:E`}7╴?B<‟│ ``` [Try it here!](https://dzaima.github.io/Canvas/?u=JXUyMDFDNSV1RkYwQiV1MjU1MSVCMyV1MjU3NSV1MjIxMU8ldUZGMUFFJTYwJTdENyV1MjU3NCV1RkYxRiV1RkYyMiUzQyV1MjAxRiV1MjUwMg__,v=8) [Answer] # Python 2, ~~54~~, ~~53~~, ~~50~~, 48 bytes ``` print' '+'_'*9+'\n| |'*3+'\n|_________|' ``` -1 Thanks to Kevin Cruijssen. -3 Thanks to Okx -2 Thanks to Vedant Kandoi [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 66 bytes ``` Console.Write(" {0}\n|{1}{1}{1}{0}|","_________"," |\n|"); ``` [Try it online!](https://tio.run/##Sy7WTc4vSv1fWpyZl64QXFlckpprrZCck1hcrOCoUK1QXJJYkpmsUJafmaLgm5iZp6GpUP3fOT@vOD8nVS@8KLMkVUNJodqgNiavptqwFooMamuUdJTiYQDIVoCBGqBCJU3r/7W1/wE "C# (.NET Core) – Try It Online") * Prints the first argument of `Console.Write()` * `{0}` refers to the second argument (`"_________"`) * `{1}` refers to the third argument (`" |\n|"`). [Answer] ## [Turing Machine But Way Worse](https://github.com/MilkyWay90/Turing-Machine-But-Way-Worse) - 3251 bytes ``` 0 0 0 1 1 0 0 0 1 0 1 2 0 0 0 2 1 0 3 1 0 0 3 1 0 4 0 0 0 4 0 1 0 0 0 1 0 1 1 1 0 0 1 1 0 0 2 0 0 1 2 1 1 5 0 0 0 5 0 1 6 0 0 0 6 1 0 7 0 0 0 7 0 1 3 0 0 1 3 1 1 8 0 0 0 8 1 0 4 0 0 1 4 1 1 5 0 0 1 5 1 1 9 0 0 0 9 1 0 6 0 0 1 6 1 1 7 0 0 1 7 1 1 10 0 0 0 10 1 1 11 0 0 0 11 1 0 8 1 0 1 8 1 0 9 1 0 1 9 1 0 10 1 0 1 10 1 0 11 1 0 1 11 1 1 12 1 0 1 12 1 0 13 1 0 1 13 1 1 14 1 0 1 14 1 0 15 1 0 1 15 1 1 16 1 0 1 16 1 1 17 0 0 1 17 0 1 18 0 0 1 18 1 1 19 0 0 1 19 0 0 20 0 0 1 20 1 0 12 0 0 0 12 0 0 21 0 0 1 21 1 0 22 0 0 1 22 0 0 13 0 0 0 13 0 0 23 0 0 1 23 0 0 14 1 0 0 14 0 1 15 0 0 0 15 1 0 16 0 0 0 16 0 1 24 0 0 1 24 1 1 17 0 0 0 17 1 0 25 0 0 1 25 1 1 26 0 0 1 26 1 1 18 0 0 0 18 1 0 27 0 0 1 27 1 1 28 0 0 1 28 1 1 29 0 0 1 29 1 1 19 0 0 0 19 1 1 30 0 0 1 30 0 0 31 1 0 1 31 0 0 32 0 0 1 32 0 0 33 0 0 1 33 0 0 34 0 0 1 34 1 0 35 0 0 1 35 0 0 20 1 0 0 20 0 1 21 1 0 0 21 0 1 36 1 0 1 36 1 1 22 1 0 0 22 0 1 23 1 0 0 23 0 0 24 1 0 0 24 0 1 25 1 0 0 25 0 0 26 1 0 0 26 0 1 27 1 0 0 27 1 1 28 0 0 0 28 1 0 37 0 0 1 37 1 0 29 0 0 0 29 1 0 38 0 0 1 38 1 0 30 0 0 0 30 1 0 31 1 0 0 31 0 1 39 0 0 1 39 0 0 32 0 0 0 32 0 1 33 0 0 0 33 0 1 40 0 0 1 40 0 0 34 0 0 0 34 0 1 35 0 0 0 35 0 1 41 0 0 1 41 0 0 36 0 0 0 36 0 1 37 0 0 0 37 0 1 42 0 0 1 42 1 1 43 0 0 1 43 0 1 38 0 0 0 38 1 0 39 1 0 0 39 1 1 44 0 0 1 44 0 0 45 0 0 1 45 1 0 46 0 0 1 46 1 0 40 0 0 0 40 1 0 41 0 0 0 41 1 0 42 0 0 0 42 1 0 43 1 0 0 43 0 1 47 0 0 1 47 0 0 44 0 0 0 44 0 1 45 0 0 0 45 0 1 48 0 0 1 48 1 1 49 0 0 1 49 0 0 50 0 0 1 50 1 1 46 0 0 0 46 0 1 51 0 0 1 51 0 1 52 0 0 1 52 0 0 47 1 0 0 47 0 0 48 1 0 0 48 0 1 49 1 0 0 49 0 0 50 1 0 0 50 0 1 51 1 0 0 51 0 0 52 1 0 0 52 0 1 53 1 0 0 53 0 0 54 1 0 0 54 0 1 55 1 0 0 55 1 1 56 0 0 0 56 1 0 53 0 0 1 53 1 0 57 0 0 0 57 1 0 54 0 0 1 54 1 0 58 0 0 0 58 1 0 59 1 0 0 59 0 1 55 0 0 1 55 0 0 60 0 0 0 60 0 1 61 0 0 0 61 0 1 56 0 0 1 56 0 0 62 0 0 0 62 0 1 63 0 0 0 63 0 1 57 0 0 1 57 0 0 64 0 0 0 64 0 1 65 0 0 0 65 0 1 58 0 0 1 58 1 1 59 0 0 1 59 0 1 66 0 0 0 66 1 0 67 1 0 0 67 1 1 60 0 0 1 60 0 0 61 0 0 1 61 1 0 62 0 0 1 62 1 0 68 0 0 0 68 1 0 69 0 0 0 69 1 0 70 0 0 0 70 1 0 71 1 0 0 71 0 1 63 0 0 1 63 0 0 72 0 0 0 72 0 1 73 0 0 0 73 0 1 64 0 0 1 64 1 1 65 0 0 1 65 0 0 66 0 0 1 66 1 1 74 0 0 0 74 0 1 67 0 0 1 67 0 1 68 0 0 1 68 0 0 75 1 0 0 75 0 0 76 1 0 0 76 0 1 77 1 0 0 77 0 0 78 1 0 0 78 0 1 79 1 0 0 79 0 0 80 1 0 0 80 0 1 81 1 0 0 81 0 0 82 1 0 0 82 0 1 83 1 0 0 83 1 1 84 0 0 0 84 1 0 69 0 0 1 69 1 0 85 0 0 0 85 1 0 70 0 0 1 70 1 0 86 0 0 0 86 1 0 87 1 0 0 87 0 1 71 0 0 1 71 0 0 88 0 0 0 88 0 1 89 0 0 0 89 0 1 72 0 0 1 72 0 0 90 0 0 0 90 0 1 91 0 0 0 91 0 1 73 0 0 1 73 0 0 92 0 0 0 92 0 1 93 0 0 0 93 0 1 74 0 0 1 74 1 1 75 0 0 1 75 0 1 94 0 0 0 94 1 0 95 1 0 0 95 1 1 76 0 0 1 76 0 0 77 0 0 1 77 1 0 78 0 0 1 78 1 0 96 0 0 0 96 1 0 97 0 0 0 97 1 0 98 0 0 0 98 1 0 99 1 0 0 99 0 1 79 0 0 1 79 1 1 80 0 0 1 80 0 0 81 0 0 1 81 1 1 100 0 0 0 100 0 1 82 0 0 1 82 1 1 83 0 0 1 83 1 1 84 0 0 1 84 1 1 101 0 0 0 101 1 1 102 0 0 0 102 1 0 85 1 0 1 85 1 0 86 1 0 1 86 1 0 87 1 0 1 87 1 0 88 1 0 1 88 1 1 89 1 0 1 89 1 0 90 1 0 1 90 1 1 91 1 0 1 91 1 0 92 1 0 1 92 1 1 93 1 0 1 93 1 1 94 0 0 1 94 1 1 95 0 0 1 95 0 1 96 0 0 1 96 0 0 103 0 0 0 103 0 0 97 0 0 1 97 1 0 98 0 0 1 98 1 0 99 0 0 1 99 1 0 104 0 0 0 104 1 0 100 1 1 ``` Made with the help of ASCII\_only's program generator. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~27~~ 21 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) (using compression and mirror) ``` …_ |•ʒßKèËß•3вèJ5ä».º ``` Straightforward approach. [Try it online.](https://tio.run/##AS8A0P9vc2FiaWX//@KApl8gfOKAosqSw59Lw6jDi8Of4oCiM9Cyw6hKNcOkwrsuwrr//w) **Explanation:** ``` …_ | # Push string "_ |" •ʒßKèËß• # Push compressed integer 68865864629382 3в # Convert to Base-3 as list # [1,0,0,0,0,0,2,1,1,1,1,1,2,1,1,1,1,1,2,1,1,1,1,1,2,0,0,0,0,0] è # Index each into the string # [" ","_","_","_","_","_","|"," "," "," "," "," ","|"," "," "," "," "," ","|"," "," "," "," "," ","|","_","_","_","_","_"] J # Join all characters together # " _____| | | |_____" 5ä # Split the string into 5 equal-sized substrings # [" _____","| ","| ","| ","|_____"] » # Join them by newlines # " _____\n| \n| \n| \n|_____" .º # Mirror with overlap (and output implicitly) # " _________ \n| |\n| |\n| |\n|_________|\n" ``` [See this 05AB1E tip of mine (section *How to compress integer lists?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `•ʒßKèËß•3в` is `[1,0,0,0,0,0,2,1,1,1,1,1,2,1,1,1,1,1,2,1,1,1,1,1,2,0,0,0,0,0]`. --- # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~28~~ 26 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) (using the Canvas) ``` '_9∍ð'|4∍JDðKðJŽWêSÌsŽ9¦SΛ ``` I like this approach a lot more, but unfortunately it's a bit longer.. This approach uses [the Canvas builtin `Λ`](https://codegolf.stackexchange.com/a/175520/52210). [Try it online.](https://tio.run/##yy9OTMpM/f9fPd7yUUfv4Q3qNSZA2svl8Abvwxu8ju4NP7wq@HBP8dG9loeWBZ@b/f8/AA) **Explanation:** ``` '_9∍ '# Push string "_" and enlarge it to size 9: "_________" ð # Push a space character '|4∍ '# Push string "|" and enlarge it to size 4: "||||" J # Join the entire stack together to a single string D # Duplicate it ðK # Remove the space ð # Push a space character J # Join all the entire stack together to a single string # (We now have "_________ ||||_________|||| ") ŽWê # Push compressed integer 8393 S # Convert it to a list of digits: [8,3,9,3] Ì # Add 2 to each: [10,5,11,5] s # Swap the list and string on the stack Ž9¦ # Push compressed integer 2460 S # Convert it to a list of digits: [2,4,6,0] Λ # Use the Canvas with options (and output immediately implicitly): # [10,5,11,5] as lengths # "_________ ||||_________|||| " as string to draw # [2,4,6,0] as directions, which is [left,down,right,up] respectively ``` Here a few alternatives for creating the strings (`'_9∍ð'|4∍JDðKðJ`) with the same amount of bytes: * `ð'|4×'_5שJû®ûì`: [Try it online.](https://tio.run/##ATIAzf9vc2FiaWX//8OwJ3w0w5cnXzXDl8KpSsO7wq7Du8Osxb1Xw6pTw4xzxb05wqZTzpv//w) * `'_9∍Dðs'|4∍.øðJ`: [Try it online.](https://tio.run/##yy9OTMpM/f9fPd7yUUevy@ENxeo1JkCW3uEdhzd4Hd0bfnhV8OGe4qN7LQ8tCz43@/9/AA) [Answer] # [MathGolf](https://github.com/maxbergmark/mathgolf), 27 bytes ``` '_9*_3{'|_ 9*▌+\}'|_@++]n \ ``` [Try it online!](https://tio.run/##y00syUjPz0n7/1893lIr3rhavSZewVLr0bQe7ZhaINtBWzs2TyHm////AA "MathGolf – Try It Online") Pretty much the simplest way to do it. [Answer] # JavaScript, 54 bytes As with [Kevin's Java solution](https://codegolf.stackexchange.com/a/176783/58974), the boring option ended up being the shortest :\ ``` _=>` _________ ${`| | `.repeat(3)}|_________|` ``` [Try It Online](https://tio.run/##y0osSyxOLsosKNHNy09J/Z@cn1ecn5Oql5OfrqHxP97WLkEhHga4VKoTahRgoIYrQa8otSA1sUTDWLO2Bq6qJuG/poam5n8A) --- ## Alternative, 59 bytes ``` _=>` _ | | | | | | |_|`.replace(/../g,x=>x.padEnd(10,x[1])) ``` [Try It Online](https://tio.run/##y0osSyxOLsosKNHNy09J/Z@cn1ecn5Oql5OfrqHxP97WLkEhnqtGoQaB42sS9IpSC3ISk1M19PX09NN1KmztKvQKElNc81I0DA10KqINYzU1/2tqAAkA) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 19 bytes ``` ŽP—S"_| _"SŽNžS.Λ.º ``` [Try it online!](https://tio.run/##ASQA2/9vc2FiaWX//8W9UOKAlFMiX3wgXyJTxb1Oxb5TLs6bLsK6//8 "05AB1E – Try It Online") **Explanation** ``` ŽP—S # push [6,5,2,5] (lengths) "_| _"S # push ["_", "|", " ", "_"] (characters to print) ŽNžS # push [6,0,2,2] (directions) .Λ # draw to canvas without printing .º # mirror horizontally ``` [Answer] # [Red](http://www.red-lang.org), 53 bytes ``` prin[" _________^/"r:"| |^/"r r"|_________|"] ``` [Try it online!](https://tio.run/##K0pN@R@UmhId@7@gKDMvWkkhHgbi9JWKrJRqFGCgBiSgUKRUA1dRoxT7/z8A "Red – Try It Online") [Answer] # Java, 59 Bytes ``` v-> " _______\n| |\n| |\n| |\n|_______|" ``` [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 317 bytes ``` ((((((((()()()()()){}){})()){}{}){}))<>)<>((((((((({}[(((()()()){}()){}){}()])))))))))(<>{}<>)((()()()()()){})(<>()()()){<>(((((((()()()()()){}){})()){}{}){})<>)<> ((((((((((((()()()()){}){}){})))))))))(<>{}<>)((()()()()()){})<>({}[()])}<>(((((()()()()){}){}){}))((((((((((({})){}{}[()])))))))))((((()()()()){}){}){}) ``` [Try it online!](https://tio.run/##SypKzMzTTctJzP7/XwMGNGFQs7oWhMAMCFPTxg6I4Cqra6PhGoDSMB0amrGaMKBhY1ddC9SFbi5QHMZBGIjHZrDFChrIAFUtyHUE7ARaBHIx0HW1MDsxzUCyAMQF2R@N4iGs2v7//6/rCAA "Brain-Flak – Try It Online") Not golfy at all, just a test. [Answer] # [CJam](https://sourceforge.net/p/cjam), 31 28 bytes ``` S'_9*S++'|S9*'|++___4$.e>]N* ``` Explanation ``` S'_9*S++'|S9*'|++___4$.e>]N* e# Whole code S'_9*S++ e# Push the string ' _________ ' '|S9*'|++ e# Push the string '| |' ___ e# Duplicate it 3 times 4$ e# Copy the 4th stack element (' _________ ') .e> e# Combine the last '| |' with the e# ' _________ ' to get '|_________|' ]N* e# Join with newlines e# Implicit output ``` [Try it online!](https://tio.run/##S85KzP3/P1g93lIrWFtbvSbYUku9Rls7Pj7eREUv1S7WT@v/fwA) [Answer] # [R](https://www.r-project.org/), 55 bytes ``` cat(gsub(0,"| | "," _________ 000|_________|")) ``` [Try it online!](https://tio.run/##K/r/PzmxRCO9uDRJw0BHqUYBBmq4lHSUFOJhgMvAwKAGzqtR0tT8/x8A "R – Try It Online") [Answer] # [BrainFuck](https://esolangs.org/wiki/brainfuck), 129 bytes ``` +++>++++++++[>++++>>>>+<<<<<-]>[>+++>++++>+<<<-]>->---->>++<.<<.........>>>.<<<<<<[>>>>.>.........<.>>.<<<<<<-]>>>>.<.........>. ``` This was my first code golf post so it isn't that optimized. [Answer] # [Deadfish~](https://github.com/TryItOnline/deadfish-), 226 bytes ``` iisiisddddc{dd}ddsdddddccccccccc{ddddddddd}ddsicisiiic{{d}dd}iisddddccccccccc{dd}dsiiic{{d}dd}dsicisiiic{{d}dd}iisddddccccccccc{dd}dsiiic{{d}dd}dsicisiiic{{d}dd}iisddddccccccccc{dd}dsiiic{{d}dd}dsicisiiic{ddd}icccccccccd{iii}c ``` [Try it online!](https://tio.run/##vY5LCsAwCAVP1EMVp6VvnaV4dhsDlpyggws/80Cuk1vjOTKlMYuJOQSsHmucpm6y0mXuNUYnNznYhZ8T9aU@E5/LsMwX "Deadfish~ – Try It Online") [Answer] # [Stax](https://github.com/tomtheisen/stax), 18 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` é☻x+▓ïqÉ┬i╦↨|╛₧│&▬ ``` [Run and debug it](https://staxlang.xyz/#p=8202782bb28b7190c269cb177cbe9eb32616&i=&a=1) [Answer] # Brainfuck, 93 bytes ``` --[[<+++>----->->>+++<<<]>]<<.<<-.........<.>>-->>+++[-<<.>.........<.<<.>>>>]<<.<.........>. ``` [Try it online!](https://tio.run/##TYtBCoBADAMfVNIXhHyk7EEFQQQPwr6/dhcU55ZMst7Lce19OzOBCJqZMBCkCiSbGukk/IWuGk0fKKefGbGYl6@WZz4 "brainfuck – Try It Online") [Answer] # [PHP](https://php.net/), 81 bytes ``` while($x<9)echo str_pad(str_repeat(($l='_ | | |_|')[$x++],9),11,$l[$x++],2)," "; ``` [Try it online!](https://tio.run/##K8go@G9jXwAkyzMyc1I1VCpsLDVTkzPyFYpLiuILElM0QHRRakFqYomGhkqOrXq8gkINCMbXqGtGq1Roa8fqWGrqGBrqqORAuUaaOkpcStb//wMA "PHP – Try It Online") [Answer] # [///](https://esolangs.org/wiki////), ~~43~~ 38 bytes ``` /~/| | //-/_________/ - ~~~|-| ``` [Try it online!](https://tio.run/##K85JLM5ILf7/X79Ov0YBBmq49PV19eNhQF9Bl6uurq5Gt@b/fwA "/// – Try It Online") *-5 bytes thanks to [@PkmnQ](https://codegolf.stackexchange.com/users/91569/pkmnq)* [Answer] # [FEU](https://github.com/TryItOnline/feu), 44 bytes ``` a/ ~\n---|~| m/-/| |\n/~/_________/g ``` [Try it online!](https://tio.run/##S0st/f8/UV@hLiZPV1e3pq6GK1dfV79GAQZqYvL06/TjYUA//f9/AA "FEU – Try It Online") ]
[Question] [ Inspired by [this](https://codegolf.stackexchange.com/questions/66878/find-the-number-in-the-champernowne-constant) and [this](https://codegolf.stackexchange.com/questions/265634/print-100-digits-of-%cf%80) question #### Challenge Your challenge is to print any 100 consecutive digits of Champernowne's Constant. You must give the index at which that subsequence appears. The 0 at the beginning is not included. For example, you could print any of the following: ``` +-----+----------------------------------------------------------------------------------------------------+ |Index|Output | +-----+----------------------------------------------------------------------------------------------------+ |0 |1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545| +-----+----------------------------------------------------------------------------------------------------+ |50 |0313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798| +-----+----------------------------------------------------------------------------------------------------+ |100 |5565758596061662636465666768697071727374757677787980818283848586878889909192939495969798991001011021| +-----+----------------------------------------------------------------------------------------------------+ ``` #### Rules * Output may be a string/digit list/etc. * You may provide a function or a program * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code wins! [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~4 3~~ 2 bytes ``` ³Ṭ ``` A full program that accepts no arguments and prints a list of one hundred consecutive places starting at the 0-indexed index (you may need to scroll): $$98888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888890$$ **[Try it online!](https://tio.run/##y0rNyan8///Q5oc71/z/DwA "Jelly – Try It Online")** ### How? By definition, Champernowne's constant's decimal places are the concatenation of the natural numbers, so \$10^{99}\$, the first number with \$100\$ decimal digits, appears. The index of \$N = 10^{99}\$ may be calculated like so: $$d = \text{digit\_length}(N) = \lfloor log\_{10}(N) \rfloor + 1$$ $$\text{index} = d \times N - \frac{10^{d}-1}{9}$$ $$= 100 \times 10^{99}-\frac{10^{100}-1}{9}$$ $$= 10^{101}-\frac{10^{100}-1}{9}$$ $$=98888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888889$$ The next digit of Champernowne's constant after the last zero of \$N\$ is the first digit of \$N+1\$ which is \$1\$, so let's get the trailing \$99\$ zeros of \$N\$ and a \$1\$... ``` ³Ṭ - Main Link: no arguments ³ - 100 Ṭ - untruth -> [0,0,0,...,1] (99 zeros followed by a one) - implicit print ``` --- #### Original @ 4 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page): ``` 55ḊV ``` A full program that accepts no arguments and prints the 2nd to 101st decimal places. **[Try it online!](https://tio.run/##y0rNyan8/9/U9OGOrrD//wE "Jelly – Try It Online")** ### How? ``` 55ḊV - Main Link: no arguments 55 - fifty-five Ḋ - dequeue -> [2,3,4,...,54,55] V - evaluate as Jelly code -> (integer) 234...5455 - implicit print ``` [Answer] # C, 41 bytes ``` main(i){for(i=9;i++<59;)printf("%d",i);} ``` Goes through numbers 10 to 59 (indexes 9 to 108), printing exactly 100 digits (without a newline). --- # C, 28 bytes ``` main(){printf("1%099d",0);} ``` Inspired by Jonathan Allan's solution, just prints 10^99, starting at index 98888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888889 (if my short Python script did not fail me :p): ``` n = 0 for i in range(1, 100): n = n + 9 * pow(10, i - 1) * i print(n) ``` [Answer] # [brainfuck](https://github.com/TryItOnline/brainfuck), 23 bytes ``` -[----->+>+<<]>-[->..<] ``` [Try it online!](https://tio.run/##SypKzMxLK03O/v9fN1oXBOy07bRtbGLtgFw7PT2b2P//AQ "brainfuck – Try It Online") Outputs 100 `3`s, which appears at index 16888888888888888888888888888888888888888888888888872. This program first obtains the value 51 (which is the ASCII code of `3`), calculating it as 255/5, in two cells. It then decrements one of those cells to 50, and then uses it as a counter for a loop in which each iteration outputs the other cell's value twice. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes ``` 2r55DF ``` [Try it online!](https://tio.run/##y0rNyan8/9@oyNTUxe3/fwA "Jelly – Try It Online") Starts at index 1 (digit 2 in the number `2`). Range from 2 to 55 and then the decimal representation of each, then flattened. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 6 bytes ``` ⭆⁵⁰⁺χι ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRCO4BEil@yYWaJga6CgE5JQWaxgCGZmamprW////1y3LAQA "Charcoal – Try It Online") Link is to verbose version of code. Starts at index `9`. Explanation: Loops over the first `50` integers adding `10` to each, then joins everything together. Alternative version, also 6 bytes: ``` ⪫…χ⁶⁰ω ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMMrPzNPIygxLz1Vw9BAR8HMQFNHoVxT0/r///@6ZTkA "Charcoal – Try It Online") Link is to verbose version of code. Starts at index `9`. Explanation: Lists the integers from `10` to `60`, then joins everything together. Alternatively, starting at index `1`, also for 6 bytes: ``` ⭆⁵⁴⁺²ι ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRCO4BEil@yYWaJia6CgE5JQWaxjpKGRqampa////X7csBwA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Loops over the first `54` integers adding `2` to each, then joins everything together. Boring 4-byte solution: ``` ”);e ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvREPJgA5ASdP6////umU5AA "Charcoal – Try It Online") Link is to verbose version of code. Starts at index `988888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888890`. Explanation: Compressed string of `100` `0`s. Slightly less boring 5-byte solution: ``` IXφ³³ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEIyC/PLVIw9DAwEBHwdhYU1PT@v///7plOQA "Charcoal – Try It Online") Link is to verbose version of code. Starts at index `98888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888889`. Explanation: Calculates `1000³³`. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~5~~ 3 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` 1т× ``` -2 bytes porting [*@Tbw*'s APL answer](https://codegolf.stackexchange.com/a/267388/52210). Outputs at 0-based index \$55555555555555555555555555555555555555555555555555551\$. [Try it online.](https://tio.run/##yy9OTMpM/f/f8GLT4en//wMA) **Original 5 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) answer(s):** * `Y55ŸJ` - Outputs at 0-based index \$1\$ - [Try it online](https://tio.run/##yy9OTMpM/f8/0tT06A6v//8B); * `T59ŸJ` - Outputs at 0-based index \$9\$ - [Try it online](https://tio.run/##yy9OTMpM/f8/xNTy6A6v//8B); * `46₃ŸJ` - Outputs at 0-based index \$81\$ - [Try it online](https://tio.run/##yy9OTMpM/f/fxOxRU/PRHV7//wMA). Here also the program with an infinite list of all valid outputs: ``` ∞Sü100J ``` [Try it online.](https://tio.run/##yy9OTMpM/f//Uce84MN7DA0MvP7/BwA) **Explanation:** ``` 1т # Push 1; Push 100 × # Pop both, and push a string of 100 1s # (which is output implicitly as result) Y55 # Push 2; Push 55 Ÿ # Pop both, and push a list in the range [2,55] J # Join the list together to a single string # (which is output implicitly as result) T59 # Push 10; Push 59 ŸJ # Same as above 46₃ # Push 46; Push 95 ŸJ # Same as above ``` ``` ∞ # Push an infinite positive list: [1,2,3,...] S # Convert it to a flattened list of digits ü100 # Pop and push a list of all overlapping lists of 100 digits J # Join each inner list of digits together to a string # (after which this infinite list is output implicitly) ``` [Answer] # [APL (Dyalog Classic)](https://www.dyalog.com/), 5 bytes ``` 100⍴1 ``` [Try it online!](https://tio.run/#%23SyzI0U2pTMzJT9dNzkksLs5M/g8EhgYGj3q3GAIA) Prints 1, one hundred times. Similar approach to @Jonathan Allan and others. First appears as ``` 1111111111111111111111111111111111111111111111111 #fifty-one 1s 11111111111111111111111111111111111111111111111(12) ``` Index is \$51\cdot\frac{10^{51}-1}{9}+ \sum\_{n=1}^{50}(9n \cdot 10^{n}) = \frac{5}{9}(10^{53}-1)-4\$. Explicitly, this is \$55555555555555555555555555555555555555555555555555551\$ (fifty-one 5s and one 1). # 7 bytes If we want to print as a string rather than a list. ``` 100⍴'1' ``` [Here's a more legit APL solution by Graham](https://codegolf.stackexchange.com/a/267386/117598) [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal/tree/version-2) `H`, 14 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 1.75 bytes ``` 1ẋ ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=2&c=1#WyJIPSIsIiIsIjHhuosiLCIiLCIiXQ==) Bitstring: ``` 01000010111110 ``` Prints `1` 100 times, same as APL [Answer] # [///](https://esolangs.org/wiki////), 17 bytes ``` /10/00000001/1100 ``` [Try it online!](https://tio.run/##K85JLM5ILf7/X9/QQN8AAgz1DQ0NDP7/BwA "/// – Try It Online") Outputs 98 `0`s followed by 2 `1`s, which appears (in `1[000...0001 1]000...0002`) at index 98888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888990. The replacement multiplies the number of `0`s by 7 as they move across each `1`. --- Some alternative solutions, of the same length: ``` /10/0001/10010110 ``` [Try it online!](https://tio.run/##K85JLM5ILf7/X9/QQN/AwMAQSBsYGhgaGvz/DwA "/// – Try It Online") Outputs 96 `0`s followed by 4 `1`s. ``` /10/00001/0110010 ``` [Try it online!](https://tio.run/##K85JLM5ILf7/X9/QQN8ACAz1DQwNgZTB//8A "/// – Try It Online") Outputs 97 `0`s followed by 3 `1`s. [Answer] # APL+WIN, ~~11~~ 10 bytes i byte saved thank to Tbw A function taking no arguments with output from index 2 with index origin = 1 ``` 1↓⊃,/⍕¨⍳55 ``` [Try it online! Thanks to Dyalog Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcQJanP5BlyPWooz3tv@GjtsmPupp19B/1Tj204lHvZlPT/0AJrv9pXAA "APL (Dyalog Classic) – Try It Online") [Answer] # [GolfScript](http://www.golfscript.com/golfscript/), 6 bytes ``` 55,(;5 ``` [Try it online!](https://tio.run/##S8/PSStOLsosKPn/39RUR8Pa9P9/AA "GolfScript – Try It Online") Prints the first 100 digits. ``` 55, # the list 0..55 (; # drop the 0 5 # push 5 to the stack # the stack is implicitly printed without separator ``` Alternatively, this one prints a hundred 1s: # [GolfScript](http://www.golfscript.com/golfscript/), 6 bytes ``` 1+100* ``` [Try it online!](https://tio.run/##S8/PSStOLsosKPn/31Db0MBA6/9/AA "GolfScript – Try It Online") Gets `"1"` by appending 1 to the implicit empty input, then repeats it 100 times. ]
[Question] [ `for` loops are useful in python in many ways, but one of the most common usages associated with a `for` loop is it's ability to repeat a certain amount of times. Like this: ``` for times in range(50): print "I'm repeating this 50 times..." ``` The challenge I propose to you is to make a `for` repeat **forever**. If you can find a way to do it without using a recursion, kudos to you. You can use **any** major version of Python. Just specify which one you are using. The goal is to do this in the smallest file size you can get, and a method that won't "break" after a while. Good luck! [Answer] This can be done quite easily by abusing floating point addition. ``` def frange(start, stop, step): r = start while r < stop: yield r r += step for x in frange(0, 1e16, 1): print (x) ``` IEEE754 64-bit floats have 53 bits of mantissa (including the implicit bit), so if `x > 1<<53` then `x + 1 == x`. `1 << 53` is approximately `9e15`. [Answer] Because this was turned to a codegolf, have a **48 bytes** version as a one-liner. 3 bytes could be removed from both by replacing `print i` with `pass`. ``` for i in __import__('itertools').count():print i ``` Or a **47 bytes** version with two lines. ``` from itertools import* for i in count():print i ``` --- Old message: Easy it is. ``` def f(i = 0): while True: yield i i += 1 for i in f(): print(i) ``` [Answer] This is an interesting way of doing it (32 chars for `class x`, 46 not counting the `print`): ``` class x:__iter__=next=lambda s:s for i in x():print "Hello" ``` This defines an iterable whose `next` method never raises a `StopIteration` [Answer] I don't usually golf in Python, probably some reason people haven't already done posted this 23-character solution. ``` x=[1] for i in x: x+=x ``` Much less memory-hungry if you do `x+=[i]` instead. Either one hangs my 2.7.5 [Answer] ``` for i in iter(lambda : 0, 1): print (i) # prints 0 forever ``` The `iter` function is normally used to create an iterator from an iterable. The `iter` function can also take two arguments, a callable and a sentinel value. In that case it returns an iterator that yields the result of the callable until the callable returns the sentinel value. In this case, the callable is a lambda that always returns 0. Since it never can return the sentinel value (1), this will loop forever. Since this is code golf, this version is **28 characters and only one line**: ``` for i in iter(lambda:0,1):i ``` [Answer] # 28 bytes, infinite, and no itertools ``` for x in iter(int,1):print 1 ``` Shouldn't end without system program cutoffs (i.e. not my fault). ### 22 bytes without printing anything: ``` for x in iter(int,1):1 ``` [Answer] ## 39 Characters, no itertools and no crashing ``` def f(): while 1:yield for i in f():1 ``` Itertools is unnecessary, you can define your own generator. [Answer] # Python 2 & 3: 37 characters ``` class P:__getitem__=id for t in P():1 ``` ¡No infinite memory required! [Answer] Itertools, to the rescue: ``` from itertools import count for i in count(): print i ``` or ``` from itertools import repeat for i in repeat(42): print i ``` [Answer] ### Python 3.3: 2 lines, 29 characters ``` j=[1] for i in j: j.append(1) ``` Does this break? I've run it for a short while, doesn't seem to hang. ]
[Question] [ I like patterns in time. My favorite is when the time lines up. For example, all of these line up: ``` 3:45 12:34 23:45 3:21 6:54 ``` This is because each digit in the hour/minute is increasing/decreasing by one each time. Your task is to take the current time and check if it "lines up" in this pattern in a program. (You will output a truthy or falsey value according to this check.) Along with the times above, your program should match these: ``` 1:23 4:32 2:10 ``` And *not* match these: ``` 1:00 12:13 1:21 1:34 ``` You may take the time as an argument to a function/through STDIN, but this incurs a **+125%** byte penalty on your program. You may take the time from UTC or system time; 12-hour or 24-hour. This is a code golf, so the shortest program in bytes wins. [Answer] # Jolf, ~~10~~ ~~21~~ ~~19~~ 28 bytes Replace `♂` with `\x11`, or use [this link](http://conorobrien-foxx.github.io/Jolf/#code=IGVaZBHOnGY1ZHBxK0VIMjBkJj1GbkggaMKxMDFI). ``` eZd♂Μf5dpq+EH20d&=FnH h±01H ``` This can be golfed (?). Explanation: ``` eZd♂Μf5dpq+EH20d&=FnH h±01H f5 [hours, minutes] Μ dpq+EH20 pad (>_>) ♂ singleton; so [13,45] => [1,3,4,5] Zd delta list; [1,3,4,5] => [2,1,1] _e d check if =FnH each member is equal to the first & _h±01H and if it is in the array [-1,1] (0 +- 1) ``` [Answer] ## Pyth, ~~67.5~~ ~~54~~ 38 bytes ``` sm.v%"q1l.{.e%skvb+`.d6.[\0`.d7 2"d"+- ``` Or old version, 30 bytes (takes input from stdin) ``` zsm.v%"q1l.{.e%skvb:z\:k"d"+- ``` Thanks [@drobilc](https://codegolf.stackexchange.com/users/30715/drobilc) for reminding me of the other `.d` arguments ;) Explanation: ``` sm.v%"q1l.{.e%skvb+`.d6.[\0`.d7 2"d"+- m "+- - [V for d in "+-"] % d - V%d " " - stringify code V `.d6 - repr(current_hour) + - ^+V `.d7 - repr(current_minute) .[\0 2 - pad("0",^,2) .e - [V for k,b in enumerate(^)] vb - eval(b) %s - V (either + or -) ^ k - k .{ - set(^) l - len(^) q1 - ^==1 .v - eval(^) s - True in ^ ``` Basically, for both `+` and `-` it tests to see if by performing that operation on the index on the character and the character itself you get the same values. [Try it here!](http://pyth.herokuapp.com/?code=+zsm.v%25%22q1l.%7B.e%25skvb%3Az%5C%3Ak%22d%22%2B-&input=3%3A45&debug=0) [Or try a test suite!](http://pyth.herokuapp.com/?code=+zsm.v%25%22q1l.%7B.e%25svbk%3Az%5C%3Ak%22d%22%2B-&input=3%3A45&test_suite=1&test_suite_input=3%3A45%0A12%3A34%0A23%3A45%0A3%3A21%0A6%3A54%0A1%3A23%0A4%3A32%0A2%3A10%0A1%3A00%0A12%3A13%0A1%3A21&debug=0) [Answer] ## Bash, ~~79~~ 78 bytes ``` [[ $(date +%-H%M|fold -1|sed 'p;{1d;$d}'|paste -sd-\\n|bc|sort -u) =~ ^-?1$ ]] ``` Remarkably competitive for the usually-painfully-verbose Bash. Thanks to [@DigitalTrauma](https://codegolf.stackexchange.com/users/11259/digital-trauma) for 2 bytes! Walkthrough: * `date +%-H%M`: returns the date in HHMM form (ex. `1234`). * `fold -1`: puts each character on a separate line (so now we have `1\n2\n3\n4\n`). * `sed`: + `p`: duplicate each line. + `{1d;$d}`: delete the first and last lines.Now we have `1 2 2 3 3 4` (spaces used in place of newlines for readability). * `paste -sd '-\n'`: turns this into `1-2 2-3 3-4`. * `bc`: piped through an arithmetic calculator, now we have `-1 -1 -1`. * `sort -u`: remove duplicates, so now we have `-1`. * `[[ $(...) =~ ^-?1$ ]]`: check if the resulting string matches the regex `/^-?1$/`. If the time is "linear," the differences between each consecutive line will all be either `1` or `-1`. [Answer] ## Pyth, 23 22 bytes ``` }+.d6%"%02d".d7jks_BU7 ``` Constructs the string "0123456543210" and check if the time without the colon is a substring of it. In pythonic pseudocode: ``` k = "" }+.d6%"%02d".d7 ( currentHour() + format("%02d",currentMinute()) ) in \ jks_BU7 sum([range(7),range(7)[::-1]]).join(k) ``` [Answer] # Jelly, ~~24.75~~ 22.5 bytes ``` ~ḟ0IµḢ×=1P ``` The code is **10 bytes** long and is subject to the **125% penalty**. [Try it online!](http://jelly.tryitonline.net/#code=fuG4nzBJwrXhuKLDlz0xUA&input=&args=MToyMQ) ### How it works ``` ~ḟ0IµḢ×=1P Main link. Input: S (time string) ~ Apply bitwise NOT to all characters. This attempts to cast to integer, and returns 0 on failure. For example, '1'~ -> 1~ -> -2, but ':'~ -> 0. ḟ0 Filter out the 0, which corresponds to the colon. I Compute all increments/deltas. µ Begin a new, monadic chain. Argument: A (list of deltas) Ḣ Pop the first delta. × Multiply the remaining list items by the popped one. The list should now consist of 1's for a truthy test case. =1 Compare the list items with 1. P Take the product of the resulting Booleans. ``` [Answer] ## Batch, 130 bytes ``` @set t=%time:~,5% @goto %t::=% 2>nul :0012 :0123 :0210 :0234 :0321 :0345 :0432 :0456 :0543 :0654 :1234 :2345 @echo 1 ``` Edit: Back to the old approach. `%time%` contains the time in hh:mm:ss.ss format. The first 5 characters are extracted into `t` and the colon is deleted. If the result is one of the 12 possible linear times then `1` is output to indicate a truthy value, otherwise there is no output to indicate a falsy value. [Answer] # JavaScript (ES6), ~~75~~ 73 bytes ``` _=>"0123456543210".match((m=(new Date+"").match`([1-9].?):(..)`)[1]+m[2]) ``` *2 bytes saved thanks to @Neil!* ## Explanation *Credit to @busukxuan for the digit string idea!* Checks the digits of the current time in the string `0123456543210`. Returns `null` for `false` and an array containing the time digits for `true`. ``` _=> "0123456543210".match( // check if the time digits are in this string (m= (new Date+"") // get a string with the current time (among other things) .match`([1-9].?):(..)` // get time digits with leading zero removed ) [1]+m[2] // construct a string of only the time digits ) ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 10 × 125% = ~~24.75~~ 22.5 bytes Code: ``` R.d¬¹1£ŸJQ ``` Explanation: ``` R # Reverse the input .d # Keep the digits ¬ # Head, push the first character of the string ¹ # First value from the input register 1£ # Take the first character from the input Ÿ # Inclusive range J # Join the list to a string Q # If equal to the input, return 1, else 0 ``` [Try it online!](http://05ab1e.tryitonline.net/#code=Ui5kwqzCuTHCo8W4SlE&input=MjM6NDU) or [Try all test cases at once!](http://05ab1e.tryitonline.net/#code=W1fFvQoKWj8gIiB5aWVsZHMgIj8KUi5kwqxaMcKjxbhKUSwKCl0&input=Mzo0NQoxMjozNAoyMzo0NQozOjIxCjY6NTQKMToyMwo0OjMyCjI6MTAKMTowMAoxMjoxMwoxOjIxCg) [Answer] # [MATL](https://esolangs.org/wiki/MATL), 24 ~~18~~ ~~19~~ bytes ``` '%i%2i'1$4:5Z'YDdtdw|qh~ ``` [Try it online!](http://matl.tryitonline.net/#code=JyVpJTJpJzEkNDo1WidZRGR0ZHd8cWh-&input=) Output is an array consisting of only ones (which is truthy) if the time matches, and an array with at least one zero (that's falsy) otherwise. To test the code it's better to split it in two parts as follows: * [`1$4:5Z'`](http://matl.tryitonline.net/#code=MSQ0OjVaJw&input=) produces a 2-number vector with the current hour and minute. * [`'%i%2i'iYDdtdw|qh~`](http://matl.tryitonline.net/#code=JyVpJTJpJ2lZRGR0ZHd8cWh-&input=WzIgMTBd) takes from stdin a 2-number vector with hours and minutes and computes the result. In the combined code, the second part takes its input from the stack as produced by the first. ### Explanation A matching occurs if the following two conditions are met: * All differences between consecutive digits have absolute value 1; * All differences between those consecutive differences are 0. Minutes have to be zero padded (*thanks to Dennis for that!*). Zero-padding, if it actually occurs (minute is 9 or less) will always produce a falsy result. So I use space-padding instead, whivh has the same effect. Code: ``` '%i%2i' % format string for sprintf, including padding for minutes 1$4:5Z' % get current hour and minute as a 2x1 numeric array d % differences between consecutive digits (chars) td % duplicate. Compute differences again. Will be all zero if time matches w|q % swap, absolute value, subtract 1. Will be all zero if time matches h~ % concatenate both arrays and apply logical negate ``` [Answer] # Pyth, 38\*2.25 = 86 bytes ``` JsMfnT\:zK.b-NYt.>J1tJ|qlKlx1KqlKlx_1K ``` [Try it here!](http://pyth.herokuapp.com/?code=JsMfnT%5C%3AzK.b-NYt.%3EJ1tJ|qlKlx1KqlKlx_1K&input=1%3A23&test_suite=1&test_suite_input=3%3A45%0A12%3A34%0A23%3A45%0A6%3A54%0A1%3A23%0A4%3A32%0A2%3A10%0A1%3A00%0A1%3A21%0A12%3A13&debug=0) ### Explanation Works by converting the time to a list of integers, mapping this to a list of differences and checking if this list only contains -1 or 1. Difference checking works by rotating the integer list one to right and doing an elementwise subtraction with the original integer list using all elements but the first one in each list. ``` JsMfnT\:zK.b-NYt.>J1tJ|qlKlx1KqlKlx_1K # z = input fnT\:z # filter the : out sM # map the digits to integers J # assign the list to J .b # parallel map (with N and Y) to -NY # difference of N and Y t.>J1 # over all but the first element of J, rotated right tj # and all but the first element of J K # assign the result to K |qlKlx1KqlKlx_1K # check if K only contains -1 or 1 ``` [Answer] # Bash + coreutils, 59 ``` t=`date +%-H%M` ((`eval printf %s {${t::1}..${t: -1}}`==t)) ``` Shell return code is set to `0` (truthy) or `1` (falsey). * Save just the hours and minutes numbers of the date in variable `t` * Construct a bash brace expansion that runs from the first digit to the last digit of `$t`. The run produced by the expansion will automatically run in the right direction * `eval` allows the variable expansions to happen before the brace expansion * `printf` outputs the concatenated expansion as one string with no space separators * The result will be equal to `$t` in the truthy case - arithmetic evaluation to test this is shorter than the usual `[ ... ]` test. [Ideone.](https://ideone.com/ARKM7i) [Answer] # Julia, ~~92~~ 71 bytes ``` f(d=diff(["$(Dates.hour(now()))""$(now())"[15:16]...]))=all(d[1]d.==1) ``` This is a function that takes no arguments and returns a boolean. To call it, simply execute `f()`. We define the keyword argument `d` of `f` to be the cumulative difference in the ASCII codes associated with the digits of the hours and minutes of the current time. Then, for each difference, we multiply the first difference in the list by each successive difference and determine whether all are equal to 1. If so, the digits of the time are either monotone increasing by 1 or monotone decreasing by 1. Saved 21 bytes and fixed an issue thanks to Dennis! [Answer] # Mathematica, ~~85~~ 84 bytes ``` #==Range[#[[1]],Last@#,Sign[Last@#-#[[1]]]]&@Flatten@IntegerDigits@DateList[][[4;;5]] ``` Pretty basic. Compares the time (as a list of digits) to a range from [first digit] to [last digit]. [Answer] # Retina, ~~78~~ ~~63~~ ~~62~~ 60 \* 125% = 135 ``` : . $0$*aa: ^(a*)(:\1a:\1aa(:\1aaa)?|aaa:\1aa:+\1a(:\1)?):$ ``` 15 bytes thanks to Maria^H^H^H^H^HDigital Trauma, and for paving the way for 3 additional bytes. Prints 1 for success, 0 for failure. I imagine this isn't optimal, but I can't think of a better approach. This method requires that 1 be added to each of the time digits, otherwise 0 causes some problems. [Try it online!](http://retina.tryitonline.net/#code=OgoKLgokMCQqYWE6Cl4oYSopKDpcMWE6XDFhYSg6XDFhYWEpP3xhYWE6XDFhYTorXDFhKDpcMSk_KTok&input=MjM6NDU) You can try a slightly modified program [here](http://retina.tryitonline.net/#code=OgoKXGQKJDAkKmFhOgptYF4oYSopKDpcMWE6XDFhYSg6XDFhYWEpP3xhYWE6XDFhYTorXDFhKDpcMSk_KTokCnBhc3MKLio6LioKZmFpbA&input=U2hvdWxkIFBhc3MKLS0tLS0tLS0tLS0KCjM6NDUKMTI6MzQKMjM6NDUKMzoyMQo2OjU0CjE6MjMKNDozMgoyOjEwCgpTaG91bGQgbm90IHBhc3MKLS0tLS0tCgoxOjAwCjEyOjEzCjE6MjEKMTozNA) that runs on multiple lines. [Answer] # Perl, ~~90~~ 65 bytes ``` @i=`date +%R`=~/\d/g;@n=reverse@m=0..9;print"@m"=~/@i/|"@n"=~/@i/ ``` New approach: generate strings `"0 1 2 3 4 5 6 7 8 9"` and it's reverse and do a regexp match. --- The previous approach (90 bytes): ``` @l=map{("$_=>1,","$_-")}`date +%R`=~/\d/g;@a=%h=eval"@l[1..$#l-1]";print@a==2&&1==abs$a[1] ``` Commented: ``` @l= map{ ("$_=>1,","$_-") # return parts of expressions } `date +%R`=~ # grab the time, quick 'n' dirty, and apply a regexp /\d/g; # match all digits and return a list @a= # 'cast' the hash to a list %h= # 'cast' the list to a hash eval # evaluate the string "@l # this string is interpolated as join ' ', @l [1..$#l-1]"; # but only after discarding the first and last element print @a==2 && 1==abs $a[1] # check that the hash has 1 key and that it's value is +1/-1 ``` It's not going to win any prizes, but I had fun on this one so I'll share my work. The basic idea is the same as some/most other answers: calculate the deltas and make sure they are all either -1 or +1. The expression that is `eval`ed for the time `12:34` is constructed as follows: ``` @l= [1, $#l] "@l[...]" %h (("1=>1", "1-"), ( "1-", ("2=>1", "2-"), -> "2=>1", "2-", -> 1-2=>1, 2-3=>1, 3-4=>1 (-1 => 1) ("3=>1", "3-"), "3=>1", "3-", ("4=>1", "4-")) "4=>1", ) ``` Some things I tried that don't work: * using `exit` to save a byte. It sometimes returns `2`. * merely calculating the number of hash keys (74 bytes). This also matches all the time pattern where all the digits are the same. ``` @l=map{("$_=>1,","$_-")}`date +%F`=~/\d/g;%h=eval"@l[1..$#l-1]";print%h==1 ``` * calculating the absolute normalized sum of the deltas (79 bytes). This grew from the approach to `eval` into a scalar. The total sum would have to be ±2 for 3 digits and ±3 for 4 digits, easily normalized with the `$#array` syntax. The false positive `12:24` made this approach unfeasible: ``` @l=map{($_,"+","$_-")}@x=`date +%R`=~/\d/g;print 1==eval"abs(@l[2..$#l-2])/$#x" ``` [Answer] # Python 2, 93 bytes ``` import time,numpy print len(set(numpy.diff([int(time.asctime()[10+k])for k in[1,2,4,5]])))==1 ``` Not subject to the byte penalty. Small chance this doesn't work if `time.asctime()` changes during the loop. +4 bytes to fix this: ``` import time,numpy x=time.asctime() print len(set(numpy.diff([int(x[10+k])for k in[1,2,4,5]])))==1 ``` ]
[Question] [ # Background As you maybe know Ramanujan made this [magic square](https://en.wikipedia.org/wiki/Magic_square) by \$4x4\$ Matrix: ![](https://i.ytimg.com/vi/pWutwQkqV3g/hqdefault.jpg) This works like all [magic squares](https://en.wikipedia.org/wiki/Magic_square). But the special thing in this square is that his birthdate is hidden in the first row, the 22\$^{nd}\$ Dec 1887. # Challenge ****Can you make one for your birthdate?**** # Input The User will give Input in this format: DD/MM/yyYY. The input can't be a list of 3 numbers([DD,MM,yyYY]). Here is the formula to make a square for your birthdate ![](https://i.stack.imgur.com/KT9od.png) # Output The output should be a "unnormal" or special square, in your languages equivalent for a list. Note: These are not really magic squares, because as Abigail mentioned tin some dates there are duplicate numbers, but every row, column and diagonal there will e the same number of sum # Test cases: ``` In: 20/08/2000 Out: [20, 8, 20, 0] [1, 19, 5, 23] [6, 22, 2, 18] [21, -1, 21, 7] In: 10/01/2020 Out: [10, 1, 20, 20] [21, 19, -2, 13] [-1, 12, 22, 18] [21, 19, 11, 0] In: 10/05/2020 Out: [10, 5, 20, 20] [21, 19, 2, 13] [3, 12, 22, 18] [21, 19, 11, 4] In: 00/00/0000 Out: [0, 0, 0, 0] [1, -1, -3, 3] [-2, 2, 2, -2] [1, -1, 1, -1] ``` # Rules This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code wins [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~88~~ 84 bytes *Saved 4 bytes thanks to @NahuelFouilleul* ``` d=>`-BWe fV?0 @/gU Xd.A`.replace(/./g,c=>d.substr((n=Buffer(c)[0])/7-6,2)-3+n%7+' ') ``` [Try it online!](https://tio.run/##hc1JDoIwAEDRfU/BxrQNdKBGcVNU7uCQqAnYgWhIS1rw@ohbNyR/@ZL/bj5NVOHVD8R5bSYrJy3LmlQXA@x5z8GBtSdw1fRY02D6rlEGMcraTMlS0zg@4xAQcrIarTUBKXzjD8wKss0EJuvUrYoUJhBPyrvoO0M73yKLoOCM75jgnEOcpAm8O4jBn8lnk89GLJjNguGz@fV74ekL "JavaScript (Node.js) – Try It Online") ### How? Each value in the matrix is encoded as a character whose ASCII code is: $$7k+o+42$$ where \$k\$ is the 0-indexed position of the variable in the input string and \$o-3\$ is the offset to add. *Example:* For `MM-2`, the position is \$3\$: ``` "DD/MM/yyYY" ^ 0123456789 ``` and the offset is\$-2\$, leading to: $$7\times3+(-2+3)+42=64$$ which is `'@'`. [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 66 [bytes](https://codegolf.meta.stackexchange.com/questions/9428/when-can-apl-characters-be-counted-as-1-byte-each/) ``` {4 4⍴(∊(⊣,-)¨3-⍨1011304⊤⍨8⍴6)+,(⊢⍪⌽∘⊖⍪⌽⍪⊖)2 2⍴10⊥⍉⍎¨4 2⍴'/'⎕R''⊢⍵} ``` [Try it online!](https://tio.run/##dYw9CsJAEEZ7T5FuE0zI7CZKehttjRcQRBtBWxErIcTFFS0M1v5AEMFGS5sc5btIHIPYCcPHzLw305@OvcGsP56MynIeWiHMw0aqbeiT6zlFHngwuSQpAwqhzzxErDSdusvKEeaK9QvpATr79pw6c5SlWJMEfYFZwWyKPKxWwhfY7LtCVNfPRTlEsmUOvYS5sVDcAyQ7duJui7PX7sTl0OKOPaHIp8hXRCRq35Wo/ahkKpmqv7TxlxLTT/HnNw "APL (Dyalog Unicode) – Try It Online") ### How? The key insight is that the rows correspond to a single 2×2 matrix that has been mirrored vertically, horizontally, not at all, or both. ``` {4 4⍴(∊(⊣,-)¨3-⍨1011304⊤⍨8⍴6)+,(⊢⍪⌽∘⊖⍪⌽⍪⊖)2 2⍴10⊥⍉⍎¨4 2⍴'/'⎕R''⊢⍵} ⍝ Anonymous inline function ⍵ ⍝ Input, e.g. '22/12/1887' '/'⎕R'' ⍝ Replace '/' with '', giving e.g 22121887 10⊥⍉⍎¨4 2⍴ ⍝ Reshape and execute to give vector (22,12,18,87) 2 2⍴ ⍝ Reshape to 2×2 matrix (22 12)(18 87) (⊢⍪⌽∘⊖⍪⌽⍪⊖) ⍝ Mirror the matrix in 4 ways to get the 4 rows , ⍝ Flatten to a row vector 1011304⊤⍨8⍴6 ⍝ Base 6 encoding of 3 3 4 0 1 5 4 4 3-⍨ ⍝ Subtract 3 from each: 0 0 1 ¯3 ¯2 2 1 1 ∊(⊣,-)¨ ⍝ Append the negative to each and flatten: 0 0 0 0 1 ¯1 ¯3 3 ¯2 2 2 ¯2 1 ¯1 1 ¯1 + ⍝ Add these constants to each element 4 4⍴ ⍝ Reshape to give a 4×4 matrix ``` [Answer] # [K (ngn/k)](https://bitbucket.org/ngn/k), ~~53~~ 51 bytes **Solution:** ``` {4 4#x,(3-7\5330941200)+(x:.'4 2#x^"/")@4\14962353} ``` [Try it online!](https://tio.run/##Rco9CoAwDEDh3VOUdrBFa9Mk9W/yIOKog@BcEM9e4yS85YN3@uu4yj7frNjk1pIf1kQEE0cEcI3Nc1ezQpM3HbRbeI089UiJnrIrjRBgDHKCroRRGIX4M/0E4ZfMpbw "K (ngn/k) – Try It Online") **Explanation:** Probably further golfable... ``` {4 4#x,(3-7\5330941200)+(x:.'4 2#x^"/")@4\14962353} / the solution { } / lambda taking implicit x 4\14962353 / decode 14962353 into base 4 => 3 2 1 0 1 0 3 2 2 3 0 1 @ / use that to index into ( ) / do all this together x^"/" / x except (^) "/" 4 2# / reshape as 4x2 grid .' / 'value each', convert e.g. "20" to 20 x: / save back into x + / add to ( ) / do this together 7\5330941200 / decode 5330941200 into base 7 => 2 4 6 0 5 1 1 5 2 4 2 4 3- / subtract from 3 => 1 -1 -3 3 -2 2 2 -2 1 -1 1 -1 x, / prepend x 4 4# / reshape into 4x4 grid ``` **Extra:** * -1 byte with `^"/"` (except "/") instead of dropping indices 5 and 2 (`_/5 2`) * -1 byte with `3-7\5330941200` instead of `-3+7\8510346000` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~27~~ ~~26~~ 24 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` þ2ôÀā+āδ-˜•Itíˀߕ.I4ô ``` -2 bytes by porting [*@JonathanAllan*'s Jelly answer](https://codegolf.stackexchange.com/a/207099/52210), so make sure to upvote him as well! [Try it online](https://tio.run/##ATwAw/9vc2FiaWX//8O@MsO0w4DEgSvEgc60LcucxIHigKJJWs6Ubc67UuKAoi5Jw6g0w7T//zEyLzExLzE5OTE) or [verify all test cases](https://tio.run/##yy9OTMpM/V9TpuSZV1BaYqWgZF@pw6XkX1oC4elU/j@8z@jwlsMNRxq1jzSe26J7es6RxkcNizyjzk3JPbc7CMjU8zy8wuTwlv@2SgFFqSUllboFRZl5JakpCvlwUw7t1jm0zf6/oZG@oaG@oaWlIZeRgb6Bhb6RgYEBlyGQaQhkGkGYphCmAZAJQkAFQFkDS6CoqQEA). --- **Old ~~27~~ 26 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) approach:** ``` þ2ôÂD2ôR˜Â)•CV¤½‘àý•S4ä3-+ ``` [Try it online](https://tio.run/##yy9OTMpM/f//8D6jw1sON7kAyaDTcw43aT5qWOQcdmjJob2PGmYcXnAYSC0KNjm8xFhX@/9/QyN9Q0N9Q0tLQwA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9TpuSZV1BaYqWgZF@pw6XkX1oC4elU/j@8z@jwlsNNLkAy6PScw02ajxoWOYcdWnJo76OGGYcXHAZSi4JNDi8x1tX@b6sUUJRaUlKpW1CUmVeSmqKQDzfo0G6dQ9vs/xsa6Rsa6htaWhpyGRnoG1joGxkYGHAZApmGQKYRhGkKYRoAmSAEVACUNbAEipoaAAA). **Explanation:** ``` þ # Leave the digits of the (implicit) input-string: "dd/MM/YYyy" to "ddMMYYyy" 2ô # Split it into parts of size 2: [DD,MM,yy,YY] À # Rotate it once towards the left: [MM,yy,YY,DD] ā # Push a list in the range [1,length] (without popping): [1,2,3,4] + # Add the values at the same indices: [MM+1,yy+2,YY+3,DD+4] ā # Push [1,2,3,4] again δ # Apply double-vectorized on these lists: - # Subtract # (results in: [[MM,MM-1,MM-2,MM-3],[yy+1,yy,yy-1,yy-2],[YY+2,YY+1,YY,YY-1], # [DD+3,DD+2,DD+1,DD]]) ˜ # Flatten it: # [MM,MM-1,MM-2,MM-3,yy+1,yy,yy-1,yy-2,YY+2,YY+1,YY,YY-1,DD+3,DD+2,DD+1,DD] ā # Push a list in the range [1,length] (without popping) again: [1,...,16] •IZΔmλR• # Push compressed integer 19556972234337 .I # Get the 19556972234337'th permutation of the [1,16] list è # Index each into the list of values (modular 0-based, so 16 is the first): # [DD,MM,yy,YY,YY+1,yy-1,MM+3,DD+3,MM-2,DD+2,YY+2,yy-2,yy+1,YY-1,DD+1,MM-1] 4ô # And split it into parts of size 4 again # (after which the result is output implicitly þ2ô # Same as above: [DD,MM,yy,YY]  # Bifurcate this list (short for Duplicate & Reverse copy) # [DD,MM,yy,YY] → [YY,yy,MM,DD] D # Duplicate it 2ô # Split it into pairs # [YY,yy,MM,DD] → [[YY,yy],[MM,DD]] R # Reverse the pairs # [[YY,yy],[MM,DD]] → [[MM,DD],[YY,yy]] ˜ # Flatten it back again to a quartet # [[MM,DD],[YY,yy]] → [MM,DD,YY,yy]  # Bifurcate that as well # [MM,DD,YY,yy] → [yy,YY,DD,MM] ) # And wrap all list on the stack into a list # → [[DD,MM,yy,YY],[YY,yy,MM,DD],[MM,DD,YY,yy],[yy,YY,DD,MM]] •CV¤½‘àý• # Push compressed integer 3333420615514242 S # Convert it to a list of digits: [3,3,3,3,4,2,0,6,1,5,5,1,4,2,4,2] 4ä # Split it into 4 equal-sized parts: [[3,3,3,3],[4,2,0,6],[1,5,5,1],[4,2,4,2]] 3- # Subtract 3 from each: [[0,0,0,0],[1,-1,-3,3],[-2,2,2,-2],[1,-1,1,-1]] + # Add the values in the lists together: # [[DD,MM,yy,YY], # [YY+1,yy-1,MM-3,DD+3], # [MM-2,DD+2,YY+2,yy-2], # [yy+1,YY-1,DD+1,MM-1]] # (after which the result is output implicitly ``` [See this 05AB1E tip of mine (sections *How to compress large integers?* and *How to compress integer lists?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `•IZΔmλR•` is `19556972234337` and `•CV¤½‘àý•` is `3333420615514242`. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~27~~ 26 bytes ``` ḟṂs2Vṙ1+J$_Ɱ4F“Œñḳ⁶.C’œ?ṁƲ ``` A monadic Link accepting the list of characters as specified which yields a list of lists of integers. **[Try it online!](https://tio.run/##AUQAu/9qZWxsef//4bif4bmCczJW4bmZMStKJF/isa40RuKAnMWSw7HhuLPigbYuQ@KAmcWTP@G5gcay////MjAvMDgvMjAwMA "Jelly – Try It Online")** ### How? ``` ḟṂs2Vṙ1+J$_Ɱ4F“Œñḳ⁶.C’œ?ṁƲ - Link: list of characters, D e.g. "01/09/2000" Ṃ - minimum '/' ḟ - filter discard "01092000" s2 - split into twos ["01","09","20","00"] V - evaluate [1,9,20,0] ṙ1 - rotate left 1 [9,20,0,1] $ - last two links as a monad: J - range of length [1,2,3,4] + - add [10,22,3,5] Ɱ4 - map across [1..4] with: _ - subtract [[9,21,2,4],[8,20,1,3],[7,19,0,2],[6,18,-1,1]] Ʋ - last four links as a monad - f(x): F - flatten [9,21,2,4,8,20,1,3,7,19,0,2,6,18,-1,1] “Œñḳ⁶.C’ - base 250 integer = 19644039699318 œ? - nth permutation [1,9,20,0,1,19,6,4,7,3,2,18,21,-1,2,8] ṁ - mould like (x) [[1,9,20,0],[1,19,6,4],[7,3,2,18],[21,-1,2,8]] ``` [Answer] # perl -nl -M5.010, 106 bytes ``` /.(\d\d).(\d\d)/;$,=$";say$`,$1,$2,$';say$'+1,$2-1,$1-3,$`+3;say$1-2,$`+2,$'+2,$2-2;say$2+1,$'-1,$`+1,$1-1 ``` [Try it online!](https://tio.run/##LYtBCoNADEXvUgJjmcQxEakgHsEbuJiCXRREpeOmlzeaQQj/8z4v2@c3N6qhLMZpnJ53hQ6wh0eX3n@ICIwgCC6j80Z0BVONEH2dZyYxMM1CSPIsZjuzo88vrCoS@Lq2fR3rtn/XJSkts9LQlBVXJw "Perl 5 – Try It Online") ## How does it work? ``` /.(\d\d).(\d\d)/; ``` This lines parses the input. It matches the `/MM/yy` part of the input, leaving `MM` in `$1` (the first capture) and `yy` in `$2`. `DD` is available in `$`` (the "prematch"), and `YY` is available in `$'` ("postmatch"). ``` $, = $"; ``` This sets the output field separator equal to the list separator, the latter is by default a space. This makes that our output numbers are separated by a space. ``` say $` , $1 , $2 , $'; say $' + 1, $2 - 1, $1 - 3, $` + 3; say $1 - 2, $` + 2, $' + 2, $2 - 2; say $2 + 1, $' - 1, $` + 1, $1 - 1 ``` Print out the 16 required numbers. In the top row, it will keep any leading spaces, as the values are printed "as is". [Answer] # [Perl 5](https://www.perl.org/) + `-pF/\/?(\d\d)/ -Mbigint`, 74 bytes ``` $_="1357 7531 3175 5713";s!.!$F[$&]-3+(3333420615514242=~/./g)[$i++].$"!ge ``` [Try it online!](https://tio.run/##DcLRCoMgFADQd/8ikVGIuqveGYzYW2/7gozBKESIktXzPn13HU6ZPwsSiVfHwWFgAR0wBwEZBnD8vle6Ev0gLqNysnYnb683QARvve2@RpvUDCJLOWrBqzQTWWvg3Lbht5Ujb@tOqvQmmkcdpzg1htTznVNejz8 "Perl 5 – Try It Online") [Verify all test cases online!](https://tio.run/##JcZLCoMwFEDReXahhGIRfZ/4GkGkM2ddgUqhKBIQleq4S2@a4uUOzja@Z/Ha1Vh5/axjMmKVFUPKkBUllkxc7VEe6abVlz4zaWJCBeONRKjggusP5DBdW@3StM91HE2j98xA4bK0ihGwBEZERYEUyCflJAb@R/yu2@HWZffZNjfQwT3phm64gs8eLze55fgB "Perl 5 – Try It Online") ## Explanation The `-F` flag, splits the input into `@F` as `('',22,'',12,'',18,'',87)`. In the code `$_` is set to a string containing the index of `@F` that we need the number from, then `s///` replaces any char (`.` - this excludes newline) with the the corresponding value from `@F` minus `3`, plus the digit from `3333420615514242` at the `$i`ndex, appending `$"` (space). [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 46 bytes ``` E⪪+5?IJ>2.3-K=@H,4⁴⪫Eι◧I⁺⁻﹪℅λχ³§I⪪⪫⪪θ/ω²÷℅λχ² ``` [Try it online!](https://tio.run/##XY3LDoIwEEV/pemqjVVKwZXxFV0ISiTxCxqKcZKmRSjo39cKcePinswk91E9ZFtZqb0vWzCOFLIht0aDI3i23Gb5RiyS@Xm9O7EUM5RShnILZrQBQ6VUl/ruyEF2jpS670gB5kurem3JtVVgpCY6xGIekATtXWZU/Z4y09RYOZ1PhnCEg@0VJGhAZtwRBlD1fx2lPwtGODwr72Me8TgSXHA/H/QH "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` E⪪+5?IJ>2.3-K=@H,4⁴ ``` Split the string literal `+5?IJ>2.3-K=@H,4` into chunks of 4 characters and loop over each chunk, which represents a row of the magic square. ``` ⪫Eι◧I...² ``` Loop over each character, and pad each result to 2 characters and join them together to form the row. ``` ⁺⁻﹪℅λχ³§...÷℅λχ ``` Take the ASCII code of the character and divmod it by 10. Subtract 3 from the remainder to give a value in the range `-3`..`3` and add the date part given by the quotient (this is offset by 4 but that works due to Charcoal's cyclic indexing). ``` I⪪⪫⪪θ/ω² ``` Delete the `/`s from the input string, split the result into pairs of digits and take their value. ]
[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/25606/edit). Closed 3 years ago. [Improve this question](/posts/25606/edit) Count the number of unique fractions with numerators and denominators from 1 to 100, and print the counted number. Example: 2/3 = 4/6 = ... Rules: You must actually count in some way. Only integers are allowed, no floating point numbers or fraction types. Integers count as fractions. So 1/1, 2/1, etc is valid. [Answer] # J - 21 17 char ``` +/1=,+./~1+i.100 ``` Explained: * `1+i.100` - The integers from 1 to 100. * `+./~` - Table of GCDs. * `1=,` - Run into a list, and then check for equality to 1. * `+/` - Add together the results (true is 1, false is 0). Usage: ``` +/1=,+./~1+i.100 6087 ``` 21 char version that actually constructs all the pairs of numbers: ``` #~.,/(,%+.)&>:/~i.100 ``` `&>:` increments all the integers and also sets up another golfy thing, while `~.` takes all the unique entries in the list of pairs we construct, and then `#` gives the length of that. [Answer] # Ruby, 57 (67 without `Rational`) (-3 if run in IRB) ``` p((a=[*1..100]).product(a).map{|x|Rational *x}.uniq.size) ``` Output: ``` 6087 ``` Can be 3 less characters if run in IRB, because you can remove the `p(` and `)`. Uses `product` for the numerator and denominator getting process, and then uses `Rational` for converting them to fractions. If you remove the `.size` at the end, it prints all of the fractions instead of how many there are. It seems like it might take a long time to run, but it's actually almost instantaneous. Here's an example IRB session to explain how the code works a bit better: ``` irb(main):027:0> (a=[*1..5]).product(a) => [[1, 1], [1, 2], [1, 3], [1, 4], [1, 5], [2, 1], [2, 2], [2, 3], [2, 4], [2, 5], [3, 1], [3, 2], [3, 3], [3, 4], [3, 5], [4, 1], [4, 2], [4, 3], [4, 4], [4, 5], [5, 1], [5, 2], [5, 3], [5, 4], [5, 5]] irb(main):028:0> Rational 1, 2 => (1/2) irb(main):029:0> Rational 2, 4 => (1/2) ``` `Rational *x` uses the "splat" operator to call the `Rational` function with arguments given in the array `x`. This "splat" is also used in `[*1..100]`. Here's an alternative that doesn't use `Rational`, weighing in at 66 characters: ``` p((a=[*1..100]).product(a).map{|x,y|z=x.gcd y;[x/z,y/z]}.uniq.size) ``` The fraction simplification method is replaced with this: ``` z=x.gcd y;[x/z,y/z] ``` which divides the numberator and the denominator by their GCD (greatest common denominator), and then sticks them back in an array so that `uniq` can work. [Answer] # Bash + GNU tools, 47 ``` $ echo 10^9\*{1..100}/{1..100}\;|bc|sort -u|wc -l 6087 $ ``` Looks like a similar method to [@Doorknob's answer](https://codegolf.stackexchange.com/a/25608/11259). [Answer] # JavaScript, 64 characters ``` for(n=101,o=0,c={};--n;)for(d=101;--d;)!c[n/d]&&(c[n/d]=++o);o ``` Put into the JS console, returns 6087. [Answer] ## Mathematica - 24 This is just a sequence [A018805](https://oeis.org/A018805). `EulerPhi[n]` is the number of coprime to `n` integers `m` that are below `n` (gcd n m == 1) ``` 2 Tr@EulerPhi@Range@100 - 1 ``` ## J - 15 ``` <:+:+/5&p:i.101 ``` [Answer] # [Haskell](https://www.haskell.org/), 32 bytes ``` sum[1|1<-gcd<$>r<*>r] r=[1..100] ``` [Try it online!](https://tio.run/##y0gszk7NyfmfbRvzv7g0N9qwxtBGNz05xUbFrshGy64olqvINtpQT8/QwCD2f25iZp6CrUJBUWZeiYKKQvb/f8lpOYnpxf91kwsKAA "Haskell – Try It Online") Tries to follow the spirit of actually computing the result by having a "100" that can be replaced with any number. [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 12 bytes ``` ≢⍸1=∘.∨⍨⍳100 ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn//1Hf1EdtEx51LnrUu8PQ9lHHDL1HHSse9QLRZkMDg///AQ "APL (Dyalog Extended) – Try It Online") Original: ``` (+/1=∘,⍳∘.∨⍳)100 ``` Explanation: ``` (+/1=∘, ⍳∘.∨⍳ )100 ⍝ ^~~~~~v ^~~~v ^~~~v ⍝ | | 100 x 100 ⍝ | greatest common divisor table of dimensions ⍝ flatten, count all values equal to one in ``` [Answer] ## Sage, 62 or 42 *Runs in the interactive prompt.* ``` c=0 R=range(1,101) for i in R: for j in R: c+=gcd(i,j)==1 c ``` Short and easy to understand. If use of Euler's totient function is allowed, here's a 42-char one-liner: ``` 2*sum(euler_phi(n)for n in range(1,101))-1 ``` [Answer] # Haskell 47 ``` sum$filter(<2)[gcd a b|a<-[1..100],b<-[1..100]] ``` Run this from the interpreter. [Answer] # CJam - ~~18~~ 22 ~~100,:):X{dXf/}%:|,~~ Oops, I had missed the "no floating point" requirement. Here is an integer-based solution: ``` 100,:):X_:*f*{Xf/}%:|, ``` CJam is a new language I am developing, similar to GolfScript - <http://sf.net/p/cjam>. Here is the explanation: `100,` makes an array [0 1 ... 99] `:)` increments all the elements of the array `:X` assigns to variable X `_` duplicates the last value (the array) `:*` multiplies the array elements together, thus calculating 100! `f*` multiplies each array element with 100! `{`...`}%` performs a "map" - applies the block to each element `Xf/` divides the current number by each element in X; since the numbers were already multiplied by 100!, it is an exact division `:|` performs a fold with the `|` (set union) operator, on the array of arrays we obtained `,` counts the number of elements [Answer] # [Husk](https://github.com/barbuz/Husk), 11 bytes ``` LumF/π2ḣ100 ``` [Try it online!](https://tio.run/##yygtzv7/36c0103/fIPRwx2LDQ0M/v8HAA "Husk – Try It Online") [Answer] # Mathematica, 77 ``` Length@Select[Range[100]~Tuples~2,#[[1]]==Numerator@Simplify[#[[1]]/#[[2]]]&] ``` Wow, this is the longest one here. Guess I'm not too good at thinking outside the box... [Answer] # C++ - 64 ``` #include<iostream> main(){int i=0;while(++i<6087);std::cout<<i;} ``` It counts in *some* way! [Answer] # Python, 81 characters I guess the following solution is more math golf than code golf: it prints all the fractions as well. The algorithm might be an inspiration for code golfers, though. ``` def f(i,j,k,l): m,n = i+k,j+l if m > 100 or n > 100: return 0 print("%d/%d" % (m,n)) return f(i,j,m,n)+f(m,n,k,l)+1 print(f(0,1,1,0)) ``` So after proving that this does the right thing (it would not be producing all the right fractions if it didn't, would it?), we can write this as ``` f=lambda i,j,k,l:i+k<101>j+l and f(i,j,i+k,j+l)+f(i+k,j+l,k,l)+1;print f(0,1,1,0) ``` Which is 81 characters. At the interactive prompt, you can save the six characters "print " but that seems like a bit of cheating. It's worth noting that putting 10001 instead of 101 and adding ``` import sys sys.setrecursionlimit(100000) ``` in front allows to calculate the number of all fractions with nominator/denominator smaller than 10000 in less than a minute. Which is impressive since every single of the 60794971 fractions is actually generated as well as counted separately. And another thing worth noting is that discounting the break-off condition, all positive fractions in shortest terms are generated by this recursion, one per call. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 7 bytes Port of isaacg's Haskell answer. ``` тLãʒ¿}g ``` [Try it online!](https://tio.run/##yy9OTMpM/f//YpPP4cWnJh3aX5v@/z8A "05AB1E – Try It Online") ## Explanation ``` т Push 100 L Length range: [1 .. 100] ã All possible pairs ʒ Filter where: ¿ The gcd of the pairs } is equal to 1 g Find the length ``` ]
[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/219246/edit). Closed 2 years ago. [Improve this question](/posts/219246/edit) Inspired from [Is this site down or is it just me?](https://codegolf.stackexchange.com/questions/129492/is-this-site-down-or-is-it-just-me?rq=1) # Challenge You have to print if a website server is online or not, for you. # Input The domain name, like `codegolf.stackexchange.com` # Output * 1/True if online * 0/False if offline # Rules * Any kind of web access is allowed * URL shorteners allowed * Except 2 no. Rule, all standard loopholes forbidden * You cannot use a language which cannot access internet * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer wins Cheers! [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 15 [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. Prompts for URL from stdin. ``` 1≠≢⎕SH'ping ',⍞ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKO94L/ho84FjzoXPeqbGuyhXpCZl66grvOodx5I8r8CGBQAAA "APL (Dyalog Unicode) – Try It Online") `⍞` prompt for URL `'ping ',` prepend command `⎕SH` **sh**ell out `≢` count the number of lines in the response (will be 1 on fail, more on success) `1≠` does 1 differ from that? (1 or 0) [Answer] # PowerShell, 21 26 bytes +5 bytes thanks to Joel Coehoorn, who correctly pointed out that I misunderstood the challenge. ``` !!((ping @args)-match's=') ``` [Answer] # [MATL](https://esolangs.org/wiki/MATL), 4 bytes This answer takes the challenge literally and ensures that an HTTP web server is successfully running at the address. ``` 4#Xi ``` The online MATL compilers do not have access to arbitrary URLs, but this can be run using MATL locally. **Explanation** ``` % Implicitly retrieve the input URL 4# % Specify that we want only the second output of the next function call Xi % Call urlread function which attempts to make an HTTP request to the URL. % The second output value that we save indicates success (1) or failure (0). ``` [Answer] # [Bash](https://www.gnu.org/software/bash/), 10 bytes ``` curl -f $1 ``` [(Can't) try it online!](https://tio.run/##S0oszvifVpqXXJKZn6eQpqGpUP0/ubQoR0E3TUHF8H8tV2pyRr6CikaaQnl5uV5yfkpqen5Oml5xSWJydmpFckZiXnoqUDhX8z8A "Bash – Try It Online") Works fine on my laptop. Returns `0` (linux truthy) if all is well or some other int if not (linux falsey). From `man curl`: > > -f, --fail > (HTTP) Fail silently (no output at all) on server errors. This is mostly done to better enable scripts etc to better > deal with failed attempts. > > > [Answer] # Powershell, ~~32~~ 25 bytes ``` !!(resolve-dnsname @args) ``` Equal byte alternative (Will take 4 seconds, to send 4 pings): ``` !!(test-connection @args) ``` -7 bytes thx to @ZaelinGoodman [Answer] # PowerShell, 13 bytes ``` !!(iwr @args) ``` There's also this, at 30 bytes: ``` (iwr @args).StatusCode -eq 200 ``` Which isn't as short as some other answers, but IMO so far it's the only one that actually meets the goal of validating the web server. Others could be getting an HTTP 500-series response and saying everything is fine. Powershell 7 also has `-SkipHttpErrorCheck`, so we can avoid some exceptions and show a nice `False` more often, but that almost doubles the size. [Answer] Using only built-in libs. # [Python 3](https://docs.python.org/3/), 77 bytes ``` from urllib.request import* try:print(bool(urlopen(input()))) except:print(0) ``` [Try it online!](https://tio.run/##LcoxCoAwDAXQ3VM4VgcruPU4lYiBmsT4C3r66uCbnz3YVZbWNtejr14K58nprHSh58PUMXbwJ5mzIGTVEr6lRhJYrCIMn47ulQx/mofWdsCuFCNYJ68SXw "Python 3 – Try It Online") -42 bytes by @Makonede! [Answer] # [PHP](https://php.net/) (-F), 34 bytes ``` <?=$argn!=gethostbyname($argn)?:0; ``` [(Cannot) Try it online!](https://tio.run/##K8go@P/fxt5WJbEoPU/RNj21JCO/uCSpMi8xN1UDLKhpb2Vg/f9/cn5Kanp@TppecUlicnZqRXJGYl56ql5yfu6//IKSzPy84v@6bgA "PHP – Try It Online") Will display `1` or `0`. Reminds me a recent answer.. don't know why.. Explanation: `gethostbyname` returns the domain string when it fails, and when the first alternative `b` is missing in ternary `a?b:c`, `a`'s value is used. Truthy values are displayed `1` by default Such kind of requests are disabled on TIO though. [Answer] # [Python 2](https://docs.python.org/2/), ~~80~~ 66 bytes ``` try:get(x).ok except:print 1 else:print 0 from requests import* ``` [Try it online!](https://tio.run/##Lcc7EkAwEADQ3im2IwqDMrcxsYuR2Nis3@lD4XUvPjrz1ucRCai6jc2g8tgJ9UvDawF4O4xqoyybQvfdJ/zXFiQcQHA/MGmCJUQWrTNVZdLBrXyikOercRxKk18 "Python 2 – Try It Online") -14 bytes for @Suever! [Answer] # [SlimSharp](https://github.com/jcoehoorn/SlimSharp/), 56 bytes ``` P((new System.Net.WebClient.DownloadData(R())).L() > 0); ``` Can't test this on .Net Fiddle because it guts the `WebClient` type. [Answer] # Windows Batch, 38 bytes ``` @ping %1 >nul&&(echo 1&exit /b)&echo 0 ``` ]
[Question] [ ### Challenge I think everyone of us heard of URL encoding mechanism - it's basically everywhere. Given an URLEncoded string on stdin, decode it, and output the decoded form to stdout. The encoding is very simple, `+` or `%20` is representing space. Every percent followed by two hex digits (uppercase or lowercase) has to be replaced with ASCII character code of this number. [Related, but it's the other way round](https://codegolf.stackexchange.com/questions/89767/percent-encode-a-string) ### Example ``` 100%25+working => 100% working %24+%26+%3C+%3E+%3F+%3B+%23+%3A+%3D+%2C+%22+%27+%7E+%2B+%25 => $ & < > ? ; # : = , " ' ~ + % %414243 => A4243 ``` Test case that fails: ``` %24%XY+%%% ^~~~~~~ => $ ``` ### Rules * [Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. * If your programming language has built-in function to decode the URL, using it *(the function)* is forbidden. * Assume ASCII character set. No Unicode and all that stuff. * This is a code-golf, so the answer with the fewest bytes used to accomplish the task wins. * Please include a link to an online interpreter for your code. * Your program has to decode until EOF or an error (eg. percent without valid hex digits - `%xy`) is spotted (you can safetly terminate). * If anything is unclear, please let me know down in the comments. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~41~~ 30 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` '+ð:Δć©'%Qi2ôćuDHç©Ç`hÊiq}J}®? ``` -11 bytes thanks to *@Grimy*. [Try it online](https://tio.run/##yy9OTMpM/f9fXfvwBqtzU460H1qprhqYaXR4y5H2UhePw8sPrTzcnpBxuCuzsNar9tA6@///VY1MtFWNzLRVjZOB2BWI3YDYCShmDKQdgdgFyHYGYiMgNtdWNQeqMQLJmwIA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9TpuSZV1BaYqWgZF@pw6XkX1oC4/1X1z68werclCPth1aqqwZmGh3ecqS91MXj8PJDKw@3J2Qc7so0VK71qj20zv5/7aFtOv8NDQxUjUy1y/OLsjPz0rlUjUy0VY3MtFWNnYHYFYjdgNgJKGYMpB2B2AXIBsoZGQGxubaqOVCNEUjelEvVxNDEyMQYZIZqRKS2qqoql2pioqqjo2qio6pjIgA). **Explanation:** ``` '+ð: '# Replace all "+" in the (implicit) input with spaces Δ # Loop until the result no longer changes: ć # Extract head; pop and push remainder-string and first character © # Store the character in variable `®` (without popping) '%Qi '# If this character is a "%": 2ô # Split the remainder-string into parts of size 2 # i.e. "abcde" → ["ab","cd","e"] ć # Extract head again u # Convert it to uppercase D # Duplicate it H # Convert it from hexadecimal to integer # (NOTE: even if it isn't a valid hexadecimal string, # it will still result in an integer regardless) ç # And then from integer to ASCII-character with this codepoint © # Replace variable `®` with this (without popping) Ç`h # Reverse process: ASCII-character → integer → hexadecimal string Êi # If both are NOT equal (so it initially was invalid hexadecimal): q # Stop the program }J # And join the list of 2-char strings back together }®? # And then print `®` without newline ``` [Answer] # [JavaScript (V8)](https://v8.dev), 112 bytes ``` u=>u.match(/([^%]|%[\da-f]{2})*/i)[0].replace(/%..|./g,d=>d=="+"?" ":d[1]?String.fromCharCode("0x"+d[1]+d[2]):d) ``` [Try it online!](https://tio.run/##XYzdasJAEIXvfQpZGNh1dZNM4g/CKm3avkBvWuIKSzbRtGrCNqaF2mdPx5tCvfhmhnPOnDfb2Y/cV0076RZ9Z/2w1P1Zr87qaNt8zwOebcFcINs4OynNN/6IUVCJLDTKF83B5gUPQKmLCnZjp1dOaybZmg3Z0mWRWT@3vjrtVOnrY7q3Pq1dwVn4xeTVpYFGLJ3oG0q1vOQsCkPAqfys/Tv9MSEGfxZgIgFnEuKUeCSeiHvSYtp3xAPd5CEScwlzyuDVn/7vSaIEk/i2G15eJQCQ3P8C "JavaScript (V8) – Try It Online") Noticed Arnauld's [92 byte](https://codegolf.stackexchange.com/a/189146/79857) Node.js answer shortly after spending some time golfing this. Porting that method would save quite a few bytes (with the main difference being `Buffer` vs. `String.fromCharCode`), but I wanted to post this one as it's more interesting and the V8 port wouldn't be worth a separate answer. This challenge requires input validation, so the first `.match` takes only the valid part of the URL. Then, each part of it is `replace`d using a function. One trick I used that's kind of neat is the `"0x"+d[1]+d[2]`. Ordinarily you can convert hexadecimal to decimal using `+("0x"+n)`, but it seems `String.fromCharCode` casts to number on its own, saving three bytes. Instead of slicing the initial `%`, I just concatenate the second and third characters, which is shorter. [Answer] # [Gema](http://gema.sourceforge.net/), 45 characters ``` += %<X2>=@int-char{@radix{16;10;$1}} %=@fail ``` Insensitive on hexadecimal case. Sample run: ``` bash-5.0$ gema '+= ;%<X2>=@int-char{@radix{16;10;$1}};%=@fail' <<< $'100%25+working\n%24+%26+%3C+%3E+%3F+%3B+%23+%3A+%3D+%2C+%22+%27+%7E+%2B+%25\n%414243\n%24+%XY+%%%' 100% working $ & < > ? ; # : = , " ' ~ + % A4243 $ ``` [Try it online!](https://tio.run/##JcxNCsIwEAXgfU7hwrcahGaStosaib9nqMugtga1QhAUSs8eR1x8zPDeMP3lEXImN1NYtrxyPg6vxeka0uhTOMfPqKtGF81cT5OC812I95x1UYBLej/TLQ69AlsCVwSzFXtxEBvJjMy12MkuHbOoCbXc8K8vFay2bM3/R3skAF8 "Gema – Try It Online") [Answer] # Perl 5 (`-0777p -Mre=/si`), 45 bytes ``` s/%.?[^\da-f].*//;y/+/ /;s/%(..)/chr hex$1/ge ``` [TIO](https://tio.run/##FYvLCsIwEEX3@YouDKihmXaamkUR8bnzA8QHiMa2KElJCtafN46Lw1zm3NsZ/ypjDMDl4ng53a/p4yynANUHBCRQkRhLOYFb45PGDKMcahNjnmUcS/F2/tnamjGOSnCcCV6siS2xI1b0K@guiQ1lcoiEFlxTB/@@pLHKFaqCwnBgzLo@CcZY9nVd3zobYppprbuY7r2ZQ2h/) [Answer] # [JavaScript (Node.js)](https://nodejs.org), 92 bytes ``` f=([x,y,z,...a])=>x=='%'?1/(n='0x'+y+z)?Buffer([n])+f(a):'':x?(x=='+'?' ':x)+f([y,z,...a]):a ``` [Try it online!](https://tio.run/##bY3bCoJAEIbve4oIht1lzHS1AmGTjs9QiBdLuWLFbtjJenkbr4Lo4mMO38/MUT/0dV9Xl9vQukPRtkbxrPFe3tvzfV/nQs0apRiwNBxxq1jQMHzhW6SLuzFFzTObCzRci4SxpEl5F0aWsj5Nnci@lxLd7p29unPhn13JDR@EQQByjE9XnypbDoTo/QRAxghyghAtiTWxIRa0i6jOiRX15KQkpghTysjOj/9di8NYxtH/P7DdIQCQbD8 "JavaScript (Node.js) – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 90 bytes ``` def d(s):t='%'!=s[0];print(end=t*s[0].replace('+',' ')or chr(int(s[1:3],16)));d(s[3-2*t:]) ``` [Try it online!](https://tio.run/##JY3NasMwEITvegr1sEiK0mJLdgIKPqh/z9BiTBG2kpgWWUgqbZ7eXdPDxy4zw0y8lesS9LpO/kwnnoUpHQN21@W@Gk4xzaFwH6au7DbhIfn45UbPmWR7RplYEh2viW@p3NdGD/v6IIQ4YVOv79WumEGsZ0x90DnQ5MLF81YYQku6GdybQ/wuXAhC/e/oYzE0upwJ/R8Wa11VoFr5s6TPOVwIqEaCOkjQT8gL8oo8oqbxWuQZf/SUQo4SjphRm98SaOpGNXrrgLd3CQAEnANrwVmw7g8 "Python 3 – Try It Online") # Explanation Checks if the first character is `%`. If that is the case, it will try to hex-decode the following two characters and print the result. If not, it will just print the first character and replaces `x` with if necessary. If the first character was `%`, the first three characters are sliced off the string and the function is called recursively. If not, only the first character is sliced off and the function is called again. Raises an error if the hex string cannot be decoded or if end of line is reached. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 35 bytes ``` ṣ”+Kṣ”%µḊḢ;ḢƊ€ŒuØHiⱮⱮ’ḅ⁴⁸żFO<0œṗƊḢỌ ``` [Try it online!](https://tio.run/##y0rNyan8///hzsWPGuZqe0No1UNbH@7oerhjkTUQH@t61LTm6KTSwzM8Mh9tXAdCDTMf7mh91LjlUeOOo3vc/G0Mjk5@uHP6MZCOh7t7/ls/apijoGunADTJ@nA718PdWw63A82I/P/f0MBA1chUuzy/KDszL51L1chEW9XITFvV2BmIXYHYDYidgGLGQNoRiF2AbKCckREQm2urmgPVGIHkTblUTQxNjEyMQWaoRkRqq6qqAgA "Jelly – Try It Online") A monadic link that takes a string as its argument and returns the decoded string, terminating early at any invalid hex. I’ve assumed for now that standard I/O rules apply. If it really has to be stdin, that will cost a byte. [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 62 bytes ``` {S:g{(<-[%]>*)\%?(..)?}={TR/+/ /}($0).print+print chr "0x"~$1} ``` [Try it online!](https://tio.run/##HczdCoJQDAfw@/MUQ5pph/w4WkFm0ecDVBdFdRGhJZnKUSgRe3WbXfy2P9tYFsh42LxKUEPwm2o3vlfapH/Cy7Snn3GmGYY@q/1qvzW5CWatdSzdyGSUFPxf4faQoFgf5dux6yZMJWhxlAS5DhUDKGQJhhp6FPNrCd2ux@rGtiwUA/5O5TNK7gyFy1EMOTo3siYbsqCZQ31OVpSXRJARxxHdiHY/YOjarnCd9gcejhwRWRHkBf4A "Perl 6 – Try It Online") Anonymous code block that outputs to STDOUT and then errors. This assumes that the input cannot contain spaces. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 65 bytes ``` ≔E¹⁶⍘ιφθWθ«≔⮌⪪S%ι⊟ιW∧ι⊟ι«¿∧›Lκ¹⬤01№θ↧§κμ«℅⍘↧…겦¹⁶✂κ²»«≔υι≔υθ»»D⎚ ``` [Try it online!](https://tio.run/##TVBda8IwFH22vyIUAintoI1VH/ZU6zYEBzJftsdQ72ww9iNNdWP427ubmjFLD0nOzTn33BSl0EUt1DBkXScPFXsVDUvmEVmKDnZGy@rAZESSOI6DICJt8OhdSqmAsDYgP97Eqd7gDLoDtmuUNGxdNb1xYhT51LdaidrJFknDtnXDZGDPziyr9raN40fnify88S8ahAHNNlAdTMmOaJUgMqWYHyd@RPK6R882Ipv6ArrA4Cwz62oPX@wYkVMwfqOla5/j0KKwnndT/ovz70JBXmIWlHMbPZkHY9o/g52SBbiqpa8EVAe3Fu5FejfwPdHeLnv2X/WnhtlzrkBou7sOAz4z5bPwUusjRvIoT0PK5yGd5ognxDNiidwU1wyxwj3WOEcsQrrAO9zWZx5Nk5SnU@tB3z9CSunwcFa/ "Charcoal – Try It Online") Link is to verbose version of code. Note that Charcoal prompts "Enter input:" if it runs out of input. Explanation: ``` ≔E¹⁶⍘ιφθ ``` Grab the list of hex digits into a variable. ``` Wθ« ``` Repeat while the variable is not empty. This is used as a flag to break out of the loop, since Charcoal has no other way of terminating the loop. ``` ≔⮌⪪S%ι ``` Read the next line of text and split it on `%`s. ``` ⊟ι ``` Output the first split. ``` W∧ι⊟ι« ``` Repeat while there are more splits to process, but stop if any of them are empty. ``` ¿∧›Lκ¹⬤01№θ↧§κμ« ``` Also check that the length of the split is at least 2 and that the first 2 characters are hex digits. (Inconveniently I can't use a literal `2`, I have to use a string of length 2 instead.) ``` ℅⍘↧…겦¹⁶ ``` Convert the first two characters from hex and output the character with that code. ``` ✂κ² ``` Output the rest of that split. ``` »«≔υι≔υθ»»D⎚ ``` Otherwise clear the loop variables so that we terminate processing. The canvas is also printed after each loop as otherwise Charcoal's input handling gets in the way again. [Answer] # [Python 3](https://docs.python.org/3/), 91 bytes ``` lambda s:re.sub('%([A-Fa-f\d]{2})',lambda t:chr(int(t[1],16)),s.replace('+',' ')) import re ``` [Try it online!](https://tio.run/##XYzbCoJAFEXf@woRDjPDmOh4CYIepovfUKgPU1pJpTJORETfbkeIwB4W57D3YrdPc27qoC8WWX9Vt32hrG6uS7e77ykBmsppoqbHrMhf4s2I81XM/HDWtKoNNamfO37MmNO5umyv6lBSwolDLMLYpLq1jTaWLvtWD3ZBbd/zQET80ehLVZ9slH4ViJCDiDkEK2SDJMgSswCvRNb4YycEMuMwQ0cMfTTeCf1QhMH/Nmx3HADGsVIgJSgJUmHRfwA "Python 3 – Try It Online") Approach this with regular expressions. [Answer] # [Stax](https://github.com/tomtheisen/stax), 29 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` í☼∩ò☺µ◘Γπ╓l▄╓█₧ß:♦+ÇP¢Y╚↑░ºHÑ ``` [Run and debug it](https://staxlang.xyz/#p=a10fef9501e608e2e3d66cdcd6db9ee13a042b80509b59c818b0a748a5&i=%2524%2B%2526%2B%253C%2B%253E%2B%253F%2B%253B%2B%2523%2B%253A%2B%253D%2B%252C%2B%2522%2B%2527%2B%257E%2B%252B%2B%2525%0A%25414243%0A100%2525%2Bworking%0A%2524%25XY%2B%25%25%25&a=1&m=2) It's mostly regex. ]
[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/210742/edit). Closed 3 years ago. [Improve this question](/posts/210742/edit) # Introduction Arrays are usually used with for-loops or iterators. One different task might be the use as a cheap way to rotate through a set of items, so after reaching the last index, the next item would be the first item of the array. This is useful for cases like menus and physical controls. # Challenge Given the size of an array, the initial index, and the movement (which can be positive, zero, or negative), output the resulting index in the array after cyclically moving through it. As soon as a number which is greater than the current array index `+` the number of remaining indices, the added index would go out of bounds. The other way arround, substracting a greater negative value than the current index from itself, the index would be negative and therefore invalid. This should be compensated by the solution. Also, when exceeding the index by not only one, but two or more array lengths, this should also be compensated (see example 2). # Example input and output > > We assume (for the sake of simplicity) that arrays start at `0`. > > > Array for visualization: `['a', 'b', 'c', 'd', 'e', 'f']` > > > ### Example 1 **Input:** Array size: `6` Current Index: `1` (-> `'b'`) Movement: `+5` **Index Movement:** `2` -> `3` -> `4` -> `5` -> `0` **Output:** Index: `0` (-> `'a'`) ### Example 2 **Input:** Array size: `6` Current Index: `2` (-> `'c'`) Movement: `-10` **Index Movement:** `1` -> `0` -> `5` -> `4` -> `3` -> `2` -> `1` -> `0` -> `5` -> `4` **Output:** Index: `4` (-> `'e'`) # Objective The solution with the fewest bytes wins the challenge. Using Lists, Linked Lists etc. is not allowed, fixed arrays only. Non-codegolfing languages are preferred. [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~5~~ 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")) Note: APL is not a golfing language. -1 thanks to Bubbler. Anonymous tacit prefix function. Takes (array size, current index, movement) as argument. ``` ⊃|+/ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT////1FXc422/v@0R20THvX2AXmPetc86t1yaL3xo7aJj/qmBgc5A8kQD8/g/2kKZgqGCqZcINpI4dB6QwMA "APL (Dyalog Unicode) – Try It Online") `+/`‌ sum the right argument `⊃|` division remainder when divided by the first element of the argument [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 2 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` S% ``` A dyadic Link accepting the start index and the rotation on the left and the length on the right which yields the finish index. **[Try it online!](https://tio.run/##y0rNyan8/z9Y9f///0Y6CrqGBv/NAA "Jelly – Try It Online")** ### How? ``` S% - Link: [start, rotation]; length S - sum -> start + rotation % - modulo (length) ``` [Answer] # [J](http://jsoftware.com/), 3 bytes ``` |+/ ``` [Try it online!](https://tio.run/##y/qvpKegnqZga6WgrqNgoGAFxLp6Cs5BPm7/a7T1/2v@N1NIUzBUMOUC0UYK8YYGAA "J – Try It Online") We've got APL and Jelly, so here comes J which is between APL and Jelly in the language hierarchy. Turns out the byte count is also in the middle :) And J is not a golfing language either. Now the byte count is the exact average of Jelly (2B) and APL (4B)! ### How it works ``` |+/ Left: array size, Right: 2-item array of initial index and offset +/ index + offset | modulo array size ``` [Answer] # [Python](https://docs.python.org/), 19 bytes ``` lambda l,p:sum(p)%l ``` An unnamed function accepting `length, (start index, rotation)` which returns the finish index. **[Try it online!](https://tio.run/##K6gsycjPM7YoKPqfZhvzPycxNyklUSFHp8CquDRXo0BTNed/QVFmXolGmoaZjoaRjq6hgaam5n8A "Python 3.8 (pre-release) – Try It Online")** --- 20s: ``` lambda l,i,r:(i+r)%l ``` [TIO](https://tio.run/##K6gsycjPM7YoKPqfZhvzPycxNyklUSFHJ1OnyEojU7tIUzXnf0FRZl6JRpqGmY6Rjq6hgabmfwA) ``` lambda l,*i:sum(i)%l ``` [TIO](https://tio.run/##K6gsycjPM7YoKPqfZhvzPycxNyklUSFHRyvTqrg0VyNTUzXnf0FRZl6JRpqGmY6Rjq6hgabmfwA) ``` lambda*a:sum(a)%a[0] ``` [TIO](https://tio.run/##K6gsycjPM7YoKPqfZhvzPycxNyklUSvRqrg0VyNRUzUx2iD2f0FRZl6JRpqGmY6Rjq6hgabmfwA) [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~27~~ 26 bytes ``` r;f(z,i,m){r=(m%z+z+i)%z;} ``` [Try it online!](https://tio.run/##S9ZNT07@/7/IOk2jSidTJ1ezushWI1e1SrtKO1NTtcq69n9mXolCbmJmnoKGZjWXQkERkJ@moRScWZVqpZqioJOZUgGmc/PLIAJFqcWlOSVAZkyeko6ZjqGOqU6aBpjW1LQmwwAjHV1DA7ARYBbIkNr/AA "C (gcc) – Try It Online") Saved 1 thanks to @att ! [Answer] # [Japt](https://github.com/ETHproductions/japt), 5 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` Nx uU ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=TnggdVU&input=NgoyCi0xMA) ``` Nx - sum inputs uU - modulo first input ``` ]
[Question] [ Imagine simple math problem. You have a number, say it's 1000. And you want to find the next multiple of 32 that follows 1000. You automatically make some simple calculations and get the result. Typical algorithm looks like this: ``` int number = 1000, result; result = (1 + (number/32)) * 32; // integer division ``` It's kind of easy and obvious, right? And now the challenge. **Make this calculation without using `*`, `/` and loops.** Rules: * Don't use `*`, `/` and loops. * Assume that input number is already stored in variable `n`, store result in the variable `r` (already declared). * The shortest code wins. *Sample input:* (already stored in `n`) ``` 1000 ``` *Sample output:* (value of `r`) ``` 1024 ``` --- *Sample input:* ``` 31 ``` *Sample output:* ``` 32 ``` --- *Sample input:* ``` 32 ``` *Sample output:* ``` 64 ``` It is assumed that `n` is a positive number. [Answer] # JavaScript (26 13 chars) `alert((+prompt()>>5)+1<<5)` Re-read the problem statement. Here's my amended answer: `r=(n>>5)+1<<5` And this seems to be the best javascript answer at 10 chars: `r=(n|31)+1` [Answer] ## GolfScript (10 chars) ``` 32n+31~&:r ``` Problems this trivial aren't interesting. [Answer] # C (11 chars) ``` r=(n|31)+1; ``` # Python (10 chars) ``` r=(n|31)+1 ``` Work for negative numbers also [Answer] # Mathematica - ~~15~~ 13 ``` ⌈##⌉&[n+1,32] ``` It's quite simple if `Ceiling` (`⌈...⌉`) isn't forbidden [Answer] **EXCEL (14 characters):** ``` =n-MOD(n;32)+32 ``` n is declared name for a an input cell. put the formula in a cell declared as 'r'. No use of / and \* ... [Answer] ## R, 12 ``` r=n+32-n%%32 ``` This uses modulo `%%`, subtraction `-`, and addition `+`. [Answer] ## Julia, 8 ``` r=n|31+1 ``` (This is based on the C solution.) Some parentheses can be saved in Julia due to the order in which the functions are called: ``` :(r=n|31+1) # : returns the ATK :(r = +(|(n,31),1)) ``` [Answer] # PowerShell: 14 ``` $r=$n-$n%32+32 ```   [Answer] # R (~~10~~ 16) ~~r=-n%%32+n~~ ``` r=-(n=n+1)%%32+n ``` # R (recursive, long) ``` r<-(function (n) if(n%%32) Recall(n+1) else n)(n+1) ``` # Python (~~9~~ 14) ~~r=-n%32+n~~ ``` n+=1 r=-n%32+n ``` [Answer] # Python (11 chars) ``` r=n+32-n%32 ``` Using modulo Alternative (10 chars), using bitwise OR like everbody else: ``` r=(n|31)+1 ``` [Answer] C (16 characters): ``` r=((n>>5)+1)<<5; ``` [Answer] ## Kona (21) ``` r:{_(1+(x%32))%(%32)} ``` No `*`, `/`, nor a loop in the above. [Answer] # J - 11 characters ``` r=:2^>.2^.n ``` [Answer] ## J (10) This returns n if n is a multiple of 32. So it doesn't satisfy everything I think you want. ``` r=:n-_32|n ``` If we need to be stringent on that rule, the following works. ## (14) ``` r=:>:n-_32|>:n ``` [Answer] ### C - 19 characters not the shortest, but a different method ``` j=i%32?i+32-i%32:i; ``` [Answer] # Perl 6 (9 bytes) ``` r=n+|31+1 ``` `r` and `n` can be declared as sigilless variables (`my \variable`). In Perl 6, bitwise operators (like `+|`)'s precedence is better, so no parens are needed. [Answer] # Perl5 14 ``` $r=($n+32)&~31 ``` In Perl5 variables needs sigilia. $n gets added 32 and we strip the last 5 bits by anding by the inverse of 31. [Answer] ### R, 40 Just for kicks, a solution that doesn't use the modulo operator either: ``` r=tail(which(!cbind(1:n,31:0)[,2]),1)+32 ``` `cbind(1:n,31:0)` creates an array with one column going from 1 to n and another from 31 to 0. That column is recycled to fit the size of the first one. `which(!cbind(1:n,31:0)[,2])` returns the indices of the elements for which the second column is 0 (`0` being FALSE, `!0` is TRUE), i.e. the multiples of 32. Finally we take the last one using `tail` and add 32. Solution at 34 characters with `rep`: ``` r=tail(which(!rep(31:0,l=n)),1)+32 ``` [Answer] ## x86 Machine Code - 6 bytes Assuming that the register 'ax' is 'n', and 'bx' is 'r' then ``` 83C81F 40 89C3 ``` Assembled from: ``` or ax, 0x1F inc ax mov bx, ax ``` [Answer] ## Game Maker Language, 8 ``` r=n|31+1 ``` Yes, `|` is evaluated before `+` (see [here](http://gamemaker.info/en/manual/401_04_expressions)) [Answer] ### GolfScript, 7 characters ``` 31n|):r ``` Takes input from variable `n` and puts the result into `r`. Note that for testing it is advisable to use another variable name since `n` is also part of the `p` and `puts` built-ins. [Answer] ## TI-BASIC, 12 ``` 32(1+N/32)→R ``` [Answer] **C 45** ``` int a=32,b,c;b=31;c=b%a;c=a-c;b=b+c;return c; ``` ]
[Question] [ According to [TIO](https://tio.run/) there are two types of programming languages: * Practical (seen in many corporate environments as a development standard). * Recreational (if seen in a corporate environment, you're probably fired). ## Your Task Mix together one language from each of these realms to achieve the simple goal of calculating the median of a list. You will write a program (or function) in one language of each type. The list will be composed entirely of integers, and will be fed as input to your first program. The output of that program will then be fed as input to the second program. For a valid answer, the output of the second language must always be the median of the list. Both programs must be at least 1 byte in length, and both must have an output that differs from their input in at least one case (e.g., neither program may be a cat program). If the list has an even number of elements, your program may output any value between the two elements of the list closest to the median (inclusive). The list is guaranteed to contain at least one element, and consist entirely of integers. # Test Cases ``` [1,2,3,4,5] = 3 [1,2,3,4,5,6] = 3-4 [-1,4,3,-2,0] = 0 [0,1,2,7,8,9] -> 2-7 [1,2,3,7,8,9] -> 3-7 ``` ## Scoring: This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), lowest sum of the byte-count of the two programs wins. [Answer] # [Python](https://docs.python.org/3/) + [Actually](https://github.com/Mego/Seriously), 6 + 1 = 7 bytes ``` sorted ``` **[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzvzi/qCQ15X9BUWZeiUaaRrSuoY6JjrGOrpGOQaym5n8A "Python 3 – Try It Online")** ``` ║ ``` **[Try it online!](https://tio.run/##S0wuKU3Myan8///R1In//0frGuqY6Bjr6BrpGMQCAA "Actually – Try It Online")** The twist is that the Actually built-in for median (`║`) doesn't sort the list, hence it is perfectly combined with Python's `sorted()` built-in. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly) + [Python](https://docs.python.org/), ~~4 3~~ 2 + 3 = 5 bytes -1 thanks to [Mr. Xcoder](https://codegolf.stackexchange.com/users/59487/mr-xcoder) (`;0` -> `W` - I considered this but incorrectly disregarded it as an option) -1 thanks to [Luis Mendo](https://codegolf.stackexchange.com/users/36398/luis-mendo) (drop the `W` and change from `sum` to `int`) Part 1, [Jelly](https://github.com/DennisMitchell/jelly) function: ``` Æṁ ``` A function which, given a list of integers will return their median. e.g. `[-1,-9,-2,-8,0,-7]` yields `-4.5`. **[Try it online!](https://tio.run/##y0rNyan8//9w28Odjf8Ptx@d9HDnjP//o3UNdXQtdXSNdHQtdAx0dM1jAQ "Jelly - Try It Online")** Part 2, [Python](https://docs.python.org/) function: ``` int ``` A function which given an integer or a floating point number returns an integer (dropping any fractional part). e.g. `-4.5` yields `-4`. **[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPzOv5H9BEZDUSNPQNdEz1dT8/x8A "Python - Try It Online")** [Answer] # [MATL](https://github.com/lmendo/MATL) + [R](https://www.r-project.org/), 1 + 19 = 20 bytes ``` S ``` [Try it online!](https://tio.run/##y00syfn/P/j/fwA "MATL – Try It Online") `S` reads in input as a matrix `[a_1, a_2, ..., a_n]` and then sorts it. Then the program terminates, printing the values as `b_1 b_2 ... b_n`, which is then read by R's `scan()` as a vector. The R program then computes the median and prints it out. ``` cat(median(scan())) ``` [Try it online!](https://tio.run/##K/r/PzmxRCM3NSUzMU@jOBlIaGpq/v8PAA "R – Try It Online") [Answer] # [JavaScript (Node.js)](https://nodejs.org) + [Pyth](https://github.com/isaacg1/pyth), 11 + 10 = 21 bytes ``` n=>n.sort() ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/P1i5Przi/qERD839yfl5xfk6qXk5@ukaaRrSuoY6JjrGOrpGOQaym5n8A "JavaScript (Node.js) – Try It Online") ``` .O@R/lQ2_B ``` [Try it online!](https://tio.run/##K6gsyfj/X8/fIUg/J9Ao3un//2gFXUMdBV0jHQUDHQVjHQUThVgA "Pyth – Try It Online") ## How the Pyth code works ``` .O@R/lQ2_B ~ Full program. _B ~ Bifurcate with reverse; Yields [Input, Reverse(Input)] /lQ2 ~ The length of the input divided by two, and floored. @R ~ For each in ^^, get the element at index ^. .O ~ Average (arithmetic mean). ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly) + [Bash](https://www.gnu.org/software/bash/), ~~5~~ 4 + 3 = 7 bytes ``` ÆṁṾṚ ``` [Try it online!](https://tio.run/##ASgA1/9qZWxsef//w4bhuYHhub7huZr/xpPDh/9bMTAsMjAsMzAsNDAsNTBd "Jelly – Try It Online") *-1 byte* thanks to *Jonathan Allan* A monadic chain that takes a list and returns (is that the right terminology?) the stdin for the bash program. ``` rev ``` [Try it online!](https://tio.run/##S0oszvj/vyi17P9/A2MA "Bash – Try It Online") ## Explanation ``` ÆṁṾṚ Ṿ String representation Æṁ of the median Ṛ reversed ``` [Answer] # [Actually](https://github.com/Mego/Seriously) and [Python](https://docs.python.org/3/), 1 + 3 = 4 bytes ## Actually, 1 byte ``` ║ ``` Full program that computes the median, possibly with a decimal part. [Try it online!](https://tio.run/##S0wuKU3Myan8///R1In//0cb6BjqGOmY61joWMYCAA) ## Python, 3 bytes ``` int ``` Defines a function that rounds towards zero. [Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPzOv5H9BEZDUSNPQNdEz1dT8/x8A) ]
[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/12608/edit). Closed 10 years ago. [Improve this question](/posts/12608/edit) try to write shortest possible variant of logic which converts binary input by this table: ``` 00 -> 00 01 -> 10 10 -> 01 11 -> 11 ``` You can use only bitwise and bitshift operations. I calculate only operations and don't care brackets, spaces, constants and etc. But you can't use any control (if, while, ternary) and arithmetic operations. If you are using bitwise and bitshift operations, your operations number will be multipled by two: ``` op_num = (your_op_num << types_of_operation_num) >> 1 ``` **edit: sorry, this is not real code-golf, because I calculate operations in logic, not characters.** [Answer] # 6 operations ``` 216>>i>>i&3 ``` Same idea: ``` 216>>(i<<1)&3 ``` [Answer] ## 8 operations (4 \* 2) Ok, here a real answer: ``` (i&1)<<1|i>>1 ``` [Answer] **Javascript, 0 operators** ``` alert(prompt().split('').reverse().join('')) ``` [Answer] ## Tcl, 0 operators ``` string rev $i ``` [Answer] # Mathematica 0 operators? If a string, `s`, is input, any of the following should work: ``` StringReverse[s] StringRotateLeft[s] StringRotateRight[s] ``` If the input is a list of digits (the standard way to represent binary digits in Mathematica), this will work: ``` (# /. {{0,1} -> {1,0}, {1,0} -> {0,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/187499/edit). Closed 4 years ago. [Improve this question](/posts/187499/edit) Given 2 positive integers in any format you'd like, return their sum using only logic gates and bit shifts (see example below). Don't worry about overflow. EDIT: Using pre-written addition is obviously not allowed. So no `a + b`, `Add(a, b)`, `a - (-b)` etc. This is code golf, so [standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply. Shortest program in characters wins. Some test cases: ``` 3, 4 => 7 5, 7 => 12 9, 10 => 19 12, 31 => 43 ``` Example code in C#, readable (471 characters): ``` int Add(int numA, int numB) { int result = 0; int mask = 1; int carryOver = 0; while (numA > 0 || numB > 0) { int A_bit = numA & 1; int B_bit = numB & 1; if ((carryOver ^ A_bit ^ B_bit) == 1) { result |= mask; } carryOver = carryOver == 1 ? A_bit | B_bit : A_bit & B_bit; numA >>= 1; numB >>= 1; mask <<= 1; } return carryOver == 1 ? result | mask : result; } ``` Example code in C#, unreadable (118 characters): ``` int r=0,m=1,c=0;while(a>0|b>0){int A=a&1,B=b&1;if((c^A^B)==1)r|=m;c=c==1?A|B:A&B;a>>=1;b>>=1;m<<=1;}return c==1?r|m:r; ``` [Answer] # JavaScript (ES6), 71 bytes Takes input as `(a)(b)`. ``` a=>g=(b,r=0,m=1,c,y=a&m,z=b&m)=>m?g(b,!(y^z)^!c?r|m:r,m<<1,c?y|z:y&z):r ``` [Try it online!](https://tio.run/##XcxBCoMwFEXReVdhJ5IPaTVqEcWvOxFiqtJiTImlkODe0xQ7yuCNzuM@@YdvQj9e78uq7qOb0HFsZyQD1ZhSiYwKapDHklocYgnYym72eiamt9CfRad3WWsqm8ZfO7Pb2sQWau2EWje1jNdFzWQiUQq/QZQkUXoKLPdWHFaGdvNWHsayECsg7B9lVYAsA5KzA4vcfQE "JavaScript (Node.js) – Try It Online") [Answer] # JavaScript (ES6), 28 bytes ``` f=(a,b)=>b?f(a^b,(a&b)<<1):a ``` [Try it online!](https://tio.run/##hclBC0AwFADgu1/xTnqvNm07avgn6g0TyYT8/UluIpfv8o188Nasw7LLObRdjL5AFo6K0lUeuXYCOXVkraacYxPmLUxdNoUewSMAGHFBQMnztFICjFIvJ39Pf5@8L54 "JavaScript (Node.js) – Try It Online") [Answer] # [Logicode](https://esolangs.org/wiki/Logicode), 185 Bytes Seeing as Logicode only has AND, OR, and NOT operators, I thought it might be fun to try to implement addition in Logicode for this challenge. ``` circ t(a,m)->cond a&m->1/0 circ x(a,b)->(a&!b)|(b&!a) circ f(a,b,c,m,n)->cond n&10000000->0/f(a,b,(t(a,m)&(t(b,m)|c))|(t(b,m)&c),m+0,n+0)+x(x(t(a,m),t(b,m)),c) circ a(a,b)->f(a,b,0,1,1) ``` [Try it Online!](https://tio.run/##TY7BCsMgDIbvfYr2IoZGmrxA30XTbRSmwtigh767i9NBvSR/vs/oMz92ydutFNlfMr6txwhulZy20ZvoVl5o@KFDUVBkvZkCnDaYyUND94pQMGL6302GqR230tIE27YbrUHrKaBrWm8EMM6EaSaYD3t0FRsFlP6S759oCwkZGUr@qG1ZeyKAoUfSzHzJdUB8MXRUlSqVLw) [Answer] # C (gcc) Not golfed to the max ``` c;d(a,b){while(b){ c=1;while(~b&c)b^=c,c<<=1;b^=c; c=1;while( a&c)a^=c,c<<=1;a^=c;} return a;} ``` Explanation, it's basically ``` while(b--)a++; ``` Will not work for negative b [Try it online](https://tio.run/##S9ZNT07@/z/ZOkUjUSdJs7o8IzMnVQPI4Eq2NbSG8OqS1JI1k@Jsk3WSbWyAoiCmNZK8QiJQPhEhD2Ja13IVpZaUFuUpJFrX/s9NzMzTAJpZUJSZV5KmoaSaEpOnpJOiYaxjoqlpjSFsqmOOTdhSx9AAm7ihkY6xIUii9j8A) [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 13 [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 prefix function. Takes list of two equal-length binary representations. ``` ⊃(≠/,1⌽¨∧/)⍣≡ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT/8fku@UmfeobYKGoZm@keajjhmPupYcWsHlVpSfC5EwAost/f@oq1njUecCfR3DRz17D6141LFcX/NR7@JHnQv/pwGVPerte9Q31dMfqOzQeuNHbROBvOAgZyAZ4uEZ/B9qnkKaAthCBWMdBRMudEFTHQVzDEFLHQVDAwxRQyMdBWNDAA "APL (Dyalog Unicode) – Try It Online") `(`…`)⍣≡` apply the following function until two consecutive applications are identical:  `∧/` AND of the two (lit. AND-reduce, so this enclose the result to reduce rank)  `1⌽¨` shift the content of that enclosure a single step left  `≠/,` prepend the XOR of the two (lit. XOR-reduction, so this also encloses) eventually the all carries have been done, so the second element (AND) is all-zero `⊃` pick the first element [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 65 bytes ``` +`(.?)(,\d*)(\d) $2;$1$3 +`(.), ,;$1 {`00 0 01|10 1 }`;11 1;0 \D ``` [Try it online!](https://tio.run/##FYwxDgIxEAN7v2ORksvqtL6ATigFDc9IEaRQ0FAgOuDtYSNXtsd@3d@P523UniALUgtMsRKSDIfQjODwcL3EoLUvMdQeIVsRSp70GhXqDp9mBhe/NBC/VujbYqhXDHruNGc/H7MecdIdZ53wppl/ "Retina 0.8.2 – Try It Online") Link includes test cases in decimal; the header and footer perform base 2 conversion. Explanation: ``` +`(.?)(,\d*)(\d) $2;$1$3 +`(.), ,;$1 ``` Interleave the bits of both numbers, starting from the right. ``` {`00 0 01|10 1 }`;11 1;0 ``` XOR each pair of bits together, and also AND the bits and carry 1 in that case. Repeat so that the carries propagate if necessary. ``` \D ``` Delete the separator punctuation. ]
[Question] [ **This question already has answers here**: [All your bijective base are belong to us](/questions/54105/all-your-bijective-base-are-belong-to-us) (8 answers) Closed 7 years ago. # Task The task is to convert a string to a number. It must accept the string via stdin and output the number via stdout. You convert a string to a number by replacing each letter of the string by its index (mind that you don't need to replace it with the index, that's just an example. You are allowed to replace it with anything you like, as long as the output is decodable) in the following list (you don't *need* to convert any other characters): Characters: `abcdefghijklmnopqrstuvwxyz1234567890` (the input will only either be lowercase letters, or/and a number). Additionally, you must make the output decodable, so if you have output `0` for input `a`, and somebody inputs `bl`, then the output will be something like `111`. This is not decodable since the program might interpret it as `bbb` or `lb` or `bl`. You might make it decodable by making sure the the number that each character outputs always has a length of 2. Any other way of making sure your output is decodable *is* allowed, but you must explain how one would decode the output in your answer. Standard loopholes are not allowed. This is code golf, so shortest code wins! EDIT: By decodable, just to clarify, I mean that you can convert the output back into the input. Your program doesn't need to feature decoding features, only encoding. # Examples ``` Input Output a 00 ab 0001 1 26 ``` [Answer] ## Pyth, 1 byte ``` C ``` [Try it here!](http://pyth.herokuapp.com/?code=C&input=%22Hello+123%22&debug=0) Converts a string to a number Decode with the following Python code: ``` def decode(x): rest, char = divmod(x, 256) if rest < 256: return chr(rest)+chr(char) return decode(rest)+chr(char) ``` [Answer] ## C ~~69~~ ~~61~~ ~~52~~ 62 Bytes ``` i;char v[99];main(){gets(v);while(v[i])printf("%.3d",v[i++]);} ``` Now taking input from stdin, each character code is 3 digits. a.exe thisisatest 116104105115105115097116101115116 [Answer] # Bash + coreutils, 20 ``` od -vbAn|tr -d ' \n' ``` The index of each character in the ASCII table is given in octal by `od`, which ensures each octal number for each input character is exactly 3 digits long (padded with leading zeros as necessary). `tr` removes the whitespace. Decoding would be performed by grouping output into groups of 3 digits and then conversion from octal back to ASCII. [Answer] ## Ruby, ~~97~~ ~~37~~ 44 bytes ``` lambda{|s|s.chars.map{|c|c.upcase.ord}.join} ``` Take the ordinal of each character in `s` converted to uppercase (to ensure 2 chars per number for ordinals) [Answer] ## PowerShell v2+, ~~42~~ 32 bytes ``` -join([char[]]$args[0]|%{$_-38}) ``` Takes input `$args[0]`, treats it as a `char`-array, sends it into a loop, and each loop cast the `char` as an `int` (implicit) minus `38`. Those are all encapsulated in parens and `-join`ed into one string. That string is left on the pipeline and printing is implicit. The lowest ASCII point of `abcdefghijklmnopqrstuvwxyz0123456789` is `0`, with `48`. The highest is `z` with `122`. By subtracting `38` from each code point, we're guaranteed distinct two-digit number for each input character. ### Examples ``` PS C:\Tools\Scripts\golfing> .\convert-string-to-number.ps1 'ab' 5960 PS C:\Tools\Scripts\golfing> .\convert-string-to-number.ps1 'ppcg' 74746165 PS C:\Tools\Scripts\golfing> .\convert-string-to-number.ps1 'error404' 6376767376141014 PS C:\Tools\Scripts\golfing> .\convert-string-to-number.ps1 'abcdefghijklmnopqrstuvwxyz0123456789' 596061626364656667686970717273747576777879808182838410111213141516171819 ``` [Answer] # [S.I.L.O.S](https://github.com/rjhunjhunwala/S.I.L.O.S), ~~63~~ ~~60~~ 55 bytes ``` loadLine b=256 lbla c=get b printIntNoLine c b+1 if c a ``` Prints ASCII value. [Try it online!](http://silos.tryitonline.net/#code=bG9hZExpbmUKYj0yNTYKbGJsYQpjPWdldCBiCnByaW50SW50Tm9MaW5lIGMKYisxCmlmIGMgYQ&input=&args=YWIwMQ) [Answer] # [GS2](http://github.com/nooodl/gs2), 1 byte Byte 14, which, in CP437, is `♫`. [Try it online!](http://gs2.tryitonline.net/#code=4pmr&input=YWJjZGU) Decoding is possible: get all matches of the regex `(1..|..)` and map them from decimal ASCII code points to ASCII characters. [Answer] # Python 3, 86 bytes I appear to have misunderstood what the question allows... Either way, this exactly matches the test cases given. ``` print(''.join('%02d'%'abcdefghijklmnopqrstuvwxyz0123456789'.index(i)for i in input())) ``` [**Ideone it!**](https://ideone.com/r6oZja) ]
[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/245511/edit). Closed 1 year ago. [Improve this question](/posts/245511/edit) [kolmogorov-complexity](/questions/tagged/kolmogorov-complexity "show questions tagged 'kolmogorov-complexity'") is one of the tags on this site, representing challenges that test how much code is needed to output a given fixed result (usually a piece of text). The [info page](https://codegolf.stackexchange.com/tags/kolmogorov-complexity/info) for this tag lists the string `4c1j5b2p0cv4w1x8rx2y39umgw5q85s7uraqbjfd` as an example of a string with a high Kolmogorov complexity, stating that printing this string literally is probably the shortest way to output it. I would like to test this statement, and thus your challenge is to output this string, without using a literal representation of it. ## Rules * You must write a full program that takes no input, and outputs exactly the result string, with a single optional trailing newline. Output may be in any format allowed by default IO rules (writing to STDOUT, writing to a file, displaying to the screen, etc) * No submitting the trivial solution of your language's equivalent of `print "4c1j5b2p0cv4w1x8rx2y39umgw5q85s7uraqbjfd"`, however, I will create a community wiki answer to list trivial solutions for comparison, so if you answer in a language not added to that answer, please edit that language's trivial solution (if it exists) into that post. * Use of built-ins is allowed, if your language somehow has a built-in that contains or can easily generate this string, I would love to see that. [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so lowest bytecount is best score, but please also list the difference in length between your bytecount and the bytecount of your language's trivial solution with your score. [Answer] # Trivial Solutions If you answer this question and the trivial solution to this problem is not currently listed here, please edit it into this post, to serve as a point of comparison against non-trivial solutions in that language. For purposes of clarity, the trivial solution to this problem is defined as your language's equivalent of a `print` statement, plus your language's equivalent of a string literal, containing `4c1j5b2p0cv4w1x8rx2y39umgw5q85s7uraqbjfd`, and being passed to the `print` statement, plus whatever boilerplate is necessary to make it a full program. When adding a language to this, please format with a level three heading containing the language name and bytecount (formatting: `### Language Name, XX bytes ###`). Follow this with a codeblock (formatting: ```` code here ````) containing the code of the trivial solution. Please try to keep the list in alphabetical order by language name. **Place solutions below this line:** --- ### 05AB1E, [41 bytes](https://tio.run/##yy9OTMpM/f9fySTZMMs0yajAILnMpNywwqKowqjS2LI0N73ctNDCtNi8tCixMCkrLeX/fwA) ``` "4c1j5b2p0cv4w1x8rx2y39umgw5q85s7uraqbjfd ``` ### Charcoal, [29 bytes](https://tio.run/##S85ILErOT8z5/z@gKDOvREPJJNkwyzTJqMAgucyk3LDCoqjCqNLYsjQ3vdy00MK02Ly0KLEwKSstRUnT@v///7plOQA "Charcoal – Try It Online") ``` ”E#-¡2e·ⅉÀθº,"GEσG>υ[C=↥↗μω⮌ψ ``` It's a compressed string literal, but it's still a string literal, so I guess this counts as a trivial solution. The link is to the equivalent Verbose Charcoal, which is an even more trivial solution, but the Charcoal deverbosifier helpfully prints the actual solution before executing it. ### Java 8, [45 bytes](https://tio.run/##LY7LDoIwFET3fsUNK1hABCFiiP6BbEzcGBelPFIsBfoCYvj2WiKbm8ydzMxpkUZ@W34MpkgIuCPCvgcAwmTFa4QryDcJ8JCcsAZq99mTErSX2e96sEdIJAmGHBhcjfZvTozDNimi4Yh1PIVzyudoOV1U10zJmCbirDgai7YuHZNt@UEV1Ob3Gr21dxbC/Q@@3sjbARYhqy7olQwG60iXBbXLFKXezrKaHw) ``` v->"4c1j5b2p0cv4w1x8rx2y39umgw5q85s7uraqbjfd" ``` ### Jelly, [41 bytes](https://tio.run/##y0rNyan8//9RwxyTZMMs0ySjAoPkMpNywwqLogqjSmPL0tz0ctNCC9Ni89KixMKkrLSU//8B) ``` “4c1j5b2p0cv4w1x8rx2y39umgw5q85s7uraqbjfd ``` ### Julia, [49 bytes](https://tio.run/##yyrNyUw0rPj/v6AoM69EQ8kk2TDLNMmowCC5zKTcsMKiqMKo0tiyNDe93LTQwrTYvLQosTApKy1FSfP/fwA) ``` print("4c1j5b2p0cv4w1x8rx2y39umgw5q85s7uraqbjfd") ``` ### Python 2, [47 bytes](https://tio.run/##K6gsycjPM/r/v6AoM69EySTZMMs0yajAILnMpNywwqKowqjS2LI0N73ctNDCtNi8tCixMCkrLUXp/38A) ``` print"4c1j5b2p0cv4w1x8rx2y39umgw5q85s7uraqbjfd" ``` ### Python 3, [49 bytes](https://tio.run/##K6gsycjPM/7/v6AoM69EQ8kk2TDLNMmowCC5zKTcsMKiqMKo0tiyNDe93LTQwrTYvLQosTApKy1FSfP/fwA) ``` print("4c1j5b2p0cv4w1x8rx2y39umgw5q85s7uraqbjfd") ``` ### Retina, [41 bytes](https://tio.run/##K0otycxL/P@fyyTZMMs0yajAILnMpNywwqKowqjS2LI0N73ctNDCtNi8tCixMCkrLeX/fwA "Retina 0.8.2 – Try It Online") ``` 4c1j5b2p0cv4w1x8rx2y39umgw5q85s7uraqbjfd ``` ### Rust, [61 bytes](https://tio.run/##KyotLvn/Py1PITcxM09Ds7qgKDOvRFFDySTZMMs0yajAILnMpNywwqKowqjS2LI0N73ctNDCtNi8tCixMCkrLUVHSbP2/38A) ``` fn main(){print!("4c1j5b2p0cv4w1x8rx2y39umgw5q85s7uraqbjfd")} ``` ### APL, 42 bytes ``` '4c1j5b2p0cv4w1x8rx2y39umgw5q85s7uraqbjfd' ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~35~~ 34 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ØBḟØA“÷ȯḋ²÷Œmṗ)¿+¹ỊỴ7ĠYṖP0ṡẋœ{ỵC’ṃ ``` **[Try it online!](https://tio.run/##AU4Asf9qZWxsef//w5hC4bifw5hB4oCcw7fIr@G4i8Kyw7fFkm3huZcpwr8rwrnhu4rhu7Q3xKBZ4bmWUDDhuaHhuovFk3vhu7VD4oCZ4bmD//8 "Jelly – Try It Online")** ### How? ``` ØBḟØA“...’ṃ - Main Link: no arguments ØB - base-62 digits = "0..9A..Za..z" ØA - uppercase characters = "A..Z" ḟ - filter-discard -> "0..9a..z" “...’ - big integer in a base 250 representation ṃ - base decompress (use the characters as base 62 digits of the integer) - implicit print ``` [Answer] # [Julia](http://julialang.org/), 49 bytes ``` print(4,:c1j5b2p0cv4w1x8rx2y39umgw5q85s7uraqbjfd) ``` [Try it online!](https://tio.run/##yyrNyUw0rPj/v6AoM69Ew0THKtkwyzTJqMAgucyk3LDCoqjCqNLYsjQ3vdy00MK02Ly0KLEwKSstRfP/fwA "Julia 1.0 – Try It Online") Same length as the trivial solution. I guess it's not trivial ? And it's technically not concatenation. It prints the number 4 and then a [Symbol](https://docs.julialang.org/en/v1/base/base/#Core.Symbol) (technically not a string). Feel free to debate whether this is too trivial or not [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 36 bytes ``` ⍘⍘AN%)~:0+VJEkbeQYeRX!$2_[^}8g?\xγ³⁵ ``` [Try it online!](https://tio.run/##S85ILErOT8z5//9R7wwgcvRT1ayzMtAO83LNTkoNjEwNilBUMYqPjqu1SLePqTi3@dDmR41b//8HAA "Charcoal – Try It Online") Explanation: Converts the literal string `AN%)~:0+VJEkbeQYeRX!$2_[^}8g?\x` from base 95 (using printable ASCII) to base 35 (using `0-9a-y`). If the compressed string literal form of the above literal string is allowed, then for 34 bytes: ``` ⍘⍘“\`"Zζ﹪⊕↙84¤κq≡IT⁵⭆℅?R¤Bg÷φm⊙”γ³⁵ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMMpsTg1uATITEdmKjn6qWrWWRloh3m5ZielBkamBkUoqhjFR8fVWqTbx8RUKOkopGvqKBibampa////X7csBwA "Charcoal – Try It Online") Link is to verbose version of code. Alternatively, the compressed string literal form of the numeric value of the base 35 conversion also results in 34 bytes: ``` ⍘I”)¶&K‖◨"Sγ]ιJG÷φïzjμp⬤XχφωqE·”³⁵ ``` [Try it online!](https://tio.run/##DcZLCsIwEADQq5SuErAwk5nMB3d6AcEThCIqlBba4PXHvtWbP22ft7ZEPPbv2tOtHa9nP/tO93b0NCqaIoErOasKMwmwEWNBEnEsDsiiXMEL@RkoXgnNRMzGfBmo5nyNiOm3/AE "Charcoal – Try It Online") Link is to verbose version of code. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), ~~35~~ 34 bytes ``` »gtWŀż⌊l,∇ɖ∩꘍√ṘȮ∞*"Cβ1⋎ʀv@Ḃ»kakd+τ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLCu2d0V8WAxbzijIpsLOKIh8mW4oip6piN4oia4bmYyK7iiJ4qXCJDzrIx4ouOyoB2QOG4gsK7a2FrZCvPhCIsIiIsIiJd) -1 thanks to @whqwert Ez ``` »gtWŀż⌊l,∇ɖ∩꘍√ṘȮ∞*"Cβ1⋎ʀv@Ḃ»kakd+τ # Full program τ # Convert the number to base len(str) using the number... »gtWŀż⌊l,∇ɖ∩꘍√ṘȮ∞*"Cβ1⋎ʀv@Ḃ» # 149288472330050833510329217157030174401240445325930074868876423 kakd+ # And the string "abcdefghijklmnopqrstuvwxyz0123456789" ``` ]
[Question] [ # Introduction An elementary cellular automaton is a cellular automaton that is 1-dimensional and has 2 states, 1 and 0. These cellular automata are categorized based on a simple code: the Wolfram code, invented by Stephen Wolfram (yes, the Wolfram | Alpha guy). It works like this: * First, you the set of all possible states for a cell and its 2 neighbors; this gives you 8 (2^3) states. You then arrange them in order (in this case) from left to right, so you have 000, 001, 010, 011, 100, 101, 110, and 111. * Then, for each state, you take the resulting state of the center cell, either a 0 or 1. Then, you are left with 8 bits. * You can guess what you do next: you combine the 8 bits into a single 1-byte number. This gives you 255 possible cellular automatons. # Challenge Given the Wolfram code number of a cellular automaton and a 3-bit state, you must write a program that will output the state of the center cell for that state. * The two integers may be taken from any input method that is convenient (ie. variable, stdin, command line arguments, function arguments) Input can be taken as any type, as long as that type is capable of representing integers. For example, you could take input as an array of digits, a string, or an integer. Input can be in any base you want. * The output may also be in any convenient method (ie. variable, stdout, exit code, return value) The only restriction is that the use must be able to see the output (no outputting to /dev/null). Output can be given as any type as well. # Example I/O > > Number: `255`, State: `101` > > States: `1, 1, 1, 1, 1, 1, 1, 1` > > Output: `1` > > > --- > > Number: `129`, State: `110` > > States: `1, 0, 0, 0, 0, 0, 0, 1` > > Output: `0` > > > --- > > Number: `170`, State: `001` > > States: `1, 0, 1, 0, 1, 0, 1, 0` > > Output: `0` > > > # Rules This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins! [Answer] # [Haskell](https://www.haskell.org/), 4 bytes The *number* is taken as a binary string and the *state* is taken as a (decimal) integer. This let us use the *state* as an index to the *number*, which immediately results in the desired output. So this answer just consists of an indexing function `!!`. ``` (!!) ``` [Try it online!](https://tio.run/##y0gszk7NyfmfZqsQ819DUVHzf25iZp6CrUJBUWZeiYKKQpqCkqEBBCopGP7/l5yWk5he/F83wjkgAAA "Haskell – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 1 byte Based on @flawr's previous MATL answer. Remember to give them an upvote! (Note: this takes input in a reversed order.) ``` è ``` [Try it online!](https://tio.run/##yy9OTMpM/f//8Ir//025DA3AwBAA "05AB1E – Try It Online") [Answer] # [Keg](https://github.com/JonoCode9374/Keg), 5 SBCS bytes -2 bytes from Jono 2906 via the `-hr` flag ``` ?(¿|_ ``` [Try it online!](https://tio.run/##y05N///fXuPQ/pr4//8NDcDAkMv0v25GCgA "Keg – Try It Online") [Answer] # [APL (Dyalog Classic)](https://www.dyalog.com/), 8 bytes I don't know how to set this to a callable function or turn it into a full program. (Based on @flawr's Haskell answer, remember to upvote them!) Format: `'state' {⍺[⍵+1]} number` ``` {⍺[⍵+1]} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v//Ud/UR20T1A0NIFC9@lHvruhHvVtjaw3//wcA) [Answer] # [GolfScript](http://www.golfscript.com/golfscript/), 2 bytes ``` ~= ``` [Try it online!](https://tio.run/##S8/PSStOLsosKPn/v872/38lQwMIVDLUVzAEAA "GolfScript – Try It Online") ## Explanation ``` ~ # Dump the input onto the stack = # Index ``` [Answer] # [Wren](https://github.com/munificent/wren), 17 bytes Based on @flawr's previous JavaScript answer. Remember to give them an upvote! ``` Fn.new{|a,b|a[b]} ``` [Try it online!](https://tio.run/##Ky9KzftfllikkFaal6xgq/DfLU8vL7W8uiZRJ6kmMToptvZ/cGVxSWquXnlRZkmqBkiZXnJiTo6GkqEBBCrpGGpq/gcA "Wren – Try It Online") [Answer] # [JavaScript (Node.js)](https://nodejs.org), 34 bytes ``` (n)=>(s)=>n.toString(2)[+('0b'+s)] ``` [Try it online!](https://tio.run/##TcqxCoMwEIDhV3G7O1LlEpDioC/hWBysNaLInSShrx9Dpy7/8PEf83eOS9ivVIt@1uz7jEL9gLFEmqRjCrts6OhlEPgNJtKUF5Wo59qcuqFH17aEYK0FMvCowHi0rvsR/9GTCzGXi/IN "JavaScript (Node.js) – Try It Online") Pretty sure the `toString(2)` call can be golfed better. ]
[Question] [ **This question already has answers here**: [A program that deletes itself](/questions/19355/a-program-that-deletes-itself) (30 answers) Closed 6 years ago. For this code golf challenge, you must produce a .exe runnable on windows. After running this .exe from any path with any name it must be deleted after execution. My reason for limiting this to windows is something like this may be significantly easier if you have some niche OS. Language(and code) used to produce the .exe is irrelevant, the file size of the executable is what will be measured for this. But still post the code used to produce it, along with the resulting file size. This is code golf, but again the goal is the smallest executable file. [Answer] ## Assembly, 4608 bytes The source code for the assembly program, using `nasm` syntax, is as follows: ``` BITS 32 GLOBAL _main EXTERN _system SECTION .data cmd: db 'echo>).bat start cmd /c del ).bat ' cmdarg: times 128 db 0 SECTION .text _main: mov eax, [esp + 8] mov esi, [eax] mov edi, cmdarg copy: lodsb or al, al stosb jnz copy push cmd call _system add dword [esp], 5 call _system pop edx ret ``` I built the executable using the following commands: ``` nasm -f win32 selfdel.asm gcc -Wall -s -o selfdel.exe selfdel.obj ``` (I'm curious if the size of the executable would be different if MS's linker were to be used in place of gcc's, but I don't have access to MS development tools.) Hopefully the code is straightforward enough to not need much explanation. Basically the program creates a batch file that deletes the program (as well as itself) after the program has exited. [Answer] # Perl (11 bytes) ``` MZ+unlink$0 ``` Save this as `a.exe`, or something, and run it with Perl. And yes, this is Win16 executable, except I don't know what it will do. [Answer] ## Tcl, 48 ``` exec cmd /c "ping ::1&&del [file na [info n]]" & ``` Use a tclsh basekit to create the executable. **Note**: a process can not delete its own executable, because it is locked when the process is running. So your only option is to get some other process to delete your executable when it stops running. [Answer] # C - 857 byte source, 18,432 byte compilation ``` #include <stdlib.h> size_t stringlen(const char *); char * stringcat(char *, const char *); main(int argc, char *argv[]) { if(argc > 0) { char *str = calloc(stringlen(argv[0])+11, sizeof(char)); stringcat(str, "start del "); stringcat(str, argv[0]); system(str); } } /* Simple implementation of strcat to avoid including string.h */ char * stringcat(char *dest, const char *source) { size_t i=0,j=0; while(dest[i] != '\0') { ++i; } while(source[j] != '\0') { dest[i+j] = source[j]; ++j; } dest[i+j] = '\0'; return dest; } /*Simple implementation of strlen to avoid including string.h */ size_t stringlen(const char *str) { size_t i=0; while(str[i] != '\0') { ++i; } return i; } ``` Compiled with: ``` gcc self-delete.c -pedantic -s -o self-delete.exe ``` It is now tested and works perfectly. [Answer] # Python (59 bytes) ``` import os,sys;os.remove(sys._getframe().f_code.co_filename) ``` [Answer] ## Assembly - 1548 bytes Executes a delayed system command to find and delete itself ``` EXTERN system IMPORT system msvcr100.dll SECTION .text USE32 GLOBAL main main: push string call [system] ret string: db "start cmd /C ", 34, "timeout /t 3&for /f %a in ('dir /b *.exe') do (find ", 34, "someuniquestring134123asdfasd41324", 34, " %a &if not errorlevel 1 del %a)", 34, 0 ``` Compiled with: ``` nasm.exe -f obj filename.asm alink.exe -oPE -entry main filename.obj ``` The executed script: ``` timeout /t 3 for /f %a in ('dir /b *.exe') do ( find "someuniquestring134123asdfasd41324", %a if not errorlevel 1 del %a ) ``` [Answer] ## HTML + JS (33) ``` <body onload=document.write('')> ``` ]
[Question] [ Make a program that outputs the number of seconds from the beginning of today (00:00:00 of the day you run it) to the second you ran it. However, if this number is divisible by three, print `Fizz` instead. If it is divisible by five, print `Buzz` instead. If it is divisible by three and five, print `FizzBuzz`. Don't pad the number printed with extra zeroes (44 instead of 00044). You don't need to take leap seconds into account (saying for the universe in which people answer this years after I post it). Standard loopholes apply, shortest program wins. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 26 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) A simple port of [Dennis's "1-2-fizz-4-buzz" solution](https://codegolf.stackexchange.com/a/70216/53748) which evaluates the formatted time as seconds first ``` 7ŒTṣ”:Vḅ60µ3,5ḍTị“¡Ṭ4“Ụp»ȯ ``` **[Try it online!](https://tio.run/##AToAxf9qZWxsef//N8WSVOG5o@KAnTpW4biFNjDCtTMsNeG4jVThu4vigJzCoeG5rDTigJzhu6RwwrvIr/// "Jelly – Try It Online")** [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~33~~ 30 bytes *-3 bytes from Grimy* ``` žažbžc)60βÐ3Öi"Fizz"?}5Öi”ÒÖ”, ``` [Try it online!](https://tio.run/##yy9OTMpM/f//6L7Eo/uSju5L1jQzOLfp8ATjw9Myldwyq6qU7GtNgexHDXMPTzo8DUjp/P8PAA "05AB1E – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 73 bytes ``` import time a=time.time()%86400//1 print(a%3<1)*"Fizz"+(a%5<1)*"Buzz"or a ``` [Try it online!](https://tio.run/##K6gsycjPM/r/PzO3IL@oRKEkMzeVK9EWROmBCA1NVQszEwMDfX1DroKizLwSjURVYxtDTS0lt8yqKiVtINcUzHUqBXLzixQS/0OVaf4HAA "Python 2 – Try It Online") -37 bytes using time.time instead of datetime thanks to negative seven -4 bytes thanks to ArBo (switched to Python 2) [Answer] ## Batch, 145 bytes ``` @set s=%time:~,8% @set/as=((%s::=)*60+%,f=s%%3,b=s%%5,t=f+b @for %%a in (Fizz.%f% Buzz.%b% FizzBuzz.%t%)do @if %%~xa==.0 set s=%%~na @echo %s% ``` Explanation: `%time%` is (at least on my system) formatted `hh:mm:ss.ff` so we start by chopping off the fractions of seconds. Then the shortest way to do the base 60 conversion is to replace the `:`s with operators and evaluate, and the divisibility by 3, 5 and 15 is also calculated. This is then tested and the number of seconds replaced with the appropriate string if necessary before being printed. [Answer] # [MathGolf](https://github.com/maxbergmark/mathgolf), 24 bytes ``` t♪/╔%_╕Σ╠δ╕┌╠δ`+Γ\35α÷ä§ ``` [Try it online!](https://tio.run/##y00syUjPz0n7/7/k0cxV@o@mTlGNfzR16rnFj6YuOLcFyHo0pQfMTNA@NznG2PTcxsPbDy85tPz/fwA "MathGolf – Try It Online") ## Explanation ``` t unix timestamp as integer milliseconds ♪/ divide by 1000 ╔% modulo 86400 _ duplicate TOS ╕Σ╠δ Decompress "Σ╠" and capitalize to get "Fizz" ╕┌╠δ Decompress "┌╠" and capitalize to get "Buzz" ` duplicate the top two items + pop a, b : push(a+b) Γ wrap last four elements in array \ swap top elements (swaps 2nd copy of time to TOS) 35α push [3, 5] ÷ is divisible ä convert from binary § get from array ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~117~~ ~~94~~ ~~90~~ 71 bytes -23 bytes thanks to mazzy -4 bytes thanks to AdmBorkBork -19 bytes thanks to mazzy again ``` (([int]$x=date|% tim*|% t*ls*),('Fizz'*!($x%3)+'Buzz'*!($x%5))|sort)[1] ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfmvkmZb/V9DIzozryRWpcI2JbEktUZVoSQzVwtEaeUUa2nqaKi7ZVZVqWspaqhUqBpraqs7lcK5ppqaNcX5RSWa0Yax/2u5uAz19AwNalSr1VTSrBWKc1JTCxQMa/8DAA "PowerShell – Try It Online") An even cheaper way to compute the day's seconds. TotalSeconds also returns as a float so that had to be truncated as well. Plugs that value into [this Fizzbuzz answer by AdmBorkBork](https://codegolf.stackexchange.com/a/58624/78849) so give him a thumbs-up as well. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 45 bytes ``` %3,5¬ȧ"“Fizz“Buzz”o"““”Fȯ⁸ 7ŒTṣ”:V×⁽½c,60,1SÇ ``` [Try it online!](https://tio.run/##y0rNyan8/1/VWMf00JoTy5UeNcxxy6yqAlJOpSBqbj5ICIzmup1Y/6hxB5f50UkhD3cuBgpYhR2e/qhx76G9yTpmBjqGwYfb//8HAA "Jelly – Try It Online") This is so bad [34 bytes if I steal Dennis's FizzBuzz](https://tio.run/##AUQAu/9qZWxsef//Myw14biNVOG7i@KAnMKh4bmsNOKAnOG7pHDCu8ivCjfFklThuaPigJ06VsOX4oG9wr1jLDYwLDFTw4f//w) [Answer] # Bash, 154 ``` z=$(($(date +%s)-$(date -d "$(date +%F) 0" +%s))) [[ 0 -eq "($z%3)" ]]&&a=1&&echo -n "fizz" [[ 0 -eq "($z%5)" ]]&&echo "buzz"||[ $a -eq 1 ]&&echo||echo $z ``` could probably golf down last two lines... [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~125~~ 120 bytes ``` x=Date().match(/\d\d/g).slice(3,6).reduce((a,j,i)=>a+=60**(2-i)*j) console.log((x%3==0?'Fizz':'')+(x%5==0?'Buzz':'')||x) ``` [Try it online!](https://tio.run/##LcjRCoMgFADQ9/3H8N4yi8V6GLjBGPuKXkSlKZYjbUj07y7G3g7Hio8IcjbvWE1e6ZwTf4ioAdkoonxB3ate1QOy4IzU0NIO2azVshsEtdQgv4qSd01RwKkyWFg8SD8F7zRzfgBIx5bz5kaeZl3JhRAs9zr/6r78a9sS5vwF "JavaScript (Node.js) – Try It Online") --- First line parses a date string for `[hours, minutes, seconds]` and adds them together, second line is just FizzBuzz. [Answer] # [Perl 5](https://www.perl.org/), 74 bytes ``` $t+=$_*60**$g++for(gmtime)[0..2];say+(($t%3==0&&Fizz).($t%5==0&&Buzz))||$t ``` [Try it online!](https://tio.run/##K0gtyjH9/1@lRNtWJV7LzEBLSyVdWzstv0gjPbckMzdVM9pAT88o1ro4sVJbQ0OlRNXY1tZATc0ts6pKUw/ENwXznUqBfM2aGpWS////5ReUZObnFf/X9TXVMzA0AAA "Perl 5 – Try It Online") [Answer] # [Bash](https://www.gnu.org/software/bash/), 76 bytes ``` date +'%H 60*%M+60*%S+[p]sc[[]sc[Fizz]n]sa[[]sc[Buzz]n]sbd3%0=ad5%0=blcx'|dc ``` [Try it online!](https://tio.run/##S0oszvj/PyWxJFVBW13VQ8HMQEvVVxtEBmtHF8QWJ0dHgwi3zKqq2LzY4kQI16kUwk1KMVY1sE1MMQWSSTnJFeo1Kcn//wMA "Bash – Try It Online") [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 40 [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") ``` {∨/d←0=4/3 5|⍵:d/'FizzBuzz'⋄⍵}60⊥3↑3↓⎕TS ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKO94H/1o44V@imP2iYY2JroGyuY1jzq3WqVoq/ulllV5VRaVaX@qLsFKFRrZvCoa6nxo7aJQDz5Ud/UkGCQ/v8KYFAAAA "APL (Dyalog Unicode) – Try It Online") `⎕TS` **T**ime **S**tamp; e.g. `[2019,06,14,07,48,20,317]` `3↓` drop three; e.g. `[07,48,20,317]` `3↑` take three; e.g. `[07,48,20]` `60⊥` evaluate as base-60 digits; e.g. `28100` `{`…`}` apply the following anonymous lambda to that:  `⍵` the argument; e.g. `28100`  `3 5|` the division remainder when that is divided by 3 and 5; e.g. `[2,0]`  `0=` Boolean mask where that is equal to 0; e.g. `[0,1]`  `4/` replicate those numbers for 4 copies of each; e.g. `[0,0,0,0,1,1,1,1]`  `d←` assign that to `d`  `∨/`…`:` if any of those are true (OR-reduction); e.g. `true`:   `d/'FizzBuzz'` use `d` to mask the characters of the string; e.g. `"Buzz"` `⋄` else:  `⍵` the argument; e.g. `28100` [Answer] # [AutoIt](https://www.autoitscript.com/site/autoit/), 90 bytes ``` $a=(@HOUR*60+@MIN)*60+@SEC ConsoleWrite($a&(Mod($a,3)=0?"Fizz":"")&(Mod($a,5)=0?"Buzz":"")) ``` It looks really bad without whitespace. (FYI: AutoIt is a Windows basic-like scripting language) [Answer] # [Pyth](https://github.com/isaacg1/pyth), 36 bytes ``` Js%.dZ84600|+*!%J3"Fizz"*!%J5"Buzz"J ``` [Try it online!](http://pythtemp.herokuapp.com/?code=Js%25.dZ84600%7C%2B%2a%21%25J3%22Fizz%22%2a%21%25J5%22Buzz%22J&debug=0) Loosely based on the Python 2 answer. ]
[Question] [ **This question already has answers here**: [Creating a Crossed Square](/questions/91068/creating-a-crossed-square) (30 answers) Closed 5 years ago. The following problem is a [common interview question](https://www.reddit.com/r/ProgrammerHumor/comments/89uhql/wtf_why_did_i_fail_this_interview_question/), thus dull answers are discouraged. Go short or creative, best if both: *Create the following pattern* ``` ########### ## ## # # # # # # # # # # # # # # # # # # # # # # # # # # # ## ## ########### ``` In case you cry ["dupe"](https://codegolf.stackexchange.com/questions/93707/draw-an-ascii-rectangle), I see your point but this is a slight variation and I hope it differs enough to be greenlit. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 9 bytes ``` P¬↙×⁶#‖O¬ ``` [Try it online!](https://tio.run/##ASIA3f9jaGFyY29hbP//77ywwqzihpnDl@KBtiPigJbvvK/CrP// "Charcoal – Try It Online") [Answer] # [Canvas](https://github.com/dzaima/Canvas), 14 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md) ``` 6#×:\ω↷11╋11╋┼ ``` [Try it here!](https://dzaima.github.io/Canvas/?u=JXVGRjE2JTIzJUQ3JXVGRjFBJXVGRjNDJXUwM0M5JXUyMUI3JXVGRjExJXVGRjExJXUyNTRCJXVGRjExJXVGRjExJXUyNTRCJXUyNTND,v=1) uses an older version of Canvas as in the latest one I undid a thing I undid with a logical reason.. [Answer] # [R](https://www.r-project.org/), 92 bytes ``` write(c(" ","#")[1+!!`[<-`(`[<-`(diag(11)+diag(11)[11:1,],c(1,11),,1),,c(1,11),1)],1,11,,"") ``` [Try it online!](https://tio.run/##NYdBCoAgFAWvkr/NF1@Lt41uIoJhEW4l6Pi/JFzMMNPMnlbvU4vKJJBZfGRwLsdtyfr7qPulpA8jIrkSCUWJb4HOGPqEXoCIN3sB "R – Try It Online") That is...a lot of `1`s. [Answer] # [Python 2](https://docs.python.org/2/), 100 bytes ``` for i in range(11):s=[" "]*11 if 0<i<10 else ["#"]*11;s[0]=s[10]=s[0+i]=s[10-i]="#";print ''.join(s) ``` [Try it online!](https://tio.run/##JYoxDoMwEAS/snIKIAjkSxngJRYFhQ0XRWfkc8PrDYJmRzPa/chblE8pISYwWJAWWX1N1Hx1cgZmfhOBA@zII1n4v3o487r7oM7Okzq617b8SHfxegx7Ysmoqv4XWWptSjkB "Python 2 – Try It Online") **Explanation** : ``` for i in range(11): s=[" "]*11 if 0<i<10 else ["#"]*11; #Ternary Expression to set cap lists s[0]=s[10]=s[0+i]=s[10-i]="#"; #Set '#'s in the right spots print ''.join(s) #Convert to string and print ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~129~~ 122 bytes * Saved seven bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat). ``` *s;f(j,k){for(j=puts(s="###########")-2;--j;)printf("#%*c%*c%*c\n",k-(k==5),k-5?35:32,10-k-k,35,k=j>5?10-j:j,35);puts(s);} ``` [Try it online!](https://tio.run/##RY1BCsIwEEXvkiLMlAxoQzYdYi/iRgKRzmAsTbsSzx4jXfh5i/9WL9Ijxlr7wgnEKr7TawUJy74VKMF0/xmkgYmEcVnnvCUw3amPB7dsrBJoCB7b8ZPzoxvs5UxKap23GuTqp@YySnPkI4D8qc/7nKF14Sdf "C (gcc) – Try It Online") ]
[Question] [ **This question already has answers here**: [What's the file extension?](/questions/120925/whats-the-file-extension) (103 answers) Closed 5 years ago. Given a printable ASCII string representing a path to a file on a POSIX-compliant system, return just the filename, i.e. remove everything until and including the last slash (`/`): `/full/path/file.name.ext` → `file.name.ext` `nopath.here` → `nopath.here` `dir/.hidden` → `.hidden` `/dirs.can/have.exts/file` → `file` `./here` → `here` `don't\do this` → `don't\do this` [Answer] # [QuadR](https://github.com/abrudz/QuadRS), 4 bytes # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 4 bytes ``` .*/ ``` [Try QuadR online!](https://tio.run/##VY3BDcIwDEXvniI3JA72Qlys2pUjhaQkKWICBmBEFglgVRW92e99/X9bWeoYeCYYg@Y1JVq4G80xKWa@Kuqjh/fzFQ4EIJdfDk2ruv77ASRWQosiml1uNwB9TcOJMxnfvan51L4AgLR3bmUln/pFSugWm/MD@QA "QuadR – Try It Online") [Try Retina online!](https://tio.run/##VY3BDcIwDEXvniI3pB5ssQ8Xi7iKpeBUiUFMwACMyCKhRFVFb/Z7X/9XcTU@944TQe8033OmhT3RrFnQ@CYoTw@f1zscCICVXw6TVBn67weIWgmTxig25HYD0GoaXtko8WM0tTG1LwAg7Z1bWbGTX2IJnrQNfiBf "Retina – Try It Online") Replace as many characters as possible, followed by a slash, with nothing. Equivalent to the 9-byte Dyalog APL function `'.*/'⎕R''`. [Answer] # [Python 2](https://docs.python.org/2/), ~~41~~ ~~27~~ 25 bytes ``` lambda s:s.split('/')[-1] ``` [Try it online!](https://tio.run/##XcwxDgIhEIXh3lOQbZDCmWhp4klci1EgkLADWWaNnh7XLQyx/d7LX94SMp@av4wt0XS3pOq5Qi0pyl6jNtfD8dbKHFmUX8EvKWEhCehjcsA0OXAv0Wb3@3D@7hDc7Hq2cUYI0VrHPePqFR7EGOi5teqW7j@Af7HBZtYy2qwkxDqY9gE "Python 2 – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 4 bytes ``` '/¡θ ``` [Try it online!](https://tio.run/##MzBNTDJM/V9TVvlfXf/QwnM7/lcqHd6voGuncHi/ks5//bTSnBz9gsSSDP20zJxUvbzE3FS91IoSrrx8kKBeRmpRKldKZpG@XkZmSkpqHpc@kFOsl5yYp5@RWAZWWgzWyaWnD1Gbn6deEpOSr1CSkVkMAA "05AB1E – Try It Online") [Answer] # [Java (OpenJDK 9)](http://openjdk.java.net/projects/jdk9/), 25 bytes ``` s->s.replaceAll(".*/","") ``` [Try it online!](https://tio.run/##jY6xboMwEIZ3nuLkJRAl57mijdSlW6aMTYcrNsHE2JZ9oEZVnp0Swl6mk@7@77u/pYH2PmjXquvLaLrgI0M7LbFnY7HuXcXGO9yWWWUpJTiScfCbASQmNhV8LInXE0fjLrvnOEANb2PaHxJGHSxV@t3aXOBWip0QxVhOgtB/20mweAZvFHQPef5UfH4BxUsq5mcAp1ti3aHvGcN0ZuvyGikEe8uFrHtrZSBuZG2sRkedRv3DoijKf2HnHyA2OupVeWWixMYopd2qvJyAhBU52dAw10pzy1UwyvW9vNvw@aw8cGPSgtyz@/gH "Java (OpenJDK 9) – Try It Online") ### Honorable mention 26 bytes: ``` s->("/"+s).split(".*/")[1] ``` [Answer] # [Red](http://www.red-lang.org), 24 bytes ``` func[s][last split s"/"] ``` [Try it online!](https://tio.run/##XYwxCgMhEEV7TyHbpHP6HCOtsZCdEQUziuOGQNizm80WQdL84v3Ha4TjRqitU@E6wsarFWezl66l5nTsAosbtSXuOug3hC1nqL5HCCmTYf8gQ6@@q5/C5XubSI0miqmBiQmReKJwYDGrZ4j@eYbk7E6Kgf9S4Uu/Y9E9JtnV@AA "Red – Try It Online") Red has a built-in `split-path` but it needs a path agrument and not a string. `f: func[p][last split-path to-file p]` [Answer] # [Stax](https://github.com/tomtheisen/stax), 4 bytes ``` '//H ``` [Run and debug online!](https://staxlang.xyz/#c=%27%2F%2FH&i=%2Ffull%2Fpath%2Ffile.name.ext%0Anopath.here%0Adir%2F.hidden%0A%2Fdirs.can%2Fhave.exts%2Ffile%0A.%2Fhere%0Adon%27t%5Cdo+this&a=1&m=2) ## Explanation Split on "/", take last part. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 12 bytes A built-in. ``` FileNameTake ``` [Try it online!](https://tio.run/##PYzBDsIgEER/ZUMTvVT2CzSePBoP3toeNmUJRKANoDExfjtCDx7fzLzxlA17ynamouFYLtbxlTzf6cHlFm3IQ9eDgMMJRA966KYJdoBn@AjUT@dwrQeoqyVD1SS/c92JsLRcGo7cUNmI0lilODTEyknOFNDQa3PSdtE6iX9pCfs8jmqBbGwS3/ID "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), 29 bytes ``` r.fst.span(/='/').r r=reverse ``` [Try it online!](https://tio.run/##BcExDoMwDADAva@wUCXagfgF@UG3rl0MigGRJpZt@nzcu43sKLUG509oYvNkQu2BecTxmfSmWcuvqJX40t4gg5z@dn01uAPDgEK@oXfk3nEmHeJauNJqMS0ifw "Haskell – Try It Online") [Answer] # [Coconut](http://coconut-lang.org/), 19 bytes ``` n->n.split('/')[-1] ``` [Try it online!](https://tio.run/##LY5RCsMgEESvIqFgAs0uPUBzkTQfElcUzCpxU/rRu9sY@vlmeMOsaU18SHXPV@VxYig5Buk16mEeH0udNbojRsxGPLoQCdhsBPQRfVeaU8vB004NbdgRfLCWuCGeXGA1jN68L6dcE60D/EudTazlZZMSH0q3qO@kNpNvfd4DC4AbWnKeLMdG9Qc "Coconut – Try It Online") ]
[Question] [ **This question already has answers here**: [Transpose a 3x3 matrix across the anti-diagonal](/questions/24893/transpose-a-3x3-matrix-across-the-anti-diagonal) (24 answers) Closed 6 years ago. # Objective To flip the rows and columns of a table in a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge. # Instructions You will be passed a "table" of 3 arrays/lists with 3 items each as input. Your job is to flip the rows and columns on it by writing a **program** that can do this efficiently and creatively. You will flip the "table" according to the example below. # Example ## Input ``` ["foo", 5, 0b1011] [3.14, "bar", 10] ["apple", 90, "monty"] ``` ## Output ``` ["foo", 3.14, "apple"] [5, "bar", 90] [0b1011, 10, "monty"] ``` # Qualification In order to qualify for winning, you must: 1. Solve the challenge (use the above input for a test case) 2. *Optional:* Post a link to an [ideone](http://ideone.com) or [repl.it](http://repl.it) 3. Follow standard loopholes 4. Put a header in the format: `Language, XX bytes`. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so least bytes wins. Good Luck! # Leaderboard ``` var QUESTION_ID=127611,OVERRIDE_USER=46066;function answersUrl(e){return"https://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"https://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] # Mathematica, 3 bytes ```  ``` This character (U+F3C7) is Mathematica's builtin `Transpose` suffix operator. [Answer] # Math.JS, 1 byte ``` ' ``` `'` is a named operator which takes it's left argument and transposes it. [Try it out](https://a-ta.co/math/%5B%5B%22foo%22%2C%205%2C%2011%5D%2C%0A%5B3.14%2C%20%22bar%22%2C%2010%5D%2C%0A%5B%22apple%22%2C%2090%2C%20%22monty%22%5D%5D%27) [Answer] # Pyth, 1 byte ``` C ``` Pyth's `C` command transposes the given nested list. [Answer] # TI-Basic, 2 bytes > AnsT Not eligible for "winning" due to specification #2 but a valid answer nonetheless. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 1 byte ``` Z ``` [Try it online!](https://tio.run/##y0rNyan8/z/q/@F29///o6OV0vLzlXQUTHUUDJIMDQwNY3W4oo31DE10FJSSEouAMoYGICGlxIKCnFQg19IAKJObn1dSqRQbCwA "Jelly – Try It Online") Footer added on the TIO link to make the result easier to see. This is Jelly's builtin for Zip. [Answer] # Python, 3 bytes ``` zip ``` Note that you must pass the arguments not in a list, but rather as separate arguments, which I believe is acceptable. If not, `lambda x:zip(*x)` works too for a list as a parameter. If builtins are not allowed (which was not specified), `lambda x:[[b[a]for b in x]for a in range(len(x[0]))]` works, or, since it's specified to be 3 × 3, `lambda x:[[b[a]for b in x]for a in[1,2,3]]` works. If you're going to enforce the strict IO, then here you go: ``` print(zip(*[input()for i in'3cs'])) # '3cs' because why not, CalcCat ``` [Answer] # Python 2, ~~44~~ 51 bytes *Crossed out 44 is still ~~44~~ :(* ``` for i in zip(*[input()for i in"hi!"]):print list(i) ``` [Try it online!](https://tio.run/##K6gsycjPM/r/Py2/SCFTITNPoSqzQEMrOjOvoLREQxMmqpSRqagUq2lVUJSZV6KQk1lcopGp@f9/tKGOkY5xLFe0iY6pjhmQNtex0LGMBQA "Python 2 – Try It Online") Follows original IO rules. Only works for 3 high input (other heights are not required). Change the length of `"hi!"` to height of input. [Answer] # MacOS bash, 6 ``` rs -Tc ``` Works on Linux as well, if `rs` is installed, as TIO: [Try it online](https://tio.run/##S0oszvj/v6hYQTck@f//tPx8TlNOgyRDA0NDLmM9QxPOpMQiTkMDrsSCgpxUTksDztz8vJJKLgA). [Answer] ## Haskell, 26 bytes ``` import Data.List transpose ``` This is a built-in ]
[Question] [ Input is a single integer in ascending digit order. ## The **only** valid inputs are: `12` `123` `1234` `12345` `123456` `1234567` `12345678` `123456789` ## The **only** valid output is an array (set; list) of `length` equal to the factorial of input: Input - Factorial of input - Output array `length` `12` -> `1*2` -> `2` `123` -> `1*2*3` -> `6` `1234` -> `1*2*3*4` -> `24` `12345` -> `1*2*3*4*5` -> `120` `123456` -> `1*2*3*4*5*6` -> `720` `1234567` -> `1*2*3*4*5*6*7` -> `5040` `12345678` -> `1*2*3*4*5*6*7*8` -> `40320` `123456789` -> `1*2*3*4*5*6*7*8*9` -> `362880` The output array is all integers of input length in lexicographical order. For example, given input `123` -> factorial of input is `1*2*3=6` -> for each of the six array elements output the input integer and the five remaining integers of the array in lexicographic order -> `[123,132,213,231,312,321]`. Notice that the last element is always the input integer in reverse order. ## Test Cases ``` Input Output `12` -> `[12,21]` // valid output, ascending numeric order `12` -> `[12.0,21.0]` // invalid output, output must be rounded to integer `123` -> `[123,132,213,231,312,321]` // valid output `123` -> `[123,132,213,222,231,312,321]` // invalid output: `222` are duplicate digits `123` -> `[123,142,213,231,213,321]` // invalid output: `142` outside range `1-3` `123456789` -> `[987654321,...,123456789]` // valid output, descending numeric order `123456789` -> `[987654321,...,123456798]` // invalid output, `123456798` is greater than the minimum required integer in resulting array `123456789` ``` ## Rules * Do **not** use standard library functions for permutations or combinatorics. * If the algorithm produces an integer greater or less than input minimum or maximum **only** the integers in the specified range must be output. (Technically, if input is `12345` we could generate all integers to `21` or `12`, though for input `12345` the only valid output **must** be within the range `12345` through `54321`). * Output must be an array (set; list) of integers, **not** strings. * The integers output must **not** be hardcoded. * The output integers must **not** include duplicate digits (more than one of the same digit at that array index). ## Winning criteria [fastest-code](/questions/tagged/fastest-code "show questions tagged 'fastest-code'") ## Hardware, OS Where submissions will be run ``` ~$ lscpu Architecture: i686 CPU op-mode(s): 32-bit, 64-bit Byte Order: Little Endian CPU(s): 2 On-line CPU(s) list: 0,1 Thread(s) per core: 1 Core(s) per socket: 2 Socket(s): 1 Vendor ID: GenuineIntel CPU family: 6 Model: 37 Model name: Intel(R) Pentium(R) CPU P6200 @ 2.13GHz Stepping: 5 CPU MHz: 2133.000 CPU max MHz: 2133.0000 CPU min MHz: 933.0000 BogoMIPS: 4256.26 L1d cache: 32K L1i cache: 32K L2 cache: 256K L3 cache: 3072K ~$ free -m total used free shared buff/cache available Mem: 3769 1193 802 961 1772 1219 Swap: 0 0 0 ~$ uname -r 4.8.0-36-lowlatency ``` Kindly explain the algorithm within the body of the answer. For languages used other than JavaScript (which will test at Chromium 70) will take the time to install the language and test the code for the time taken to output the requirement, as there is no way (that have found) to provide uniform results as to time for every possible language used to derive output (see this [comment](https://codegolf.stackexchange.com/questions/175206/fastest-algorithm-to-output-array-containing-all-integers-in-range-excluding-dup#comment422234_175206)). [Answer] # [Haskell](https://www.haskell.org/), 6.9 s ``` f [] [x] = [[x]] f [] [x,y] = [[x,y],[y,x]] f l (x:r) = map (x:) (f [] $ l++r) ++ f (l++[x]) r f _ [] = [] g :: Int -> [Int] g = map read . f [] . show ``` [Try it online!](https://tio.run/##LYxLCsIwAET3OcUsumhILfjXgu49QwgSsD9Ma0kF29PH6Wc1wzzmVbZ/586FUEAb6MHgBs0wYh2ScZ1YEj0mC3KIh8xLksZ2U5eI50MEpxSBUigQs9Ml4Xl5TpgmI0SJLMOj/WJzh2YaLovJ5/aFFLMqRV99fqGxdUva@ZqHCCW2u/3heDpfruEP "Haskell – Try It Online") `g` is the main function which converts the input to a string and the result to a list of integers. `f` recursively performs the shuffling. The algorithm works as follows: Given `123`, we need to generate `[123,132,213,231,312,321]`. This can be done in parts by taking the first digit `1`, recursively computing the list for the remaining digits `23 -> [23,32]` and adding `1` to the front again: `[123,132]`. Then we do the same with `2` and the remaining digits `13` to get `[213,231]` and with `3` and `12` to get `[312,321]`. Finally, the three lists are concatenated. This works in the same way for larger numbers. `f` handles two lists, the first one (`l`) contains all digits left from the current digit, the second one (`x:r`) has the current digit `x` at the first position, followed by the remaining digits `r`. We recursively call `f` with all but the current digit (that is `l` and `r` concatenated) `(f [] $ l++r)` and add the current digit `x` to the front of each element in the resulting list: `map (x:)`. We then finished processing `x` and add it to the end of the `l` list and recursively call `f (l++[x]) r` to handle the next digit. --- The largest test case `g 123456789` takes ~6.9s on OPs machine: ``` real 0m6.877s user 0m4.439s sys 0m0.056s ``` (~0.1s on my own machine) [Answer] # JavaScript 0.185 Seconds ``` function fact(x) { x+="" var rL=1,rI=0,i=0 if(x.length <2)return [x] for(i;i<x.length;i++)rL*=(i+1); var r = new Array(rL); function loop(p, s) { var l = s.length, i=0; if (l === 2) { r[rI++] = (p + s)*1; r[rI++] = (p + s.charAt(1) + s.charAt(0)) * 1; return; } while (i < l) { loop(p + s.charAt(i), s.substr(0,i) + s.substr(++i)); } } loop("",x) return r; } ``` This function creates an array r of length "factorial of input length". It then has a recursive loop of with parameters for prefix and suffix (p and s). It starts the loop with an empty prefix and a suffix of the input. It then checks the base case of suffix length equal to 2 and if reached adds those results. If it's not a base case then loop through the suffix characters, take a character at index and add it to prefix, remove that character from the suffix, and loops those as a new prefix and suffix. This will continue until input length factorial results are added to array r. [Answer] **Common Lisp SBCL 0.157 seconds** ``` (defun num-permutations (list) (cond ((null list) nil) ((null (cdr list)) (list list)) (t (loop for element in list append (mapcar (lambda (l) (cons element l)) (num-permutations (remove element list))))))) ``` here is the run with 1-9 ``` CL-USER> (time (num-permutations '(1 2 3 4 5 6 7 8 9))) Evaluation took: 0.157 seconds of real time 0.156455 seconds of total run time (0.140332 user, 0.016123 system) [ Run times consist of 0.081 seconds GC time, and 0.076 seconds non-GC time. ] 99.36% CPU 468,738,490 processor cycles 165,083,680 bytes consed ``` [Answer] ## C# (31 ms) ``` static int[] Foo(int perm) { int n = perm.ToString().Length, fact = n; int[] pow10 = new int[n]; pow10[n - 1] = 1; for (int k = n - 2; k >= 0; k--) { pow10[k] = 10 * pow10[k + 1]; fact *= k + 1; } int[] rv = new int[fact]; rv[0] = perm; int z = 1, i = n - 1, pi = perm/pow10[i]%10; while (true) { int pidec = perm/pow10[i-1]%10; if (pidec > pi) { if (--i == 0) return rv; pi = pidec; } else { int j = n - 1; while (perm/pow10[j]%10 < pidec) j--; perm += (perm/pow10[i-1]%10 - perm/pow10[j]%10) * (pow10[j] - pow10[i-1]); for (j = n - 1; i < j; i++, j--) perm += (perm/pow10[i]%10 - perm/pow10[j]%10) * (pow10[j] - pow10[i]); rv[z++] = perm; i = n - 1; pi = perm/pow10[i]%10; } } } ``` [Online demo](https://tio.run/##lZNNb9swDIbP9q/gZYBdx57dfcNNL/s4tcCADNgh8EFwFEepIxmSEmMd8ttTUpLbtFgPyyE2yfclH1Fwa/JWaX467Y2QHSz@GMt3dXweFd8E66QyVrSmjuO2Z8bAT606zXbwN46MZViCgxIruGVCJsZqdC8bYLozKUmiA9NgRpiD5CMsrBpGZttNktZYM2OxsExbH5FSH1D5Q6mkunz3/sPHT5@/PAnV4HVflTSq58VvLSy/EZInWP7es8HwVfFLWdbfir4XhrdKrgxZjvEjq5AW8WgCvsHA9c5jUiRxNmWwycIdJEmLGy47u5nBmrWWDlF7LfYY1FiV4VyUkQ3VXHYpIYeqwWJFubXS4MbdkRxLlzW@Xs@hxGeee4DgvHOuEi4gxJBhJ@oSOYSLObgUZehYAcbtbSIhobPow7JswqECONxT/xmIgIKvgwiSt36kaN5UJcnHjeg5JFbveWB0OxMr3r5w5NXkicQaEi@5RmnwuWye4yA8dAqa272WCO0ckQcgj4uP9Md7wycvDt1OuN4RyM4QtgQAV75NCts8r2PfHDWQzZ@JAy/2e9khxcUnU0z1R33qJ7u7fKLBPV7BFh9ZNqOhKYrgld8/Sf6PgygcBt7sfZad3y3u6fmOXr1Wt@AjfRXH0@kB) The algorithm is the [standard one](https://en.wikipedia.org/wiki/Permutation#Generation_in_lexicographic_order). [Answer] # C++ ``` #include <iostream> #include <string> #include <vector> #include <algorithm> #include <chrono> #include <cstring> #include <emmintrin.h> #include <smmintrin.h> unsigned char bsr(unsigned long* index, unsigned long long mask) { if (!mask) return 0; *index = 63 - __builtin_clzll(mask); return 1; } std::vector<uint32_t> findPermulations(uint32_t input) { std::string tmp = std::to_string(input); size_t size = std::distance(tmp.begin(), tmp.end()); uint8_t* perm = (uint8_t*)_mm_malloc(32, 64); memcpy(perm, tmp.data(), size); memset(perm + size, 0, 64 - size); for (size_t i = 0; i < size; i++) { perm[i] -= '0'; // Convert char to uint8_t } size_t fact = 1; for (size_t i = 0; i < size; i++) { fact *= perm[i]; } std::vector<uint32_t> results; results.reserve(fact); results.push_back(input); for (size_t i = 1; i < fact; i++) { uint8_t k; __m128i mask = _mm_cmplt_epi8(_mm_load_si128((__m128i*)perm), _mm_loadu_si128((__m128i*)(perm + 1))); unsigned long index = 0; if (!bsr(&index, _mm_extract_epi64(mask, 1))) { if (!bsr(&index, _mm_extract_epi64(mask, 0))) k = size - 1; else k = index / 8; } else k = (index / 8) + 8; uint8_t l = 8; mask = _mm_cmplt_epi8(_mm_set1_epi8(perm[k]), _mm_load_si128((__m128i*)perm)); if (!bsr(&index, _mm_extract_epi64(mask, 1))) { bsr(&index, _mm_extract_epi64(mask, 0)); l = 0; } l += index / 8; std::swap(perm[k], perm[l]); std::reverse(perm + k + 1, perm + size); uint32_t result = 0; for (size_t i = 0; i < size; i++) { result *= 10; result += perm[i]; } results.push_back(result); } _mm_free(perm); return results; } int main() { std::cout << "Press any key to begin...\n"; std::cin.get(); auto start = std::chrono::high_resolution_clock::now(); auto perms = findPermulations(123456789); auto end = std::chrono::high_resolution_clock::now(); std::cout << "Completed in " << std::chrono::duration<double, std::milli>(end - start).count() << "ms\n"; return 0; } ``` Regular algorithm. If `std::reverse` count counts as a library permutation function, replace with: ``` void reverse(uint8_t* first, uint8_t* last){ while ((first != last) && (first != --last)) { std::iter_swap(first++, last); } } ``` Swaps don't really count as permutations, put you could change them anyway. Compile with clang 6.0: `clang++-6.0 find.cpp -O3 -mssse3` `./a.out` ]
[Question] [ **This question already has answers here**: [Find the absolute value of a number without built-in functions [closed]](/questions/15668/find-the-absolute-value-of-a-number-without-built-in-functions) (49 answers) Closed 5 years ago. The abs() function in most languages does one thing: give the positive version of the input. Most of the times this is done using something similar to ``` int abs (int i) { return i < 0 ? -i : i; } ``` I was wondering if there is any way to do this with less bytes. Note that this doesn't have to be more efficient, just smaller Edit: i forgot to add that you can't use the abs() function in your language [Answer] ## [Retina](https://github.com/m-ender/retina/wiki/The-Language), 2 bytes ``` - ``` [Try it online!](https://tio.run/##K0otycxLNPz/X5cLiI25dI24dA25DLgMuYy4jAE "Retina – Try It Online") Just remove the minus sign... [Answer] # TI-Basic, 3 bytes ``` √(AnsAns ``` Square root of input \* input. Alternatively, `√(Ans²` is also 3 bytes. [Answer] # [R](https://www.r-project.org/), 8 bytes ``` (x^2)^.5 ``` [Try it online!](https://tio.run/##K/pfYZusYaijYKRnrKOgC2TomuoZKugomAFZ5pr/NSrijDTj9Ez//wcA "R – Try It Online") thanks to @Giuseppe --- Former, 1 byte longer version : # [R](https://www.r-project.org/), 9 bytes ``` x*sign(x) ``` [Try it online!](https://tio.run/##K/pfYZusYaijYKRnrKOgC2TomuoZKugomAFZ5pr/K7SKM9PzNCo0//8HAA "R – Try It Online") [Answer] # [Whitespace](https://web.archive.org/web/20150618184706/http://compsoc.dur.ac.uk/whitespace/tutorial.php), ~~48~~ 47 bytes ``` [N S S N _Create_Label_LOOP][S S S N _Push_0][S N S _Duplicate][T N T S _Read_STDIN_as_character][T T T _Retrieve][S N S _Duplicate][S S S T S T T S T N _Push_45_-][T S S T _Subtract][N T S N _If_0_jump_to_Label_LOOP][T N S S _Print_as_character][N S N N _Jump_to_Label_LOOP] ``` Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only. `[..._some_action]` added as explanation only. [Try it online](https://tio.run/##K8/ILEktLkhMTv3/n0tBAYiAmEuBk4tTgZOTE8xXADHBImCCixOsjovr/39dQyNjLl1TLgMuUy5DAwMA) (with raw spaces, tabs and new-lines only). **Explanation in pseudo-code:** ``` Start LOOP: Character c = STDIN as character if(c == '-') Go to next iteration of LOOP Print c Go to next iteration of LOOP ``` --- **Old 48 bytes answer:** ``` [S S S N _Push_0][S N S _Duplicate][T N T T _Read_STDIN_as_integer][T T T _Retrieve][S N S _Duplicate][N T T S N _If_negative_jump_to_Label_NEG][N S N N _Jump_to_Label_PRINT][N S S S N _Create_Label_NEG][S S T T N _Push_-1][T S S N _Multiply][N S S N _Create_Label_PRINT][T N S T _Print_as_integer] ``` Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only. `[..._some_action]` added as explanation only. [Try it online](https://tio.run/##K8/ILEktLkhMTv3/X0FBgQsIObk4QQDEBpFACohBUgqcQCkFkAhQBqju/39dUwA) (with raw spaces, tabs and new-lines only). **Explanation in pseudo-code:** ``` Integer i = STDIN as integer if(i is negative) i = i * -1 Jump to function PRINT else Jump to function PRINT function PRINT: Print i as integer to STDOUT ``` [Answer] # 05AB1E, 2 bytes ``` nt ``` [Try it online.](https://tio.run/##MzBNTDJM/X9u6/@8kv@H18ce2v0/WtfQQEdB11RHAUgZ6igAGYYGsQA) **Explanation:** ``` n # Square # i.e. 5 → 25 # i.e. -5 → 25 t # Square-root # 25 → 5 ``` [Answer] # sed, 5 bytes ``` s/-// ``` Strip the negative sign [Answer] # Java 8, 13 bytes ``` n->n<0?n*-1:n ``` [Try it online.](https://tio.run/##LY7NDoIwEITvPMXGE7Up0YMXfvQJ5MJRPdQCZhEWQguJMTx7bZHLJDv77ew0cpaiKd9WtVJruEqkbwCAZKqxlqqC3I@rASr0SixxzhI40UYaVJADQQaWxJnSw4X24hiTTTwwTM/WARs391hC5z6EhRmRXrcHSPaPr/txDcdMnBLANPPKOVuXAMVHm6qL@slEg7s0LYXId/Hd7DhFrhbbOi32Bw) Boring, but can't be done shorter without `Math.` or using `-n` directly (a.f.a.i.k.). [Answer] # [J](http://jsoftware.com/), 2 bytes Anonymous tacit prefix function. `%*` The argument (implicit) divided by its sign. [Try it online!](https://tio.run/##y/r/P83WSlXrf2pyRr5CmoKuMReUZQBjGJnDWIZZhv8B "J – Try It Online") Handles complex numbers as well. [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 3 [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") There are a few interesting approaches to this. All are anonymous tacit prefix functions. H.PWiz added two more. `⊢××` The argument multiplied by its sign. [Try it online!](https://tio.run/##SyzI0U2pTMzJT////1HXosPTD0//n/aobcKj3r5HfVM9/R91NR9ab/yobSKQFxzkDCRDPDyD/6cp6BpzpSkYALGROQA "APL (Dyalog Unicode) – Try It Online") `⊢⌈-` Max of the argument and its negation. [Try it online!](https://tio.run/##SyzI0U2pTMzJT////1HXokc9Hbr/0x61TXjU2/eob6qn/6Ou5kPrjR@1TQTygoOcgWSIh2fw/zQFXWOuNAUDIDYyBwA "APL (Dyalog Unicode) – Try It Online") `⊢∧×` The LCM of the argument and its sign. [Try it online!](https://tio.run/##SyzI0U2pTMzJT////1HXokcdyw9P/5/2qG3Co96@R31TPf0fdTUfWm/8qG0ikBcc5AwkQzw8g/@nKegac6UpGACxkTkA "APL (Dyalog Unicode) – Try It Online") `⊢∨-` The GCD of the argument and its negation. [Try it online!](https://tio.run/##SyzI0U2pTMzJT////1HXokcdK3T/pz1qm/Cot@9R31RP/0ddzYfWGz9qmwjkBQc5A8kQD8/g/2kKusZcaQoGQGxkDgA "APL (Dyalog Unicode) – Try It Online") `⊢÷×` The argument divided by its sign. [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qi2fYo7YJhv8fdS06vP3w9P9pQN6j3j6gjKf/o67mQ@uNH7VNBPKCg5yBZIiHZ/D/NAVdY640BQMgNjIHEoZehgA "APL (Dyalog Unicode) – Try It Online") Handles complex numbers but needs `⎕DIV` (**Div**ision method) set to 1. [Answer] # [Python 2](https://docs.python.org/2/), 18 bytes ``` lambda x:max(-x,x) ``` [Try it online!](https://tio.run/##Dco7CoAwEAXAq2wZ4S1oPk3Am9hEJBgwH0KK9fTRqae9465Fz7gf8wn5vAKJz0EUC2SZsXYSSoXYgS3YgDV4w4oNGgYWzreeyqCo/v4B "Python 2 – Try It Online") **Previous (20 bytes)** ``` lambda x:(x,-x)[x<0] ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUaHCSqNCR7dCM7rCxiD2f1p@kUKFQmaegq6xjq6Rjq6hjoGOoY6RjrFVQVFmXolCmkaF5n8A "Python 2 – Try It Online") [Answer] # Japt, 2 bytes Multiply input by its sign. ``` *g ``` [Try it](https://ethproductions.github.io/japt/?v=2.0a0&code=Kmc=&input=LTg=) Another square/root solution. ``` ²q ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=snE=&input=LTg=) Slightly less trivial 4 byte solution: convert to string, remove non-digit characters and convert back to integer. Or, if input can be taken as a string, this one can simply be `r-`. ``` sr\D ``` [Try it](https://ethproductions.github.io/japt/?v=2.0a0&code=c3JcRA==&input=LTg=) ]
[Question] [ # Intoroduction If you've ever been to [Epcot](https://commons.wikimedia.org/wiki/File:Epcot_map.png) at Disney World, you've probably been to the world showcase: a lake surrounded by various country-themed locations. One thing that's always bothered me about it is that the countries don't appear in the order you would run into them around the world. There are officially eleven of them, and the order is (going clockwise around the circle): ``` Mexico Norway China Germany Italy United States Japan Morocco France United Kingdom Canada ``` # Challenge Write a function or program that takes the list of countries (as a list, separated string, or other convenient form) in the order given above, and return/output them in an order that you would run into them if you were head around the world (either east-west or west-east) from a start point of your choosing. For specificity, lets define the capital of each country as it's "position", and order [longitudinally](https://en.wikipedia.org/wiki/Longitude). Output format should be the same as the input format. Standard code golf rules apply. Shortest code wins, with exception to the bonus below. The winner will be determined by the code with the lowest score that accomplishes the criteria, and will be selected in a minimum of seven days. # Bonus If your code can take in arbitrary country names (beyond just the eleven listed above) and order them as well, subtract 33% from your score. If you invoke this bonus, you must start from the [Prime Meridian](https://en.wikipedia.org/wiki/Prime_meridian), but which direction you go from there is up to you. Because the total number of "[sovereign states](https://en.wikipedia.org/wiki/Sovereign_state)" is a disputed thing, I'll settle for at least 190 of them. # Example ## Input ``` ['Mexico', 'Norway', 'China', 'Germany', 'Italy', 'Unites States', 'Japan', 'Morocco', 'France', 'United Kingdom', 'Canada'] ``` ## Output ``` ['Mexico', 'United States', 'Canada', 'Morocco', 'United Kingdom','France', 'Norway', 'Italy', 'Germany', 'China', 'Japan'] ``` [Answer] # Mathematica, 50 bytes ``` f=SortBy[CountryData[#,"CapitalLocation"][[1,2]]&] ``` Example: ``` In[12]:= f@{"Mexico", "Norway", "China", "Germany", "Italy", "United States", "Japan", "Morocco", "France", "United Kingdom", "Canada"} Out[12]= {Mexico,United States,Canada,Morocco,United Kingdom,France,Norway,Italy,Germany,China,Japan} ``` Mathematica has built-in functions for every kind of data like this... --- With bonus: # Mathematica, 58 bytes − 33% = 38.86 bytes ``` f=SortBy[CountryData[#,"CapitalLocation"][[1,2]]~Mod~360&] ``` [Answer] ## CJam (18 bytes) This is an anonymous function which takes input as an array of strings and returns it as an array of strings. ``` {36061983185Bb\f=} ``` [Online demo](http://cjam.aditsu.net/#code=q~%0A%0A%7B36061983185Bb%5Cf%3D%7D%0A%0A~%60&input=%5B%22Mexico%22%20%22Norway%22%20%22China%22%20%22Germany%22%20%22Italy%22%20%22United%20States%22%20%22Japan%22%20%22Morocco%22%20%22France%22%20%22United%20Kingdom%22%20%22Canada%22%5D) A slightly more general version, which takes any subset of the 11 countries in any order and sorts them correctly, is 26 bytes: ``` {{71b226%75585218525Bb=}$} ``` For the 30% bonus to give a better score, it would be necessary to encode the data for 190 countries in at most 37 bytes (including the code to use it); that's about 1.5 bits per country. But 190! is about 2^1169.3, requiring 147 bytes, so the 30% bonus is obviously not at all interesting without cheating by using external data sources. ]
[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 8 years ago. [Improve this question](/posts/47890/edit) Without changing the actual function, call it in such a way that it prints "True" ``` void Puzzle(out int x, out int y) { x = 0; y = 1; Console.WriteLine(x == y); } ``` [Online Tester](http://volatileread.com/utilitylibrary/snippetcompiler?id=9663) [Answer] Reusing reference: ``` //C# Puzzle: Call the Puzzle() function in Main such that it prints True. //You have to do this without changing the Puzzle method. public void Main() { int x,y; Puzzle(out x, out x); } void Puzzle(out int x, out int y) { x = 0; y = 1; Console.WriteLine (x == y); } ``` [Answer] Solved! ``` Puzzle(out x, out x); ``` <http://volatileread.com/utilitylibrary/snippetcompiler?id=9697> ]
[Question] [ A string like this one: "a, 4.25, ((true, 5), 3, (false, false, false)), abc" Describes a tree with 13 nodes, 9 of which are leaf nodes. In C# the leaf nodes in this example would be of types `string`, `float` and `bool`, this differs between languages and depending on your implementation. The important structure forming symbols here are `,` `(` and `)` with spaces being ignored. See the diagram in David Carrahers answer for a tree of the desired shape. ``` var a = new cake(4, "abc") ``` The above contains 8 symbols, I'm counting bracket and `"` pairs as a half and things like `.` as 1. The goal is to write code with the fewest symbols which given a string like the one shown above, creates the tree it represents. For example in the form of arrays inside each other, or interconnecting node objects. 60 extra points if you don't sort of cheat by adjusting the input string slightly then executing it. I won't count the symbols that define the input string. ``` daniero 100 - (10 symbols) +40 points for understanding numbers, strings, bools and any other basic types the language understands. +20 points for using a reasonably general language. 150 total points fejesjoco 100 - (est 37 symbols) +20 points for it understanding numbers as well as strings. +40 points for using a reasonably general language. 97 total points tomas 100 - (10 symbols) 90 total points David Carraher 100 - (est 19 symbols) 81 total points ``` [Answer] **JavaScript** ``` s="a, 4.25, ((true, 5), 3, (false, false, false)), abc" eval(("["+s+"]").replace(/\(/g,"[").replace(/\)/g,"]").replace(/([a-z]+)/g,"'$1'")) ``` The exact syntax, input and output format weren't exactly defined... I replace every a-z character to become a string, even true/false, which could be booleans, but there's no indication if there should be a distinction. I don't know if other characters are allowed or not (ő, $, \uFA20, ...), so my code doesn't care about that either. [Answer] # Mathematica `StringReplace` replaces all instances of `(` with `List[`; instances of `)` with `]`. The FullForm of `List` must be used (instead of `{…}`); otherwise `ToExpression` will not parse the string correctly. ``` f@t_:=ToExpression["List["<>StringReplace[t,{"("->"List[",")"->"]"}]<>"]"] ``` --- **Example** ``` f["a, 4.25, ((true, 5), 3, (false, false, false)), abc"] ``` > > {a, 4.25, {{true, 5}, 3, {false, false, false}}, abc} > > > --- **Verification** `TreeForm[<expression>]` displays the Mathematica expression as a tree. ``` TreeForm[f["a, 4.25, ((true, 5), 3, (false, false, false)), abc"]] ``` ![tree form](https://i.stack.imgur.com/oVzwx.png) [Answer] # R, 36 chars ``` plot(read.tree(,paste0("(",a,");"))) ``` package ape must be loaded. ### Output: ![enter image description here](https://i.stack.imgur.com/piUNZ.png) [Answer] # Common Lisp I *think* it would count as something around 11 symbols? Wrap parentheses around the string, remove the commas and evaluate it, and you have a LISP list. ``` (read-from-string (remove #\, (concatenate 'string "(" s ")" ))) ``` `s` is the string. For the given example it returns a list `(A 4.25 ((TRUE 5) 3 (FALSE FALSE FALSE)) ABC)` ]
[Question] [ I use "sentence" here loosely to mean "any sequence of words separated by spaces" and "words" to mean "sequences of alphanumeric (hexatrigesimal) characters unseparated by spaces". --- Conversion is from base-36 (0123456789abcdefg...) or (0123456789ABCDEFG...) Conversion to base-16 (0123456789abcdef) or (0123456789ABCDEF) **Bonus -1** off your byte score if you are case-insensitive on input **Bonus -1** off your byte score if you are insensitive to non-alphanumeric characters (ignore them, except space) --- Conversion of sentences E.g. if your input sentence is "The meaning of life is 31313" then your out put should convert the following base-36 "words" into base-16 numbers (the, meaning, of, life, is, 31313) and then output them in order. **Bonus -1** off your byte score for retaining spaces in output sentence ## Test Cases You may convert these to your preferred single-case form if you choose not to opt for the case-insensitive bonus, strings end after spaces. Assume input will never start with a space. --- ``` Input text: "The meaning of life is 31313" Output: ("9542 B59F1602C 36F F508A 2A4 4DA897") - with or without spaces, with lower or upper case letters ``` **Bonus -1** off your byte score for removing **leading zeroes** i.e. "9542" not "000009542". --- ``` Input text: "Jet fuel can't melt steel beams" Output: ("6245 B47AD 8C0F9 FF371 2E28A2D 1241854") ``` --- ``` Input text: "fhs8230982t90u20's9sfd902 %2'+13jos32*'ej eos" Output: ("74510A686B453A2B1933C7AADA25DD2 BB8E18A11AEB 4A5C") ``` ## The Winner This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the fewest bytes wins (including **bonus -1** bytes). :) Can accept the inputs in any way that works, as long as your code can solve arbitrary problems like the test cases. [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-S`](https://codegolf.meta.stackexchange.com/a/14339/), 6 - 3 = 3 bytes ``` ¸®n36G ``` Saved two bytes thanks to @Shaggy [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVM&code=uK5uMzZH&input=IlRoZSBtZWFuaW5nIG9mIGxpZmUgaXMgMzEzMTMi) [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 28 bytes - 2 = 26 ``` {S:g{\S+}=:36(~$/).base(16)} ``` [Try it online!](https://tio.run/##DcqxCsIwFEbh2TzFP0hJESqlkKHSF3Cto0sqNzWQpNIbhxLiq8dwpg/Oh3anij/QGEwoaR7X9JwveRoHJX/na9stmkn2qs3lJsy2QzobiFskcWJ9oGuMyOXxJnjSwYYVm4GzhmAZQ18Td4owX3J46RDr5iI4UvVC2vMf "Perl 6 – Try It Online") [Answer] # [MATL](https://github.com/lmendo/MATL) array, 9 - 1 = 8 bytes ``` Yb36ZA1YA ``` [Try it online!](https://tio.run/##HcqxDsMgDEXRX3lbVmOkKoxZO3dJN9KahgjIYOf7CarudKVTo5Xe180/3otbl96n1y6oEltuP5wJJSdBVng3AhHhKYZ0ScEnNhu0GNRk/Cax6p@kXWf2FGa2QBeTBk3fQAx2/jjVsxyQU6cb "MATL – Try It Online") Case-insensitive, but turns spaces into line breaks. # [MATL](https://github.com/lmendo/MATL) inline, 20-2 = 18 bytes (inelligible) ``` Yb36ZA1YAO10Z(!999e! ``` [Try it online!](https://tio.run/##DcqxCoAgFEbhV/mdalSEwNG1paVFN41rCWqDt@c3OdMHpwYuY7ioN2@Vs4eSfhXGGBJjLOdDqBRabjfehJITIXdoNYOUEjsx0kcFV2g818LoTNORQu3LDw "MATL – Try It Online") Takes case-insensitive and preserve-spaces bonuses, ([last test case fails due to implicit size assumptions = inelligible submission](https://tio.run/##y00syfn/PzLJ2CzK0TDS0d/QIEpD0dLSMlXx/3/1tIxiCyNjA0sLoxJLg1Ijg2LL4rQUSwMjBSND46z8YmOj1CyF1PxidQA)) ``` Yb % Split the input at spaces, place the results in a cell array 36ZA % convert from base-36 1YA % Convert to hexadecimal. Gives a char array O10Z( % Assign char 0 to 10th column. Adds "Spaces" !999e! % Reshape in row-major order as a 999-column char array % Implicitly display. Display 0 as space. ``` (I hope Luis Mendo comes and improves on this, because I got most of this from his answers [here](https://codegolf.stackexchange.com/questions/103403/print-the-f-%C3%97-f-times-table/103406#103406), [here](https://codegolf.stackexchange.com/questions/66426/numbers-that-are-actually-letters/66431#66431), [here](https://codegolf.stackexchange.com/questions/102781/output-the-html-colors/102803#102803) and sundar's answer [here](https://codegolf.stackexchange.com/questions/168640/search-text-for-a-prefix-and-list-all-its-suffixes-in-the-text).) [Answer] # [Ruby](https://www.ruby-lang.org/) `-p`, 23-1 = 22 bytes Only uses the case-insensitive bonus. ``` $_=$_.to_i(36).to_s(16) ``` [Try it online!](https://tio.run/##FYqxCsIwFEX39xUP7GARtU1AzODq4Oxe2npjU2IivlfEn7dW7nLO4b6m7jPPRXMqmp3mJqztofyDrOtDuXTenLjY84rP@cU6gBPeMSRwB30DiRWi3LcC4ZziZ74OoAfaFNKdsqcYPCgI2XoZXaDkJ0Tq26TLLSqJYvEO7UPID3I0tnJHo66aTCVO/M1VhkxtxyzWYCRk@eanhpxk3j5/ "Ruby – Try It Online") ## Ruby `-p`, 33-2 = 31 bytes Takes case-insensitive and preserve-spaces bonuses. ``` gsub(/\w+/){$&.to_i(36).to_s(16)} ``` [Try it online!](https://tio.run/##FYpBCsIwEADvfcUeRFqkNk2gNF/w7FGQRDdtSpsUd4OI@HVjZS4zMI9kXzkPlGzZXJ6Hpnrv9keOV1@qrvoLlW1XfXI@jwgLmuDDANHB7B2CJ1DtRnFCBpdwhpsJvG0zAzFubdEsVLiReqmE7iVrkaQgTe6uhQTZqimSkjgBRvrGlX0MlOv1Bw "Ruby – Try It Online") # Ruby `-p`, 46-3 = 43 bytes Takes all 3 bonuses. ``` gsub(/\S+/){$&.gsub(/\W/){}.to_i(36).to_s(16)} ``` [Try it online!](https://tio.run/##LYrBDoIwEAXvfMUe1IJEKG1C4Be8auLFxIBuoQRa4paDMfy6tSZmLm9e5rm0L@87Wto4v57SPHlvdtlfL8HWzNmbjmWZ/AbFRZms3p97hAkbo00HVsGoFYImkEUgOqIDteAI98YwF7rRATkMR4vNRJHqqRKS15VwNV8EZ1STetRcwFawtJCDJSn2DAdASx87O20N@cP8BQ "Ruby – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), score 3 (4 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) - 1 bonus) ``` #₆öh ``` Bonus -1: no leading 0s, since this is done implicitly. Outputs as a list of converted words. [Try it online.](https://tio.run/##yy9OTMpM/f9f@VFT2@FtGf//h2SkKuSmJuZl5qUr5Kcp5GSmpSpkFisYGwKhgldqiUJaaWqOQnJiXglQWU6JQnFJKpCflJqYWwwA) --- # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), score 8 (12 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) - 4 bonus) ``` u#εžKÃ}₆öhðý ``` All four bonuses: -1 for no leading 0s, since this is done implicitly; -1 case-insensitivity by first converting to uppercase with `u`; -1 for retaining spaces in the output by joining the list by spaces with `ðý`; -1 for ignoring every character apart from `[A-Za-z0-9 ]`, by keeping `[A-Za-z0-9]` after the split\_on\_spaces with `εžKÃ}` [Try it online.](https://tio.run/##DcoxDgIhEEDRq0xiDIk27NAsV9DWC7A6CBt2KQbKbTTxPDbaaUNsPYQXQfK7lx/ZDJ5qzavv4/Pel@vyu9zK05V7edV6cAQTmdnPZ4gWgrcEnkF1LdhRApspwNHMIrUvJOBEDQYyE4N13KOSusekZUYpWLM9aYmwRrHt1BhZ4UbQCBT5Dw) **Explanation:** ``` # # Split the (implicit) input-string on spaces ₆ö # Convert each string from base-36 to integers h # Convert those integers to hexadecimal # (and output the list implicitly as result) u # Convert the (implicit) input to uppercase # # Split it on spaces ε # Map each string to: žK # Push builtin string "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" à # And only keep those characters in the mapped string }₆ö # After the map: convert each string from base-36 to integer h # Convert those integer to hexadecimal ðý # And join them by spaces # (after which the result is output implicitly) ``` [Answer] # [Python 2](https://docs.python.org/2/), 47 - 2 = 45 bytes ``` lambda S:[hex(int(s,36))[2:]for s in S.split()] ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSHYKjojtUIjM69Eo1jH2ExTM9rIKjYtv0ihWCEzTyFYr7ggJ7NEQzP2f0ERUI1CmoZ6SUaqQmpeioKBkaGRobrmfwA "Python 2 – Try It Online") Because case insensitive. And also leading `0`s. [Answer] # [Perl 5](https://www.perl.org/) `-Mbigint -MList::Util=reduce -p`, 92 - 4 = 88 bytes ``` y/_/*/;s|\S+|Math::BigInt::as_hex reduce{$a*36+$b}map{7x/\d/+ord(uc)-55}$&=~/\w/g|ge;s/0x//g ``` [Try it online!](https://tio.run/##Jc5BC4IwGIDhv@LBshT71sRKpUu3IE/RTRDNNRfmxG@SkfbTW0Kn9z0@DWsrX@sXpGBDhENydoY4U2UYHgQ/1ioMM0xL1hstK7ore5uZ7W0cMx8fWfPe9pAU4Mi2WHTXpev7oznffyB5Ah84ixBID8C1vpUp7qhHgh1VAekosTDAWxEQasyo5ay9u0SP2ha7G0ziVzZKyBq1G/srsiZTc8FFraY5CZxIFyWq/R@k3eYH "Perl 5 – Try It Online") Qualifies for all 4 bonuses (case insensitive, keeps spaces, ignores punctuation, no leading 0s). Handles even large test cases properly, including the last one. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 14 bytes - 1, score 13 ``` ⪫E⪪S ⍘⍘ι³⁶¦¹⁶ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMMrPzNPwzexQCO4ICezRMMzr6C0JLgEKJWuoamjoKSgBCSdEotToWJIzEwdBWMzoKyhmSZUpab1//8lGakKuamJeUAVCvlpCjmZaakKmcUKxoZAyPVftywHAA "Charcoal – Try It Online") Link is to verbose version of code. Only qualifies for the leading zeros bonus. Explanation: ``` S Input string ⪪ Split on spaces E Map over words ι Current word ⍘ ³⁶ Convert from base 36 ⍘ ¹⁶ Convert to base 16 ⪫ Join on spaces Implicitly print ``` * If output of the hex numbers on separate lines is acceptable, then the first and last characters can be removed for a 2-byte saving. * Case insensitive input is possible at a cost of 1 byte, which would not affect the score. * Preservation of multiple spaces is possible at a cost of 2 bytes, unless the current misbehaviour is a Charcoal bug, in which case it would work once the bug is fixed. * Skipping of punctuation is possible at a cost of 4 bytes. (Currently the only supported case is a single trailing `.`) [Answer] # Java, 94-2 = 92 bytes These "bonuses" are too expensive to intentionally claim. I get case insensitive and leading zeros for free though. ``` s->{for(var w:s.split(" "))System.out.print(new java.math.BigInteger(w,36).toString(16)+" ");} ``` [TIO](https://tio.run/##LY67CsIwFIb3PMWhU4IaEMHBooOD4Fw3cThoUk9tk5IcW6T02Wu88I/ff6uww0V1e0zk2ASLVwOHQXSebmBlwYFcCVHlIjIyXeELGiT3Z@cLqkEcwMJ2iovdYH2QHQboN1HHtiaWGWRKFa/IptH@ybpNMZbO9FClad0g3/WeymOaL02Q/Xy1Vpr9r14u12r2acjHKRdWW5md7gYag@5zzFuoyRqgCKtlUvKJcZze) [Answer] # [Gema](http://gema.sourceforge.net/), 20 characters ``` <A>=@radix{36;16;$1} ``` Sample run: ``` bash-4.4$ gema '<A>=@radix{36;16;$1}' <<< 'The meaning of life is 31313' 9542 B59F1602C 36F F508A 2A4 4DA897 ``` [Try it online!](https://tio.run/##S0/NTfz/38bRztahKDEls6La2Mza0MxaxbD2//@QjFSF3NTEvMy8dIX8NIWczLRUhcxiBWNDIOTySi1RSCtNzVFITswrASrLKVEoLkkF8pNSE3OLAQ "Gema – Try It Online") [Answer] # Ecmascript 2020, score 90 - 3 = 87 Likely it would be there, already works in Firefox 68+ and Chrome 67+. ``` s=>s.replace(/\w+/g,x=>[...x].reduce((r,x)=>36n*r+BigInt(parseInt(x,36)),0n).toString(16)) ``` Bonuses: * Bonus -1 off your byte score if you are case-insensitive on input * Bonus -1 off your byte score for retaining spaces in output sentence * Bonus -1 off your byte score for removing leading zeroes i.e. "9542" not "000009542". Test: ``` f=s=>s.replace(/\w+/g,x=>[...x].reduce((r,x)=>36n*r+BigInt(parseInt(x,36)),0n).toString(16)) console.log([ ["The meaning of life is 31313", "9542 B59F1602C 36F F508A 2A4 4DA897"], ["Jet fuel can't melt steel beams", "6245 B47AD 8C0F9 FF371 2E28A2D 1241854"], ["fhs8230982t90u20's9sfd902 %2'+13jos32*'ej eos", "74510A686B453A2B1933C7AADA25DD2 BB8E18A11AEB 4A5C"], [" 123 1234 tyu ", " 55B C0D0 97B6 "], ].map(([t,k])=>f(t.replace(/(?!\s|_)\W/g,"")).toUpperCase()==k)) ``` ]
[Question] [ Here's an example IRC log (this will be your program's input): ``` [01:00] == User [*****] has joined #Channel [01:00] == ChanServ [ChanServ@services.] has left #Channel [] [01:00] == mode/#Channel [+o User] by ChanServ [01:00] <Bot> Welcome, User! [01:01] <User> Hello bot [01:02] <Bot> Hi there [01:38] <OtherUser> I like pie [01:38] <User> Me too :D [19:58] <@Mod> I am a mod!!!1!!11! [19:59] <User> That's fascinating ``` Your task is to parse that into XML, like this (this will be your program's output): ``` <irc> <message type='event'> <text>User [*****] has joined #Channel</text> <time>01:00</time> </message> ... <message type='chat'> <user>Bot</user> <text>Welcome, User!</text> <time>01:00</time> </message> ... </irc> ``` Further specification: * must be well-formed XML (except for the XML declaration at the top), whitespace/indentation unnecessary * you don't have to worry about escaping; `>`, `<`, etc. will never appear in messages * messages can be in two forms: + `[{hh:mm}] <{username}> {message}` - this should be parsed as: ``` <message type='chat'> <user>{username}</user> <text>{message}</text> <time>{hh:mm}</time> </message> ``` + `[{hh:mm}] == {message}` - this should be parsed as: ``` <message type='event'> <text>{message}</text> <time>{hh:mm}</time> </message> ``` * XML consists of a single `irc` element with zero or more `message` elements in it * order of the elements within the `message` element don't matter, but order of `message` elements does * input and output can be any reasonable method (i.e. stdin and stdout, reading from/writing to files, etc.) but input cannot be hardcoded * this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest code wins [Answer] ### GolfScript, 140 characters ``` {.@+'<>'1/*@+\'</>'2/*+}:^;n%{" "/(1>5<'''time'^\(.'='>{;'event'}{1>-1<'''user'^@+\'chat'}if`' type='\+\' '*'''text'^@+\'message'^}%'''irc'^ ``` I meant to use a language, especially designed for xml processing. Input/output is STDIN/STDOUT. You can remove a few chars by replacing `''` with `n` but that makes the output more unreadable. Output for the example given above ([online](http://golfscript.apphb.com/?c=OyJbMDE6MDBdID09IFVzZXIgWyoqKioqXSBoYXMgam9pbmVkICNDaGFubmVsClswMTowMF0gPT0gQ2hhblNlcnYgW0NoYW5TZXJ2QHNlcnZpY2VzLl0gaGFzIGxlZnQgI0NoYW5uZWwgW10KWzAxOjAwXSA9PSBtb2RlLyNDaGFubmVsIFsrbyBVc2VyXSBieSBDaGFuU2VydgpbMDE6MDBdIDxCb3Q%2BIFdlbGNvbWUsIFVzZXIhClswMTowMV0gPFVzZXI%2BIEhlbGxvIGJvdApbMDE6MDJdIDxCb3Q%2BIEhpIHRoZXJlClswMTozOF0gPE90aGVyVXNlcj4gSSBsaWtlIHBpZQpbMDE6MzhdIDxVc2VyPiBNZSB0b28gOkQKWzE5OjU4XSA8QE1vZD4gSSBhbSBhIG1vZCEhITEhITExIQpbMTk6NTldIDxVc2VyPiBUaGF0J3MgZmFzY2luYXRpbmcKIgoKey5AKyc8PicxLypAK1wnPC8%2BJzIvKit9Ol47biV7IiAiLygxPjU8JycndGltZSdeXCguJz0nPns7J2V2ZW50J317MT4tMTwnJyd1c2VyJ15AK1wnY2hhdCd9aWZgJyB0eXBlPSdcK1wnICcqJycndGV4dCdeQCtcJ21lc3NhZ2UnXn0lJycnaXJjJ14%3D&run=true)): ``` <irc><message type="event"><text>User [*****] has joined #Channel</text><time>01:00</time></message><message type="event"><text>ChanServ [ChanServ@services.] has left #Channel []</text><time>01:00</time></message><message type="event"><text>mode/#Channel [+o User] by ChanServ</text><time>01:00</time></message><message type="chat"><text>Welcome, User!</text><user>Bot</user><time>01:00</time></message><message type="chat"><text>Hello bot</text><user>User</user><time>01:01</time></message><message type="chat"><text>Hi there</text><user>Bot</user><time>01:02</time></message><message type="chat"><text>I like pie</text><user>OtherUser</user><time>01:38</time></message><message type="chat"><text>Me too :D</text><user>User</user><time>01:38</time></message><message type="chat"><text>I am a mod!!!1!!11!</text><user>@Mod</user><time>19:58</time></message><message type="chat"><text>That's fascinating</text><user>User</user><time>19:59</time></message></irc> ``` [Answer] ### Tcl, 268 I believe Perl would be better for the job, but who cares. ``` puts <irc>[regsub -all -line {^\[([^\]]*)\] == (.*$)} [regsub -all -line {^\[([^\]]*)\] <([^>]*)> (.*)} [gets stdin] {<message type='chat'><user>\2</user><text>\3</text><time>\1</time></message>}] {<message type='event'><text>\2</text><time>\1</time></message>}]</irc> ``` Every task that can be solved with 2 regsub is boring. [Answer] ### R 254 characters ``` cat("<irc>",gsub("\\[(.*)\\] <(.*)> (.*)","<message type=\\'chat\\'><user>\\2</user><text>\\3</text><time>\\1</time></message>",gsub("\\[(.*)\\] == (.*)","<message type=\\'event\\'><text>\\2</text><time>\\1</time></message>",scan(,"",se="\n"))),"</irc>") ``` Very simple solution: take input as newline-separated stdin, apply two `gsub` to it (one for events, one for chats) and output. Example output with example input from question: ``` <irc> <message type='event'><text>User [*****] has joined #Channel</text><time>01:00</time></message <message type='event'><text>ChanServ [ChanServ@services.] has left #Channel []</text><time>01:00</time></message <message type='event'><text>mode/#Channel [+o User] by ChanServ</text><time>01:00</time></message <message type='chat'><user>Bot</user><text>Welcome, User!</text><time>01:00</time></message <message type='chat'><user>User</user><text>Hello bot</text><time>01:01</time></message <message type='chat'><user>Bot</user><text>Hi there</text><time>01:02</time></message <message type='chat'><user>OtherUser</user><text>I like pie</text><time>01:38</time></message <message type='chat'><user>User</user><text>Me too :D</text><time>01:38</time></message <message type='chat'><user>@Mod</user><text>I am a mod!!!1!!11!</text><time>19:58</time></message <message type='chat'><user>User</user><text>That's fascinating</text><time>19:59</time></message </irc> ``` [Answer] # Ruby: 186 characters ``` BEGIN{puts"<irc>"} END{puts"</irc>"} sub(/.(.{5}). (<(.+?)>|==) (.+)/){"<message type='#{$3?:chat:"event"}'>#{$3?"<user>#{$3}</user>":""}<text>#{$4}</text><time>#{$1}</time></message>"} ``` Sample run: ``` bash-4.1$ ruby -p irc2xml.rb < irc.txt <irc> <message type='event'><text>User [*****] has joined #Channel</text><time>01:00</time></message> <message type='event'><text>ChanServ [ChanServ@services.] has left #Channel []</text><time>01:00</time></message> <message type='event'><text>mode/#Channel [+o User] by ChanServ</text><time>01:00</time></message> <message type='chat'><user>Bot</user><text>Welcome, User!</text><time>01:00</time></message> <message type='chat'><user>User</user><text>Hello bot</text><time>01:01</time></message> <message type='chat'><user>Bot</user><text>Hi there</text><time>01:02</time></message> <message type='chat'><user>OtherUser</user><text>I like pie</text><time>01:38</time></message> <message type='chat'><user>User</user><text>Me too :D</text><time>01:38</time></message> <message type='chat'><user>@Mod</user><text>I am a mod!!!1!!11!</text><time>19:58</time></message> <message type='chat'><user>User</user><text>That's fascinating</text><time>19:59</time></message> </irc> ``` Test run: ``` bash-4.1$ ruby -p irc2xml.rb < irc.txt | xmlstarlet val - - - valid ``` [Answer] # Sed: ~~183~~ 180 characters ``` 1i<irc> s!.(.{5}). (.*)!\2<time>\1</time>! Ta s!<(.+?)> (.*)!chat\n\2<user>\1</user>! ta s!== !event\n! :a s!(.+)\n([^<]+)!<message type='\1'><text>\2</text>! a</message> $a</irc> ``` Sample run: ``` bash-4.1$ sed -rf irc2xml.sed < irc.txt <irc> <message type='event'><text>User [*****] has joined #Channel</text><time>01:00</time> </message> <message type='event'><text>ChanServ [ChanServ@services.] has left #Channel []</text><time>01:00</time> </message> <message type='event'><text>mode/#Channel [+o User] by ChanServ</text><time>01:00</time> </message> <message type='chat'><text>Welcome, User!</text><time>01:00</time><user>Bot</user> </message> <message type='chat'><text>Hello bot</text><time>01:01</time><user>User</user> </message> <message type='chat'><text>Hi there</text><time>01:02</time><user>Bot</user> </message> <message type='chat'><text>I like pie</text><time>01:38</time><user>OtherUser</user> </message> <message type='chat'><text>Me too :D</text><time>01:38</time><user>User</user> </message> <message type='chat'><text>I am a mod!!!1!!11!</text><time>19:58</time><user>@Mod</user> </message> <message type='chat'><text>That"s fascinating</text><time>19:59</time><user>User</user> </message> </irc> ``` Test run: ``` bash-4.1$ sed -rf irc2xml.sed < irc.txt | xmlstarlet val - - - valid ``` [Answer] # Awk: 203 characters ``` BEGIN{print"<irc>"}END{print"</irc>"}{gsub(/\[|\]/,"",$1) $2=gsub(/<|>/,"",$2)?"<user>"$2"</user>":"" $1="<message type='"($2?"chat":"event")"'><time>"$1"</time>" $3="<text>"$3 $0=$0"</text></message>"}1 ``` Sample run: ``` bash-4.1$ awk -f irc2xml.awk < irc.txt <irc> <message type='event'><time>01:00</time> <text>User [*****] has joined #Channel</text></message> <message type='event'><time>01:00</time> <text>ChanServ [ChanServ@services.] has left #Channel []</text></message> <message type='event'><time>01:00</time> <text>mode/#Channel [+o User] by ChanServ</text></message> <message type='chat'><time>01:00</time> <user>Bot</user> <text>Welcome, User!</text></message> <message type='chat'><time>01:01</time> <user>User</user> <text>Hello bot</text></message> <message type='chat'><time>01:02</time> <user>Bot</user> <text>Hi there</text></message> <message type='chat'><time>01:38</time> <user>OtherUser</user> <text>I like pie</text></message> <message type='chat'><time>01:38</time> <user>User</user> <text>Me too :D</text></message> <message type='chat'><time>19:58</time> <user>@Mod</user> <text>I am a mod!!!1!!11!</text></message> <message type='chat'><time>19:59</time> <user>User</user> <text>That"s fascinating</text></message> </irc> ``` Test run: ``` bash-4.1$ awk -f irc2xml.awk < irc.txt | xmlstarlet val - - - valid ``` [Answer] # Perl: 168 characters ``` BEGIN{say"<irc>"}END{say"</irc>"}/.(.{5}). (<(.+?)>|==) (.+)/;say"<message type='",$3?chat:event,"'>",$3&&"<user>$3</user>","<text>$4</text><time>$1</time></message>" ``` Sample run: ``` bash-4.1$ perl -nE 'BEGIN{say"<irc>"}END{say"</irc>"}/.(.{5}). (<(.+?)>|==) (.+)/;say"<message type='"'"'",$3?chat:event,"'"'"'>",$3&&"<user>$3</user>","<text>$4</text><time>$1</time></message>"' < irc.txt <irc> <message type='event'><text>User [*****] has joined #Channel</text><time>01:00</time></message> <message type='event'><text>ChanServ [ChanServ@services.] has left #Channel []</text><time>01:00</time></message> <message type='event'><text>mode/#Channel [+o User] by ChanServ</text><time>01:00</time></message> <message type='chat'><user>Bot</user><text>Welcome, User!</text><time>01:00</time></message> <message type='chat'><user>User</user><text>Hello bot</text><time>01:01</time></message> <message type='chat'><user>Bot</user><text>Hi there</text><time>01:02</time></message> <message type='chat'><user>OtherUser</user><text>I like pie</text><time>01:38</time></message> <message type='chat'><user>User</user><text>Me too :D</text><time>01:38</time></message> <message type='chat'><user>@Mod</user><text>I am a mod!!!1!!11!</text><time>19:58</time></message> <message type='chat'><user>User</user><text>That's fascinating</text><time>19:59</time></message> </irc> ``` Test run: ``` bash-4.1$ perl -nE 'BEGIN{say"<irc>"}END{say"</irc>"}/.(.{5}). (<(.+?)>|==) (.+)/;say"<message type='"'"'",$3?chat:event,"'"'"'>",$3&&"<user>$3</user>","<text>$4</text><time>$1</time></message>"' < irc.txt | xmlstarlet val - - - valid ``` ]
[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/11955/edit). Closed 10 years ago. [Improve this question](/posts/11955/edit) Given the integers N and M, can you print all numbers from N to M comma-seperated? The hitch is to use one single expression. The output for *N=23* and *M=42* should look like this: ``` 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42 ``` I'll start with Ruby: ``` puts (23..42).to_a.join(', ') ``` [Answer] # k 17 chars. Expression returns 1 but prints output to `stdout` ``` 1@", "/:$23_!1+42 ``` To return a string with the comma seperated values, simply use: ``` ", "/:$23_!1+42 ``` [Answer] ## Sage CLI, 14 Edit: Sage has a `range` shorthand. ``` `[n..m]`[1:-1] ``` [Answer] # Ruby: 18 characters ``` $><<[*23..42]*", " ``` Sample run: ``` bash-4.1$ ruby -e '$><<[*23..42]*", "' 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42 ``` ## Forcing the rules: 10 characters As seen in the other answers: * variables instead of numeric literals * comma only instead of comma and space * no output, just generated value ``` [*n..m]*?, ``` Sample run: ``` irb(main):001:0> n=23 => 23 irb(main):002:0> m=42 => 42 irb(main):003:0> [*n..m]*?, => "23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42" ``` [Answer] # Bash, 21 bytes ``` echo {23..42}|tr \ , ``` [Answer] # Tcl, 63 bytes ``` puts "$n,[join [lmap a [lrepeat [expr {$m-$n}] 0] {incr n}] ,]" ``` [Answer] # Python: 39 ``` print(",".join(map(str,range(23,42)))) ``` [Answer] ### J, 28 characters ``` echo(,', ',])&":/[23}.i.>:42 ``` * `i.43` creates an array of 43 values `0..42`. Unfortunately, we have to compute `43`. * `23}.` drops first 23 of them, leaving `23..42`. If precomputation is allowed, `23+i.20` fares better byte-wise (-3 characters) * `,', ',]` concatenates both arguments with `', '` between them * `...&":` does that after converting both arguments to strings * `.../` does that as a reduction step. * `echo` is a built-in to perform standard output. If simply returning is enough, you can drop this (-4 characters) [Answer] ## R: 17 characters ``` cat(n:m,sep=", ") ``` Example: ``` > n=23 > m=42 > cat(n:m,sep=", ") 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42 ``` ]
[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/269006/edit). Closed last month. This post was edited and submitted for review last month and failed to reopen the post: > > Original close reason(s) were not resolved > > > [Improve this question](/posts/269006/edit) So simple: Provide some code that outputs `foo` and with the reversed source outputs `bar`. But before you come up with something like [this boring python 2](https://tio.run/##K6gsycjPM/r/v6AoM69EQSktP19JWakoMUlJoSQvs6jg/38A): ``` print "foo"#"rab" tnirp ``` you should know the **score: You multiply the number of bytes with (1 + dead bytes)**, where dead bytes are bytes that can be changed to most other characters without changing the behaviour in the current execution direction (in the sense that more can be changed than not). This is valid for comments or labels or code after some exit statement or such workarounds (you know what I mean, so don't feel a hero because your language has some feature with a different name to ignore code). I want to see your creativity in reusing code depending on the direction! **Examples** for score count * In the example above, the `#` is no dead code, because you cannot simply replace it, but the following 11 bytes are dead code, thus we get a score of 23 \* (1+11) = **276**! Valid, but not so nice anymore. * A [`sh` answer](https://tio.run/##yy7O@P8/NTkjXyEtP19BWaEoMUkhPyM59f9/AA) like `echo foo # rab ohce` would score a slightly better **190**. * An [`sed` answer](https://tio.run/##K05N0U3PK/3/v9gqziotP9/K2qooMQnILv7/HwA) `s:^:foo:;:rab:^:s` misuses the `:` label to hide code, but the label is still dead code, resulting in a score of **136**. * `foo//rab` in `///` has the open `//` as valid exit, so this would have only three bytes of dead code, reaching a score of **32**. **Rules** * Dead code can be different for both directions, so **for scoring, the number of dead bytes for the worse direction is counted**: If you have three deads bytes forward, but 7 backwards, your multiplier will be 8. * Your code must not output anything visible after the `foo` or `bar`, just something like whitespaces or newlines. * `foo` and `bar` can be lowercase or uppercase, as you like * Your program has to end execution by itself, so don't try to loophole through some infinite loop after output! * Don't use any non-empty input, of course. * Why do I add +1 to the dead bytes? Because I don't want a zero score for living-code-only answers like [this `///` solution](https://tio.run/##HYuxCcBADANXyQRSr1nS@CEmRcBg749j3BycDtVn9T7V7REEJZHiPXAEDgyp9YtDKWc5U1zr3AeYdrp/) (actual score 65): `foo/./::://:/\//:f.o.b.a.r::/\// //\/::r.a.b.o.f://\/://:::/./rab` * Did I mention the **smallest score wins**? [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 8 bytes, score 32 ``` bar←←oof ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z8psehR2wQgys9P@/8fAA "Charcoal – Try It Online") Outputs `foo`. Explanation: The first word is overprinted in reverse by the reversed second word. The second `←` is needed to overprint and the first `←` is needed to overprint in the correct location, but the first word can be e.g. any three ASCII characters. ``` foo←←rab ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z8tP/9R2wQgKkpM@v8fAA "Charcoal – Try It Online") Outputs `bar`. [Answer] # Vyxal 3, ~~11 \* 6 = 66~~, 10 \* 5 = 50 ``` "rab""foo" ``` [Forwards](https://vyxal.github.io/latest.html#WyIiLCIiLCJcInJhYlwiXCJmb29cIiIsIiIsIiIsIjMuNC4wIl0=) ``` "oof""bar" ``` [Backwards](https://vyxal.github.io/latest.html#WyIiLCIiLCJcInJhYlwiXCJmb29cIiIsIiIsIiIsIjMuNC4wIl0=) ]
[Question] [ "Bracket" numerals are a type of 'numerals' I made up once, and thought would be a nice challenge here. Basically, you convert the input number into base 6, and then transliterate the `012345` respectively with `()[]{}`*†*, so every `0` becomes `(`, every `1` becomes `)`, etc. You don't have to use `()[]{}` per se. As long as you specify what characters you use, you can use any other characters (except for digits, otherwise *just* converting to base-6 would have been enough!) Since this is tagged [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the score is in bytes, where the least amount of bytes wins. A few examples: 6 = `)(`. 100200 = `[(})}[(`. 44790 = `}{][)(`. Here is some lengthy JavaScript code which accomplishes what I described above. Since it's a snippet (using variable `x`) instead of a function or full program, it isn't valid however: ``` var [x,q,w] = [0,0,0];q = x.toString('6');w = q.replace(/0/g, '(');q = w.replace(/1/g, ')');w = q.replace(/2/g, '[');q = w.replace(/3/g, ']');w = q.replace(/4/g, '{');q = w.replace(/5/g, '}');console.log(q); ``` Yes, that is 207 bytes. You probably can do better! I will accept an answer on June 1st, 2019, but you can continue to post answers afterwards of course. [Standard rules apply](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422) for your answer with [default I/O rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/), so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call. So you aren't allowed to have a `var x` like I did in my example JavaScript snippet. [Default Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. [Answer] # [Japt](https://github.com/ETHproductions/japt), 4 bytes Uses `[objec`. ``` s6îM ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=czbuTQ&input=OA) ## Alternative 4 bytes Uses the (unprintable) characters at codepoints `1-6`. ``` s6õd ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=czb1ZA&input=OAotUQ) Or, if that's not allowed: ### 5 bytes Using `!"#$%&`. ``` s6õdH ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=czb1ZEg&input=OA) Or, also (using `wander`): ``` s`æ`â ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=2.0a0&code=c2DmYOI&input=OA) If I can figure out a 6 letter word that Shoco can compress to a single character then that last one can be golfed to 3 bytes. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~11~~ ~~10~~ ~~5~~ 4 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) All three programs below will return a list of characters instead of a joined string. ``` žOÅв ``` Uses `aeiouy` instead of `()[]{}` for `0123456` respectively. [Try it online.](https://tio.run/##yy9OTMpM/f/f0dPswqbDK/7/NzQyNgEA) --- Answers which actually use `()[]{}`: **~~11 10~~ 8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)**: ``` žu„<>мÅв ``` [Try it online](https://tio.run/##yy9OTMpM/f//6L7SRw3zbOwu7DncemHT//@GRsYmAA) **8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) alternative by *@Grimy***: ``` …([{º{Åв ``` [Try it online.](https://tio.run/##yy9OTMpM/f//UcMyjejqQ7uqD7de2PT/v6GRsQkA) **Explanation:** ``` žO # Push string builtin "aeiouy" Åв # Convert the (implicit) input to this custom base-"aeiouy" # (which is output implicitly as result) žu # Push string builtin "()<>[]{}" „<>м # Remove the "<>" from this string: "()[]{}" Åв # Convert the (implicit) input to this custom base-"()[]{}" # (which is output implicitly as result) …([{ # Push string "([{" º # Mirror it vertically to "([{}])" { # Sort the characters in the string: "()[]{}" Åв # Convert the (implicit) input to this custom base-"()[]{}" # (which is output implicitly as result) ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 8 bytes ``` ⍘N()[]{} ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMMpsTg1uATITNfwzCsoLfErzU1KLdLQ1FFQ0tCMjq2uVdLUtP7/38TE3NLgv25ZDgA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` N Input as a number ⍘ Base convert using specified characters ()[]{} Literal string of required characters ``` 5 bytes using the letters `a-f` (or `A-F` also works): ``` ⍘N…β⁶ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMMpsTg1uATITNfwzCsoLfErzU1KLdLQ1FFwrkzOSXXOyC/QSNJRMNPU1LT@/9/ExNzS4L9uWQ4A "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` N Input as a number ⍘ Base convert using … ⁶ First six characters of β Lowercase alphabet ``` [Answer] # JavaScript (ES6), ~~36~~ 34 bytes *Saved 2 bytes thanks to @Shaggy* Character set: `[`,`o`,`b`,`j`,`e` and `c`. ``` f=n=>(n>5?f(n/6|0):'')+({}+0)[n%6] ``` [Try it online!](https://tio.run/##FY2xDsIgFEV3v4LFAOFRoRViNODkVzQdSC1V0zxMa1zUb0c6nJOTu9xHeIeln@/Pl8R0HXKODp1n6M05MtzZr@JHSrlgn59QvMWt7fKpVaChhgb2YMCCVtCsViulD7o23aaKab6E/saQOE/6hEuahmpKYxkEoURKXyxIueGc5z8 "JavaScript (Node.js) – Try It Online") [Answer] # [Bash](https://www.gnu.org/software/bash/), ~~65~~ ~~63~~ 60 bytes Using STDIN and not command line arguments: ``` while read n;do echo "obase=6;$n"|bc|tr 012345 '()[]{}';done ``` [Try it online!](https://tio.run/##S0oszvj/vzwjMydVoSg1MUUhzzolXyE1OSNfQSk/KbE41dbMWiVPqSYpWUG3sKakSMHA0MjYxFRBXUMzOra6Vh2oOi/1/38DLkMuUy4zLkMgwwCMDbiMLQyNTAE "Bash – Try It Online") [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 64 bytes ``` #~IntegerDigits~6/.Table[k->StringTake["()[]{}",{k+1}],{k,0,5}]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n277X7nOM68kNT21yCUzPbOkuM5MXy8kMSknNTpb1y64pCgzLz0kMTs1WklDMzq2ulZJpzpb27A2FkjpGOiY1saq/Q8AqilRiFZSsrFLjzYzM4uN/f8fAA "Wolfram Language (Mathematica) – Try It Online") [Answer] # [PHP](https://php.net/), 53 bytes ``` <?=strtr(base_convert($argn,10,6),'012345','()[]{}'); ``` [Try it online!](https://tio.run/##K8go@G9jX5BRwMWlkliUnqdgq2BoYGBgzcVlbweUsC0uKSop0khKLE6NT87PK0stKtEAq9MxNNAx09RRNzA0MjYxVddR19CMjq2uVde0/v8fAA "PHP – Try It Online") I'll be honest, I still don't understand the bonus, but here's a PHP version. [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 47 bytes ``` n=>m=>{do m[0]+="()[]{}"[n%6];while((n/=6)>0);} ``` [Try it online!](https://tio.run/##JY2xCsIwFEVn@xUhICS0Yrp0MH0BF0Ho7lA7xVYf2Fdon3QI@fYacbp3OOdevxz8gtvlQ75G4uLsGSeqrw0uXC88Iz2dcwNsBG4EFx6TGFvT5SCVbrsQZUv7qrPrC9@9UnSESjujbdxs9rfbjoH6NbFSRpsN06zSj0AwFmsoTYo81yJkO067IKXNdoNCrVindpuR@wapVzKYeOeTCGWUBRY/OAFx@wI "C# (Visual C# Interactive Compiler) – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes ``` ṃØỵ ``` [Try it online!](https://tio.run/##ASwA0/9qZWxsef//4bmDw5jhu7X/MTAwxbs74oCcIC0gPiDigJ07w4fGsuKCrFn//w "Jelly – Try It Online") Uses ‘aeiouy’ for ‘01235’. [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 13 bytes ``` '()[]{}'⊇⍨6∘⊤ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qG@qp/@jtgkG/9U1NKNjq2vVH3W1P@pdYfaoY8ajriX/04Byj3r7IMq6mg@tN37UNhHICw5yBpIhHp7B/1OASgxN7Q0NDAy4HvWuStE5tCLt0IoUAA "APL (Dyalog Extended) – Try It Online") Pretty straightforward tacit function. Test cases used are 15 randomly selected integers between 0 and 999. Uses `⎕IO←0`. Thanks to @Adám for 2 bytes ### How: ``` '()[]{}'⊇⍨6∘⊤ ⍝ Tacit function 6∘⊤ ⍝ Convert input to base 6 ⊇ ⍝ Index the right argument with the indices in the left argument ⍨ ⍝ With arguments swapped '()[]{}' ⍝ Character vector ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 28 bytes Uses `abcdef` in place of `012345`. ``` ->x{x.to_s(6).tr'0-5','a-f'} ``` [Try it online!](https://tio.run/##KypNqvyfZhvzX9euorpCryQ/vljDTFOvpEjdQNdUXUc9UTdNvfZ/QWlJsUJatEo8SEFm7H9DCy5LSy7Df/kFJZn5ecX/dfMA "Ruby – Try It Online") ]
[Question] [ **Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers. --- Closed 8 years ago. * Questions without an **objective primary winning criterion** are off-topic, as they make it impossible to indisputably decide which entry should win. * **General programming questions** are off-topic here, but can be asked on [Stack Overflow](http://stackoverflow.com/about). [Improve this question](/posts/48630/edit) I'm working on something and came across this after I interpreted some brainfuck code. It looks like another esoteric language but I'm not sure what. Anyone know? ``` (CB;:9]~}5Yz2Vw/StQr*)M:,+*)('&%$#"!~}|{zyx875t"2~p0nm,+jch'`% ``` [Answer] After one second of Googling a portion of the string (`5Yz2Vw`), I found the following page: <http://www.xchg.info/wiki/index.php?title=ICTF_2011_:_Challenge_13_-_250_Points> On that page it's deduced the code is Malbolge. ]
[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/15783/edit). Closed 10 years ago. [Improve this question](/posts/15783/edit) Take any type of nested list(s) containing numbers. Check for how many even/odd numbers are within and output even, same or odd (-1, 0, 1) in some way. Example: ``` [[1,2,3],4,[5,6],[[7,8], 9]] => 5 odd > 4 even => odd or -1 [1,2,2,1,2,2,2] => 5 even > 2 odd => even or 1 [1,2,2,1] => 2 even = 2 odd => same or 0 ``` [Answer] ## Python - 63 This returns a negative number if its got more evens, `0` if their are an equal amount or a positive number if there are more odds. ``` x=input() i=0 for o in x: try:x+=o except:i+=o%2-.5 print i ``` edit: Type checking, who needs that, lets just stab blindly. [Answer] # Befunge 98 - 19 ``` &2%6*j\1+\2j1+3j@.` ``` Outputs 1 if even, 0 if odd or the same. I'm still trying to figure out how to indicate that they are the same. However, I have not tested this because I don't have a Befunge 98 compiler. It works as follows: ``` & receives input as a number, all parts that aren't numbers are ignored and skipped 2% takes that number and divides it by two, then gets the remainder (1 if odd, 0 if even) 6*j jump 6 characters if odd, 0 if even when even: \ swap top two numbers on stack (I'm storing evens under the odds) 1+ add one to that value \ swap back 2j jump 2 characters when odd: 1+ add 1 to top number on stack 3j jump 3 characters (to end of line ie the beginning (Befunge wraps)) ``` When `&` is hit again, if there are no more values, it acts like a reflector, sending the instruction pointer back the other way and running this: ``` @.` ``` (executed in reverse order): ``` ` compares the even and odd values, if even is greater, then push 1, else 0 . prints it out @ ends the program ``` --- With one simple change, it can be made to print some negative number if there are more odds, some positive number if there are more evens, and 0 if there are the same amount: ``` &2%6*j\1+\[[email protected]](/cdn-cgi/l/email-protection) ``` [Answer] # R, 64 ### three possible outputs ``` function(x)c("even","same","odd")[sign(mean(unlist(x)%%2)-.5)+2] ``` Examples: ``` (function(x)c("even","same","odd")[sign(mean(unlist(x)%%2)-.5)+2])( list(list(1, 2, 3), 4, list(5, 6), list(list(7, 8), 9))) [1] "odd" (function(x)c("even","same","odd")[sign(mean(unlist(x)%%2)-.5)+2])( list(list(2, 3), 4)) [1] "even" (function(x)c("even","same","odd")[sign(mean(unlist(x)%%2)-.5)+2])( list(list(2, 3), list(4, 5))) [1] "same" ``` [Answer] ## R 58 This was written at a time the OP was asking for two "even" or "odd" possible outputs. ``` function(x)c("even","odd")[which.max(table(unlist(x)%%2))] ``` Example usage: ``` (function(x)c("even","odd")[which.max(table(unlist(x)%%2))])( list(list(1, 2, 3), 4, list(5, 6), list(list(7, 8), 9))) # [1] "odd" ``` [Answer] # k 34 characters. Outputs `o` for odd, `e` for even, `s` for same. ``` {"ose"1+{(x>0)-x<0}@+/-1 xexp,//x} ``` ``` {(`s#-0w -.5 .5!"ose")@+/-1 xexp,//x} ``` Example: ``` {"ose"1+{(x>0)-x<0}@+/-1 xexp,//x}((1 3;5 10);12 2 4 6 8) "e" ``` [Answer] ## [Golf-Basic 84](http://timtechsoftware.com/?page_id=1261 "Golf-Basic 84"), 17 ``` i`Ad`fpart(A/2)*2 ``` Returns `0`s for even numbers and `1`s for odd numbers. Accepts nested arrays - 1D, 2D, 3D, 4D, etc. --- **Old version, 30 characters:** ``` i`A@fpart(A/2)*2t`ODD"#t`EVEN" ``` **Explanation** (for old version) ``` i`A ``` Store input in A. Accepts arrays, e.g. `{1,2,3,4}` or `{{1,2},3,{4,5,{6,7}},8}` ``` @fpart(A/2)*2t`ODD"#t`EVEN" ``` If (`@`) one or more numbers in array `A` are odd, display `ODD`. Else (`#`) display `EVEN`. [Answer] ## Ti-Basic 84, 26 characters ``` :Input A:Disp fpart(A/2)*2 ``` Returns `1` for odd numbers and `0` for even numbers. Takes nested arrays - 1D, 2D, 3D, 4D, 5D, etc. --- Old version, **50** characters: ``` :Input A:If fpart(A/2)*2:Disp"ODD":Else:Disp"EVEN" ``` Takes arrays like `{1,2,3}` and also `{1,{2,3},4,{5,{6,7}},{{8,9},10},11}` Returns `EVEN` for all even and `ODD` if it contains odd. [Answer] ## JavaScript, 65 ``` c=l=>l.reduce((a,b)=>a+(+b?b%2-.5:c(b)),0),l=>c(l)<0?"even":"odd" ``` Defaults to “odd” if there are equal numbers of each. Requires arrow function support, which currently means “SpiderMonkey”. If you don’t mind output as a number, it’s just this part, at **42**: ``` c=l=>l.reduce((a,b)=>a+(+b?b%2-.5:c(b)),0) ``` [Answer] ## JavaScript, 51+ ### Variation 1, 61 or 51 Reads input via `prompt`, outputs via `alert`, encodes answer as a number with sign denoting if more evens or odds. ``` b=0;prompt().replace(/\d+/g,function(s){b+=s%2*2-1});alert(b) // ES5, 61 b=0;prompt().replace(/\d+/g,s=>b+=s%2*2-1);alert(b) // ES6, 51 ``` ### Variation 2, 72 or 49 As above, but as a function taking an array instead of using `prompt`/`alert`. ``` function f(s){b=0;return s.big?b+=s%2*2-1:s.join().replace(/\d+/g,f)&&b} // ES5, 72 f=a=>b=0,a.join().replace(/\d+/g,s=>b+=s%2*2-1),b // ES6, 49 ``` ]
[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/12655/edit). Closed 10 years ago. [Improve this question](/posts/12655/edit) I want to give a task. The main rule is not to use the same code again, it means no loops, no jumps, no goto, no recursion, if you declare procedure it can be called only once and etc. Also if you call some standart function it should meet the requirements inside. The main point of this task is to write the shorter code which prints the longest output. **NOTE:** printing functions, for example `printf` probably do not meat requirements but it is allowed to use this kind of functions. **EDIT:** after reading some comments I have to tell that output needs to be longer then input. Also you cannot use the same function twice because it means you are using the same code, sorry for not very clear requirements. [Answer] # Python: 11 characters → 857 characters ``` import this ``` Sample run: ``` >>> import this The Zen of Python, by Tim Peters Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those! ``` [Answer] # Golfscript, 1 -> 2 ``` ` ``` if the requirement is to produce the shortest code with an output longer than input, this is the winner (unless we count error messages of languages where an empty source is invalid program). Backtick means "inspect/uneval". Since the empty string (input) happens to be already present on the stack, this produces a string containing only two double quotes, which is then printed out. # C++, 22 -> 2^31-1 (= 2147483647) ``` printf("%*i",~0u>>1,0) ``` It's hard to argue that string concatenation or infinite precision arithmetic doesn't loop internally. In such case, we are restricted to built-in finite precision data types. However, the best place for a large value is the output precision, not the value to be printed. In C++, the variable precision type is int, so we can print with no more than 2^31-1 digits of precision. Sure, the printing routine will loop a bit, but printing routines are allowed to. But, if built in operators (but not library functions) are allowed to loop as well, # J, (extreme growth) ``` !9 !!9 !!!9 !!!!9 ``` the factorial of an n-digit number has in the order of e^n digits for some small e. This means the sequence factorial of (factorial of(factorial of ... (factorial of 9) ...))) grows *very* quickly. It's unclear what "same code twice" exactly means, but I'll assume that two invocations of the same system function are allowed as long as the function itself is allowed. "*if you declare procedure* it can be called only once" Of course, if function exponentiation doesn't count as iteration, we can grow much more quickly than that: ``` !^:(!^:]9)9 ``` this will apply factorial to nine nine times, then use *that* as the number of applications of factorial to (another) nine. Of course, these can be nested ad lib. Say, we could take the factorial of `!^:9]9` `!^:9]9` times. We'll also shorten `!^:9]9` to just `!^:]9`. ``` !^:]!^:]9 ``` Ninth composition of `!^:]` can be shortened to `!^:]^:9`. The argument'th composition is `!^:]^:]`. Unfortunately, function power cannot be applied to conjunctions like function power, so let's stop here for now (arg compositions of (arg compositions of (arg compositions of ... factorial))): ``` !^:]^:]^:]^:] ``` We could apply "eval" here, but we're way so far off the realm of definitely not iterating I better stop here and not get to stuff like string multiplication and evaluation in order to crank up this immense number even higher. # Golfscrcript, n -> theta(2^n) ``` ````````````... ``` Languages without built-in infinite precision arithmetic can still achieve exponential growth via string concatenation (twofold increase in two characters). Or, we could inspect the inspection of the inspection of ... yielding twofold increase in just a single char. [Answer] My code is: `help` and it is Windows batch script. Output is: ``` For more information on a specific command, type HELP command-name ASSOC Displays or modifies file extension associations. ATTRIB Displays or changes file attributes. BREAK Sets or clears extended CTRL+C checking. BCDEDIT Sets properties in boot database to control boot loading. CACLS Displays or modifies access control lists (ACLs) of files. CALL Calls one batch program from another. CD Displays the name of or changes the current directory. CHCP Displays or sets the active code page number. CHDIR Displays the name of or changes the current directory. CHKDSK Checks a disk and displays a status report. CHKNTFS Displays or modifies the checking of disk at boot time. CLS Clears the screen. CMD Starts a new instance of the Windows command interpreter. COLOR Sets the default console foreground and background colors. COMP Compares the contents of two files or sets of files. COMPACT Displays or alters the compression of files on NTFS partitions. CONVERT Converts FAT volumes to NTFS. You cannot convert the current drive. COPY Copies one or more files to another location. DATE Displays or sets the date. DEL Deletes one or more files. DIR Displays a list of files and subdirectories in a directory. DISKCOMP Compares the contents of two floppy disks. DISKCOPY Copies the contents of one floppy disk to another. DISKPART Displays or configures Disk Partition properties. DOSKEY Edits command lines, recalls Windows commands, and creates macros. DRIVERQUERY Displays current device driver status and properties. ECHO Displays messages, or turns command echoing on or off. ENDLOCAL Ends localization of environment changes in a batch file. ERASE Deletes one or more files. EXIT Quits the CMD.EXE program (command interpreter). FC Compares two files or sets of files, and displays the differences between them. FIND Searches for a text string in a file or files. FINDSTR Searches for strings in files. FOR Runs a specified command for each file in a set of files. FORMAT Formats a disk for use with Windows. FSUTIL Displays or configures the file system properties. FTYPE Displays or modifies file types used in file extension associations. GOTO Directs the Windows command interpreter to a labeled line in a batch program. GPRESULT Displays Group Policy information for machine or user. GRAFTABL Enables Windows to display an extended character set in graphics mode. HELP Provides Help information for Windows commands. ICACLS Display, modify, backup, or restore ACLs for files and directories. IF Performs conditional processing in batch programs. LABEL Creates, changes, or deletes the volume label of a disk. MD Creates a directory. MKDIR Creates a directory. MKLINK Creates Symbolic Links and Hard Links MODE Configures a system device. MORE Displays output one screen at a time. MOVE Moves one or more files from one directory to another directory. OPENFILES Displays files opened by remote users for a file share. PATH Displays or sets a search path for executable files. PAUSE Suspends processing of a batch file and displays a message. POPD Restores the previous value of the current directory saved by PUSHD. PRINT Prints a text file. PROMPT Changes the Windows command prompt. PUSHD Saves the current directory then changes it. RD Removes a directory. RECOVER Recovers readable information from a bad or defective disk. REM Records comments (remarks) in batch files or CONFIG.SYS. REN Renames a file or files. RENAME Renames a file or files. REPLACE Replaces files. RMDIR Removes a directory. ROBOCOPY Advanced utility to copy files and directory trees SET Displays, sets, or removes Windows environment variables. SETLOCAL Begins localization of environment changes in a batch file. SC Displays or configures services (background processes). SCHTASKS Schedules commands and programs to run on a computer. SHIFT Shifts the position of replaceable parameters in batch files. SHUTDOWN Allows proper local or remote shutdown of machine. SORT Sorts input. START Starts a separate window to run a specified program or command. SUBST Associates a path with a drive letter. SYSTEMINFO Displays machine specific properties and configuration. TASKLIST Displays all currently running tasks including services. TASKKILL Kill or stop a running process or application. TIME Displays or sets the system time. TITLE Sets the window title for a CMD.EXE session. TREE Graphically displays the directory structure of a drive or path. TYPE Displays the contents of a text file. VER Displays the Windows version. VERIFY Tells Windows whether to verify that your files are written correctly to a disk. VOL Displays a disk volume label and serial number. XCOPY Copies files and directory trees. WMIC Displays WMI information inside interactive command shell. For more information on tools see the command-line reference in the online help. ``` I didn't count size of output because it is my own question and I'm not willing to win. [Answer] # Mathematica ``` RandomInteger[{10^980, 10^990}] ``` ![randominteger](https://i.stack.imgur.com/oYXeM.png) [Answer] ## Ruby, 13 chars, 599994 char output, ~46153:1 ratio ``` 999999**99999 ``` Simply raises a very large number to the power of another very large number. Takes about ten seconds to run. I could increase the numbers, but that would make the running time even longer. ]
[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/114649/edit). Closed 6 years ago. [Improve this question](/posts/114649/edit) This is a fairly simple challenge. Write a program that computes the distance between two points on a 2D plane. However, you can't use any functions or operators (referred to here as symbols) that are 1 character long. **Examples:** * `-=`, `+=`, `*=`, `/=`, `%=`, etc. are allowed. * `||`, `&&`, `--`, `++` are allowed as well. * `+`, `-`, `/`, `*` are not allowed. * `f(x)` is not allowed, but `fn(x)` is. * `S 5 4` is not allowed, but `SUM 5 4` is. * `if(lol==lel)` is allowed. * Simply putting two separate single-character operators one after the other is not allowed, eg. `!!(true)` isn't allowed. **Exceptions:** * Single semicolons or the equivalent are allowed, e.g. `foo();`, as long as they are being used as an end-of-command symbol. * Commas (`,`) and periods (`.`) are allowed. * Parentheses (`()`) and other symbols that are used in such a way to require a second match are allowed. Examples: + `foo();` is allowed, as is `foo(x);`. + `[5,6]` is allowed. + `"strings"` are allowed. + `for(i+=5;;i++){}` is allowed + `if(1<2 && 2>3)` is not allowed, as the symbols are being interpreted as greater than and less than symbols, and so do not require the other. + `([{<>}])` is allowed. + `][` is not allowed, as the symbols do not match. + Essentially, the interpreter/compiler/etc.(?) should recognize the symbols as matching. **Specifications:** * Whitespace does not count for the single character rule, e.g. `this == that` and `this ==that` etc. are both allowed. * Standard rules for loopholes etc. apply. * Input can be in any reasonable format of two points. Examples: + `[{x:0,y:0},{x:9,y:786}]`\* + `[[5,4],[6,8]]` + `"54,37,68,9760"` + `new Point(0,0), new Point(5,6)` + `["34,56","23,98657"]` + etc. * Output should be a double or equivalent with 5 significant digits. * **No eval!** * This is code-golf, so shortest allowed and functioning code wins! \*You would have to construct the objects a different way, as colons are single symbols. Good luck without being able to use the `=` operator! :P **Edit:** Imaginary 5 kudo points for not using a built-in. [Answer] # [Python 2](https://docs.python.org/2/), 35 bytes ``` print abs(input().__sub__(input())) ``` Example input for points (5,4) and (6,8): ``` 5+4j 6+8j 4.12310562562 ``` or: ``` complex(5,4) complex(6,8) 4.12310562562 ``` [Try it online!](https://tio.run/nexus/python2#@19QlJlXopCYVKyRmVdQWqKhqRcfX1yaFB8P42tq/v9vqm2SxWWmbZH1NS9fNzkxOSMVAA "Python 2 – TIO Nexus") [Answer] # Mathematica, 17 bytes ``` EuclideanDistance ``` A function invoked like `EuclideanDistance[{5,4}, {6,8}]`. Works in other dimensions as well. Mathematica and its long command names thank you for your support. [Answer] ## JavaScript, 10 bytes ``` Math.hypot ``` Returns a function that does the job. For 13 bytes, I can do it using only paired puncutation: ``` Math['hypot'] ``` [Answer] # R, 33 bytes ``` cd<-function(a,b)dist(rbind(a,b)) ``` [Try it online!](https://tio.run/nexus/r#HccxDoAgDAXQ67RJGVBHb2Ic4Bdjl2IQj@6MiW97A7qG43F0q05JMqvdnVo21788rmbeCUqgKBMLaJaFeYs7j9drQMJZPg) # R, 26 bytes ``` dist(rbind(scan(),scan())) ``` [Answer] # Octave, 20 bytes ``` abs(diff(input(''))) ``` Takes input on the form: `[5+4j, 6+8j]`. Anonymous functions can't be used since `@` is a single character. It takes a vector with two complex numbers as input, calculated the difference, and takes the absolute value. ]
[Question] [ **This question already has answers here**: [Interpret brainfuck](/questions/84/interpret-brainfuck) (78 answers) Closed 1 year ago. There [already is](https://codegolf.stackexchange.com/q/84/107299) a Brainfuck interpreter question, but it is from 2011 and not up to date with current site standards and vague in places. I have [proposed](https://chat.stackexchange.com/rooms/240/conversation/repost-interpret-bf) reposting this in chat, and it was well-received. Here goes. ## Objective Given the Brainfuck code and the program's input as input, run the Brainfuck code. As there are various variants of Brainfuck, here is the one I will use for the challenge: * There are least 128 cells. * Cell values are positive integers, having a maximum value of at least 128. * Going into negative cells in undefined. * Going into negative numbers is undefined. * Going above the maximum cell value is undefined. * Going above the maximum cell is undefined. * EOF is 0 You may assume that the code will conform to the above constraints and that brackets will be balanced. You may also assume that all input code will be nothing but `<>,.+-[]`. # Testcases ``` "+[+[<<<+>>>>]+<-<-<<<+<++]<<.<++.<++..+++.<<++.<---.>>.>.+++.------.>-.>>--." -> "Hello, World!" ",[.,]", "abc" -> "abc" ``` # Scoring As this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest answer in bytes wins. [Answer] # simply, 425 bytes This big boy defines an anonymous function which takes an input string and returns the output of the Brainfuck program. This anonymous function has to be stored into a variable, and receives the code as the 1st argument (`$C`), and the input as the 2nd argument (`$T`). This is a language being interpreted by JavaScript, which then interprets Brainfuck to generate JavaScript code. 🤯 ``` fn($C$I){if run&empty($I)$I=''$T=&json_decode(<<<J {".":"O+=String.fromCharCode(T[P]);",",":"T[P]=I[0]?I.shift().charCodeAt(0):0;","<":"P=P?P-1:255;",">":"P=(P+1)%256;","-":"T[P]=T[P]?T[P]-1:255;","+":"T[P]=T[P]?(T[P]+1)%256:1;","[":"while(T[P]){","]":"}"} J)$N=''each$X in$C if$T[$X]$N=&str_concat($N$T[$X])$F=run$argv->map->constructor('X'run&str_concat("var I=Array.from(X+''),O='',T=[],P=0;"$N"return O"))send run$F($I);} ``` It is an absolute mess! ## Ungolfed - to plain English ``` Set $fn to the anonymous function($code, $input) { If call &empty($input) then { Set $input to "". } Set $tokens to the result of calling &json_decode(<<<JSON { ".": "output += String.fromCharCode(tape[pointer]);", ",": "tape[pointer] = input.length ? input.shift().charCodeAt(0) : 0;", "<": "pointer = pointer ? pointer - 1 : 255;", ">": "pointer = (pointer + 1) % 256;", "-": "tape[pointer] = tape[pointer] ? tape[pointer] - 1 : 255;", "+": "tape[pointer] = tape[pointer] ? (tape[pointer] + 1) % 256 : 1;", "[": "while(tape[pointer]){", "]": "}" } JSON); Set $inner_code to "". Foreach $char in $code { If $tokens[$char] then { Set $inner_code to the result of calling &str_concat($inner_code, $tokens[$char], "\n"). } } Set $js_code to the result of calling &str_concat( "input = Array.from(input + '');\nvar output = '';\nvar tape = [];\nvar pointer = 0;\n", $inner_code, "return output;" ). Set $fn to the result of calling $argv["map"]["constructor"]("input", $js_code). Return the result of calling $fn($input). } ``` Now it is a lot more readable! --- ## How does it work? This will simply read the input code, character by character, and replace the valid tokens into JavaScript code. Using the `array["filter"]["constructor"](code)` (but using `"map"` to save bytes) trick in [JSFuck](http://www.jsfuck.com/), I can receive a JavaScript function which I can execute normally! This is **FAAAAAAAAAAAAR** from the intended way of doing things, but ... it works! --- ## Example output This is the *JavaScript* code generated for the test cases. Hello world: `+[+[<<<+>>>>]+<-<-<<<+<++]<<.<++.<++..+++.<<++.<---.>>.>.+++.------.>-.>>--.` ``` var fn = function anonymous(X ) { var I=Array.from(X+''),O='',T=[],P=0;T[P]=T[P]?(T[P]+1)%256:1;while(T[P]){T[P]=T[P]?(T[P]+1)%256:1;while(T[P]){P=P?P-1:255;P=P?P-1:255;P=P?P-1:255;T[P]=T[P]?(T[P]+1)%256:1;P=(P+1)%256;P=(P+1)%256;P=(P+1)%256;P=(P+1)%256;}T[P]=T[P]?(T[P]+1)%256:1;P=P?P-1:255;T[P]=T[P]?T[P]-1:255;P=P?P-1:255;T[P]=T[P]?T[P]-1:255;P=P?P-1:255;P=P?P-1:255;P=P?P-1:255;T[P]=T[P]?(T[P]+1)%256:1;P=P?P-1:255;T[P]=T[P]?(T[P]+1)%256:1;T[P]=T[P]?(T[P]+1)%256:1;}P=P?P-1:255;P=P?P-1:255;O+=String.fromCharCode(T[P]);P=P?P-1:255;T[P]=T[P]?(T[P]+1)%256:1;T[P]=T[P]?(T[P]+1)%256:1;O+=String.fromCharCode(T[P]);P=P?P-1:255;T[P]=T[P]?(T[P]+1)%256:1;T[P]=T[P]?(T[P]+1)%256:1;O+=String.fromCharCode(T[P]);O+=String.fromCharCode(T[P]);T[P]=T[P]?(T[P]+1)%256:1;T[P]=T[P]?(T[P]+1)%256:1;T[P]=T[P]?(T[P]+1)%256:1;O+=String.fromCharCode(T[P]);P=P?P-1:255;P=P?P-1:255;T[P]=T[P]?(T[P]+1)%256:1;T[P]=T[P]?(T[P]+1)%256:1;O+=String.fromCharCode(T[P]);P=P?P-1:255;T[P]=T[P]?T[P]-1:255;T[P]=T[P]?T[P]-1:255;T[P]=T[P]?T[P]-1:255;O+=String.fromCharCode(T[P]);P=(P+1)%256;P=(P+1)%256;O+=String.fromCharCode(T[P]);P=(P+1)%256;O+=String.fromCharCode(T[P]);T[P]=T[P]?(T[P]+1)%256:1;T[P]=T[P]?(T[P]+1)%256:1;T[P]=T[P]?(T[P]+1)%256:1;O+=String.fromCharCode(T[P]);T[P]=T[P]?T[P]-1:255;T[P]=T[P]?T[P]-1:255;T[P]=T[P]?T[P]-1:255;T[P]=T[P]?T[P]-1:255;T[P]=T[P]?T[P]-1:255;T[P]=T[P]?T[P]-1:255;O+=String.fromCharCode(T[P]);P=(P+1)%256;T[P]=T[P]?T[P]-1:255;O+=String.fromCharCode(T[P]);P=(P+1)%256;P=(P+1)%256;T[P]=T[P]?T[P]-1:255;T[P]=T[P]?T[P]-1:255;O+=String.fromCharCode(T[P]);return O }; console.log(fn()); ``` Cat program: `,[.,]` ``` var fn = function anonymous(X ) { var I=Array.from(X+''),O='',T=[],P=0;T[P]=I[0]?I.shift().charCodeAt(0):0;while(T[P]){O+=String.fromCharCode(T[P]);T[P]=I[0]?I.shift().charCodeAt(0):0;}return O }; console.log(fn(prompt("What does the cat say?", ""))); ``` [Answer] # [Factor](https://factorcode.org/) + `brainfuck`, 13 bytes ``` run-brainfuck ``` [Try it online!](https://tio.run/##S0tMLskv@h8a7GqlkFSUmJmXVpqczcWlpB2tHW1jY6NtBwSx2ja6QAjk2Whrx9rY6AEpMNbTBjHAPF1dXT07Oz07sJAuGOjZgYSAtBLX/6LSPF248f//AwA "Factor – Try It Online") [Try it online!](https://tio.run/##S0tMLskv@h8a7GqlkFSUmJmXVpqczcWlpBOtpxOrxPW/qDRPFy7@/79SYlKyEgA "Factor – Try It Online") (with input) [Answer] # [Rust](https://www.rust-lang.org) + `-C overflow-checks=off`, 370 bytes ``` |p:&[u8]|{let(mut o,mut c,mut t,mut k)=(0,0,[0;128],0);loop{match p[o]{62=>c+=1,60=>c-=1,43=>t[c]+=1,45=>t[c]-=1,46=>print!("{}",t[c]as char),44=>t[c]=stdin().bytes().next().unwrap_or(Ok(0)).unwrap(),91=>if t[c]<1{k=1;while k>0{o+=1;if p[o]==91{k+=1};if p[o]==93{k-=1}}},93=>if t[c]>0{k=1;while k>0{o-=1;if p[o]==91{k-=1}if p[o]==93{k+=1}}},_=>()}o+=1}};use std::io::*; ``` [Attempt This Online! (Hello World)](https://ato.pxeger.com/run?1=XVFBjtMwFBXbnsJkgWxqW8m0VG0Se8MB2LGJoirjcWiUNI4ch4IyOQkbJOAALFhyEDjNfCedEcyX_P_z-3nP386X73bo3e8sYG8DigLzUduyMRemTlrVvTBlGeQ_yxadi6rFBI2NdqgUPwZXsv3fF_a-i19lwz6_9w18Hhwy1Gc1Zzfnmggc0pBmYRLd7HMakqQxphvPhVMn1GUmH3c3Qqq1iOguBMAAbDdCukzlnty-WfDM74TsbNW6lzgYp4B6vuiROhWW0O12-VD07s6Py28_O91DbfUnB2VoL7bojsbidzUOySOBCT1EQlYl8uI0GmsRJZdT1WhUy3A0MEMCTT-pEAdoAzH9w2zGGkabpokeNk82IHxmw57beNF_LuvF5SgkJpOZd8nQawTXiePKxPHrZLU8_Z9f_kd01nywxRkJFKyvkcnH7MGyUgiWS0CSSbnO0txvJZeMMX7VcQ84kCnj6YzZHNcCAJQc_HiQrFYlvh799MLKNI1WLo7T91pBHvYSLsGL_tg3ldKYEJBNy_BfvxW3aoEP) [Attempt This Online (Cat)](https://ato.pxeger.com/run?1=XVFLTsMwFBTbnsJkgWzqVEkbqjSps-EAsGITRVVqHBLl48hxKCjNSdggAQfgABwEToOdQAXdzHue5xnNs59eRdvIj9AwLw0MDH7PRFLwnUlTRvOG8CQxovekAmWcVRCBrmASJOStlYnpfp2Ife2dha0b7fUAlq0EHGukA8oBc0SghS0cWr49dyNsIb_gvO7KWNIU1CGPuuWcBHRKbLy0VGOqxlmQQIY00qRzMfYDvyRBLbJKnkKj6w2s-bgBNI0Fwo4zXiSNvNVxZ9tHyRpVK_YgVWmrnYjrDRfwKocW-iUgwiubBFkCtHhtdzmx_V2aFQzkgdVxlcFXQ52UkJUaK6L_wyy6XEXr-x6vFgcbJTyyMY9ttOify3R02ZAAop4PJ79tGFDreF7GPe_cn4xP_3mtP6IW_E7EJSDAwOEMR4Y_mSTwhz0sT3lRMCo9b33DqMLWDZT_LG42TZFRBhFSsn70fX6Jt3RsvwE) Will crash when it reaches the end of the program. ]
[Question] [ Well, you know it's Snow White, and the evil Queen is at it again. Will Snow White be saved? Will she fall asleep once again? Will the Prince find her? # Challenge: Given an arbitrary number (>= 2) of possibly duplicated hexadecimal color values (ranging from #000000 to #FFFFFF) and paired strings, calculate the following: * If #FF0800 (Candy apple red) appears in the input, return "Return to Sleeping Death" * If #000000 appears in the input, return "Saved by Grumpy" * If #A98AC7 or #111111 appears in the input, return "Saved by Happy" * If #21E88E or #222222 appears in the input, return "Saved by Sleepy" * If #32DCD5 or #333333 appears in the input, return "Saved by Bashful" * If #43D11C or #444444 appears in the input, return "Saved by Sneezy" * If #54C563 or #555555 appears in the input, return "Saved by Dopey" * If #65B9AA or #666666 appears in the input, return "Saved by Doc" * If #76ADF1 or #777777 appears in the input, return "Saved by the Seven Dwarfs" * If #FFFAFA (Snow) appears in the input, return "Saved by Love's first kiss" * If an F variant appears in the input, return "Press F to pay respects to Snow White" + An F variant is any number that contains at least one `F` in its hexadecimal form, and is otherwise all `0`s (e.g. #0FF0F0, #FFFFFF, #00000F, #F00F00) * If **multiple** of the preceding occur, return the "fairest" answer. The "fairest" answer is calculated as follows: + For all N occurrences of special color values, choose the (N-1)/2-th (truncating division) occurrence. The associated special output is the "fairest" answer. *"Appears in the input" here refers to only the hexadecimal color values, and not to the paired strings.* * If none of the preceding occur, return the "fairest" answer. The "fairest" answer is calculated as follows: + Take the hexadecimal color value at the end of input values, write it down, and exclude that single color-string pair from consideration as the "fairest" answer + Show its binary form to the mirror, computing a reflection of only the last 24 (#FFFFFF is the mask) bits. + Choose the hexadecimal color with least Hamming distance from the reflection. If there are multiple (N) such colors, choose the middle ((N-1)/2-th, truncating division) instance of the color. The "fairest" answer is the associated string for the color. # Inputs: A sequence of hexadecimal color values and String values separated by a space. The input may also be read as two separate sequences of hexadecimal color values and String values, or a single sequence of 2-tuples (either `(hexValue, stringValue)` or `(stringValue, hexValue)` is permissible, as long as the ordering is consistent across all 2-tuples). Input order matters - for each index, the corresponding element in the supply of color values is "associated" with the corresponding element in the supply of String values, and duplicates can affect the "fairest" answer. The effect is something like `Function(List(HexColorValue),List(AssociatedStrings)) -> "fairest" answer`. Hexadecimal color values may be represented as either (your choice of) a String "#"+6 digits, or 6 digits alone, as long as the representation is consistent across all color values. Here's an example input: ``` 76ADF1 Return to Sleeping Death 2FE84E Return whence ye came! ``` Here's another example input: ``` 2FE84E Return to Sender 4FFAFC Return of the Obra Dinn 2FE84E Return to the house immediately, young lady! 2FE84E Return to Sleeping Death 2FE84E Return of the Jedi ``` Here's the third example input: ``` 2FE84E Return to Sender 4FFAFC Return of the Obra Dinn 2FE84E Return to the house immediately, young lady! 2FE84E Return to Sleeping Death 7217F8 Return of the King ``` Here's the final sample input: ``` F4A52F Eating hearts and livers F4A52F Eating apples F4A52F Eating porridge F4A52F Eating candy houses F4A52F A Modest Proposal ``` # Outputs: The "fairest" answer as computed by the specified logic. For example, on the first sample input, the "fairest" answer would be **`Saved by the Seven Dwarfs`**, due to the special hex color `76ADF1` appearing within the input. In the second sample, there are no special inputs. First, we take "2FE84E Return of the Jedi", which has value #2FE84E. In binary, this is: ``` 001011111110100001001110 ``` We take the reflection from the mirror, getting: ``` 011100100001011111110100 ``` We compare it against `2FE84E (001011111110100001001110)` and `4FFAFC (010011111111101011111100)`, which have Hamming distances of 18 and 12 from the reflection, respectively. Since #4FFAFC has the uniquely lowest Hamming distance from the reflection, the "fairest" answer is **`Return of the Obra Dinn`**. In the third sample input, there are no special inputs. First, we take "7217F8 Return of the King", which has value #7217F8. In binary, this is: ``` 011100100001011111111000 ``` We take the reflection from the mirror, getting: ``` 000111111110100001001110 ``` We compare it against `2FE84E (001011111110100001001110)` and `4FFAFC (010011111111101011111100)`, which have Hamming distances of 2 and 8 from the reflection, respectively. All 3 instances of hexadecimal color value #2FE84E have minimum Hamming distance from the reflection, so we take the `(3-1)/2`=`1th` instance (0-indexed) of #2FE84E. Therefore, the "fairest" answer is **`Return to the house immediately, young lady!`**. In the last sample input, there are no special inputs. First, we take "F4A52F A Modest Proposal", which has value #F4A52F. In binary, this is: ``` 1111010011001100101111 ``` We take the reflection from the mirror, getting: ``` 1111010011001100101111 ``` We compare it against `F4A52F (1111010011001100101111)`, which has Hamming distance 0 from the reflection. All instances of hexadecimal color value #F4A52F have minimum Hamming distance from the reflection. There are *FOUR* instances of #F4A52F, because we always exclude the last hexadecimal color instance from evaluation. Therefore, we take the `(4-1)/2=1th` instance (0-indexed) of #F4A52F, and the "fairest" answer is **`Eating apples`**. *If* you don't exclude the last value from consideration, you actually get the `(5-1)/2=2th` instance of #F4A52F (`Eating porridge`), which is wrong. # Rules: * No standard loopholes * Input/output taken via standard input/output methods. * The output must be exactly equal to the "fairest" answer # Scoring: This is code golf, so shortest program wins. *Here's the [sandbox link](https://codegolf.meta.stackexchange.com/questions/2140/sandbox-for-proposed-challenges/18140#18140)* [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 557 bytes ``` a=>b=>{var k=a.Select(l=>l==0xFF0800?"Return to Sleeping Death":$"{l:X}".All(x=>x>69|x<49)?"Press F to pay respects to Snow White":"Saved by "+"Grumpy,Happy,Sleepy,Bashful,Sneezy,Dopey,Doc,the Seven Dwarfs,Love's first kiss, ".Split(',')[l==0xFFFAFA?8:l==11111111?0:l%1118481<1?l/1118481:l%1111111<1?l/1111111:9]);int j=a.Last(),i=0,e=24;for(;e-->0;i|=j%2,j>>=1)i*=2;var m=k.Where(o=>o[9]!=9);var t=a.SkipLast(1).Select(o=>Convert.ToString(o^i,2).Sum(y=>y-48)).ToList();return(m.Any()?m:m=b.SkipLast(1).Where((x,y)=>t.Min()==t[y])).ToList()[~-m.Count()/2];} ``` [Try it online!](https://tio.run/##zVRtb9owEP68/YprtKlJZ2gSsZaXOoiVZm/tVo1JnYTYZOAoLokd2YaStd1fZw5Q0XadNG1f5g/J@Z7z89z5bA90aaD5Ip6KwcHbY67NARcmInDHoY3i4tz6ZP8CByaKYAQUFoxGfRpdzZiCCWXlDiYWdBMaJZT68zj2q77fdD6hmSoBRkInQcwsEbSRmbFTf@ZcJfUvN065lSTunEbzaK92PT@o1Lymc6pQa4iLZRnLwc4yS66XNEJewtmYG3TqTofNcAj9HJwXzms1TbOcvGGZ/S7FcvKK6fFompCOQPyek7bMsPgOiBkjdHCGAtqXTI00OZYz3NYw4kobmHCtyROn3MkSbtxtsu1110XFrbjVrNbtLFiPpl9Pntt/tVINDoJmsru2V95i3HqLUa/1vIbdYbiwW3bMtHE9wqlPkIaVxkgqt4GlUuQ3@DW9eB6Siyiigcd3aNgo9jmlk/LZGBW6kkayW@tt0Zq3REzRgQnPlpSBd9sNG3YoxQyVKX@WnWUfXfmVk9BGTFM3p1FeqlQ9z6JFq12voZb9ctNyS@Su10zrKe3fY17pu3OSezQy5RMuXI9S0817d2i6P0pp@VBOhbV3w17jZtF4emrVjTtyBV52e1f@fH@v1Y4DAv48jI@qlaMbbw39/syQW@hyjGKAkCMMWIpbzo3n/SqwooVCoVI07hA2Yo9ZjyaAYohqIyxHUBydj33FoM2F2CA2uEDGcqoReJrikDODSU4gt/twDgkb5lv3wh8WBw9E3lmKf61sPwz24@r/Vtl7iz1eWVxpvQzjZTl/am6KO2KmEB0jU/atYGIICbdnX9vc1pB9GxK8M8@kUnx4jhvPwC7LV7XqIvEWnMgh2jfhVMlMapY8lndYCWB3x94Y@DBN@6jgTKqJ3tm1WfbXF/9bcN/wg79JvNBe/AQ "C# (Visual C# Interactive Compiler) – Try It Online") [Answer] # [JavaScript (Node.js)](https://nodejs.org), 433 bytes Takes input as a list of tuples `[color, string]`. ``` a=>(h=a=>a[a.length-1>>1])(a.flatMap(([c])=>(s=c-0xFFFAFA?"Grumpy/Happy/Sleepy/Bashful/Sneezy/Dopey/Doc/the Seven Dwarfs".split`/`[(d=c-11111111?c/1118481:1)%1?c/1111111:d]:"Love's first kiss")?"Saved by "+s:c-0xFF0800?(g=n=>n?n%16%15||g(n>>4):0)(C=c)?[]:"Press F to pay respects to Snow White":"Return to Sleeping Death"))||h(a.map(m=([c,s])=>[(d=g(c,i=24))>m?d:m=d,s],a.pop(g=n=>i--&&(n^C>>i)%2+g(n/2))).flatMap(([d,s])=>d-m?[]:s)) ``` [Try it online!](https://tio.run/##3ZTfb5tADMff@1d4SO04lSQQpW2WCaK0Cau2VauWhz5EmXoFE9iOO3RH0jLlf89MEq0/lnbd6yxhdPDhe7Y5@ztfcBPprCgbUsW4SvwV9wM79cnzCW8KlLMybXhB4E2ZzZuJ4OUFL2x7Ek0ZgcaPGu5dGIaDcNC3Puh5XlStc16QHwtEup1ykyZz0RpLxJ9Va6gKrH3UKlOEMS5QwvCW68RYTVOIrLxuXU/smGS9rfWjFvlup@v1PLa/XdbWi6c967Na4FsDSaZNCT8yYyzWt8Z8gTHcVGAdmt4mQLfrun175ks/kH257x3ve0fL5cyWQdBhPZfZZ37E@hNSvNRoDIRQKih4BbQqMCpNvR5LdQtXaVai1bO@YjnXcv24zjSTMxgiL1OLseUypVrlVKfcp0o5pq5VndXMjpzMb3cYC/J@3Mv9mN45vFmoYhNb1mgcHNjy21kQZGy/fUgBttqMsQeFjzdycSOvwzWMrd5P9gDqizy4dyfHg2HoOfB8hDB1ftPtcNTtjO7p2xRlhFAhRDzHN8QSOnUe6D/9otZHGaN@pNupz8TZPaUSqP/4lxvNYZhJ@WIQJFnDqZobhCzPMc54iaJyoFJzSkPwuHrzN4V/SHob3Efa5/9M@KTtnYTdP4L7RPSOhMPO4KgdEj3iZa2XItfUAVzGILIFavNI@ylN3S/wZaRQWmfxDF@EItqv2pTkGbUBXNDQosa/1KpQhotduaxbn@BzFEI5cKW0iHcd69B1iX0F2F7baxTXY/EVYHdtO8D7nN@tjZBQKTjlequyN91rJkqPeEQTB/wAIiWNEtgUamYnNqfRsfoF "JavaScript (Node.js) – Try It Online") ]
[Question] [ The input is an array (or space-separated string, as you wish), zero-indexed, consisting of one strictly increasing array and one strictly decreasing array (in this order, not other vice versa), each having a length of 2 at least. Example is: ``` -10 -2 4 18 38 46 28 19 10 ``` The goal is to write the fastest algorithm to find the joint of two sorted arrays. In other words, the output is the index of the greatest element. In the provided case the output should be `5`. The input is guaranteed not to contain repeating numbers. It's obvious that this can be solved with `O(n)` with ease, so please provide more interesting faster answers :) --- Other test cases (first line is input, second is output): ``` 0 1 4 3 2 ``` --- ``` 1 10 9 8 7 6 5 4 3 1 1 ``` --- ``` 1 3 4 6 7 8 0 -10 -20 5 ``` --- ``` 1 3 5 3 1 2 ``` --- You could also accept the length of the array as additional input, if needed [Answer] # [C (gcc)](https://gcc.gnu.org/) ``` int find_joint(int *array, int length) { int left_bound = 0, right_bound = length - 1, joint = length / 2; while (array[joint-1] > array[joint] || array[joint] < array[joint+1]) { if (array[joint-1] < array[joint]) left_bound = joint + 2; else right_bound = joint - 2; joint = left_bound + (right_bound - left_bound) / 2; } return joint; } ``` [Try it online!](https://tio.run/##jVTBjpswED3DV0xTRYIAKexxSfIFq9566qKIgEmcJWZlnFZtNt@eztiE2JtVtQcEMzy/eX4zdpVsq@rylYuqPdYMFr2qeTffrXwn1fKNm1P8wDBz4UJBw0W93nf4GVA4K6Us/8RA3y0TW7UL4eR7JmzUetMdRQ1LSGOQfLu7JQwYEshi0HS33Dd4yH3f@73jLYNAF/ipIUlWwAqsRAFvb268sMMoK7Qajzd3PA6wCBHkOYKNpoikeB5re0YIdwsGkhi13m0TI0sEgb0isf6FZpfeGZdKpo5SGLrcP2ubZ1smmCwVC0YrjTvGakN7Z7i2b2nDUYONzQ3SdA2Rh7JtuyoYsDPo@V/WNcP/ENHGpLRArCxFHYQwhYc0Talx@EJE00nQIl8Qk@X4WtgCMBFFZK9heiGm4ZPaEN1okQ/DjMx0OF0yzf4J4sQlTgzxYLXGodW@/6vjNbxKrLXWSV3V0BR3U61xTTA5TcL3G08/lHZdMK1jmMRXeQWtfj2qPpiciQllEM2h5CLQdXotnU5d8P3H01MYknSCKNartTgeNkyS2Wn6rgV7o2SPSiwoJlCOOQjuMNldJTbyfzyp/4HkA9U4R@O0OpPqTGn8yfnUxNfDZN02w0UzsOXDqTbALy4nNtts17M7e08w9me5gmlNFladlKxSITw@wmk@nwN1zjyA4flZTIbrKgb3QnFiN6JriMqdzXG/Fn0WSEpt6mmbvN@xeq75rdbRdFz@AQ "C (gcc) – Try It Online") [Answer] # JavaScript (ES6), O(log n) Now assuming that accessing `Array.length` is always **O(1)** (as suggested by @12Me21 and @ETHproductions) and therefore not requiring the length to be passed as input anymore. Returns a string describing the result (index + number of iterations). ``` f = (a, n = 1, min = 0, max = a.length - 1) => { let res = x => `Found index ${x} in ${n} iteration(s)`, mid; return ( // only one slot left? max == min ? res(max) : // only two slots left? max == min + 1 ? res(a[max] > a[min] ? max : min) : // is the middle slot greater than its two neighbors? a[mid = min + max >> 1] > a[mid + 1] && a[mid] > a[mid - 1] ? res(mid) : // recursive call required a[mid] > a[mid + 1] ? f(a, n + 1, min, mid - 1) : f(a, n + 1, mid + 1, max) ); } ``` [Try it online!](https://tio.run/##dVJdb8IgFH3vr7gPi2kjVfFrm8b6tj9hTGQFlQVhA@pcjL/dXWg3nXFNgMu599xzgL6xPXOlle8@14aL83kNM0gZAY0rJbCTIehhwA4YsI4SeuO3kAPNYFbAMQFQwoMVDtOHAK1eTKU5SM3FAR6OhxOGuGpcvbDMS6NTl60IMsO3k3yaYGyFr6yGNMLdLhitvnAS4JTxqLH285iKRmbR2DzIpghkMEn@8PyniTx3n9gG2pDZAuElFICB1EtEQ9kkVF03lQ78VgSvXDWONlYwPA/iTOPJXNTUQm62r8a6WjI05fCjGToXBdAfOR58LKHVqncXOA9wczjJr31YUVbWyb2AkimF249KWsEvYje9580lr@snbTdPGqYok8X85G4VbwK8Xsxn0@R0Lo12RomOMpt0nS5yij9G3icwJECfCAxwDMcE@rjSZxy9ZZYlNySk0MgY3EnSQCKAXGzxSACbjepiTNyvH8T8OJYjKTiqbfX@rR/99jt/Aw "JavaScript (Node.js) – Try It Online") [Answer] ## JavaScript (ES7) ``` function find_join(a, l) { p = 1.25 ** .5 - .5; n = 1; i = 0; j = l * p + .5 | 0; k = j * p + .5 | 0; x = a[j]; y = a[k]; while (l > 2) { n++; if (x > y) { l = j; j = k; k = j * p + .5 | 0; x = y; y = a[i + k]; } else { i += k; l -= k; k = j - k; j = l * p + .5 | 0; y = x; x = a[i + j]; } } return [n, a.indexOf(Math.max(...a.slice(i, i + l)), i)]; } ``` I was too lazy to write out the full `l < 3` case. This algorithm optimises the number of accesses of the array `a`. In practice this is not very useful, since the binary search always tests consecutive elements, which is not likely to be much slower than testing a single element. ]
[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/84675/edit). Closed 5 years ago. [Improve this question](/posts/84675/edit) # Are you tired of languages with built in quining techniques? Your challenge, should you choose to accept it, is to add a built-in quine feature to the language of your choice. ### Task Given some programming language *X*, you should define 1. A **language** *X*′ that is a subset of *X*. 2. A **quine command string** *Q*. (This is a string of your choice; it need not literally be “`Q`”.) Now you have a new language *Y*, consisting of programs that are in *X*′ except that they may also contain copies of *Q* as if *Q* were a new built-in statement or function. Your job is to implement this language *Y*, by writing 3. A **compiler**, written in *X*′, producing an output program *B* in *X* for each input program *A* in *Y*. When *B* is run, it should behave like *A* would if all its copies of *Q* had been replaced with a statement in *X* that prints the source code of *B*. You’ve therefore created a language *Y* that contains a quining builtin *Q*. ### Rules * Your chosen language subset *X′* must still satisfy the definition of a programming language. * The output programs *B* of your compiler must be [proper quines](http://meta.codegolf.stackexchange.com/questions/4877/what-counts-as-a-proper-quine). You may not use quining builtins that may already be in *X*. * This is code golf, so the shortest code in bytes (defined as your language's default native encoding) wins. [Answer] # CJam, 7 bytes ``` qp":Q~" ``` The quine command string is `Qp":Q~"o`. The language subset is programs that do not use the variable `Q` except as part of the quine command string. ### Demo Input program: ``` "I am a quine and my source is: "oQp":Q~"o" Have a nice day."o ``` [Try it online](http://cjam.aditsu.net/#code=qp%22%3AQ~%22&input=%22I%20am%20a%20quine%20and%20my%20source%20is%3A%0A%22oQp%22%3AQ~%22o%22%0AHave%20a%20nice%20day.%22o) Output program: ``` "\"I am a quine and my source is: \"oQp\":Q~\"o\" Have a nice day.\"o" :Q~ ``` [Try it online](http://cjam.aditsu.net/#code=%22%5C%22I%20am%20a%20quine%20and%20my%20source%20is%3A%0A%5C%22oQp%5C%22%3AQ~%5C%22o%5C%22%0AHave%20a%20nice%20day.%5C%22o%22%0A%3AQ~) Output of output program: ``` I am a quine and my source is: "\"I am a quine and my source is: \"oQp\":Q~\"o\" Have a nice day.\"o" :Q~ Have a nice day. ``` [Answer] # Haskell, 35 bytes ``` main=interact(\s->s++"q="++show s) ``` Includes a trailing newline. The quine command string is `(putStr$q++"q="++show q)`. The language subset is programs with a trailing newline that do not use the variable `q` except as part of the quine command string. ### Demo Input program: ``` main = do putStrLn "I am a quine and my source is:" (putStr$q++"q="++show q) putStrLn "\nHave a nice day." ``` Output program: ``` main = do putStrLn "I am a quine and my source is:" (putStr$q++"q="++show q) putStrLn "\nHave a nice day." q="main = do\n putStrLn \"I am a quine and my source is:\"\n (putStr$q++\"q=\"++show q)\n putStrLn \"\\nHave a nice day.\"\n" ``` Output of output program: ``` I am a quine and my source is: main = do putStrLn "I am a quine and my source is:" (putStr$q++"q="++show q) putStrLn "\nHave a nice day." q="main = do\n putStrLn \"I am a quine and my source is:\"\n (putStr$q++\"q=\"++show q)\n putStrLn \"\\nHave a nice day.\"\n" Have a nice day. ``` [Answer] # Java "only" 498 Bytes The following java program takes in input as command line arguments. ``` class Q{ public static void main(String[]a){ System.out.println(a[0]);System.out.print("static char[]s={");a[2]+="}static void q(){System.out.print(\""+a[0]+"\\n\");System.out.print(\"static char[]s={\");for(char c:s)System.out.print((int) c+\",\");System.out.print(\"\\b};\\n"+a[1]+"\\n\");for(char c:s)System.out.print(c);System.out.print(\"\\n}\");}";for(char c:a[2].toCharArray())System.out.print((int) c+",");System.out.println("\b};");System.out.println(a[1]);System.out.print(a[2]+"\n}"); }} ``` In this case my language "X" is (a subset of) Java, and my Quine Command string "Q" is q();for each instance of q(); the output program will print its source. Input is restricted to only four lines, and any more or less results in undefined behavior. My golfed program technically follows these same restrictions. So my subset is programs that fit on four lines as shown and do not have a function called q or use any variable named s. Sample Input ``` class sampleInput{//class def on this line public static void main(String[]argument){//method header here and optional code although avoid putting code here System.out.println("Hello World Of Quines");q();System.out.println("\n------------");q();/*Avoid comments on this line unless you use this format YOU MUST! put two braces on the next line*/ }} ``` Sample Output ``` class sampleInput{//class def on this line static char[]s={83,121,115,116,101,109,46,111,117,116,46,112,114,105,110,116,108,110,40,34,72,101,108,108,111,32,87,111,114,108,100,32,79,102,32,81,117,105,110,101,115,34,41,59,113,40,41,59,83,121,115,116,101,109,46,111,117,116,46,112,114,105,110,116,108,110,40,34,92,110,45,45,45,45,45,45,45,45,45,45,45,45,34,41,59,113,40,41,59,47,42,65,118,111,105,100,32,99,111,109,109,101,110,116,115,32,111,110,32,116,104,105,115,32,108,105,110,101,32,117,110,108,101,115,115,32,121,111,117,32,117,115,101,32,116,104,105,115,32,102,111,114,109,97,116,32,112,117,116,32,116,119,111,32,98,114,97,99,101,115,32,111,110,32,116,104,101,32,110,101,120,116,32,108,105,110,101,42,47,125,115,116,97,116,105,99,32,118,111,105,100,32,113,40,41,123,83,121,115,116,101,109,46,111,117,116,46,112,114,105,110,116,40,34,99,108,97,115,115,32,115,97,109,112,108,101,73,110,112,117,116,123,47,47,99,108,97,115,115,32,100,101,102,32,111,110,32,116,104,105,115,32,108,105,110,101,92,110,34,41,59,83,121,115,116,101,109,46,111,117,116,46,112,114,105,110,116,40,34,115,116,97,116,105,99,32,99,104,97,114,91,93,115,61,123,34,41,59,102,111,114,40,99,104,97,114,32,99,58,115,41,83,121,115,116,101,109,46,111,117,116,46,112,114,105,110,116,40,40,105,110,116,41,32,99,43,34,44,34,41,59,83,121,115,116,101,109,46,111,117,116,46,112,114,105,110,116,40,34,92,98,125,59,92,110,112,117,98,108,105,99,32,115,116,97,116,105,99,32,118,111,105,100,32,109,97,105,110,40,83,116,114,105,110,103,91,93,97,114,103,117,109,101,110,116,41,123,47,47,109,101,116,104,111,100,32,104,101,97,100,101,114,32,104,101,114,101,32,97,110,100,32,111,112,116,105,111,110,97,108,32,99,111,100,101,32,97,108,116,104,111,117,103,104,32,97,118,111,105,100,32,112,117,116,116,105,110,103,32,99,111,100,101,32,104,101,114,101,92,110,34,41,59,102,111,114,40,99,104,97,114,32,99,58,115,41,83,121,115,116,101,109,46,111,117,116,46,112,114,105,110,116,40,99,41,59,83,121,115,116,101,109,46,111,117,116,46,112,114,105,110,116,40,34,92,110,125,34,41,59,125}; public static void main(String[]argument){//method header here and optional code although avoid putting code here System.out.println("Hello World Of Quines");q();System.out.println("\n------------");q();/*Avoid comments on this line unless you use this format put two braces on the next line*/}static void q(){System.out.print("class sampleInput{//class def on this line\n");System.out.print("static char[]s={");for(char c:s)System.out.print((int) c+",");System.out.print("\b};\npublic static void main(String[]argument){//method header here and optional code although avoid putting code here\n");for(char c:s)System.out.print(c);System.out.print("\n}");} } ``` ]
[Question] [ **This question already has answers here**: [Is this number a prime?](/questions/57617/is-this-number-a-prime) (367 answers) Closed 8 years ago. Write a program that tests if a number `n` is prime by checking that none of the integers between `2` and `n-1` (inclusive) divide `n` (you must use *this* algorithm!). The input to STDIN should be an integer `n` (strictly) greater than 1. The output to STDOUT should be `prime` if `n` is prime and `not prime` if `n` is not prime. Even though you are intentionally writing an inefficient program, this is still code golf, fellas. Standard CG rules apply. Shortest code in bytes wins. [Answer] # CJam, 25 bytes ``` li_,2>f%:*!"not "*"prime" ``` [Try it online](http://cjam.aditsu.net/#code=li_%2C2%3Ef%25%3A*!%22not%20%22*%22prime%22&input=16) Explanation: ``` li Get input and convert to integer. _, Create range [0 ... n-1]. 2> Slice off first two elements, to get [2 ... n-1]. f% Apply modulo with all range members to input. :* Calculate product of the results. This will be 0 if one of the modulo results was 0, non-zero if the input is prime. ! Negate. We now have 0 for primes, 1 for non-primes. "not "* Push "not " 0/1 times based on value. "prime" Push "prime". ``` [Answer] # Pyth - ~~25~~ 23 bytes Heavily golfable, uses filter. ``` +?f!%QTr2Q"not "k"prime ``` [Test Suite](http://pyth.herokuapp.com/?code=%2B%3Ff%21%25QTr2Q%22not+%22k%22prime&input=7&test_suite=1&test_suite_input=7%0A10&debug=0). [Answer] # Pyth, 22 bytes ``` +*}0%LQr2Q"not ""prime ``` [Try it online.](https://pyth.herokuapp.com/?code=%2B%2a%7D0%25LQr2Q%22not+%22%22prime&input=17&debug=0) [Answer] # Python 2, 59 ``` i=input() print"not "*any(i%n<1for n in range(2,i))+"prime" ``` Thanks Alex! One day I will remember. [Answer] # Python 2, way too many bytes (95, to be exact) ``` n=input();x=0 for i in range(2,n): if n%i==0:x+=1;print'not prime';break if x==0:print'prime' ``` Heavily golfable for sure. [Answer] # R, 59 bytes ``` n=scan();cat(if(n>2&sum(!n%%2:(n-1)))"not ","prime",sep="") ``` Ungolfed: ``` # Read n from STDIN n <- scan() # Test primality and write to STDOUT if (n > 2 & sum(!(n %% 2:(n-1))) cat("not prime") else cat("prime") ``` ]
[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/37090/edit). Closed 9 years ago. [Improve this question](/posts/37090/edit) This is a short one: > > Only once in American history has there been a decade in which four of the years were prime numbers. > > > Your program has to output the decade after 1776 where four its years were primes. This is code golf so the shortest code wins. The output must be like so: ``` 1710s ``` or ``` 1980s ``` ***Note:*** The answer must be calculated and not explicitly hardcoded into your program. [Answer] # CJam, 24 bytes ``` 1770{A+_A,f+{mp},,4<}g's ``` At the cost of two extra bytes, this program can be modified to calculate the first decade containing four prime years after (not containing) a user-defined year: ``` liA/A*{A+_A,f+{mp},,4<}g's ``` ### Example runs ``` $ cjam <(echo "1770{A+_A,f+{mp},,4<}g's"); echo 1870s $ cjam <(echo "liA/A*{A+_A,f+{mp},,4<}g's") <<< 1776; echo 1870s $ cjam <(echo "liA/A*{A+_A,f+{mp},,4<}g's") <<< 1870; echo 2080s $ cjam <(echo "liA/A*{A+_A,f+{mp},,4<}g's") <<< 2080; echo 3250s $ cjam <(echo "liA/A*{A+_A,f+{mp},,4<}g's") <<< 3250; echo 3460s ``` ### How it works ``` li " Read an integer “Y” from STDIN. "; A/A* " Execute “Y = Y / 10 * 10”. "; { 4<}g " While the result of the loop is less than four: "; A+ " Execute “Y += 10”. "; _A,f+ " Push [ Y Y+1 Y+2 Y+3 Y+4 Y+5 Y+6 Y+7 Y+8 Y+9 ]. "; {mp},, " Compute the number of primes in that range. "; 's " Push 's'. "; ``` [Answer] # Python - ~~105 103~~ 87 Iterating over `i`th primes using `sympy`'s `prime` function: ``` import sympy p=sympy.prime for i in range(275,305): if p(i)>p(i+3)-9:print`p(i)-1`+'s' ``` **Alternative solution** iterating over years from 1780 to 2010 and counting primes per decade: ``` r=range for d in r(1780,2010,10): if sum(all([y%i>0for i in r(2,y)])for y in r(d,d+10))>3:print`d`+'s' ``` ]
[Question] [ So you are tasked with creating an open source password authentication system but you want to reveal as little about the implementation of the hash function as possible. Can you write a function that takes in a password string and a salt string and outputs a salted hash string without revealing the hashing function? End date: 6th of July Popularity contest: So whoever is voted as hardest to figure out the hashing method. Restriction: Must use an accepted as secure hashing function [Answer] # Python 3 Uninspired solution - hide your hash function with hash-looking code ``` import base64 a = b'66726F6D20686173686C696220696D706F72742A3B7072696E74287368613235' b = b'3628627974657328696E70757428292B696E70757428292C277574662D382729' c = b'292E686578646967657374282929232048656C6C6F2074686572652021402324' exec(base64.b16decode(a+b+c)) ``` [Answer] # Ruby Need a way to obfuscate your choice of hashing function? Why not use a hashing function? ``` require 'digest' three_card_monte = %w[SHA1 MD5 RMD160] part1, part2 = three_card_monte.repeated_permutation(2).find{|x,y|Digest(x).base64digest(y)[/tada!?/i]} part2.send( ('mode'..$&).find{|x|Digest(part1).base64digest(x)[/\d\dSXQ/]}<<$&.to_i.chr) puts Digest(part2).base64digest(gets+gets) ``` [Answer] # Python This one is not a hashing function, takes no salt, and is completely insecure, but can you tell what it is? ``` def f(x): a,b=ord(x),ord(x)+13 if not (97<=a<=122 or 65<=a<=90):return x if (65<=a<=90 and b>90) or b>122: b-=26 return chr(b) print(''.join(f(i) for i in input())) ``` > > It's rot13 > > > Here is an actual hashing function. ``` import hashlib salt = b'cHJpbnQoaGFzaGxpYi5zaGEyNTYoYnl0ZXMoaW5wdXQoKStpbnB1dCgpLCd1dGYtOCcpKS5oZXhkaWdlc3QoKSkKZXhpdCgp';import base64;exec(base64.b64decode(salt)) print(hashlib.md5(bytes(input(), 'utf-8') + salt).hexdigest()) ``` Note that it is not md5 and it does not use a hard coded salt. Based on qwr's solution. ]
[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/23651/edit). Closed 6 years ago. [Improve this question](/posts/23651/edit) ``` public int UndocumentedCode(int a, int b) { while (true) { a -= b; b += a; a = b - a; if (b < a) { return b; } else { b += 1; } } } ``` First figure out what it does (or look at the spoiler) the challenge is to make it as long as possible without adding lines that do absolutely nothing e.g. if (true) or do anything completely meaningless e.g. a declaration that isn't used/needed. any lines of code that can be removed, with the result still being the same, do not count the more confusing looking, the better. > > it is a function for getting the lesser of two numbers. the if (b < a) return b is self explanatory. The a and b calculations at the top are to swap b and a around, so when it loops it will check a < b. the b+=1 is to prevent infinite loops if they are the same > > > [Answer] Not sure this is quite in the spirit of things, and I'm not going to write *all* the code, but technically all of the lines in the following would be necessary for the function to work. Note, for the sake of brevity I've changed the types to `char`, which I will assume is an 8-bit signed type (I didn't spot any mention of a specific language): ``` public char UndocumentedCode(char a, char b) { if (a == -128 && b == -128) return -128; if (a == -127 && b == -128) return -128; if (a == -126 && b == -128) return -128; ... // can you see where I'm going with this? ... if (a == -128 && b == -127) return -128; if (a == -127 && b == -127) return -127; if (a == -126 && b == -127) return -127; ... // yawn... ... if (a == 125 && b == 127) return 125; if (a == 126 && b == 127) return 126; if (a == 127 && b == 127) return 127; // i think you get the idea by now } ``` The code would of course be platform dependant, and cases would need to be written for all combinations of negative and positive numbers. Perhaps some kind of script to write the file, to save aching fingers, and to automatically generate the code based on platform-specific options. If we just went with 8-bit ints, then the final code would be roughly 131075 lines long, with all lines being necessary to cover all possibilities. [Answer] ``` public int UndocumentedCode(int a, int b) { while (true) { a -= b; b += a; a = b - a; bool isGT? = b < a; if isGT? { return b; } else { b += 1; } } } ``` Add another statement with boolean condition. [Answer] ``` public int UndocumentedCode(int a, int b) { int a1 = a; int a2 = a1; int a3 = a2; int a4 = a3; int a5 = a4; int a6 = a5; int a7 = a6; int a8 = a7; int a9 = a8; // etc int a9999 = a9998 int c = a9999; while (true) { c -= b; b += c; c = b - c; if (b < c) { return b; } else { b += 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/13065/edit). Closed 7 years ago. [Improve this question](/posts/13065/edit) ### The Task Write a program to take a query from STDIN and then download the first 20 search results of that query from [google](http://www.google.com) and save them in a folder named `Search` as `html` files. Or if google points to a non-html file (like PDF), save whatever it is. Type of results may depend on the programmer, but the first 20 results should be matched. Ads etc. can also be counted as results. ### Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") ; shortest code wins. [Answer] # Ruby, ~~260~~ 256 characters ``` require'net/http';require'nokogiri';i=0;`mkdir Search`;`cd Search`;N=Net::HTTP Nokogiri::HTML.parse(N.get"www.google.cz","/search?"+URI.encode_www_form(q:gets,num:20)).css(".r a").each{|e|File.open("#{i+=1}",?w)<<N.get(URI e['href'][/q=(.*?)&/,1])rescue 0} ``` Note: when testing this multiple times, be sure to add ``cd ..`` between each test to reset the current working directory lest you end up with `whatever/Search/Search/Search/Search...` If we are allowed to fail on first unsuccessful result, we can drop `rescue 0` at the end of the second line and save 8 characters. if we may assume input is alphanumeric and a single word, we can skip encoding and shave off some more characters. (**235 chars** with error recovery, **227** without) ``` require'net/http';require'nokogiri';i=0;`mkdir Search`;`cd Search`;N=Net::HTTP Nokogiri::HTML.parse(N.get"www.google.cz","/search?num=20&q="+gets).css(".r a").each{|e|File.open("#{i+=1}",?w)<<N.get(URI e['href'][/q=(.*?)&/,1])} ``` [Answer] ## Bash ``` mkdir Search;cd Search;wget -U msie -rl 1 -e robots=off -d http://www.google.com http://www.google.com/search?q=`cat`&num=20 ``` Because `wget` is the right way to do that. ]
[Question] [ **This question already has answers here**: [Translate English to English](/questions/216108/translate-english-to-english) (9 answers) Closed 2 years ago. Inspired by a tweet by [Nathan W. Pyle](https://twitter.com/nathanwpyle/status/1437233812203782145) There is, now, a standard method of converting your boring, normal human name into a mysterious, ethereal Ghost Name™️. Ably described by Mr Pyle... ``` Use your first name: a - add “t” after it e - add “boo” after it h - becomes “s” n - add “oo” after it r - add “eee” after it y - add “oo” after it that’s it that’s your ghost name ``` (Note that the rule for h is a substitution, not an append) Well, needless to say we don't want to waste too many chars of code converting your name, time for some golfing! The task: * Convert a single-word string of a name into a Ghost Name™️ * Your code will accept a string and output a string * Upper-case letters will still be converted. The appended strings will appear after an upper-case version of their letter, and an upper-case H will become an upper-case S. * Spaces, punctuation, anything other than the prescribed letters will remain unchanged. Rules: * It's code golf, attempt to make the Ghost Name™️ conversion in as few bytes as possible. * Please include a link to an online interpreter, such as TIO. Test Cases ``` Andrew > Atnoodreeeeboow Stephanie > Steboopsatnooieboo Harry > Satreeereeeyoo Tim > Tim Tonleeboo > Tonoolebooebooboo Great Britain > Greeeebooatt Breeeitatinoo L33t H4x0rz > L33t S4x0reeez cat🐱face🐱emoji > catt🐱fatceboo🐱eboomoji ``` Satppyoo golfinoog! [Answer] # [JavaScript (Node.js)](https://nodejs.org), 92 bytes ``` s=>s.replace(/[aehnry]/gi,c=>[c+'boo',c+'t',c+'eee',c>{}?'s':'S',c+'oo'][Buffer(c)[0]%16%5]) ``` [Try it online!](https://tio.run/##bZFBTsMwEEX3nCKyVCURpSkqsEBKULtpF@zCLspi6k5aV6kdOYaSIu7ADTgDN@MGYRxolSZYssf6/7/MKN7CC5Rci8JcSbXCOgvrMozKkcYiB45ekABupK7SYC2GPIwSfukulXKHVE1zIiLV6O39wS3dezduREqkyew5y1B73E/G6eD6bnCb@jVXslQ5jnK19jKPTeVK4545p@X7ThA4UyOVIocWNdtfdKjYYLEBKZCdUSRTuijB0sLeu@ACtK5a3Y4gGNvL7qoPPYldGzlCJPeSSubNxOdzkawoRbrd/4w11wjGmWlhQEh24ubHHwDGunSngBGy/4HHycQ4i5vXsT6wVuNGjq1M7KELcTDfnx9fGT2zrbhTW8F@QbL@PMPtAI1P1UbqHw "JavaScript (Node.js) – Try It Online") ### Commented ``` s => // s = input string s.replace( // replace in s: /[aehnry]/gi, // look for all instances of these characters, // ignoring their case c => // for each character c: [ // lookup table: c + 'boo', // 0: add 'boo' to 'e' c + 't', // 1: add 't' to 'a' c + 'eee', // 2: add 'eee' to 'r' c > {} ? 's' // 3: turn 'h' into 's' and 'H' into 'S' : 'S', // c + 'oo' // 4: add 'oo' to either 'n' or 'y' ] // [ // hash function: Buffer(c)[0] // ASCII code modulo 16 modulo 5 % 16 % 5 // (this is case insensitive) ] // ) // end of replace() ``` ]
[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 3 years ago. [Improve this question](/posts/216511/edit) **Input:** binary string **Output:** binary string that represents the binary input + 1 **Example:** Given `10111` as an input, output `11000` **Limitations:** Can't use arithmetic operators or functions (like `+ - * /`) **Criterion:** code-golf, the shortest code wins the big imaginary award. [Answer] # [Perl 5](https://www.perl.org/), 38 bytes ``` s/0$/1/||s/0?(1+)$/1 .(0 x length$1)/e ``` [Try it online!](https://tio.run/##K0gtyjH9/79Y30BF31C/pgbIsNcw1NYE8hT0NAwUKhRyUvPSSzJUDDX1U///NwABLhBhCCQNDQ25DEEChgYgFghz/csvKMnMzyv@r1uQAwA "Perl 5 – Try It Online") Basically: If(last digit is zero){ change it to 1} else {change the last consecutive 1's (with possibly a 0 ahead of them) with a 1 and a count of zeros that is the same number as the number of 1's matched at the end of the line. Example input lines: 00000 00001 00111 1000 1011 111 1 Example output lines: 00001 00010 01000 1001 1100 1000 10 # [Perl 5](https://www.perl.org/), 37 bytes Or one less byte with this if it's ok to not preserve leading 0's (i.e. `0001` → `10`) ``` printf"%b\n",length 1 .(1x oct"0b$_") ``` [Try it online!](https://tio.run/##K0gtyjH9/7@gKDOvJE1JNSkmT0knJzUvvSRDwVBBT8OwQiE/uUTJIEklXknz/38DEOACEYZA0tDQkMsQJGBoAGKBMNe//IKSzPy84v@6eTkA "Perl 5 – Try It Online") [Answer] # GNU sed [<4.3](https://codegolf.stackexchange.com/questions/51323/tips-for-golfing-in-sed#comment268984_51352), ~~49 46 44 34~~ 30 bytes ``` s/.*/0&M/ # prepend 0 and append mark : # label s/0M/1/ # 0 incremented is 1 s/1M/M0/ # 1 incremented is 0 and the one to the left is incremented t # if anything just changed, repeat until it doesn't (the M has disappeared) ``` (comments and all whitespace other that newlines are just for explanation) This takes any amount of newline-separated binary numbers and increments each, it might give a number with leading 0s. [try it online](https://sed.js.org/) ]
[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/104266/edit). Closed 7 years ago. [Improve this question](/posts/104266/edit) # The Task Write a program or function which, when passed some positive integer `n` as input, returns Mills' Constant accurate up to `n` digits. # The Definition Mills' Constant worked out to six thousand digits may be located [here](https://primes.utm.edu/notes/MillsConstant.html). # Examples Let `f` be the function described by the challenge. ``` >>> f(1) 1 >>> f(3) 1.31 >>> f(100) 1.306377883863080690468614492602605712916784585156713644368053759966434053766826598821501403701197396 ``` # Rules * Your program must print or return Mills' Constant for any `n` between 1 and 1000. * Your program must approximate Mills' Constant such that all digits between the first to the `n`th returned or output are accurate to Mills' Constant. Extraneous digits are disallowed. * No form of hard-coding may be used. This means directly storing the digits of Mills' Constant or storing any of [Mills' Primes](https://oeis.org/A051254) (including those unlisted within OEIS). This rule includes compression. The solution must generate the number, not just output it. * The final digit must be rounded according to the digit following the final digit. In other words, if digit `n+1` is five or greater, add one to the final digit. * Built-in functions or constants relating directly to Mills' Constant or the Riemann zeta function may not be used. * You may assume that the Riemann hypothesis is true. [Answer] # Python 2 + gmpy2, 132 123 bytes ``` from gmpy2 import* get_context().precision=9999 n=2 exec"n=next_prime(n**3);"*8 print"{:.{}f}".format(root(n,3**9),input()) ``` The 9th Mill's prime provides enough precision for 1000 digits. So we calculate that prime, and then use it to calculate the constant. To speed up the program a lot, replace the exec statement with: ``` mills = [2] for o in [3, 30, 6, 80, 12, 450, 894, 3636, 70756, 97220, 66768, 300840]: mills.append(mills[-1]**3 + o) n = mills[8] ``` ]
[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/77316/edit). Closed 7 years ago. [Improve this question](/posts/77316/edit) [One of my favorite algorithms](https://stackoverflow.com/a/7769628/341362) was posted on Stack Overflow as an answer to [What is the fastest way to generate prime number recursively?](https://stackoverflow.com/q/4551731/341362). In pseudocode: ## Nathan's algorithm ``` bool isPrime(int n): if (n < 2) return false for p in 2..n-1: if (isPrime(p) && n%p == 0) return false return true ``` This program is lovely because it doesn't have any wasted steps (in the author's words, "it's quite efficient because it only needs to test the prime factors") but still manages to take far longer than any reasonable algorithm. For example, compare the naive algorithm: ## Unoptimized trial division ``` bool isPrime(int n): if (n < 2) return false for p in 2..n-1: if (n%p == 0) return false return true ``` This requires 10005 ≈ 104 divisions to test 10007, the smallest 5-digit prime. By contrast, Nathan's algorithm takes more than 10370 divisions, making it 10366 times slower. If every electron was a 1-googol GHz computer, and this program had been running across all electrons in the universe since the Big Bang, it wouldn't even be close to 1% done. --- The task is to write a program, in the language of your choice to test if a given number is prime as slowly as possible. The programs may not simply waste time by idling or executing unused loops; it should be clever in its sloth. # Scoring This is a [popularity-contest](/questions/tagged/popularity-contest "show questions tagged 'popularity-contest'"), so the (valid) answer with the most votes wins. Golfing is neither required nor recommended. Suggested criteria for voting: * Creativity: *How* does the program manage to do so much work? * Originality: Does the program use a novel approach? * Reasonableness: Does the code look reasonable at a glance? It's best if there are not sections which could obviously be excised to speed it up. * Simplicity: A single, well-executed idea is better than a combination of unrelated ideas (though cleverly combining approaches is encouraged). I consider Nathan's program to embody all four principles. As such, if the [original author](https://stackoverflow.com/users/995641/nathan) posts the original program here I will upvote it. [Answer] # Python 2, Really slow ``` import time def isPrime(n): if type(n) is not int: return False if n < 2: return False if n == 2: return True has_composite_factor = False for i in range(2, n): i_is_prime = isPrime(i) if n % i == 0: if not has_composite_factor and i_is_prime: has_composite_factor = True return not has_composite_factor def time_it(n): start = time.clock() prime = isPrime(n) end = time.clock() return end - start for i in range(20, 30): print "{}: {}".format(i, time_it(i)) ``` If a number is prime, it stands to reason that all of it's factors must also be prime. If we can find a single composite factor, then this number cleary isn't prime. We must also check to see if the number is valid, which is why we check `type(n)` and `n < 2`. This runs decently fast on `n < 20` but takes several seconds once you hit 25. Here is how long it takes to calculate 20-30: ``` 20: 0.141494 21: 0.282143 22: 0.565975 23: 1.132836 24: 2.266971 25: 4.525667 26: 9.050018 27: 18.110675 28: 36.372516 29: 72.920298 ``` ]
[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/71477/edit). Closed 8 years ago. [Improve this question](/posts/71477/edit) Write a square root function that takes an input, positive or negative, and calculate it's square root, correct up to six decimal places (then truncate after the sixth decimal place). But, you cannot use ANY built in power related functions. This means nothing like (but not limited to): ``` Math.pow(n,0.5) sqrt(2) root(n,2) n**0.5 etc. ``` This means that you're going to have to use (or create) a method to find the square root. Two common methods are the Babylonian/bisector method and Newton's method, but feel free to create your own! Output can be either printed to the console or returned. Your choice. Examples: ``` Input: sqrt(4) //you can call your function whatever you want Output: 2 Input: 7 Output: 2.645751 Input: 5.0625 Output: 2.25 Input: -15 Output: 3.872983i Input: -9 Output: 3i ``` This is code golf, so shortest code in bytes wins! Remember, no built ins that have anything to do with powers! If you have any questions, please, tell me in the comments and I'll clarify promptly. [Answer] # c (function), 166 Now with complex numbers. Uses the [GCC complex number extension](https://gcc.gnu.org/onlinedocs/gcc-3.3/gcc/Complex.html). Straightforward golfing of the famous [Fast inverse square root](https://en.wikipedia.org/wiki/Fast_inverse_square_root) method. This method gives `1/sqrt(n)`, so we simply multiply this by `n` to give `sqrt(n)`: ``` #include <complex.h> #define M y*=1.5-n*y*y/2 i;_Complex float f(float m){float y,n;n=m>0?m:-m;y=n;i=0x5f3759df-*(int*)&y/2;y=*(float*)&i;M;M;M;return m>0?y*n:y*n*I;} ``` The [famous snippet of Quake code](https://github.com/id-Software/Quake-III-Arena/blob/master/code/game/q_math.c#L552) only does one iteration of Newton's method, which gives a fairly inaccurate answer. Three iterations here seems to be enough for 6 decimal places, at least for the testcases. [Try it online.](https://ideone.com/XT2CbV) ]
[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/54760/edit). Closed 8 years ago. [Improve this question](/posts/54760/edit) ## Challenge You must write a program which correctly identifies the language a passage is written in. ## Rules The passage will be a string passed to your program either via STDIN or function arguments. You may not use any external sources *except* for a local text file with words. The length of the text file must be included in your overall program length. To know that your program meets the spec, it should correctly identify the languages of the following websites: ``` <code>.wikipedia.org/wiki/<Word for Wikipedia> <code>.wikipedia.org/wiki/<Language name> ``` Where `<code>` is replaced by the language's code. For example, in English: ``` en.wikipedia.org/wiki/Wikipedia en.wikipedia.org/wiki/English ``` For Lojban: ``` jbo.wikipedia.org/wiki/uikipidias jbo.wikipedia.org/wiki/lojban. ``` You are strictly forbidden to hardcode any of the content or HTML code of the links. To make sure that changes to the wiki don't affect your results, you should use the latest edit to the wiki page before the 15th August 2015, 21:00 BST (GMT+1). If your language cannot identify the language in which the passage is written, you must return the following phrase: ``` Ich ne know pas ``` You can only identify languages which are on [this list](https://en.wikipedia.org/wiki/List_of_Wikipedias). When you return the language name, you should return its English name, and in brackets its name in its own language. In your answer, you should have a list of the languages that you identify. ## Examples ### French (Français) > > Une baguette de pain ou simplement baguette, ou encore pain français (québécisme et belgicisme), est une variété de pain, reconnaissable à sa forme allongée. Cette forme de pain est emblématique de la France, et l'était déjà avant l'invention de la baguette, quand les pains longs étonnaient les visiteurs. La baguette est aussi typique de l'Algérie. > > > ### German (Deutsch) > > Die Wurst war und ist auch heute noch das Produkt des Wunsches nach einer möglichst großen Verwertung eines (geschlachteten) Tieres. Durch die Verarbeitung zur Wurst kann so auch das Fleisch länger haltbar gemacht werden. Die ersten Würste, wenn auch nicht im heutigen Sinne, wurden vermutlich bereits in der Antike oder sogar schon vorher hergestellt; siehe dazu auch Haggis oder Saumagen. Erste chinesische Erwähnung findet sich um das Jahr 589 v. Chr. zu einer Wurst, bei der Lamm- und Ziegenfleisch verwendet wurden. > > > ### Welsh (Cymraeg) > > Bara llaith o Gymru sy'n cynnwys cyrens, rhesins neu syltanas, croen candi, a sbeis melys yw bara brith. Gweinir yn dafellau gyda menyn gan amlaf, am de'r prynhawn neu de mawr. Teisen furum yw bara brith yn draddodiadol, ond mae nifer o ryseitiau modern yn defnyddio ychwanegion megis soda pobi i'w lefeinio. > > > ### English (English) > > A steak pie is a traditional meat pie served in Britain. It is made from stewing steak and beef gravy, enclosed in a pastry shell. Sometimes mixed vegetables are included in the filling. In Ireland Guinness Stout is commonly added along with bacon and onions, and the result is commonly referred to as a Steak and Guinness Pie (or Guinness Pie for short). A Steak and Ale pie is a similar creation, popular in British pubs, using one of a variety of ales in place of the Guinness. The dish is often served with "steak chips" (thickly sliced potatoes fried, sometimes fried in beef dripping). Steak pies are also available from chip shops, served with normal chips, referred to in Scotland as a steak pie supper. > > > ## Scoring Your score is the length in bytes of your program and any text files that you use divided by the number of languages that you support. The person with the lowest score wins. ``` score = (length of program + length of text file)/number of languages ``` [Answer] # ///, 8 Correctly identifies one language, Twi. Uses no text file. ``` Twi[Twi] ``` ]
[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/32616/edit). Closed 9 years ago. [Improve this question](/posts/32616/edit) The task is to find the number of characters in your source code up to the previous line. You may do some addition of two integers, or whatever that comes to mind. But at the end of your logic, you need to calculate the number of characters written in your code up to the last line. EDIT: The goal is to find the number of characters required to perform a task. For example, you are adding two numbers. The task is to find the number of characters used in doing that task. New line characters do not count. Lets start. [Answer] ## JavaScript I think that's what you want: ``` function foo() { return arguments.callee.toString() } foo().length ``` ]
[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/16076/edit). Closed 10 years ago. [Improve this question](/posts/16076/edit) This challenge is to write a program that prints a great famous speech. # Goals: * Obfuscated text (you should not be able to tell what speech it prints without running it) * Obfuscated code (it is more fun if you cant figure out how it works) * non-wrapping text and code is preferred. (78 chars/line) * Low score wins. # Rules: 1. When picking a speech it must be famous: it must have at least three published references (newspaper, history book, or similar) websites only count 1/3 unless associated with a dead tree publication. (if only using websites you need 9) 2. When picking a speech it must be great: it must not be too short (5 sentence minimum) or too long (It should be able to be read in less than 15 minutes) and have real meaning (you must assert that you have a strong opinion about the speech) 3. No input (files, web, etc.) # Scoring: 1. Punctuation and white space has no score. 2. Words found in the speech count 20 points. 3. Words not found in the speech count one point. 4. choice of language: * golf languages where the longest command is 1 letter cost 15 points. * languages that print to output by default cost 3 points. * interpreted languages cost 1 point. * java and languages where a typical method call is longer than 20 chars get a -5 point bonus. 5. three free lines of boilerplate (warnings, standard i/o, #!) boilerplate must be generic. [Answer] ## Python ``` import sys, this sys.stderr.write(''.join(map(lambda i: this.d.get(i, i), 'V nz cebhq gb pbzr gb guvf pvgl nf gur thrfg bs lbhe qvfgvathvfurq Znlbe, jub ' 'unf flzobyvmrq guebhtubhg gur jbeyq gur svtugvat fcvevg bs Jrfg Oreyva. Naq V ' 'nz cebhq gb ivfvg gur Srqreny Erchoyvp jvgu lbhe qvfgvathvfurq Punapryybe jub ' 'sbe fb znal lrnef unf pbzzvggrq Treznal gb qrzbpenpl naq serrqbz naq ' 'cebterff, naq gb pbzr urer va gur pbzcnal bs zl sryybj Nzrevpna, Trareny ' 'Pynl, jub unf orra va guvf pvgl qhevat vgf terng zbzragf bs pevfvf naq jvyy ' 'pbzr ntnva vs rire arrqrq. \n\nGjb gubhfnaq lrnef ntb gur cebhqrfg obnfg jnf ' '"pvivf Ebznahf fhz." Gbqnl, va gur jbeyq bs serrqbz, gur cebhqrfg obnfg vf ' '"Vpu ova rva Oreyvare." \n\nV nccerpvngr zl vagrecergre genafyngvat zl ' 'Trezna! \n\nGurer ner znal crbcyr va gur jbeyq jub ernyyl qba\'g haqrefgnaq, ' 'be fnl gurl qba\'g, jung vf gur terng vffhr orgjrra gur serr jbeyq naq gur ' 'Pbzzhavfg jbeyq. Yrg gurz pbzr gb Oreyva. Gurer ner fbzr jub fnl gung ' 'pbzzhavfz vf gur jnir bs gur shgher. Yrg gurz pbzr gb Oreyva. Naq gurer ner ' 'fbzr jub fnl va Rhebcr naq ryfrjurer jr pna jbex jvgu gur Pbzzhavfgf. Yrg ' 'gurz pbzr gb Oreyva. Naq gurer ner rira n srj jub fnl gung vg vf gehr gung ' 'pbzzhavfz vf na rivy flfgrz, ohg vg crezvgf hf gb znxr rpbabzvp cebterff. ' 'Ynff\' fvp anpu Oreyva xbzzra. Yrg gurz pbzr gb Oreyva. \n\nSerrqbz unf znal ' 'qvssvphygvrf naq qrzbpenpl vf abg cresrpg, ohg jr unir arire unq gb chg n ' 'jnyy hc gb xrrc bhe crbcyr va, gb cerirag gurz sebz yrnivat hf. V jnag gb ' 'fnl, ba orunys bs zl pbhagelzra, jub yvir znal zvyrf njnl ba gur bgure fvqr ' 'bs gur Ngynagvp, jub ner sne qvfgnag sebz lbh, gung gurl gnxr gur terngrfg ' 'cevqr gung gurl unir orra noyr gb funer jvgu lbh, rira sebz n qvfgnapr, gur ' 'fgbel bs gur ynfg 18 lrnef. V xabj bs ab gbja, ab pvgl, gung unf orra ' 'orfvrtrq sbe 18 lrnef gung fgvyy yvirf jvgu gur ivgnyvgl naq gur sbepr, naq ' 'gur ubcr naq gur qrgrezvangvba bs gur pvgl bs Jrfg Oreyva. Juvyr gur jnyy vf ' 'gur zbfg boivbhf naq ivivq qrzbafgengvba bs gur snvyherf bs. gur Pbzzhavfg ' 'flfgrz, sbe nyy gur jbeyq gb frr, jr gnxr ab fngvfsnpgvba va vg, sbe vg vf, ' 'nf lbhe Znlbe unf fnvq, na bssrafr abg bayl ntnvafg uvfgbel ohg na bssrafr ' 'ntnvafg uhznavgl, frcnengvat snzvyvrf, qvivqvat uhfonaqf naq jvirf naq ' 'oebguref naq fvfgref, naq qvivqvat n crbcyr jub jvfu gb or wbvarq gbtrgure. ' '\n\nJung vf gehr bs guvf pvgl vf gehr bs Treznal\xe2\x80\x94erny, ynfgvat ' 'crnpr va Rhebcr pna arire or nffherq nf ybat nf bar Trezna bhg bs sbhe vf ' 'qravrq gur ryrzragnel evtug bs serr zra, naq gung vf gb znxr n serr pubvpr. ' 'Va 18 lrnef bs crnpr naq tbbq snvgu, guvf trarengvba bs Treznaf unf rnearq ' 'gur evtug gb or serr, vapyhqvat gur evtug gb havgr gurve snzvyvrf naq gurve ' 'angvba va ynfgvat crnpr, jvgu tbbq jvyy gb nyy crbcyr. Lbh yvir va n qrsraqrq ' 'vfynaq bs serrqbz, ohg lbhe yvsr vf cneg bs gur znva. Fb yrg zr nfx lbh, nf V ' 'pybfr, gb yvsg lbhe rlrf orlbaq gur qnatref bs gbqnl, gb gur ubcrf bs ' 'gbzbeebj, orlbaq gur serrqbz zreryl bs guvf pvgl bs Oreyva, be lbhe pbhagel ' 'bs Treznal, gb gur nqinapr bs serrqbz rireljurer, orlbaq gur jnyy gb gur qnl ' 'bs crnpr jvgu whfgvpr, orlbaq lbhefryirf naq bhefryirf gb nyy znaxvaq. ' '\n\nSerrqbz vf vaqvivfvoyr, naq jura bar zna vf rafynirq, nyy ner abg serr. ' 'Jura nyy ner serr, gura jr pna ybbx sbejneq gb gung qnl jura guvf pvgl jvyy ' 'or wbvarq nf bar naq guvf pbhagel naq guvf terng Pbagvarag bs Rhebcr va n ' 'crnprshy naq ubcrshy tybor. Jura gung qnl svanyyl pbzrf, nf vg jvyy, gur ' 'crbcyr bs Jrfg Oreyva pna gnxr fbore fngvfsnpgvba va gur snpg gung gurl jrer ' 'va gur sebag yvarf sbe nyzbfg gjb qrpnqrf. \n\nNyy serr zra, jurerire gurl ' 'znl yvir, ner pvgvmraf bs Oreyva, naq, gurersber, nf n serr zna, V gnxr cevqr ' 'va gur jbeqf "Vpu ova rva Oreyvare!"'))) ``` This should be run with ``` $ python codegolf.py > /dev/null ``` I guess the text is pretty obfuscated, and the code as well, if you didn't take a closer look into the `this` module. Instead of 78 chars, I stuck to 80. ### Score: **Language choice:** Interpreted language: 1 **Code words:** The words found in the speech are `this` (1x), `for` (1x) but I guess they don't really count since they are language keywords (?). If they count, this is 29. Otherwise, it's 11. **Encoded speech words:** I guess I have a disadvantage here due to picking a long speech. But it has a total of 673 words, none of them in the speech. **Total score:** *Best case (Not counting language keywords and encoded speech words):* 1 + 11 = 12 *Worst case (Counting language keywords and encoded speech words):* 1 + 29 + 673 = 703 *Note: Speech is used from [here](http://millercenter.org/president/speeches/detail/3376).* ]