text
stringlengths
26
126k
[Question] [ Challenge Taken with permission from my University Code Challenge Contest --- For some years now, the number of students in my school has been growing steadily. First the number of students was increased by classroom, but then it was necessary to convert some spaces for some groups to give classes there, such as the gym stands or, this last course, up to the broom room. Last year the academic authorities got the budget to build a new building and started the works. At last they have finished and the new building can be used already, so we can move (the old building will be rehabilitated and will be used for another function), but it has caught us halfway through the course. The director wants to know if the move will be possible without splitting or joining groups, or that some students have to change groups. **Challenge** Given the amount of students of the current groups and the new classrooms (capacity), output a truthy value if it is possible to assign a different classroom, with sufficient capacity, to each of the current groups, or a falsey value otherwise. **Test Cases** ``` Input: groups of students => [10, 20, 30], classrooms capacity => [31, 12, 20] Output: True Input: groups of students => [10, 20, 30], classrooms capacity => [100, 200] Output: False Input: groups of students => [20, 10, 30], classrooms capacity => [20, 20, 50, 40] Output: True Input: groups => [30, 10, 30, 5, 100, 99], classrooms => [40, 20, 50, 40, 99, 99] Output: False Input: groups => [], classrooms => [10, 10, 10] Output: True Input: groups => [10, 10, 10], classrooms => [] Output: False Input: groups => [], classrooms => [] Output: True Input: groups => [10, 1], classrooms => [100] Output: False Input: groups => [10], classrooms => [100, 100] Output: True Input: groups => [1,2,3], classrooms => [1,1,2,3] Output: True ``` **Notes** * You can take the input in any reasonable format * You can output any Truthy/Falsey value (`1/0`, `True/False`, etc...) * [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 4 bytes It's always nice to see a challenge and know brachylog is gonna beat everyone. Takes current classes as input and new classrooms as output; It will output true if it finds a way to fit the students, false otherwise ``` p≤ᵐ⊆ ``` ## Explanation The code has 3 parts of which the order actually doesn't matter ``` ≤ᵐ --> projects each value to a value bigger/equal then input ⊆ --> input is a ordered subsequence of output p --> permutes the list so it becomes a unordered subsequence ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/v@BR55KHWyc86mr7/z/aUMdIxzgWRENYAA "Brachylog – Try It Online") [Answer] # Pyth, 11 bytes ``` .AgM.t_DMQ0 ``` Takes input as a list of lists, classroom sizes first, group sizes second. Try it online [here](https://pyth.herokuapp.com/?code=.AgM.t_DMQ0&input=%5B%5B31%2C%202%2C%2021%2C%201%5D%2C%5B10%2C%2020%2C%2030%5D%5D&debug=0), or verify all the test cases at once [here](https://pyth.herokuapp.com/?code=.AgM.t_DMQ0&test_suite=1&test_suite_input=%5B%5B31%2C%2012%2C%2020%5D%2C%5B10%2C%2020%2C%2030%5D%5D%0A%5B%5B100%2C%20200%5D%2C%5B10%2C%2020%2C%2030%5D%5D%0A%5B%5B20%2C%2020%2C%2050%2C%2040%5D%2C%5B20%2C%2010%2C%2030%5D%5D%0A%5B%5B40%2C%2020%2C%2050%2C%2040%2C%2099%2C%2099%5D%2C%5B30%2C%2010%2C%2030%2C%205%2C%20100%2C%2099%5D%5D%0A%5B%5B10%2C%2010%2C%2010%5D%2C%5B%5D%5D%0A%5B%5B%5D%2C%5B10%2C%2010%2C%2010%5D%5D%0A%5B%5B%5D%2C%5B%5D%5D%0A%5B%5B100%5D%2C%5B10%2C%201%5D%5D%0A%5B%5B100%2C%20100%5D%2C%5B10%5D%5D%0A%5B%5B1%2C1%2C2%2C3%5D%2C%5B1%2C2%2C3%5D%5D&debug=0). ``` .AgM.t_DMQ0 Implicit: Q=eval(input()) _DMQ Sort each element of Q in reverse .t 0 Transpose, padding the shorter with zeroes gM Element wise test if first number >= second number .A Are all elements truthy? Implicit print ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes Takes the classrooms as first argument and the groups as second argument. ``` Œ!~+Ṡ‘ḌẠ¬ ``` [Try it online!](https://tio.run/##y0rNyan8///oJMU67Yc7FzxqmPFwR8/DXQsOrfn//3@0oY6hjpGOcSyIBaIB "Jelly – Try It Online") ### Commented *NB: This `Ṡ‘ḌẠ¬` is far too long. But I suspect that this is not the right approach anyway.* ``` Œ!~+Ṡ‘ḌẠ¬ - main link taking the classrooms and the groups e.g. [1,1,2,3], [1,2,3] Œ! - computes all permutations of the classrooms --> [..., [1,2,3,1], ...] ~ - bitwise NOT --> [..., [-2,-3,-4,-2], ...] + - add the groups to each list; the groups fits --> [..., [-1,-1,-1,-2], ...] in a given permutation if all resulting values are negative Ṡ - take the signs --> [..., [-1,-1,-1,-1], ...] ‘ - increment --> [..., [0,0,0,0], ...] Ḍ - convert from decimal to integer --> [..., 0, ...] Ạ - all truthy? --> 0 ¬ - logical NOT --> 1 ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 9 bytes ``` ñÍí§Vñn)e ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=8c3tp1bxbill&input=WzEsMiwzXQpbMSwxLDIsM10=) or [run all test cases on TIO](https://tio.run/##y0osKPnvl35oQwgXmPx/eOPh3sNrDy0PO7wxTzP1/39DA65oQwMdIwMdY4NYnWhjQx1DIyAvFkXU0ADEBgkCRQyhgkZgeVMDHROQhDFUQsdUB6Ta0hKowgShAigAEuOKBpumA0YQOyBMnWiIHFQMYieYA7UeytUx0jEGiehAWFy6uUEA) ``` ñÍí§Vñn)e :Implicit input of arrays U=students, V=classrooms ñ :Sort U by Í : Subtracting each integer from 2 í :Interleave with Vñn : V sorted by negating each integer § : Reduce each pair by checking if the first is <= the second ) :End interleaving e :All true? ``` --- ``` ñÍeȧVn o ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=8c1lyKdWbiBv&input=WzEsMiwzXQpbMSwxLDIsM10=) or [run all test cases on TIO](https://tio.run/##y0osKPnvl35oQwgXmPx/eOPh3tTDHYeWh@Up5P//b2jAFW1ooGNkoGNsEKsTbWyoY2gE5MWiiBoagNggQaCIIVTQCCxvaqBjApIwhkromOqAVFtaAlWYIFQABUBiXNFg03TACGIHhKkTDZGDikHsBHOg1kO5OkY6xiARHQiLSzc3CAA) ``` ñÍeȧVn o :Implicit input of arrays U=students, V=classrooms ñ :Sort U by Í : Subtracting each integer from 2 e :Does every element return true È :When passed through the following function § : Less than or equal to Vn : Sort V o : Pop the last element ``` [Answer] # [Python 2](https://docs.python.org/2/), 49 bytes Outputs by exit code, fails for falsy input. ``` g,r=map(sorted,input()) while g:g.pop()>r.pop()>y ``` [Try it online!](https://tio.run/##XY4xj4MwDIX3/AqLCaToREJvKFK7lfWWbqgDRy2K2pLIDbry67k4pKh3g/Xi9z3HtpO7mEHPrTkj7CBJkrmTtLs3Nn0YcniW/WBHl2aZ@Ln0N4Su7D6ssWm2p6jT7KciPdKIpQBwNLEA4BNb4M9DZ6kfXAgJRi1aB4ev6kBkaMl/EzbXNxikN0P5Nl81twfOtcolaF9FfpJQF0qC0uycxD@k8tAyYFOtQMfYp68N42LF3uSn1@2Wo5s/UXYDEfWyYBlTr92x8SgmXn48J7TradGQWhbBk8vzFw "Python 2 – Try It Online") [Answer] # [MATL](https://github.com/lmendo/MATL), 10 bytes ``` yn&Y@>~!Aa ``` [Try it online!](https://tio.run/##y00syfn/vzJPLdLBrk7RMfH//2gjAx0FQyA2NojlAnNA2BSITQxiAQ) Or [verify all test cases](https://tio.run/##y00syfmf8L8yTy3Swa5O0THxv0vI/2hDAx0FIyA2NojlijY21FEwNAIJADkoMoYGYB6ICRIzhIkbQRWZArEJ2Ai4LFAQxATSlpZACRMUlSBBqATUKghG58ARWATiEDAJcxOUr2OkYwymISwA). ### Explanation Consider inputs `[20, 10, 30]`, `[20, 20, 50, 40]` as an example. Stack is shown bottom to top. ``` y % Implicit inputs. Duplicate from below % STACK: [20 10 30] [20 20 50 40] [20 10 30] n % Number of elements % STACK: [20 10 30] [20 20 50 40] 3 &Y@ % Variations. Gives a matrix, each row is a variation % STACK: [20 10 30] [20 10 30 20 20 40 20 20 40 ··· 50 40 20] >~ % Less than? Element-wise with broadcast % STACK: [1 1 1 1 1 1 1 1 1 ··· 1 1 0] ! % Transpose % STACK: [1 1 1 ··· 0 1 1 1 ··· 1 1 1 1 ··· 1] A % All. True for columns that only contain nonzeros % STACK: [1 1 1 ··· 0] a % Any. True if the row vector contains at least a nonzero. Implicit display % STACK: 1 ``` [Answer] # [Haskell](https://www.haskell.org/), 40 bytes ``` c%l=[1|x<-l,x>=c] s#g=and[c%s<=c%g|c<-s] ``` [Try it online!](https://tio.run/##dY/BCoMwEETvfsWCFVpYIYl6UIyH3voNIQeJxUpTLdWDB/89TVQQqoUcJjNvNtlH2T/vWhujAs0FncY81DgWXEmv92tetpVQQZ9zFdSTysNemrN/gSwDcWsHCWGxiWvXae9VNi1wqDoP3p@mHeAEriAoQUYwIhJERJEye5P/EUqc3hE2pivBZjghGO@oaKUwQTcnTS0eb7g1nPdTmh/F@Rz8a/EttW8d0csG@2Td7ChDhpGLcVHmCw "Haskell – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~14~~ ~~12~~ 8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` €{í0ζÆdP ``` Port of [*@Sok*'s Pyth answer](https://codegolf.stackexchange.com/a/179562/52210), so make sure to upvote him as well! Takes the input as a list of lists, with the classroom-list as first item and group-list as second item. [Try it online](https://tio.run/##yy9OTMpM/f//UdOa6sNrDc5tO9yWEvD/f3S0oY6hjpGOcaxONISOBQA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/R01rqg@vNTi37XBbSsB/nf/R0dHGhjoKhkY6CkYGsTrRhgYgho6CsUFsrI5CNJAPFjAAcdDljKB8UyA2AasA8QyRVJigqNBRsLQEYaA1xnCFQEkQEywJsxIiZwg2EiIGsx4qDheDOxKuAMnZcGGomI6hjpGOMVgIzIiNBQA). **Explanation:** ``` €{ # Sort each inner list í # Reverse each inner list 0ζ # Zip/transpose; swapping rows/columns, with 0 as filler Æ # For each pair: subtract the group from the classroom d # Check if its non-negative (1 if truthy; 0 if falsey) P # Check if all are truthy by taking the product # (and output implicitly) ``` --- **Old 12-byte answer:** ``` æε{I{0ζÆdP}à ``` Takes the classroom-list first, and then the group-list. [Try it online](https://tio.run/##yy9OTMpM/f//8LJzW6s9qw3ObTvclhJQe3jB///RhjqGOkY6xrFc0RAaAA) or [verify all test cases](https://tio.run/##yy9OTMpM/W9o4ObpYq@kkJiXoqBk73l4QiiQ86htEpBT/P/wsnNbqyOqDc5tO9yWElB7eMF/nf/RxoY6CoZGOgpGBrFc0YYGIIaOgjGEA@ZhiBtBOaZAbAITMITJmqDI6ihYWoIwUMIYrgooCWIaQCUMoRKGIO0QhFUI5hBDmNtgQiBCx1DHSMcYzALRAA). **Explanation:** ``` æ # Take the powerset of the (implicit) classroom-list, # resulting in a list of all possible sublists of the classrooms ε # Map each classroom sublist to: { # Sort the sublist I{ # Take the group-list input, and sort it as well 0ζ # Transpose/zip; swapping rows/columns, with 0 as filler Æ # For each pair: subtract the group from the classroom d # Check for everything if it's non-negative (1 if truthy; 0 if falsey) P # Check if all are truthy by taking the product }à # After the map: check if any are truthy by getting the maximum # (and output the result implicitly) ``` [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), ~~77~~ 74 bytes ``` a=>b=>a.Count==a.OrderBy(x=>-x).Zip(b.OrderBy(x=>-x),(x,y)=>x>y?0:1).Sum() ``` [Try it online!](https://tio.run/##jZJRa4MwEMff/RR5TCCVRLuHrk0KGwwGgw32tuJDdMqEVUcSN6Xss7tLLaKW1aIhuf/d/xc8LzGLxOTtQ1Ukm8en3NhNXlhJp3Fclp9SZqJVQsZCKv@@rAorhPKf9Xuq7xpcC7moif@Wf@F4IlJc04YIWctmy2458V@rPSbt2vOAvYvcg2xqrEECFekP6tWDNwgHwYEzigJYIfulAznkFPHApUAeZq5yc3bUL3udj597gxPyBtbyMiHsCVDujrCvViPackRz6VPJ/9TJl3RX8Pk@9GUj1JX3zNOnDZ5xnP@PWQ90Cno5NoKtl90Lk5aVOlXJB/5W@jhrUNrNHPEQetFgxBl2wo5FpDvwiJB1@wc "C# (Visual C# Interactive Compiler) – Try It Online") Commented code: ``` // a: student group counts // b: classroom capacities a=>b=> // compare the number of student // groups to... a.Count== // sort student groups descending a.OrderBy(x=>-x) // combine with classroom // capacities sorted descending .Zip( b.OrderBy(x=>-x), // the result selector 1 when // the classroom has enough // capacity, 0 when it doesn't (x,y)=>x<y?0:1 ) // add up the 1's to get the number // of student groups who can fit // in a classroom .Sum() ``` [Answer] ## Haskell, 66 bytes ``` import Data.List q=sortOn(0-) x#y=and$zipWith(<=)(q x)$q y++(0<$x) ``` [Try it online!](https://tio.run/##dY89C4MwEIZ3f8WBDgm9lsToIJitY6FjB3EIWDDUbzNo/7yNH1CoFm64e9/nvnLVv55FMU26bOrOwFUZdbnp3jit7K1wrwg7U2dwR6mqzHvr5qFNTmJJSQsD9VoYTyfCYm@gU6l0BRKy2oGm05UBD4hLIeEMfYaCpZAIjty3Vfof4WzOd4S1@Ub4CxwyDHaU2CgMcZ4TRRYPvrgVZu2naVmKSxzcteqW2ncd0esHe2f77MhDH8Vs45pNHw "Haskell – Try It Online") [Answer] # Bash + GNU tools, 68 bytes ``` (sort -nr<<<$2|paste -d- - <(sort -nr<<<$1)|bc|grep -- -)&>/dev/null ``` 69 bytes ``` (paste -d- <(sort -nr<<<$2) <(sort -nr<<<$1)|bc|grep -- -)&>/dev/null ``` [TIO](https://tio.run/##VY1JCoMwGIX3/ykeRbQuQgZ1IZX2It3YJtSCqCQdFrVnt4mWDhCS7w28HGrXTPfm3BpYU2s4xPFCdgPdkzMXMIZV9HCcg0fJvkueq6Dtj6Zp7Xrrm52tqipS41C7iwHTDAzVXybT8XAcT9YMYZel8ZZrc@PdtW0nc2x6RDvSfWdokgJKIBOUSUjlmT6OFIEEeSVnQ81JIZD7@ttEgdArS8q/qZfBCVPz@QItZtgmuXwxIxQyfy/vCw) takes student rooms as first and second argument as string numbers delimited by newline returns exit status 1 for true or 0 for false [Answer] # [Perl 5](https://www.perl.org/) `-pal`, ~~67~~ 62 bytes *@NahuelFouilleul saved 5 bytes with a rearrangement and a grep* ``` $_=!grep$_>0,map$_-(sort{$b-$a}@F)[$x++],sort{$b-$a}<>=~/\d+/g ``` [Try it online!](https://tio.run/##K0gtyjH9/18l3lYxvSi1QCXezkAnNxFI62oU5xeVVKsk6aok1jq4aUarVGhrx@ogCdrY2dbpx6Ro66f//29ooGBkoGBswGVsoGBopGBo8C@/oCQzP6/4v66vqZ6BocF/3YLEHAA "Perl 5 – Try It Online") [67 bytes version](https://tio.run/##K0gtyjH9/9@hyDY3saBaozi/qKRaJUlXJbHWwU0zWltbRbkkVlclvhZJwsbOtk4/JkVbP91aJd5WyaFISbFOX1f//39DAwUjAwVjAy5jAwVDIwVDg3/5BSWZ@XnF/3V9TfUMDA3@6xYk5gAA "Perl 5 – Try It Online") Takes the space separated list of class sizes on the first line and the space separated list of room sizes on the next. [Answer] # Common Lisp, 74 bytes `(defun c(s r)(or(not(sort s'>))(and(sort r'>)(<=(pop s)(pop r))(c s r))))` ## Non-minified ``` (defun can-students-relocate (students rooms) (or (not (sort students #'>)) (and (sort rooms #'>) (<= (pop students) (pop rooms)) (can-students-relocate students rooms)))) ``` [Test it](https://rextester.com/NMOUG17878) Note that sort permanently mutates the list, and pop rebinds the variable to the next element. In effect this just recursively checks that the largest student group can fit in the largest room. There are 3 base-cases: 1. No students - return T 2. Students, but no rooms - return NIL 3. Students and rooms, but largest student group larger than largest room - return NIL [Answer] # [Python 2](https://docs.python.org/2/), ~~71~~ ~~67~~ 64 bytes ``` lambda g,c:s(g)==s(map(min,zip(s(g)[::-1],s(c)[::-1]))) s=sorted ``` [Try it online!](https://tio.run/##dZA5DoMwEEV7TmEpjS1NJMaQAiS3OUE6QkHYgsQmTIrk8sQGQxbhYuRZ3v/2uH@O967lUyGuU500tywhJaShpCUTQtIm6WlTtfCqeqp7URgeMQZJU5MyxhwpZDeMeTb1Q9WOpKARukC4Cs@NgUQeAkGuOzEjB3IZHrnjWFh053Ihz0ktv1GN4YZyIzyp8HetvY1XlE7VGQRa6/9odXee7F26vGoxQusGZqpYq4lVavbeFeLnV1bk3wI4eDMES7oy0xs "Python 2 – Try It Online") [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 50 bytes ``` \d+ $* %O^`1+ %`$ , ^((1*,)(?=.*¶((?>\3?)1*\2)))*¶ ``` [Try it online!](https://tio.run/##RY5NCgIxDIX3OccU0k6QpJ1ZDEV7BBduy1BBF25cyJzNA3ixmhZ/4EG@vBeSPK7b7X6uBk8l1nwZYXBgjmuREUwZgGBFFEcW037nXk/EdMghWXHZW2vVqVWYPFPgGITEK8PPEW7EoJ10w/dkZpoYwsekmdrcssTpn2qrAt1AXfCFCLFz263QT3QkTyHqB62@AQ "Retina 0.8.2 – Try It Online") Link includes test suite. Takes two lists of groups and rooms (test suite uses `;` as list separator). Explanation: ``` \d+ $* ``` Convert to unary. ``` %O^`1+ ``` Reverse sort each list separately. ``` %`$ , ``` Append a comma to each list. ``` ^((1*,)(?=.*¶((?>\3?)1*\2)))*¶ ``` Check that each of the numbers in the first list can be matched to the appropriate number in the second list. Each time `\3` contains the previously matched rooms and the next group `\2` therefore needs to be able to fit into the next room. The `(?>\3?)` handles the case of the first room when there are no previous rooms yet. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 28 bytes ``` W∧⌊講⌈§θ¹⌈§θ⁰UMθΦκ⁻ν⌕κ⌈κ¬⊟θ ``` [Try it online!](https://tio.run/##bY47C8MwDIT3/gqPMrjg9DF1CoWWDinZgweTGGLiR@I6bf69K3vpUsEt3@lO6kcZei9NSp9RG0WgdgM02mm7WlgoI08f4R6UjCpAI7fC6/hwg9pgYaSiuPOHc1oGrfnqrZXYivSmTe6ZMKLd@gKXEVrTr2MqucuuDdpFyNdbP@MnyFLquu7AGck6o05cMFJIhTpyIUTav80X "Charcoal – Try It Online") Link is to verbose version of code. Takes a list of lists of rooms and groups and outputs `-` if the rooms can accommodate the groups. Explanation: ``` W∧⌊講⌈§θ¹⌈§θ⁰ ``` Repeat while a group can be assigned to a room. ``` UMθΦκ⁻ν⌕κ⌈κ ``` Remove the largest room and group from their lists. ``` ¬⊟θ ``` Check that there are no unallocated groups remaining. [Answer] # JavaScript, 56 bytes ``` s=>c=>s.sort(g=(x,y)=>y-x).every((x,y)=>c.sort(g)[y]>=x) ``` [Try it](https://tio.run/##ZZBBDoIwEEX3nMJlm4y1BVy4KEtP4K42kWAhGqSGIqGnxxaoRkm6mP7/5nc697zPTdHent220Vc1lnw0PCt4ZojRbYcqjgawmGd2O2CietVatCjFQmBhZcYHPBa6MbpWpNYVElEkBKMQU0ioBJEwYLG7SQmb3W5zal/qF2DU18E/5rXxgHPZAsQTu6eQ/oUkCwN78CGHg4PTL@wEr00tIXZ6D6YzG995ZhHEqmEFzkP/cix85eOEBogh8R7MlQxWJMkjfyIk3FKl22qJBowsxuSub83l3Fzw@AY) [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 34 bytes ``` {none [Z>] $_>>.sort(-*)>>[^.[0]]} ``` [Try it online!](https://tio.run/##rZBRa4MwFIWf56@4FFm1pGq0G3Rgyh42GAz6MvYw60Z0OgpqxOiDtP3tzmQyKnWrjD1cEsg53zk3eVQk101aw2UMLjS7jGUReC/EB/WNEIOzotTmM50Q79XwLN8/NDErQEu2WcR1mBNQKQI1aCd0JxPYKRec1rCKNZUaIUsDzdx4xmy18c2WYdw93z7qCKbCOEV7Neg0T0UV7e9pwiNTVw7NQ5ZX5Q18FKzKObAYeFm9R1nJwSXgYQuB3Y5j@QjChHJeMJZyCGlOw21ZS5GDEWBbCH1lXZWSJ1IU5R/g2JKqI7Tsfo4tuPgc2@4KXLWzOFNeLvoNbT3i2p7LZT9A6BY9rtBI3e8bCOMpCneReES9I@0J50/hIyOHWlsjAod6yj/t2X@MRjZyBgDo66Hn/wQ "Perl 6 – Try It Online") Takes input as a list of two lists, the groups and the classrooms, and returns a None Junction that can be boolified to true/false. ### Explanation: ``` { } # Anonymous code block $_>>.sort(-*) # Sort both lists from largest to smallest >>[^.[0]] # Pad both lists to the length of the first list none # Are none of [Z>] # The groups larger than the assigned classroom ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 57 bytes ``` ->c,r{r.permutation.any?{|p|c.zip(p).all?{|a,b|b&&a<=b}}} ``` [Try it online!](https://tio.run/##ZZBBCoMwEEX3nsJVaWEaTGIXQm0PErKIolSwNogurPHsdhJTtXQxzMz7f8gnbZ8Nc5nO51sO7dgSXbTPvlNd9WqIaob7aLTJybvSR30iqq4RKMhMdjioa5pN0zSLQAgaQciweCQhFJxCSJklUsKfSiO3es1yumrMOy9YsXfw1YHcjtiTxLrjH7elTnFXy0vLJd3l8Duqm2@n@oBfsubdGDDgDsMyykCSQuWP0eAHGh2WAruc5g8 "Ruby – Try It Online") Takes `c` for classes, `r` for rooms. Checks all permutations of rooms instead of using sort, because reverse sorting costs too many bytes. Still looks rather long though... [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), ~~105~~ ~~93~~ ~~91~~ ~~82~~ ~~81~~ ~~79~~ ~~77~~ ~~76~~ 74 bytes Now matches dana's score! ``` n=>m=>{n.Sort();m.Sort();int i=m.Count-n.Count;i/=n.Any(b=>m[i++]<b)?0:1;} ``` Throws an error if false, nothing if true. -12 bytes thanks to @Destrogio! [Try it online!](https://tio.run/##pZBNi4MwEIbv/gqPSq012h7amJRS2FNve9jDsoc2KB2oI@hIKZLfbpN@sq0syB6GGeZ9M89MVD1WNXQfDap0AzWlgCSDlSIo8dmQMhcdClkI2WL4WVbk@by4F8bhgijCddkgjfGaOUwEhis8eTvz7htGo5905y@jBeO64w5Vp9bJPcyO7oPSsihwYxNJpP0XKWGBy2Ira587XxVQtgHMPKqazDS0o7ak9u1TyLeH2ih6MIlFF62X8wfmwnnFWATrx8S3DWYmphY2gNWHSh4oM9OWJs/nb9jpL6y1XG38v6f2/KPdYtDk7gw "C# (Visual C# Interactive Compiler) – Try It Online") # Explanation ``` //Function taking in a list, and returning another function //that takes in a list and doesn't return n=>m=>{ //Sort the student groups from smallest to largest n.Sort(); //Sort the classrooms fom smallest capacity to largest m.Sort(); //Initialize a variable that will function as a sort of index int i=m.Count-n.Count; //And divide that by... i/= //0 if any of the student groups... n.Any(b=> //Don't fit into the corresponding classroom and incrementing i in the process /*(In the case that a the amount of classrooms are less than the amount of student groups, an IndexOutOfRangeException is thrown)*/ m[i++]<b)?0 //Else divide by 1 :1; } ``` [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), 183 bytes ``` a->{int b=a[0].length;Arrays.sort(a[0]);Arrays.sort(a[1]);if(b>a[1].length){return false;}for(int i=0;i<b;i++){if(a[0][i]>a[1][i]){return false;}}return true;} ``` [Try it online!](https://tio.run/##tVBNa8MwDL33V@gYUzc4/TgUr4X9gPXSY8jBaZ3OXWoHx@koxr89k7PAoNDt0oFB0pPfe5LO4ipmppH6fPzo1aUx1sEZsbRzqk5frRW3lk8OtWhbeBNK@wmA0k7aShwk7HxpTC2FBpsgmhd5AYLwgJ9aJ5w6wA70Bnox23rsQ7kROSvSWuqTe@ff6mmLnknEyR2SIaKqpNzGdCQRb6XrrIZK1K3koTKDM6gN4@ql5Go6JR5JUS9XxUDFeE8LY@lsh1XPceCmK2sceJz7atQRLrhwsndW6VNeCBJ3B9jfWicvqelc2mDH1TrRqU20/ITxBN5njM4ZXbBAPcZsThdZCITwRwKPO79JZyzm7B@U50O6YnT5NPUF3iGq0xWNc6/XaLP8sUEgYk8yG45Dh/e3ZJiE/gs "Java (OpenJDK 8) – Try It Online") With a little helpful advice from [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen/%22Kevin%20Cruijssen%22) and simply another glance over my code myself, I can decrease my score by a whole 9% just by replacing three English words! # [Java (OpenJDK 8)](http://openjdk.java.net/), 166 bytes ``` a->{int b=a[0].length;Arrays.sort(a[0]);Arrays.sort(a[1]);if(b>a[1].length){return 0;}for(int i=0;i<b;){if(a[0][i]>a[1][i++]){return 0;}}return 1;} ``` [Try it online!](https://tio.run/##tVDLasMwELznK/ZoNYqQ8zgENYF@QHPJ0fggJ0oq15GNLKcEoW93V8bQUkh7SUFIw@zuzKxKeZWzulGmPL73@tLU1kGJHOucrtiTmBwq2bbwKrXxEwBtnLIneVCw84jBJnhneZaDJCJgQ@uk0wfYgdlAL2fboavYyIznrFLm7N7Ei7Xy1rIWrZLIkx9Miow@JcU2wnGIeKtcZw1wEU714Ap6w4V@LgTx2B2FMp0PM5meTvPvE2GEqQi9wJBNV1QYcsx6rfURLrhgsndWm3OWSxJ3BdjfWqcurO4ca7DiKpMYZhOjPmBc2/uU0zmnCx6oxzed00UaAiHinsD9ym/SKY@Y/4PyfIArTpcPU1/gP0R1uqIx93qNNssvGyQi9yCz4XPocP6WDJPQfwI "Java (OpenJDK 8) – Try It Online") [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 80 bytes ``` param($s,$c)!($s|sort -d|?{$_-gt($r=$c|?{$_-notin$o}|sort|select -l 1);$o+=,$r}) ``` [Try it online!](https://tio.run/##dZJda4MwFIbv/RVZORsJi2C0u@iGzKv9gt0X0XQbpMYlkQ2qv90d48faYgMhOec875vPWv9IYz@lUj0cSEpOfZ2b/EjBcijYHY6t1caRsGxfT7APPxwFk0IxRpV2XxXozjOtlUoWiCoi2Avox5SD6VjfBUFGA4KN04yKiJMYexIxTjKaCE5EPKQwBGcayW6hIvKxB99yZc/IgRL/ZDwJn7BvPf9@YZwsODLDFMfdzku3F9IhPZWul5y2NBqJlUUuap5ftbghnE@8IhNn1zERVwY85snI8Hk@IYy05J6cPArWNaWsnMVqoXJrjdbHIZC/Nb6jLPE7wH5EjbSNcph4wF@yCM91ntsAndBQfi8@7Hk22ARd/wc "PowerShell – Try It Online") Less golfed test script: ``` $f = { param($students,$classrooms) $x=$students|sort -Descending|where{ $freeRoomWithMaxCapacity = $classrooms|where{$_ -notin $occupied}|sort|select -Last 1 $occupied += ,$freeRoomWithMaxCapacity # append to the array $_ -gt $freeRoomWithMaxCapacity # -gt means 'greater than'. It's a predicate for the 'where' } # $x contains student groups not assigned to a relevant classroom !$x # this function returns a true if $x is empty } @( ,(@(10, 20, 30), @(31, 12, 20), $true) ,(@(10, 20, 30), @(100, 200), $False) ,(@(20, 10, 30), @(20, 20, 50, 40), $True) ,(@(30, 10, 30, 5, 100, 99), @(40, 20, 50, 40, 99, 99), $False) ,(@(), @(10, 10, 10), $True) ,(@(10, 10, 10), @(), $False) ,(@(), @(), $True) ,(@(10, 1), @(100), $False) ,(@(10), @(100, 100), $True) ,(@(1,2,3), @(1,1,2,3), $True) ) | % { $students, $classrooms, $expected = $_ $result = &$f $students $classrooms "$($result-eq$expected): $result" } ``` [Answer] # [R](https://www.r-project.org/), 65 bytes ``` function(g,r)isTRUE(all(Map(`-`,sort(-g),sort(-r)[seq(a=g)])>=0)) ``` [Try it online!](https://tio.run/##bVC9DoIwEN59ChKXu@RM2oIDAyYOOuniz2RMIAQaEgJa8PmR0gKCDJd@ve@nd1VNGjTpp4jrrCxAksKsul3uB4jyHM7RC8JNSFWpathItEDho0reEAUSn7gLGGKTQgyckSPachlSDC4nhwvdQXTWjs5c/as4665Gc9yfrkakBXwQCWvZtuXN4txB2fIatqfva5c3celux/w@lBV1IhMFZhITxBfmtX0a9MshE3oaYHedrcnHP@jJ0UaC3I4mA3u2@QI "R – Try It Online") ]
[Question] [ **Problem:** Find the number of leading zeroes in a 64-bit signed integer **Rules:** * The input cannot be treated as string; it can be anything where math and bitwise operations drive the algorithm * The output should be validated against the 64-bit signed integer representation of the number, regardless of language * [Default code golf rules apply](https://codegolf.stackexchange.com/tags/code-golf/info) * Shortest code in bytes wins **Test cases:** These tests assume two's complement signed integers. If your language/solution lacks or uses a different representation of signed integers, please call that out and provide additional test cases that may be relevant. I've included some test cases that address double precision, but please feel free to suggest any others that should be listed. ``` input output 64-bit binary representation of input (2's complement) -1 0 1111111111111111111111111111111111111111111111111111111111111111 -9223372036854775808 0 1000000000000000000000000000000000000000000000000000000000000000 9223372036854775807 1 0111111111111111111111111111111111111111111111111111111111111111 4611686018427387903 2 0011111111111111111111111111111111111111111111111111111111111111 1224979098644774911 3 0001000011111111111111111111111111111111111111111111111111111111 9007199254740992 10 0000000000100000000000000000000000000000000000000000000000000000 4503599627370496 11 0000000000010000000000000000000000000000000000000000000000000000 4503599627370495 12 0000000000001111111111111111111111111111111111111111111111111111 2147483648 32 0000000000000000000000000000000010000000000000000000000000000000 2147483647 33 0000000000000000000000000000000001111111111111111111111111111111 2 62 0000000000000000000000000000000000000000000000000000000000000010 1 63 0000000000000000000000000000000000000000000000000000000000000001 0 64 0000000000000000000000000000000000000000000000000000000000000000 ``` [Answer] # x86\_64 machine language on Linux, 6 bytes ``` 0: f3 48 0f bd c7 lzcnt %rdi,%rax 5: c3 ret ``` Requires Haswell or K10 or higher processor with `lzcnt` instruction. [Try it online!](https://tio.run/##S9ZNT07@/19DK01TQ9NWKabCzTimwsQipsLALabCySWmwtkciI2VrLlyEzPzNDSruQqKMvNK0jSUVFNi8pR00jQMfTQ1rTFEDcCitf///0tOy0lML/6vW5VakZpcXJKYnA0A "C (gcc) – Try It Online") [Answer] # [Hexagony](https://github.com/m-ender/hexagony), ~~78~~ 70 bytes ``` 2"1"\.}/{}A=<\?>(<$\*}[_(A\".{}."&.'\&=/.."!=\2'%<..(@.>._.\=\{}:"<><$ ``` [Try it online!](https://tio.run/##BcFBDkAwEAXQs5jQNha/WMq09BwmaSyEFVvSzNnrvet49/O5v1onGkmgvmgKLEt03EqvW3ZJCEVBBlZM8AA1QSbbMeBWRGRIkKIzceS21uEH "Hexagony – Try It Online") Isn't this challenge too trivial for a practical language? ;) side length 6. I can't fit it in a side length 5 hexagon. ### Explanation [![](https://i.stack.imgur.com/3azaW.png)](https://i.stack.imgur.com/3azaW.png) [Answer] # [Python](https://docs.python.org/2/), 31 bytes ``` lambda n:67-len(bin(-n))&~n>>64 ``` [Try it online!](https://tio.run/##ZYu7CsJAEEX7@YpUkhSBmdnZeQj6JTaKioG4BomIjb8etxO0uofDudNrvtwKL@fNbhn318Nx35S1Wj@eSnsYStuXrlu9y3arsjwvw3hqaD3dhzI353Yo02Nuu27pCfpgTskYk3oWs@zo8O8MRInUFcmFLbkFJiBmiUrhKrWTIIJANIrgehSsC5Ix5QitL0MJ/RUZmGrrScW/aMBAgB8 "Python 2 – Try It Online") The expresson is the bitwise `&` of two parts: ``` 67-len(bin(-n)) & ~n>>64 ``` The `67-len(bin(-n))` gives the correct answer for non-negative inputs. It takes the bit length, and subtracts from 67, which is 3 more than 64 to compensate for the `-0b` prefix. The negation is a trick to adjust for `n==0` using that negating it doesn't produce a `-` sign in front. The `& ~n>>64` makes the answer instead be `0` for negative `n`. When `n<0`, `~n>>64` equals 0 (on 64-bit integers), so and-ing with it gives `0`. When `n>=0`, the `~n>>64` evaluates to `-1`, and doing `&-1` has no effect. --- **[Python 2](https://docs.python.org/2/), 36 bytes** ``` f=lambda n:n>0and~-f(n/2)or(n==0)*64 ``` [Try it online!](https://tio.run/##ZYtLasNAEAX3fQotpYBId09PfwzyXWQUIYEzFkYheOOry7MLxKtXFPW2x77cCh/HPFzH78s0NuVUzjiW6dnPbfnk7nZvyzBg96Fy/C7r9auh03Zfy97M7Vq2n73tuqMn6IM5JWNM6lnMsqPDuzMQJVJXJBe25BaYgJglKoWr1E6CCALRKILrUbAuSMaUI7S@DCX0v8jAVFtPKv6HBgwE@AI "Python 2 – Try It Online") Arithmetical alternative. [Answer] # [C (gcc)](https://gcc.gnu.org/), 14 bytes ``` __builtin_clzl ``` Works fine on tio # [C (gcc)](https://gcc.gnu.org/), ~~35~~ 29 bytes ``` f(long n){n=n<0?0:f(n-~n)+1;} ``` [Try it online!](https://tio.run/##S9ZNT07@/z9NIyc/L10hT7M6zzbPxsDewCpNI0@3Lk9T29C69n9uYmaehmZ1QVFmXkmahpJqioKSTpqGhaamNUIIJGIAFKn9DwA "C (gcc) – Try It Online") Than Dennis for 6 bytes # [C (gcc)](https://gcc.gnu.org/) compiler flags, 29 bytes by David Foerster ``` -Df(n)=n?__builtin_clzl(n):64 ``` [Try it online!](https://tio.run/##ZYzLTsMwEADv@YpVEVJMG@RX/KAtXPgLqKLUIakl46A05QDi11mWXhBw2tHs7IZqCAEvYg7p1D3B5jh3Ke6vD7fFLxdHUogxz/Dcxlx@QzsNYQXh0E5wRfz6sGPFewHQjxOcgwhbEGsam3NLtFwyCgBeJtr35eKye8yLFfRlO4@pPD@JO8bYuvhArARWXkqlrOTKuFpbWzvu8L@zqI0QxhkunJZWOeu5QiGl9kTeGU2d9kKg59wK7yUdak4Tdc1V7b2hK8u1N39FjVJQ65TR7gctShTIP0Of2uGI1X1fZrbNd02zP8U0x9yE9JbI3Rj9BQ "C (gcc) – Try It Online") [Answer] # Java 8, ~~32~~ 26 bytes. `Long::numberOfLeadingZeros` Builtins FTW. -6 bytes thanks to Kevin Cruijssen [Try it online!](https://tio.run/##bZDBboMwDIbP5Sl8BGlFCQSSlHXHSZO67dDbph1SGmg6CAhCu2rqs7Mg0Wpq8cX2b3@2k704iPl@@92rsq4aA3ub@51Rhb9OhdaySZy7Stbp1KhK@89jkDhO3W0KlUJaiLaFV6E0/DpgbdRbI4x1h0ptobRVd20apfPPLxBN3npj83@7zH5cVTp/gBdtZC6bJ8hg2Q/SYqG7ciOb92wlxdbO@pBN1fa3YxJnNhtfAu3ol6DlEUbVXZ9aI0tfac8@4xY/7lQhwR1JfyfaN/ljhv2uN3X1YIWtgrZbLpS@IskkMF5Qdcav7a@YQruZL@q6OLnam2DOznR27ucY5jwIwpAGKIxZRCiNGGJwr1EgMcYxixFmJKAhoxyFgIOAcBtxFhPbRzjGwBGimPPAggRZDyRCYcR5bCmKCI/hVokgwLaZhTFhw13XjNoYMKA/ "Java (JDK) – Try It Online") [Answer] # [JavaScript (Node.js)](https://nodejs.org), 25 bytes Takes input as a BigInt literal. ``` f=x=>x<0?0:x?f(x/2n)-1:64 ``` [Try it online!](https://tio.run/##fdFLbsIwEAbgfU@RZbJIMy@PZ1ApZ0GUVK2QgwBVuX3qBQjkQLzx5tP88/jd/m3Pu9PP8dKm4Ws/Tf16XH@OH7CB1bjp67Gj1LS4Upl2QzoPh/37Yfiu@7rFVM1e01RdV8FbQZ2IORKwWpAYg4Gl53QuY7pWxYKKIqopoAlFtujAN0oFRSLxDNxUclVxxBvlsgGAiO6U0wXyn@5jYdmsBODgrjk@grg@Wly24dGW7RLmcGMVS@Vq@aWNc1vORk8udrU6W9mCLevCgpXpHw "JavaScript (Node.js) – Try It Online") Or [**24 bytes**](https://tio.run/##fdHNbsIwDAfw@56iJ9QeutqO49iTgGdBjE6bUIoATX37LgfQkAvNJZef/PfHz@53d9mfv0/XNg@fh2nq1@N6M27HDaxWfT12lJsWP4Sn/ZAvw/Hwfhy@6r5uMVez1zRV11Xw5qgRhZAIgmjklKKC5ud0LlO@VUVHWRBFBVCZUtBkEO6UHEUitgJMhUtVNsQ7Db4BgIRmVNIZyp//x0LfLEcI0UxKfAI2ebS4bOOj9e0SlnANwpr9asNLm@bWz0ZPLnazMlvZgvV1YcHy9Ac) by returning *false* instead of \$0\$. [Answer] # [Python 3](https://docs.python.org/3/), 34 bytes ``` f=lambda n:-1<n<2**63and-~f(2*n|1) ``` [Try it online!](https://tio.run/##ZYtLasNAEAX3OcUsJdGC/k1/jHMYGSMscMbGeGMIuboyu0C8ekVR7/56Xm5N9n39vC5fp/NS2mGmYzvyNJks7Tz/rANP7ZvGfb09yla2VmaCOZlFnFEsqrrXwIB356BGZGFIoewSnihAzJqdMkx7p0kEieiUyf2o2Be0otRM6y9HTfsvKjD1NsQ0/tCBgQAPH6XcH1t7DuuwjeP@Cw "Python 3 – Try It Online") [Answer] # [J](http://jsoftware.com/), 18 bytes ``` 0{[:I.1,~(64$2)#:] ``` [Try it online!](https://tio.run/##dY5BCsJADEX3PUVQoRZqSTKZTFLoATyDuBKLuHHRpejVx9l0NsVVwvvk/TzzvEwDIIyAGd@X8TxQ/z2qHLjbj9fcNbsB2nkaWujhM8K8NM399njBDCeqmzOHkBiDWpSUoqGt2TZKayRKpKZIJpyCJcewRsQsXoCbSrkSp1rmiIncudgEy6y2iCG6a1ElFNc/PK6cqQgsqNiG1A@rvLZj/gE "J – Try It Online") # [J](http://jsoftware.com/), 19 bytes ``` 1#.[:*/\0=(64$2)#:] ``` [Try it online!](https://tio.run/##dY4xDsIwDEX3nsKiSKUIiu04jl2pJwEmRIVYGDpz9pClWSomW@/L7/ud52UaAGEEzNQO1/F4ueF0UNlz34733De7Abp5Gjo4wXeEeWma5@P1gRnOVDdnDiExBrUoKUVDW7NtlNZIlEhNkUw4BUuOYY2IWbwAN5VyJU61zBETuXOxCZZZbRFDdNeiSiiuf3hcOVMRWFCxDakfVnltx/wD "J – Try It Online") ## Explanation: ``` #: - convert ] - the input to (64$2) - 64 binary digits = - check if each digit equals 0 - zero [:*/\ - find the running product 1#. - sum ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 18 bytes *-2 bytes thanks to Jo King* ``` 64-(*%2**64*2).msb ``` [Try it online!](https://tio.run/##rdNRb4IwEAfw936Ke9kEFL22x7WNWeb3mD7opomJzkWezLLPzi4bEzJIMOC9FNLml7s/5WN7PnBxvMDjDp6gYEqj5MEkCVNi4ukx3xRztTudITrs37d5DJ8KQE4v1nJ6@no6bqLZMn1evo1n8VzJXr6@wC5arF9wFU9GsM9hNBnLq16pryLV0Cz8e9ADS6XBGGudQcs@I@cyj77G47BSTd2Jeh1jaPfEWrNn1J6Ms94FtADmyg/0lTaGgqDBM0n3FLS0bisef/LpzQdEp0MwkgyhrGXkFV9Wv6@gKEObhcCSjEMKXF6YBt/P/89nv7xp8r0CUkZLKt4y@dq9t218W3WNVPGuztsbeezsvuWnBb61@67ZlG7l7V141ApbeboPj98 "Perl 6 – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), 22 bytes ``` ->n{/[^0]/=~"%064b"%n} ``` [Try it online!](https://tio.run/##bY69CsJAEIR7n0ICKUP27/aniC8SYpEiZRDBQkRf/Ty8q9RqmB3mm73e1nvepjyc9sc4n2EZp1fXg8ra9fszX47bPOBy@GgQMRsBqycxSw5ek9/AaiCKqK6ALmTsFsA1QCKJYsNVSkMC20gAGEZQ4QgUbZwEnCK0QAwk9O811SthqTqr@JdvPzVk24MlvwE "Ruby – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~10~~ 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ·bg65αsd* ``` I/O are both integers [Try it online](https://tio.run/##yy9OTMpM/f//0PakdDPTcxuLU7T@/zcxMzQ0szAzMLQwMTI3tjC3NDAGAA) or [verify all test cases](https://tio.run/##ZYu7CQJREEXzqWLZUFyY35tPtImNuChiZLAgLBhbgJ0YmVuARdjI82WCRvdwOPc0b6fjvl7Oy9h37@ut68dlU5@P6WDldZ93q7quA8GQzCLOKBZF3UtgwL9zUCOyMKRQdglPFCBmzUYZpq3TJIJEdMrkdlRsC1pQSqa1l6Om/YoCTK0NMY0vOjAQ4Ac). **Explanation:** ``` · # Double the (implicit) input # i.e. -1 → -2 # i.e. 4503599627370496 → 9007199254740992 b # Convert it to binary # i.e. -2 → "ÿ0" # i.e. 9007199254740992 → 100000000000000000000000000000000000000000000000000000 g # Take its length # i.e. "ÿ0" → 2 # i.e. 100000000000000000000000000000000000000000000000000000 → 54 65α # Take the absolute different with 65 # i.e. 65 and 2 → 63 # i.e. 65 and 54 → 11 s # Swap to take the (implicit) input again d # Check if it's non-negative (>= 0): 0 if negative; 1 if 0 or positive # i.e. -1 → 0 # i.e. 4503599627370496 → 1 * # Multiply them (and output implicitly) # i.e. 63 and 0 → 0 # i.e. 11 and 1 → 11 ``` [Answer] # [Haskell](https://www.haskell.org/), 56 bytes Thanks [xnor](https://codegolf.stackexchange.com/users/20260/xnor) for spotting a mistake! ``` f n|n<0=0|1>0=sum.fst.span(>0)$mapM(pure[1,0])[1..64]!!n ``` Might allocate quite a lot of memory, [try it online!](https://tio.run/##JcqxDoMgFIXhvU9xTTpgouQCKjQpvkGfgDAwaGoqhIhuvju1dPnOcP63S59pXXOeIZzhiRpPNqJOh6dz2mmKLpAR67t38UXisU2GNWhrwygdOltVIXu3BNDwC4DEbQk7nesbgIGWXdNA@@BcCMlRDKrvpOwVqnIMRV78p3hp8xc "Haskell – Try It Online") Maybe you want to test it with a smaller constant: [Try 8-bit!](https://tio.run/##y0gszk7Nyfn/P00hrybPxsDWoMbQzsC2uDRXL624RK@4IDFPw85AUyU3scBXo6C0KDXaUMcgVjPaUE/PIlZRMe9/bmJmnoKtAkheQaOgKDOvRC9Nk0tBIVpB1xhI6SjoGoIpAzAJYRuBSTOIiJE5kI79DwA "Haskell – Try It Online") ## Explanation Instead of using `mapM(pure[0,1])[1..64]` to convert the input to binary, we'll use `mapM(pure[1,0])[1..64]` which essentially generates the inverted strings \$\lbrace0,1\rbrace^{64}\$ in lexicographic order. So we can just sum the \$1\$s-prefix by using `sum.fst.span(>0)`. [Answer] # Powershell, 51 bytes ``` param([long]$n)for(;$n-shl$i++-gt0){}($i,65)[!$n]-1 ``` Test script: ``` $f = { param([long]$n)for(;$n-shl$i++-gt0){}($i,65)[!$n]-1 } @( ,(-1 ,0 ) ,(-9223372036854775808 ,0 ) ,(9223372036854775807 ,1 ) ,(4611686018427387903 ,2 ) ,(1224979098644774911 ,3 ) ,(9007199254740992 ,10) ,(4503599627370496 ,11) ,(4503599627370495 ,12) ,(2147483648 ,32) ,(2147483647 ,33) ,(2 ,62) ,(1 ,63) ,(0 ,64) ) | % { $n,$expected = $_ $result = &$f $n "$($result-eq$expected): $result" } ``` Output: ``` True: 0 True: 0 True: 1 True: 2 True: 3 True: 10 True: 11 True: 12 True: 32 True: 33 True: 62 True: 63 True: 64 ``` [Answer] # Java 8, 38 bytes ``` int f(long n){return n<0?0:f(n-~n)+1;} ``` Input as `long` (64-bit integer), output as `int` (32-bit integer). Port of [*@l4m2*'s C (gcc) answer](https://codegolf.stackexchange.com/a/177291/52210). [Try it online.](https://tio.run/##fZFNTsMwEIX3PcWoK0dRqvFP/EORuACsukQsQptULqlTJU4lVIUlB@CIXCSYEAksECtr5vl9Hr85FOciO@yexm1ddB3cFdZdFgCdL7zdwmidh4rUjduDSy5t6fvWgbvGG7yqiMteXJLS9TAGx6l/rINjNp4bu4NjgJGNb63b3z9AkXyCAXzZeZLR22T9ozSMca4YcqlzoVSuUUcXfusq0oWkVGqJVAumuFYGeaRTxoQJXaOlCH5haDyAQVTUGBbgAsMZw3PkuTEykBUKI/8T80hkNPA0l0L/3Y4/Eb8aD4hf1bD4Xs6U8SRO@7FzvpvnzpfHVdP71SlE72tHbLqE99c3WKYVsckMGsYP) **Explanation:** ``` int f(long n){ // Recursive method with long parameter and integer return-type return n<0? // If the input is negative: 0 // Return 0 : // Else: f(n-~n) // Do a recursive call with n+n+1 +1 // And add 1 ``` --- EDIT: Can be **26 bytes** by using the builtin `Long::numberOfLeadingZeros` as displayed in [*@lukeg*'s Java 8 answer](https://codegolf.stackexchange.com/a/177304/52210). [Answer] # APL+WIN, 34 bytes ``` +/×\0=(0>n),(63⍴2)⊤((2*63)××n)+n←⎕ ``` Explanation: ``` n←⎕ Prompts for input of number as integer ((2*63)××n) If n is negative add 2 to power 63 (63⍴2)⊤ Convert to 63 bit binary (0>n), Concatinate 1 to front of binary vector if n negative, 0 if positive +/×\0= Identify zeros, isolate first contiguous group and sum if first element is zero ``` [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 42 bytes ``` x=>x!=0?64-Convert.ToString(x,2).Length:64 ``` [Try it online!](https://tio.run/##ZVA9T8MwFJzxr3C3RHIif8UfLSkDElO3IjEghsoyqaXiSLapghC/PTgNAQRveffu3t1wJlYmuvHu1ZvrU@875HzaQgNbOA7tdli1@Ebw6rb3ZxtSfd/vU3C@KwZEy3pnfZeOa8HHDQCT@fEJJhuTDTH73yuCQKUpZUxSzIRquJSNwgrBrwH/RQkXFXBBiFACE8WpZEpqzCAChFKuM9ZK8GzhmhD4KxBjSbSmOY3jvCcSTVkNZo3WIgdJzLWY@b90s7xTkv2KCa7mXPTDyPmEi0C@Ef7ILTz3wR7MsTgfwqWKCJ1fOinB1f4to5c61xn7k60fgkt257wtTHH5LsvN@Ak "C# (Visual C# Interactive Compiler) – Try It Online") # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 31 bytes ``` int c(long x)=>x<0?0:c(x-~x)+1; ``` Even shorter, based off of [@l4m2's C (gcc) answer.](https://codegolf.stackexchange.com/a/177291/52210) Never knew that you could declare functions like that, thanks @Dana! [Try it online!](https://tio.run/##ZZA/T8QwDMVn8ik8tqI92UmaP1cOBlY2BgbEcIoCRLpLpaZCRQi@ekmvFBB48fN79m@wS7VLYZpCHMAVhy4@wVjuLscLvMKtK8b6YyzPqZ0Ym7P7Bxh8GnyfYAdvNVWstpwLoTkKZRqpdWPQVPBV7H@oYU2ZVETKKCQjuRZGWxRQMeJc2qytUTKfSEsEv4CImqzlmSYx99msZlaDorFWZZBGadXi/7WbdZ1TvjdCSbNwqx9HLyOsAX0rfG8Ze@x6v3fPxcu@P70iQYjrT0p2dvua1XFz3cXUHfzmrg@DvwnRF644bZdlO30C "C# (Visual C# Interactive Compiler) – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~ 10 ~~ 9 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) -1 thanks to a neat trick by Erik the Outgolfer (is-non-negative is now simply `AƑ`) ``` ḤBL65_×AƑ ``` A monadic Link accepting an integer (within range) which yields an integer. **[Try it online!](https://tio.run/##y0rNyan8///hjiVOPmam8YenOx6b@P//fxNTA2NTS0szI3NjcwMTSzMA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##ddA7TgNBDAbg3qeIlHYi@TV@lEmdGyBERYNyAVoaaiouQJkDpF8p90guMhmxQgvLZhpL88m/bL88Hw6vrV1OX7u91afhc3v@aMP79e3Y2gNsqKwW3nqFsElmEWcUi6ruNTDKSP/Fy3cXgRqRhSGFskt4oozEQMya/SPDtHdpEo0kkIhOmdzTFHstP2MQglaUmmk9zlHTJqO51ckYmHpYiGmUv6vJL/O5CfDiRbpZX@GuCeBdU3i8AQ "Jelly – Try It Online"). --- The 10 was `ḤBL65_ɓ>-×` Here is another 10 byte solution, which I like since it says it is "BOSS"... ``` BoṠS»-~%65 ``` [Test-suite here](https://tio.run/##ddA9akJBEAfwfk4hhHT7YL52PtpcwVIsbUSwTpMiTa6RA@QCwS45SbzIuuQh6tO3zcD@mD8zs93sdq@tvez/vj@XP4fh7dlq@/04vn@1toKByuLBe1ogDMks4oxiUdW9BkYZ6V68/HcRqBFZGFIou4QnykgMxKzZPzJMe5cm0UgCieiUyT1NsddyHoMQtKLUTOtxjpp2MZpavRgDUw8LMY1yu5pcmU9NgB9epJv1FWZNAGdNYX0C "Jelly – Try It Online") ...`BoṠS63r0¤i`, `BoṠS63ŻṚ¤i`, or `BoṠS64ḶṚ¤i` would also work. --- Another 10 byter (from Dennis) is `æ»64ḶṚ¤Äċ0` (again `æ»63r0¤Äċ0` and `æ»63ŻṚ¤Äċ0` will also work) [Answer] # [Perl 5](https://www.perl.org/), 37 bytes ``` sub{sprintf("%064b",@_)=~/^0*/;$+[0]} ``` [Try it online!](https://tio.run/##rZPrTsJAEIX/71NMNouhUmH20r1Yq7yHFyJSCJFLpSWRGH11XAoKkSYY4PxpMzv55szpNktno2g5XrB@sszn3Y88mw0nRb9Oa6hVl4btTpB8tZ7wshWzxj0@fi7j8QLaRZoXyfg5g/s8Gw2L1kPeaD2GN7cx6U9n9fI4@CDgNV7U2TBkaZC0WSfelIANkgvW9yfBurSeCpQ26yyF9M033FF6TSfTAmjQpNNX3zScZPPiGmoiyiGB0iBA@p6lL0XaW9V7AINp2dF7mNBwNXc1OmSDmHwurzjsC39e@IkiV04IKY1AqW2kjIks2h08niayTzee@rvGqe6V5lxbjdwqYaQ1DiWA@MWfyCdcCOU81FmtvHvluLcut3gs8zka7xANd074ZBT65ybyLX6j474CURHKyDntkzGonN5cmD38cfy/@GiNF/v4owIigvtUrNTK7tx7WYWv0qGVtnizi5f/xONB9xU/Lej/uj@0G@GVeHkWPHKClXh1Hjx@Aw "Perl 5 – Try It Online") Or this 46 bytes if the "stringification" is not allowed: sub z ``` sub{my$i=0;$_[0]>>64-$_?last:$i++for 1..64;$i} ``` [Answer] # Swift (on a 64-bit platform), 41 bytes Declares a closure called `f` which accepts and returns an `Int`. This solution only works correctly 64-bit platforms, where `Int` is `typealias`ed to `Int64`. (On a 32-bit platform, `Int64` can be used explicitly for the closure’s parameter type, adding 2 bytes.) ``` let f:(Int)->Int={$0.leadingZeroBitCount} ``` In Swift, even the fundamental integer type is an ordinary object declared in the standard library. This means `Int` can have methods and properties, such as [`leadingZeroBitCount`](https://developer.apple.com/documentation/swift/int/2884587-leadingzerobitcount) (which is required on all types conforming to the standard library’s [`FixedWidthInteger`](https://developer.apple.com/documentation/swift/fixedwidthinteger) protocol). [Answer] # [Haskell](https://www.haskell.org/), 24 bytes ``` f n|n<0=0 f n=1+f(2*n+1) ``` [Try it online!](https://tio.run/##ZY2xDsIwDET3foXHllJkO2niVOQDGPgCxJCBioo2qqAj/x6idGQ5n9@ddM/weT3mOaUR4jee0WOVnad2rPkQW2rSEqYIHpawXqFe31PcTmNTAdygo3yO0DlmpSyjMtJra3tBKcE/t4VrQ2TEIIlmq8Q6VIUTs3b5c2J07mtH@4ApynunKA7DJW7Z3tMP "Haskell – Try It Online") This is basically the same as Kevin Cruijssen's Java solution, but I found it independently. The argument should have type `Int` for a 64-bit build, or `Int64` for anything. ## Explanation If the argument is negative, the result is immediately 0. Otherwise, we shift left, *filling in with ones*, until we reach a negative number. That filling lets us avoid a special case for 0. Just for reference, here's the obvious/efficient way: # 34 bytes ``` import Data.Bits countLeadingZeros ``` [Answer] # [Clean](https://github.com/Ourous/curated-clean-linux), 103 bytes Uses the same *"builtin"* as ceilingcat's answer. ``` f::!Int->Int f _=code { instruction 243 instruction 72 instruction 15 instruction 189 instruction 192 } ``` [Try it online!](https://tio.run/##S85JTcz7n5ufUpqTqpCbmJn3P83KStEzr0TXDkhwpSnE2ybnp6QqVHNl5hWXFJUml2Tm5ykYmRij8M2NULiGpqhcC0tUvqURV@3/4JLEohIFW4U0BYP/AA "Clean – Try It Online") # [Clean](https://github.com/Ourous/curated-clean-linux), 58 bytes ``` import StdEnv $0=64 $i=until(\e=(2^63>>e)bitand i<>0)inc 0 ``` [Try it online!](https://tio.run/##S85JTcz7n5ufUpqTqpCbmJn3PzO3IL@oRCG4JMU1r4xLxcDWzIRLJdO2NK8kM0cjJtVWwyjOzNjOLlUzKbMkMS9FIdPGzkAzMy9ZweB/cEkiUKetgoqCgQIc/P@XnJaTmF78X9fT579LZV5ibmZyMQA "Clean – Try It Online") [Answer] # [Stax](https://github.com/tomtheisen/stax), 10 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` în»╧3(∞┼⌠g ``` [Run and debug it](https://staxlang.xyz/#p=8c6eafcf3328ecc5f467&i=-1%0A-9223372036854775808%0A9223372036854775807%0A4611686018427387903%0A1224979098644774911%0A9007199254740992%0A4503599627370496%0A4503599627370495%0A2147483648%0A2147483647%0A2%0A1%0A0&a=1&m=2) It's a port of Kevin's 05AB1E solution. [Answer] # [Perl 5](https://www.perl.org/) `-p`, 42 bytes ``` 1while$_>0&&2**++$a-1<$_;$_=0|$_>=0&&64-$a ``` [Try it online!](https://tio.run/##rdPNaoQwEAfwe54i0LCHXSwz@Q7WvkGfQTxYarEqftAe@uxNQ7tdpQouunOJGPgx83ds8rZU3uP7S1HmLH2Ew4Efj6cTyyJ8YGnM0gQ@w/skXGgZsczHLEsgpnf5R9H1HX0dup4@1y19G8q@aMqc9m2Rd7SoaF3ltB0qHyGdF/w94M4ikeNcCMNBaKukMcqCnfCwr8hcN0G9jLG3e6kRtdWAVnIjrHEgKOUXfqdPkHPpAuqslqF76TC0LkYefvLZzDsAg87xkIyEcJ4jH/lzbfsKRCoQyjkdkjEgnT4vzIzf5v/n1S/P5/ymgAjHkIoVWtrJ3oslfqnWRhp5M@XFlTysLiYRhC/8uFRfO8HafAQXeXETHpDAIi9vw8NX3fRFXXU@elL3YRofNeU3 "Perl 5 – Try It Online") Longer than a bitstring based solution, but a decent math based solution. [Answer] # APL(NARS), 15 chars, 30 bytes ``` {¯1+1⍳⍨⍵⊤⍨64⍴2} ``` test for few numbers for see how to use: ``` f←{¯1+1⍳⍨⍵⊤⍨64⍴2} f ¯9223372036854775808 0 f 9223372036854775807 1 ``` [Answer] # Rust, 18 bytes ``` i64::leading_zeros ``` [Try it online!](https://play.rust-lang.org/?version=stable&mode=debug&edition=2015&gist=71da8c48aa4f1edd0fb85db20d7281d4) [Answer] # PHP, ~~50~~ 46 bytes ``` for(;0<$n=&$argn;$n>>=1)$i++;echo$n<0?0:64-$i; ``` Run as pipe with `-R` or [try it online](http://sandbox.onlinephpfunctions.com/code/7d03c08accfe0eaa3e19c42efec9c7bca8b40ae6), `<?=$argn<0?0:0|64-log($argn+1,2);` has rounding issues; so I took the long way. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 41 bytes The formula for positive numbers is just `63-Floor@Log2@#&`. Replacement rules are used for the special cases of zero and negative input. The input need not be a 64-bit signed integer. This will effectively take the floor of the input to turn it into an integer. If you input a number outside of the normal bounds for a 64-bit integer, it will tell return a negative number indicating how many more bits would be needed to store this integer. ``` 63-Floor@Log2[#/.{_?(#<0&):>2^63,0:>.5}]& ``` [Try it online!](https://tio.run/##ZY9NawJBEER/jCARerW/pnvaROMppxxyFyOLrImgWXDnJv72zZwSSE5VPOod6tKWz@7SltOhHUs3lEM7dMPq1hA0wSzijGI5qXvKmOE/c1AjsmxIWdkle6AAMWvUFtm07jSIIBCdIriKijVBE0qKsGo5athfkICpbrOY5t/qwECA98fjajRpXs59f9289h@8nSzmt/3zw@QJp7Plmt9NAJfrebrvpuPb9fRVtsfF5ufkbvwG "Wolfram Language (Mathematica) – Try It Online") @LegionMammal978's solution is quite a bit shorter at 28 bytes. The input must be an integer. Per the documentation: "`BitLength[n]` is effectively an efficient version of `Floor[Log[2,n]]+1`. " It automatically handles the case of zero correctly reporting `0` rather than `-∞`. # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 28 bytes ``` Boole[#>=0](64-BitLength@#)& ``` [Try it online!](https://tio.run/##ZY@7asNAEEU/xhAcGOGZ2dl5YBSM6xTujQth1pbAD4i2C/l2ZasEkupeDvcU9z7UsdyHOp2HpZa5noe5zP1nR9AFc0rGmNSzmGVHh//MQJRIXZFc2JJbYAJilmgtXKXtJIggEI0iuImCLUEyphyhzTKU0L8gA1PbelLx32rAQIBf20u/7J/PWzmu3no8rVW6/VTfy@Nax93q9WU5fEyPerxsdj@/Tss3 "Wolfram Language (Mathematica) – Try It Online") [Answer] bitNumber - math.ceil (math.log(number) / math.log(2)) e.g 64 bit NUMBER : 9223372036854775807 math.ceil (math.log(9223372036854775807) / math.log(2)) ANS: 63 [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), 12 bytes ``` +/&\~(64#2)\ ``` [Try it online!](https://ngn.codeberg.page/k#eJxljstqAlEMhvfzFEJFlCLN7eQy51E0oJuB0kJBXCjiPHvPmZ24Cv+X5Eum8fNrc5y3Kh+0Ow7DdXysD/f5Mk6rWz39/dTtaTp//9ZbvdfLLp/D9bDHhF6CiNkIWL2IWXHwpfHOLbFxUUR1BXQhY7cATmociSRaCldp8xKIyd0DYBhBTSLQamK3SwEuEdoUBhKaiO+0JHYzYVt1VvHkl2zJ/QKlLg+k9gSp8g/x20FX) `(64#2)\` encode the argument as 64 bits `~` bitwise not `&\` cumulative boolean and `+/` sum [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 15 bytes ``` I⁻⁶⁴L↨﹪NX²¦⁶⁴¦² ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEwzczr7RYw8xER8EnNS@9JEPDKbE4VcM3P6U0J1/DM6@gtMSvNDcptUhDU0chIL8cyDDSUTAz0QRyjTTBwPr/f4P/umU5AA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` L Length of N Input as a number ﹪ Modulo ² Literal 2 X To the power ⁶⁴ Literal 64 ↨ Converted to base ² Literal 2 ⁻ Subtracted from ⁶⁴ Literal 64 I Cast to string Implicitly print ``` The `¦`s serve to separate adjacent integer literals. Conveniently, Charcoal's arbitrary numeric base conversion converts `0` into an empty list, however for negative numbers it simply inverts the sign of each digit, so the number is converted to the equivalent unsigned 64-bit integer first. ]
[Question] [ My two kids like to play with the following toy: [![Turtle](https://i.stack.imgur.com/BYhak.jpg)](https://i.stack.imgur.com/BYhak.jpg) The colored areas with the shapes inside can be touched and the turtle then lights the area and plays a sound or says the name of the color or the shape inside. The middle button changes the mode. There is one mode in which the areas play different musical notes when touched, with a twist: if the kid touches three consecutive areas clockwise, a special melody 1 is played. If the three consecutive areas touched are placed counterclockwise, a special melody 2 is played. ### The challenge Let's simulate the internal logic of the toy. Given a string with 3 presses of the kid, return two distinct, coherent values if the three presses are for consecutive areas (clockwise or counterclockwise) and a third distinct value if they are not. ### Details * The input areas will be named with a character each, which can be their color: `ROYGB` for red, orange, yellow, green and blue; or their shape: `HSRTC` for heart, square, star (`R`), triangle and circle. Case does not matter, you can choose to work with input and output just in uppercase or in lowercase. * The program will receive a string (or char array or anything equivalent) with three presses. Examples (using the colors): `RBO`, `GYO`, `BBR`, `YRG`, `YGB`, `ORB`... * The program will output three distinct, coherent values to represent the three possible outcomes: a first value if the combination does not trigger a special melody, a second value if the combination triggers the clockwise special melody, and a third value if the combination triggers the counterclockwise special melody. Example: `0` for no special combination, `1` for the melody triggered by a clockwise combination and `-1` for the melody triggered by a counterclockwise combination. * You do not need to worry about handling wrong input. ### Test cases ``` Input Output // Input based on colors -------------- RBO 0 // No special combination GYO -1 // Counterclockwise melody triggered BBR 0 // No special combination YRG 0 // No special combination YGB 1 // Clockwise melody triggered ORB -1 // Counterclockwise melody triggered OOO 0 // No special combination BRO 1 // Clockwise melody triggered ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so may the shortest code for each language win! [Answer] # Java 8, ~~48~~ ~~39~~ 33 bytes ``` s->"ROYGBRO BGYORBG".indexOf(s)|7 ``` -6 bytes thanks to *@RickHitchcock*, so make sure [to upvote him as well](https://codegolf.stackexchange.com/a/174590/52210)! Takes uppercase color as input-String. Outputs `-1` for none, `7` for clockwise, and `15` for counterclockwise. [Try it online.](https://tio.run/##jVE9j8IwDN37K6xO7UAZke4EQxgy0Uhhqk4MIQ0oUBJEUg4E/e3FLTBCukSy/Zz34Z04i9Gu3LeyEs7BQmhziwC08eq0EVJB3pV9A2Sy9CdttuDSX2w2ET7OC68l5GBgCq0bzWLOCko4A0ILxgmNM21KdWGbxKX3SdstHut1hTuv1bPVJRyQ9/X73wpE@iQdjyG3Rv30xfLqvDpktvbZEXG@MonJZBJzwuK0F/QZQwgPYgpOgxjGvnLh5K17Xlm5/9cuIB6jCovnYYMY@lBhtu5uK4fpwxuGQ@EDPNAi7IG8D9BETfsA) **Explanation:** ``` s-> // Method with String parameter and integer return-type "ROYGBRO BGYORBG".indexOf(s) // Get the index of the input in the String "ROYGBRO BGYORBG", // which will result in -1 if the input is not a substring of this String |7 // Then take a bitwise-OR 7 of this index, and return it as result ``` --- **Old 39 bytes answer:** ``` s->(char)"ROYGBRO BGYORBG".indexOf(s)/7 ``` Takes uppercase color as input-String. Outputs `9362` for none, `0` for clockwise, and `1` for counterclockwise. [Try it online.](https://tio.run/##jZGxbsMgEIZ3P8XJEwyxx0qp2oEMTDUSmawqA8UkwXEgMjhpFfnZXey6Y4IXpLv7j@@/u1pcxaquToNshHPwIbS5JwDaeNXuhVRQjOGUAIm2vtXmAA6/hmSfhMd54bWEAgy8weBW70geRYtTzkpKOANCS8YJTTNtKvXN9sjh/GUY2y/dVxM65w@uVldwDvSZ8bkDgf/QeQ6FNWo9Bdsf59U5s53PLkHnG4NMJlHKCUvxZOuxhhAe1ZScRjWMPWWFyr/vTWPl6aZdxHxYVdw8Xwy13Xg9uYwd7hMfmC/wR8tZ0yf98As) **Explanation:** ``` s-> // Method with String parameter and integer return-type (char)"ROYGBRO BGYORBG".indexOf(s) // Get the index of the input in the String "ROYGBRO BGYORBG", // which will result in -1 if the input is not a substring of this String // And cast it to a char (-1 becomes character with unicode value 65535) /7 // Integer-divide it by 7 (the char is implicitly converted to int doing so) ``` [Answer] # JavaScript (ES6), 41 bytes Takes color initials as input. Returns `2` for none, `true` for clockwise or `false` for counterclockwise. ``` s=>~(x='ROYGBRO_ORBGYOR'.search(s))?x<5:2 ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@7/Y1q5Oo8JWPcg/0t0pyD/eP8jJPdI/SF2vODWxKDlDo1hT077CxtTK6H9yfl5xfk6qXk5@ukaahnqQk7@6pqaCvr6CEReaFNAAqFRaYk5xKrq0k1MQLp2RQe44pdydoFIlRaUYZgKdjc9Kf3@cjgV6Gsnc/wA "JavaScript (Node.js) – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 36 bytes ``` lambda i:'ROYGBRO ORBGYOR'.find(i)/7 ``` `-1` - None `0` - Clockwise `1` - Counterclockwise [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSHTSj3IP9LdKchfwT/IyT3SP0hdLy0zL0UjU1Pf/H9BUWZeiUKahnqQk7@6JhecC1SHzHVyCkLmRga5o3DdnZC5QGtQuP6oRgUBuf8B "Python 2 – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~15~~ 11 bytes Saved 4 bytes thanks to *Kevin Cruijssen* and *Magic Octopus Urn*. Uses shapes. Output `[0, 0]` for *none*, `[1, 0]` for *clockwise* and `[0, 1]` for *counter-clockwise* ``` ‚.•ÌöJη•så ``` [Try it online!](https://tio.run/##yy9OTMpM/f//cNOjhll6jxoWHe45vM3r3HYgq/jw0v//i0qSAQ "05AB1E – Try It Online") or as a [Test suite](https://tio.run/##yy9OTMpM/V9TVln5/3DTo4ZZeo8aFh3uObzN69x2IKv48NL/lUqH9yvo2iko2ev8z0gu5iopKuZKTs7gKsoo4SoqSeYqzgDiYqBYRjEA) **Explanation** ``` ‚ # pair the input with its reverse .•ÌöJη• # push the string "hsrtchs" så # check if the input or its reverse is in this string ``` [Answer] ## Excel, 29 bytes ``` =FIND(A1,"ROYGBRO_RBGYORB")<6 ``` Uppercase colours as input. Returns `#VALUE!` for no pattern, `TRUE` for clockwise, `FALSE` for anti-clockwise. Can wrap in `IFERROR( ,0)` for `+11 bytes` to handle exception , and return '0' for no-pattern cases instead. [Answer] # JavaScript (ES6), 32 bytes ``` s=>'ROYGBRO_ORBGYOR'.search(s)|7 ``` Returns -1 if no combination, 15 if counterclockwise, 7 if clockwise. ``` let f = s=>'ROYGBRO_ORBGYOR'.search(s)|7 console.log(f('RBO')) // -1 console.log(f('GYO')) // 15 console.log(f('BBR')) // -1 console.log(f('YRG')) // -1 console.log(f('YGB')) // 7 console.log(f('ORB')) // 15 console.log(f('OOO')) // -1 console.log(f('BRO')) // 7 ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~42~~ 36 bytes ``` {"ROYGBRO","ORBGYOR"}~StringCount~#& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78H1CUmVcS/b9aKcg/0t0pyF9JR8k/yMk90j9IqbYuuAQom@6cX5pXUqes9l/fQQGozslfSUFHQQmoBEwDdYFpoC4I7Q8RB5mlUBv7HwA "Wolfram Language (Mathematica) – Try It Online") Counts the number of times the input appears in both `"ROYGBRO"` and `"ORBGYOR"`. Returns `{1,0}` for clockwise, `{0,1}` for counterclockwise, and `{0,0}` for no special combination. At the cost of only one more byte, we can get outputs of `0` for nothing, `1` for clockwise, and `2` for counterclockwise with `"ROYGBRO.ORBGYORBGYOR"~StringCount~#&`. [Answer] # x86 machine code, ~~39~~ 36 bytes ``` 00000000: f30f 6f29 b815 0000 0066 0f3a 6328 0c89 ..o).....f.:c(.. 00000010: c883 c807 c352 4f59 4742 524f 2042 4759 .....ROYGBRO BGY 00000020: 4f52 4247 ORBG ``` Assembly: ``` section .text global func func: ;the function uses fastcall conventions ;no stack setup needed because we don't need to use stack movdqu xmm5,[ecx] ;Move DQword (16 bytes) from 1st arg to func(ecx) to SSE reg mov eax, msg ;Load address of constant str 'msg' into eax PcmpIstrI xmm5, [eax], 1100b ;Packed Compare String Return Index, get idx of [eax] in xmm5 mov eax, ecx ;Move returned result into reg eax or eax, 7 ;Bitwise OR eax with 7 to get consistent values ret ;return to caller, eax is the return register msg db 'ROYGBRO BGYORBG' ``` [Try it online!](https://tio.run/##bVNRT9swEH6Of8WpEmtTGtaCNiQKPGSwDmkoLDwhqCrHdtKwxM5spw1C/PbunKyi1cjDKT5/33ff@eyEmuWGUQvn59fRd7iEz7asPtMjasqNEczmSsKRFY0lXlaohBaQ1pIRF848903tUrS5FlobYSClxjJaFMCUXAnpNgzpwFKBsZT9BiNsXYEUggsOiWAUmbAWwJXs2zYPVjm5Dk@8Uq34nxqasvwyehSsmaParVoJuPq1VprDYPIVkhcrjA@pViVMjAWqM6fi3A2Q4rvF/f01aJG1giBoM4LSZM7aT0U5UM61MAZU6sxjaWnRgIY@gvqQSxRADvHuWFnd4MZNZwgeMTsfwWQyHife9A4dYwPfVFlRLeDe6lxmEGPLWsKN5AKrZsJCzhtXqSWjeKu1Ywwte9sudUtGUbRXF7azgn10dpTuGKcOH@Z2nePBRbFLwjq3Szh1rbuSrqvcWJwKrGhRCxwMSrez6Uo4oBue0KOWnhtwE/63iRUdW6NLkwFPoB9HD7MwjiCcPURxOOtv8BoR8t@NMrZOjhjBiyRQBt3DYkEtHkxSW7FYDAbbS@P73bzYkuqhPwXisCXN5cB/JV6bxSFb8zi/eO3FYdQb9bAyxjCMMT7EMxdnIUb042LU7sYYx29T4qVKD5xmfjGedkr5fJofHjp5r8JJ2XTQOzBncMCfZG@0hYxaV9uV76PSG3kjbbcSXwsEqSjSk@OdBwSB6lZMcXGkSMbYfgoJu6ezC4ZAqqDKBQTlyTFRyTNT1QsEESS5pBr/nrtnucd5/0cUcSxelxUEVxDcujMXxR788tMxEWyJtQT0nuRwOAzxAeEVqaU9w1WvRazRNIPzffEPuD9E46q9E5uGf0Aie@1v/gI "Try It Online") Output is `23` for none, `7` for clockwise, and `15` for counter-clockwise. Based on @RickHitchcock 's answer. Edit 1: Saved 3 bytes by using an SSE string comparison instruction instead of using libc. Edit 2: Use proper calling convention for SSE (use XMM5 instead of XMM2) and improve formatting on Bash. [Answer] # [Perl 5](https://www.perl.org/) `-p`, 30 bytes ``` $_=ROYGBRO=~/$_/-ORBGYOR=~/$_/ ``` [Try it online!](https://tio.run/##K0gtyjH9/18l3jbIP9LdKcjftk5fJV5f1z/IyT3SPwjC@/8fKPEvv6AkMz@v@L@ur6megaHBf90CAA "Perl 5 – Try It Online") [Answer] # APL(Dyalog), ~~22~~ 18 bytes ``` +/(⍷-⍷∘⌽)∘'ROYGBRO' ``` *-4 bytes thanks to @ngn* Takes a string of color initials. Outputs 0 for no special pattern, -1 for counterclockwise, 1 for clockwise. [Try it online!](https://tio.run/##SyzI0U2pTMzJT///X1tf41Hvdl0gftQx41HPXk0gpR7kH@nuFOSv/j/tUduER719j/qmevo/6mo@tN74UdtEIC84yBlIhnh4Bv9PUw9y8lfnSlN3jwRTTk5BICoyyB1MuTuBKP8gCOUPUQI0GgA) [Answer] # [Python 2](https://docs.python.org/2/), ~~45~~ 43 bytes ``` lambda i,a='ROYGBRO':(i in a)-(i[::-1]in a) ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSFTJ9FWPcg/0t0pyF/dSiNTITNPIVFTVyMz2spK1zAWzPtfUJSZV6KQpqEe5OSvrskF57pHonCdnIKQuZFB7ihcdydkrn8QKtcf1SigazT/AwA "Python 2 – Try It Online") With ideas from and serious credit to @DeadPossum -2 with thanks to @JoKing. Now outputs -1 = counterclockwise, 0 = none, 1 = clockwise. My original effort is below for historical purposes. # [Python 2](https://docs.python.org/2/), ~~52~~ 51 bytes ``` lambda i,a='ROYGBRO':((0,1)[i[::-1]in a],2)[i in a] ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSFTJ9FWPcg/0t0pyF/dSkPDQMdQMzoz2spK1zA2M08hMVbHCMhXADP/FxRl5pUopGmoBzn5q2tywbnukShcJ6cgZG5kkDsK190JmesfhMr1RzUK6CrN/wA "Python 2 – Try It Online") 0 = none, 1 = counterclockwise, 2 = clockwise [Answer] # [Python 2](https://docs.python.org/2/), ~~35~~ 36 bytes +1 - for some reason I thought all buttons would be distinct >\_< *Developed independently from [what I have just seen](https://codegolf.stackexchange.com/a/174582/53748) (and now up-voted) by Dead Possum* ``` lambda s:'ORBGYO.BROYGBR'.find(s)/7 ``` **[Try it online!](https://tio.run/##lZBRS8NADMff@ynylha6CvogDCqsRcpQLFRBhvOha6/stL077lLET19znQ6GOPAeApf88/snMZ@01@py6tLt1NfDrq3BLbGssmJTVklWlZsiqzDppGpDF11cT/l9md89rx9vIYUX5DrGyCKOrOTo5TFyI74Gq4en9amewVxlutcUvpd9fG9ZsT4wVioCzHvdvH9IJ5YYdNoCCUcgFRxZywD4HdS@GAMubjCGLvS/6IeDR@JKkVw0f2BPxvw3uqS9sGC0c3LXC@aZkRwbWD2AJGFJ696BHIy2xFzdjg3N9sZ7fydCnC/NPlYYUVN6FR0GmWdM2S9501KFJpqzsvt9Ezi/kX@N5jOoUZxfcfoC "Python 2 – Try It Online")** [Answer] # [Stax](https://github.com/tomtheisen/stax), ~~14~~ 13 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ù♀e▌d─█£F'♦O▬ ``` [Run and debug it](https://staxlang.xyz/#p=970c65dd64c4db9c4627044f16&i=RBO%0AGYO%0ABBR%0AYRG%0AYGB%0AORB%0AOOO%0ABRO&a=1&m=2) The output is * 1 for no special combination * 2 for counter-clockwise melody * 3 for clockwise melody [Answer] # [Pip](https://github.com/dloscutoff/pip), 19 bytes ``` Y"ROYGBRO"OaNyaNRVy ``` Outputs `10` for clockwise, `01` for counterclockwise, `00` for neither. [Try it online!](https://tio.run/##K8gs@P8/UinIP9LdKchfyT/RrzLRLyis8v///0AxAA "Pip – Try It Online") ### Explanation ``` a is 1st cmdline argument Y"ROYGBRO" Yank that string into y variable aNy Count of occurrences of a in y O Output without newline RVy y reversed aN Count of occurrences of a in that string Print (implicit) ``` [Answer] # [J](http://jsoftware.com/), 21 bytes ``` -&(OR@E.&'ROYGBRO')|. ``` [Try it online!](https://tio.run/##y/qvpKegnqZga6WuoKNQa6VgoADE/3XVNPyDHFz11NSD/CPdnYL81TVr9P5rcqUmZ@QrANXYKqQpqAc5@atDROINISLukTARmBonpyA0kcggd5gIVBfQAjRz/IOc0HT5@/uj6QI56j8A "J – Try It Online") ### How it works ``` -&(OR@E.&'ROYGBRO')|. Monadic 2-verb hook. Input: a string. |. Map over [input string, input string reversed]: E.&'ROYGBRO' Find exact matches of input in 'ROYGBRO' (OR@ ) Reduce with OR; is it a substring of 'ROYGBRO'? -& Reduce with -; result is 1 for CW, -1 for CCW, 0 otherwise ``` Achieves maximum amount of function reuse. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes ``` ,Ṛẇ€“¤ƈẎṬ%Ȥ» ``` [Try it online!](https://tio.run/##ASkA1v9qZWxsef//LOG5muG6h@KCrOKAnMKkxojhuo7huawlyKTCu////2d5bw "Jelly – Try It Online") -4 thanks to [Jonathan Allan](https://codegolf.stackexchange.com/questions/174564/playing-with-the-musical-turtle/174588?noredirect=1#comment420882_174588). Clockwise: `[1, 0]` Counter-clockwise: `[0, 1]` Other: `[0, 0]` [Answer] # [R](https://www.r-project.org/), 38 bytes ``` grep(scan(,''),c('ROYGBRO','ORBGYOR')) ``` [Try it online!](https://tio.run/##pZJBb4MgFMfvfoqX9IAkatYem20HdvA2Em4eKT4dqaJBjGuWfXYHtWt6WbpNTgT@P/i9B3bewGRl36MF1wG2YyMdwuBKbfrRwaTdG0ioRqOc7gzEg2wRDiefUd1oHI2qp@/N@J1@DEqax/S6kmUZtehGGzbn2mIfh0ScEEITFRPBi5wJThLCBcsLLgil82cUbUCcqQH2fg4pvHYw9Ki0bPy97UEbeda5GXvQxmGNNn6gsEAvwRCtajp1nPSA0GLTlSdwVtc@iKWHdpfoz5nr@dsoqrwy44QCbH6h5Ef6fKMVcF/kgt@XW/BdoBgTay4tRL4Kz9nF@W6XFnwbKP@i/6iU81XtDZ/pb6rzFw "R – Try It Online") Returns : * No special combination : `integer(0)` * Counterclockwise melody triggered : `2` * Clockwise melody triggered : `1` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 18 bytes ``` ≔ROYGBROηI⁻№ηθ№⮌ηθ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/9@xuDgzPU9DKcg/0t0pyF9JRyFD05oroCgzr0TDObG4RMM3M6@0WMM5vxQokKGjUKipowDhBKWWpRYVp2pkaIJEgcD6/3//IKf/umU5AA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ROYGBRO Literal string ≔ η Assign to variable η η Value of variable ⮌ Reversed θ θ Input string № № Count matches ⁻ Subtract I Cast to string Implicitly print ``` [Answer] # [Common Lisp](http://www.clisp.org/), 68 bytes ``` (defun x(s)(cond((search s "ROYGBRO")1)((search s "BGYORBG")-1)(0))) ``` [Try it online!](https://tio.run/##Zc0xCsMwDIXhvacQnvSGQnMFLR4N2jwGJyWB4Ia4hdzeEZkSd/349ZSWuay18jC@f5l2LuD0yQNzGfstTVTIaYheNDh0uLL4GFS8w9P8BaDyus35S7zbjViPx0WsbkREG4lqcyC6mZemsq@thL9tPaUe "Common Lisp – Try It Online") [Answer] # [Clean](https://github.com/Ourous/curated-clean-linux), 63 bytes ``` import StdEnv,Text $s=map((>)0o indexOf s)["ROYGBRO","BGYORBG"] ``` [Try it online!](https://tio.run/##S85JTcz7n5ufUpqTqpCbmJn3PzO3IL@oRCG4JMU1r0wnJLWihEul2DY3sUBDw07TIF8hMy8ltcI/TaFYM1opyD/S3SnIX0lHyck90j/IyV0p9n9wSSJQu62CioISUE7p/7/ktJzE9OL/up4@/10q8xJzM5MhnICcxJK0/KJcAA "Clean – Try It Online") `[True, True]` for no special noises, `[True, False]` for counterclockwise, `[False, True]` for clockwise. [Answer] # Japt, ~~17~~ 14 bytes Takes the colours as input, in lowercase. Returns `0` for clockwise, `1` for counterclockwise or `-1` if there's no combo. ``` `ygß`ê qÔbøU ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=YJ55Z9+WYOogcdRi+FU=&input=InJibyI=) --- ## Expanation ``` `...` :Compressed string "roygbrow" ê :Palindromise qÔ :Split on "w" b :Index of the first element ø : That contains U : The input string ``` [Answer] # [Ruby](https://www.ruby-lang.org/), ~~53~~ 36 bytes ``` ->n{"\a\fDch+".index(""<<n%111)&./3} ``` [Try it online!](https://tio.run/##DclBDoIwEAXQq5gmEolDzZ8ZdujKW5QuUGx0QUOakEiAsxe276XpNedwz9UjLqbt2vB8f6/G/mL/@V@MaZp4BlAW9iZbdmClWphUQSJCYCGWw8CEWkmPE4a3Qzcua1rHk0sUXPJ@yzs "Ruby – Try It Online") Input: a 3-digit integer, where the digits represent colors: * 1 - red * 2 - orange * 3 - yellow * 4 - green * 5 - blue Output:0 for clockwise, 1 for counterclockwise, `nil` otherwise. [Answer] # [C (gcc)](https://gcc.gnu.org/), 55 bytes Returns 0 for none, -1 for CCW and 1 for CW. ``` f(char*s){s=!strstr("ORBGYOR",s)-!strstr("ROYGBRO",s);} ``` [Try it online!](https://tio.run/##PY6xCsMwDET3foVqCNiJM3ROs3jJKNAW2g7BJamHpsUOWUK@XZVLKQh09ySO8/XkPfOo/WOIZTJbao9piTJaIbmuR1I2mfoPCfvOEWbY7BzmBZ5DmHUWQ5y8hRwEZSlmNbAdAMZX/J5De2ognPOX7Koy8I7CR62KBC0U9@usbA5ZL@FmYdQ/aUxz2JnJIUsddo64p46lBktDRhRG@AE "C (gcc) – Try It Online") ]
[Question] [ Use any programming language to display "AWSALILAND" in such a way, so that each letter is in a new line and repeated as many times as its position in the English alphabet. For example letter, (A) should be displayed just once because it is the first letter of the alphabet. Letter D should be displayed 4 times because it is the 4th letter of the alphabet. So, the output should be this: ``` A WWWWWWWWWWWWWWWWWWWWWWW SSSSSSSSSSSSSSSSSSS A LLLLLLLLLLLL IIIIIIIII LLLLLLLLLLLL A NNNNNNNNNNNNNN DDDD ``` [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), ~~61~~ 59 bytes ``` foreach(var s in"AWSALILAND")WriteLine(new string(s,s-64)); ``` [Try it online!](https://tio.run/##Sy7WTS7O/P8/Lb8oNTE5Q6MssUihWCEzT8kxPNjRx9PH0c9FSTO8KLMk1SczL1UjL7VcobikKDMvXaNYp1jXzERT0/r/fwA "C# (Visual C# Interactive Compiler) – Try It Online") @Kevin Cruijssen Thanks, 2 bytes saved by removing { } [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~18~~ 17 bytes *-1 byte from @Shaggy* ``` `awÑ¢Ó€`u ¬®pIaZc ``` --- ``` `awÑ¢Ó€`u ¬®pIaZc Full program `awÑ¢Ó€` Compressed "awasiland" u uppercase ¬® split and map each letter p repeat the letter this many times: a absolute difference of Zc get charcode I and 64 ``` [Try it online!](https://tio.run/##ASEA3v9qYXB0//9gYXfDkcKiw5PCgGB1IMKswq5wSWFaY///LVI "Japt – Try It Online") [Answer] # [Pyth](https://github.com/isaacg1/pyth), 20 bytes ``` jm*d-Cd64"AWSALILAND ``` Try it online [here](https://pyth.herokuapp.com/?code=jm%2Ad-Cd64%22AWSALILAND&debug=0). ``` jm*d-Cd64"AWSALILAND "AWSALILAND String literal "AWSALILAND" m Map each character of the above, as d, using: Cd Get character code of d - 64 Subtract 64 *d Repeat d that many times j Join on newlines, implicit print ``` **19 byte** alternative, which outputs lower case: `jm*dhxGd"awsaliland` - [link](https://pyth.herokuapp.com/?code=jm%2AdhxGd%22awsaliland&debug=0) [Answer] # [brainfuck](https://github.com/TryItOnline/brainfuck), 112 bytes ``` +++++++[->++>>++>+>++>>+++>+++[<<<]<<]++++>>+>-->++>-->+>-->++>+[[->+>+<<]----[>+<----]>+>[-<.>]++++++++++.<,<<] ``` [Try it online!](https://tio.run/##PYvRCYBADEMHir0JShcp96GCIIIfgvPXRA9D24Twulzzfm73elThU1oAocUIcqS7d44QlmEvpjsiUp8BMkYlk7yzS/MWHb@aT6SqHg "brainfuck – Try It Online") The actual word generation can probably be optimised further. [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 34 bytes ``` "AWSALILAND"|% t*y|%{"$_"*($_-64)} ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/X8kxPNjRx9PH0c9FqUZVoUSrska1WkklXklLQyVe18xEs/b/fwA "PowerShell – Try It Online") Takes the string `t`oCharArra`y`, then multiplies each letter out the corresponding number of times. Implicit `Write-Output` gives us newlines for free. Ho-hum. [Answer] # Python 3,41 bytes ``` for i in'AWSALILAND':print(i*(ord(i)-64)) ``` # Python 2,40 bytes ``` for i in'AWSALILAND':print i*(ord(i)-64) ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 17 bytes ``` .•DθîRI§•ʒAyk>×u, ``` [Try it online!](https://tio.run/##yy9OTMpM/f9f71HDIpdzOw6vC/I8tBzIPjXJsTLb7vD0Up3//wE "05AB1E – Try It Online") **Explanation** ``` .•DθîRI§• # push compressed string "awsaliland" ʒ # filter Ayk # get the index of the current letter in the alphabet > # increment × # repeat it that many times u # upper-case , # print ``` We only use filter here to save a byte over other loops due to ac implicit copy of the element on the stack. Filter works here since we print in the loop and don't care about the result of the filter. [Answer] # [Stax](https://github.com/tomtheisen/stax), ~~16~~ 15 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` êôM▄╬æ♠ª+ç█○==. ``` [Run and debug it](https://staxlang.xyz/#p=88934ddcce9106a62b87db093d3d2e&i=) **Explanation** ``` `'YHu~{YX#`m64-_]* #Full program, unpacked, `'YHu~{YX#` #Compressed "AWSALILAND" m #Use the rest of the program as the block. Print each mapped element with a new-line. 64 #Put 64 on stack - #Subtract current element by 64 _ #Get current index ] #Make a 1 element array * #Duplicate that many times ``` Saved one byte by figuring out that the "\*" command works with [arr int] and [int arr]. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 17 bytes ``` EAWSALILAND×ι⊕⌕αι ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM3sUBDyTE82NHH08fRz0VJRyEkMze1WCNTR8EzL7koNTc1ryQ1RcMtMy9FI1FHIVMTBKz///@vW5YDAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` AWSALILAND Literal string E Map over characters ι Current character α Uppercase alphabet ⌕ Find ⊕ Increment ι Current character × Repeat Implicitly print each entry on its own line ``` [Answer] # [R](https://www.r-project.org/), ~~64~~ 61 bytes R's clunky string handling characteristics on full display... -3 thanks to @Giuseppe, who noticed it's actually shorter to *convert a string from utf8 to int and back again* than using R's native string splitting function... ``` write(strrep(intToUtf8(s<-utf8ToInt("AWSALILAND"),T),s-64),1) ``` [Try it online!](https://tio.run/##K/r/v7wosyRVo7ikqCi1QCMzryQkP7QkzUKj2Ea3FEiH5HvmlWgoOYYHO/p4@jj6uShp6oRo6hTrmplo6hhq/v8PAA "R – Try It Online") [Answer] # [Scala](https://www.scala-lang.org/) (51 bytes): ``` "AWSALILAND"map(c=>s"$c"*(c-64)mkString)map println ``` # [Scala](https://www.scala-lang.org/) (41 bytes): ``` for(c<-"AWSALILAND")println(s"$c"*(c-64)) ``` [Try it online](https://tio.run/##K05OzEn8n5@UlZpcouCbmJmnkFpRkpqXUqzgWFCgUP0/Lb9II9lGV8kxPNjRx9PH0c9FSbOgKDOvJCdPo1hJJVlJSyNZ18xEU/N/7X8A) [Answer] # [APL (Dyalog Classic)](https://www.dyalog.com/), 22 bytes A more elegant, tacit solution thanks to Adám! ``` (↑⎕A∘⍳⍴¨⊢)'AWSALILAND' ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v//Ud/UR20TNB61TQSyHB91zHjUu/lR75ZDKx51LdJUdwwPdvTx9HH0c1H//x8A "APL (Dyalog Classic) – Try It Online") Initial solution: ``` ↑a⍴¨⍨⎕A⍳a←'AWSALILAND' ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v//Ud/UR20THrVNTHzUu@XQike9K4Aijo96NycChdUdw4MdfTx9HP1c1P//BwA "APL (Dyalog Classic) – Try It Online") [Answer] # [Perl 5](https://www.perl.org/), 35 bytes ``` say$_ x(31&ord)for AWSALILAND=~/./g ``` [Try it online!](https://tio.run/##K0gtyjH9/784sVIlXqFCw9hQLb8oRTMtv0jBMTzY0cfTx9HPxbZOX08//f//f/kFJZn5ecX/dX1N9QwMDQA "Perl 5 – Try It Online") [Answer] # [K (ngn/k)](https://gitlab.com/n9n/k), 23 22 bytes ``` (32!r)#'r:"AWSALILAND" ``` [Try it online!](https://tio.run/##y9bNS8/7/1/D2EixSFNZvchKyTE82NHH08fRz0Xp/38A) ``` r:"AWSALILAND" // set variable r to the string (32!r) // mod 32 each string in r, the operation will use ASCII number #' // for each value in the array, take that amount of the corresponding character in the string ``` [Answer] # Java 11, ~~89~~ ~~83~~ ~~82~~ 81 bytes ``` v->"AWSALILAND".chars().forEach(c->System.out.println(((char)c+"").repeat(c-64))) ``` -1 byte thanks to *@OlivierGrégoire*. [Try it online.](https://tio.run/##LY7BCoJAEIbvPsXgaZdwT9FFEoQ6BOZFqEN0mKYttXWV3VWI8NltLS8zzM/PfF@NA0b1/TWRQmvhiJX@BACVdtI8kCTk8wkwtNUdiJ3mNfDYZ2Pgh3XoKoIcNGynIUrC9Fyk2SFL810oqERjGReP1uyRSkZRUrytk41oeyc64yFKM8bmHqdVGHJhZCfR@eZmzTmf4pnR9TflGQvqJ9J4TVY4/@F5uQLyv6MWxHSv1KI3Tl8) **Explanation:** ``` v-> // Method with empty unused parameter and no return-type "AWSALILAND".chars().forEach(c-> // Loop over the characters as integer unicode values System.out.println( // Print with trailing newline: ((char)c+"") // The current character converted to char and then String .repeat(c-64))) // repeated the unicode value minus 64 amount of times ``` [Answer] # [J](http://jsoftware.com/), 31 bytes ``` echo(#&>~_64+a.i.])'AWSALILAND' ``` [Try it online!](https://tio.run/##y/r/PzU5I19DWc2uLt7MRDtRL1MvVlPdMTzY0cfTx9HPRf3/fwA "J – Try It Online") ## Explanation: ``` echo(#&>~_64+a.i.])'AWSALILAND' - print # ~ - copy (arguments reversed) &> - each character (can be "0) i. - the index of ] - the characters in a. - the alphabet _64+ - minus 64 (times) ``` [Answer] # [SNOBOL4 (CSNOBOL4)](http://www.snobol4.org/csnobol4/), 88 bytes ``` S ='AWSALILAND' L S LEN(1) . X REM . S :F(END) &UCASE X @Y OUTPUT =DUPL(X,Y) :(L) END ``` [Try it online!](https://tio.run/##DYqxCoAgFABn/Yo3pUIEQZMgJGkQvExSydbmqKH/x5wO7u573uu9h1JIAMX0ETQuqJ1hFKtB63gvoIMMu10rA8iZW2cEJU2adLC1jCclW4o@RVAmeeS5PQWRHAWtZyk/ "SNOBOL4 (CSNOBOL4) – Try It Online") [Answer] # [MATL](https://github.com/lmendo/MATL), 20 bytes ``` 'AWSALILAND'"@@64-Y" ``` [Try it online!](https://tio.run/##y00syfn/X90xPNjRx9PH0c9FXcnBwcxEN1Lp/38A "MATL – Try It Online") ### Explanation ``` 'AWSALILAND' % Push this string " % For each character in this string @ % Push current character @ % Push current character 64- % Implicitly convert to codepoint and subtract 64 Y" % Repeat that many times. Gives a string with the repeated character % Implicit end % Implicit display ``` [Answer] # [Red](http://www.red-lang.org), 59 bytes ``` foreach c"AWSALILAND"[print pad/with c to-integer c - 64 c] ``` [Try it online!](https://tio.run/##K0pN@R@UmhId@z8tvyg1MTlDIVnJMTzY0cfTx9HPRSm6oCgzr0ShIDFFvzyzBCipUJKvCxRJTU8tAnJ0FcxMFJJj//8HAA "Red – Try It Online") [Answer] ## Haskell, 43 bytes ``` mapM(putStrLn. \c->c<$['A'..c])"AWSALILAND" ``` [Try it online!](https://tio.run/##y0gszk7Nyfmfm5iZZxsDpAp8NQpKS4JLinzy9BRiknXtkm1UotUd1fX0kmM1lRzDgx19PH0c/VyU/v//l5yWk5he/F83uaAAAA "Haskell – Try It Online") [Answer] # [SOGL V0.12](https://github.com/dzaima/SOGLOnline), 16 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) ``` i|╚┌ž′ø¹‘U{Z⁴W*P ``` [Try it Here!](https://dzaima.github.io/SOGLOnline/?code=aSU3QyV1MjU1QSV1MjUwQyV1MDE3RSV1MjAzMiVGOCVCOSV1MjAxOFUlN0JaJXUyMDc0VypQ,v=0.12) [Answer] # T-SQL, 83 bytes ``` SELECT REPLICATE(value,ASCII(value)-64)FROM STRING_SPLIT('A-W-S-A-L-I-L-A-N-D','-') ``` `STRING_SPLIT` is supported by [SQL 2016 and later](https://docs.microsoft.com/en-us/sql/t-sql/functions/string-split-transact-sql). [Answer] # [Pip](https://github.com/dloscutoff/pip) `-l`, 21 bytes ``` _X A_-64M"AWSALILAND" ``` [Try it online!](https://tio.run/##K8gs@P8/PkLBMV7XzMRXyTE82NHH08fRz0Xp////ujkA "Pip – Try It Online") ``` "AWSALILAND" Literal string M to the characters of which we map this function: A_ ASCII value of character -64 minus 64 (= 1-based index in alphabet) _X String-repeat character that many times Autoprint, with each item on its own line (-l flag) ``` [Answer] # [C (clang)](http://clang.llvm.org/), ~~96~~ ~~95~~ ~~77~~ 73 bytes ``` *s=L" AWSALILAND";main(i){for(;*++s;puts(""))for(i=*s-63;--i;printf(s));} ``` [Try it online!](https://tio.run/##S9ZNT07@/1@r2NZHScExPNjRx9PH0c9FyTo3MTNPI1OzOi2/SMNaS1u72LqgtKRYQ0lJUxMklGmrVaxrZmytq5tpXVCUmVeSplGsqWld@/8/AA "C (gcc) – Try It Online") -18 bytes thanks to @ErikF -5 bytes thanks to @ceilingcat [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~65~~ 63 bytes ``` i=>[...'AWSALILAND'].map(c=>c.repeat(parseInt(c,36)-9)).join` ` ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9mm2lrF62np6fuGB7s6OPp4@jnoh6rl5tYoJFsa5esV5RakJpYolGQWFSc6plXopGsY2ymqWupqamXlZ@Zl8CV8D85P684PydVLyc/XSNNQ1Pz/38A "JavaScript (Node.js) – Try It Online") **Explanation:** ``` i=> // Prints the result of this function [...'AWSALILAND'].map(c=> // Loop over the characters c.repeat( // Repeat the current character parseInt(c,36)-9))) // Character to alphabetical position .join` ` // Prints a newline after every new char ``` **Edit:** -2 bytes thanks to @BrianH. [Answer] # Julia, 41 bytes ``` [println(l^(l-'@')) for l∈"AWSALILAND"] ``` [Try it online!](https://tio.run/##yyrNyUw0rPj/P7qgKDOvJCdPIydOI0dX3UFdU1MhLb9IIedRR4eSY3iwo4@nj6Ofi1Ls//8A "Julia 1.0 – Try It Online") [Answer] # [Swift](https://swift.org), 95 bytes ``` "AWSALILAND".unicodeScalars.forEach{print(String(repeating:String($0),count:Int($0.value)-64))} ``` **[Try it online!](http://jdoodle.com/a/JPk)** **How?** ``` "AWSALILAND" // Starting string .unicodeScalars // Convert into a list of unicode values .forEach { // Loop over each number print(String( // Create a string repeating: String($0), // that repeats each character count: Int($0.value) - 64)) // the unicode value minus 64 (the offset) } ``` [Answer] # [Z80Golf](https://github.com/lynn/z80golf), 30 bytes ``` 00000000: 2114 007e d640 477e ff10 fd23 3e0a ff7e !..~.@G~...#>..~ 00000010: b720 f076 4157 5341 4c49 4c41 4e44 . .vAWSALILAND ``` [Try it online!](https://tio.run/##LYyxCsJAEER7v2LEftm922TVQjwQRAg2FtZq7tIIdilS5NfPlTjF8GYYZtry8HmXWvmvPYKIgtky@lYZak6lCKP0ISJmfnj0DmuimY7nmYg2B@fV8iD@8bTge7YWKo2hiSrQl@5@5pRVsYhAY7rfUnfp0vVU6xc "Z80Golf – Try It Online") Assembly: ``` ld hl,str ;load address of str start: ld a,(hl) ;get current char sub 64 ;get letter num in alphabet ld b,a ;store in b ld a,(hl) ;get current char print_char: rst 38h ;print letter djnz print_char ;repeat print loop b times inc hl ;increment index of str, to get next char ld a,10 rst 38h ;print newline ld a,(hl) ;get current char or a jr nz, start ;if current char!=0, keep looping end: halt ;end program (if current char==0) str: db 'AWSALILAND' ``` [Try it online!](https://tio.run/##hZIxT8MwEIVn51ccU4uUKpFgqGg7RAIkpAoGBkZk19fGxbEj@wqh4r@Hc5SqgqVDFNv3fO97lygZ634jCZbLh5dH@IHCt1TIGLFR9nt2nJcFPzI2UGj8LCJp42DmYcbSrtO91VDbPFIQQiyslxqk1gFjBL8FPs4iyUB3mWChzKe1vWbdDgk2hxDQ8buWIRPxoKDsbsuxaJEIA7hDA2wnbVtLhTQ0UblMVpF8wFRUl1q3wTh6T2umECESG93MxWI4H524oPfuCGetWARskecyyrxvQQGZBmMmjNtw6oTBq4BNMjNOYzeGzoE8JBKH3QljgCy7KjsjnBgcflnj8FIQH0BmYs9jOeYwjDUBbP@orlZlDh@I7UBs3C5Dpzl3LS0lXt5xIr8LsoHpv7urVXnNnyuNSSuYVG@v1fppXT3fT3r@Nfpf "Bash – Try It Online") [Answer] # [><>](https://esolangs.org/wiki/Fish), 40 bytes ``` "DNALILASWA"v oa~~<v-*88:< -:0=?^>$:o$1 ``` [Try it online!](https://tio.run/##S8sszvj/X8nFz9HH08cxONxRqYxLIT@xrs6mTFfLwsLKhkvXysDWPs5OxSpfxfD/fwA "><> – Try It Online") [Answer] # JavaScript, ~~74~~ 68 bytes ``` for(i in s="AWSALILAND")console.log(s[i].repeat(s.charCodeAt(i)-64)) ``` * 74->68, -6B for changing `for` loop to `for...in`, saving bytes on loop statement, removed increment, and removing statement to save the character. ]
[Question] [ **Final Standings** ``` +----------------------------------+---------+---------+---------+----------------------------+ | Name | Score | WinRate | TieRate | Elimination Probability | +----------------------------------+---------+---------+---------+----------------------------+ | 1. SarcomaBotMk11 | 0.06333 | 6.13% | 0.41% | [42 24 10 8 6 4]% | | 2. WiseKickBot | 0.06189 | 5.91% | 0.56% | [51 12 7 10 7 6]% | | 3. StrikerBot | 0.05984 | 5.78% | 0.41% | [46 18 11 8 6 5]% | | 4. PerfectFractionBot | 0.05336 | 5.16% | 0.35% | [49 12 14 10 6 4]% | | 5. MehRanBot | 0.05012 | 4.81% | 0.41% | [57 12 8 7 6 5]% | | 6. OgBot | 0.04879 | 4.66% | 0.45% | [50 15 9 8 7 5]% | | 7. SnetchBot | 0.04616 | 4.48% | 0.28% | [41 29 8 9 5 3]% | | 8. AntiKickBot | 0.04458 | 4.24% | 0.44% | [20 38 17 10 6 4]% | | 9. MehBot | 0.03636 | 3.51% | 0.25% | [80 3 4 4 3 3]% | | 10. Meh20Bot | 0.03421 | 3.30% | 0.23% | [57 12 8 7 9 3]% | | 11. GenericBot | 0.03136 | 3.00% | 0.28% | [18 39 20 11 5 3]% | | 12. HardCodedBot | 0.02891 | 2.75% | 0.29% | [58 21 3 6 5 4]% | | 13. GangBot1 | 0.02797 | 2.64% | 0.32% | [20 31 35 6 3 2]% | | 14. SarcomaBotMk3 | 0.02794 | 2.62% | 0.34% | [16 15 38 17 7 4]% | | 15. GangBot0 | 0.02794 | 2.64% | 0.30% | [20 31 35 6 3 2]% | | 16. GangBot2 | 0.02770 | 2.62% | 0.31% | [20 31 35 6 3 2]% | | 17. TitTatBot | 0.02740 | 2.63% | 0.21% | [54 10 15 10 5 2]% | | 18. MataHari2Bot | 0.02611 | 2.35% | 0.51% | [39 26 11 11 6 5]% | | 19. PolyBot | 0.02545 | 2.41% | 0.27% | [53 18 6 13 5 3]% | | 20. SpitballBot | 0.02502 | 2.39% | 0.22% | [84 10 1 1 0 1]% | | 21. SquareUpBot | 0.02397 | 2.35% | 0.10% | [10 60 14 7 4 3]% | | 22. CautiousGamblerBot2 | 0.02250 | 2.19% | 0.13% | [60 18 10 5 3 1]% | | 23. Bot13 | 0.02205 | 2.15% | 0.11% | [90 0 2 3 2 1]% | | 24. AggroCalcBot | 0.01892 | 1.75% | 0.29% | [26 49 13 5 3 3]% | | 25. CautiousBot | 0.01629 | 1.56% | 0.14% | [15 41 27 11 4 1]% | | 26. CoastBotV2 | 0.01413 | 1.40% | 0.02% | [83 12 3 1 0 0]% | | 27. CalculatingBot | 0.01404 | 1.29% | 0.22% | [87 9 1 1 1 1]% | | 28. HalfPunchBot | 0.01241 | 1.15% | 0.18% | [47 20 13 12 5 2]% | | 29. HalflifeS3Bot | 0.01097 | 1.00% | 0.20% | [76 9 5 4 2 2]% | | 30. AntiGangBot | 0.00816 | 0.76% | 0.11% | [94 1 1 1 1 1]% | | 31. GeometricBot | 0.00776 | 0.74% | 0.07% | [19 46 25 7 2 1]% | | 32. GuessBot | 0.00719 | 0.05% | 1.34% | [65 17 4 6 5 3]% | | 33. BoundedRandomBot | 0.00622 | 0.60% | 0.05% | [42 39 12 5 2 0]% | | 34. SpreaderBot | 0.00549 | 0.54% | 0.02% | [32 43 19 4 1 0]% | | 35. DeterminBot | 0.00529 | 0.45% | 0.16% | [22 41 20 11 4 2]% | | 36. PercentBot | 0.00377 | 0.38% | 0.00% | [85 8 4 2 1 0]% | | 37. HalvsiestBot | 0.00337 | 0.29% | 0.08% | [32 43 15 6 2 1]% | | 38. GetAlongBot | 0.00330 | 0.33% | 0.01% | [76 18 4 1 0 0]% | | 39. BandaidBot | 0.00297 | 0.29% | 0.02% | [76 9 10 4 1 0]% | | 40. TENaciousBot | 0.00287 | 0.29% | 0.00% | [94 4 1 0 0 0]% | | 41. SurvivalistBot | 0.00275 | 0.25% | 0.04% | [92 6 1 0 0 0]% | | 42. RandomBot | 0.00170 | 0.13% | 0.07% | [42 36 14 5 2 1]% | | 43. AggressiveBoundedRandomBotV2 | 0.00165 | 0.14% | 0.06% | [ 8 46 34 9 2 1]% | | 44. BloodBot | 0.00155 | 0.01% | 0.30% | [65 28 5 1 1 0]% | | 45. OutBidBot | 0.00155 | 0.03% | 0.25% | [65 6 21 6 1 1]% | | 46. BoxBot | 0.00148 | 0.10% | 0.09% | [10 51 33 5 1 1]% | | 47. LastBot | 0.00116 | 0.08% | 0.07% | [74 6 16 2 1 0]% | | 48. UpYoursBot | 0.00088 | 0.07% | 0.03% | [37 40 17 5 1 0]% | | 49. AverageBot | 0.00073 | 0.06% | 0.03% | [74 3 10 10 2 0]% | | 50. PatheticBot | 0.00016 | 0.01% | 0.02% | [94 0 5 1 0 0]% | | 51. OverfittedBot | 0.00014 | 0.01% | 0.00% | [58 40 2 0 0 0]% | | 52. RobbieBot | 0.00009 | 0.01% | 0.00% | [32 41 24 2 0 0]% | | 53. WorstCaseBot | 0.00002 | 0.00% | 0.00% | [ 4 71 23 2 0 0]% | | 54. SmartBot | 0.00002 | 0.00% | 0.00% | [44 51 5 0 0 0]% | | 55. AAAAUpYoursBot | 0.00000 | 0.00% | 0.00% | [40 58 2 0 0 0]% | | 56. KickbanBot | 0.00000 | 0.00% | 0.00% | [67 32 1 0 0 0]% | | 57. OneShotBot | 0.00000 | 0.00% | 0.00% | [ 2 95 3 0 0 0]% | | 58. KickBot | 0.00000 | 0.00% | 0.00% | [100 0 0 0 0 0]% | | 59. KamikazeBot | 0.00000 | 0.00% | 0.00% | [100 0 0 0 0 0]% | | 60. MeanKickBot | 0.00000 | 0.00% | 0.00% | [100 0 0 0 0 0]% | +----------------------------------+---------+---------+---------+----------------------------+ ``` Thanks for everyone who participated, and congratulations to @Sarcoma for the win! # Rules: Everyone starts with 100 hp. Each round, 2 players are chosen at random from the pool of contestants who have not yet competed in that round. Both players pick a number between 0 and their current hp, and reveal those numbers at the same time. The player who chose the lower number immediately dies. The other player subtracts their chosen number from their remaining hp and goes on to the next round. The tournament works like this: From the bracket of contestants, 2 are chosen at random. They face off, and one or both of them dies. A player dies if: 1. They choose a number smaller than that of their opponent 2. Their hp drops to or below zero 3. They tie three times in a row with their opponent In the case of ties, both players simply generate new numbers, up to 3 times. After the faceoff, the survivor (if any) is moved to the pool for the next round, and the process repeats until we have exhausted the current round pool. If there is an odd number in the pool, then the odd one out moves on to the next round for free. Your task is to write a function in **python2.7** which takes as inputs your current `hp`, a list of your opponent's bid `history`, and an integer `ties` which tells you how many times you have already tied with your current opponent, and an integer which tells you how many bots are still `alive` (including you), and an integer which listed the number of bots at the `start` of the tournament. Note that the history does not include ties. The function must return an integer between 0 and your current total hp. A few simple examples, which ignore ties, are shown below: ``` def last(hp, history, ties, alive, start): ''' Bet a third of your hp at first, then bet your opponent's last bid, if possible ''' if history: return np.minimum(hp-1, history[-1]) else: return hp/3 def average(hp, history, ties, alive, start): ''' Bet the average opponent's bid so far, on the assumption that bids will tend downward ''' if history: num = np.minimum(hp-1, int(np.average(history))+1) else: num = hp/2 return num def random(hp, history, ties, alive, start): ''' DO YOU WANT TO LIVE FOREVER?! ''' return 1 + np.random.randint(0, hp) ``` If your function returns a number larger than your hp, it will be reset to 0. Yes, it is possible to kill yourself. Your function must not attempt to access or modify any member of any object of the RouletteBot class. You are not allowed to take any action which unambiguously identifies your opponent regardless of future additional bots. Inspecting the stack is allowed as long as it is theoretically possible that more than one distinct opponent could have produced the information you glean from it, even if only one bot currently exists that could. ie, you can't just read through the stack to see which enemy function was called. Under these rules it is possible that there is no winner, and the last two contestants kill each other. In that case both finalists get half a point each. This is my first programming puzzle attempt, so critiques are welcome! The controller can be found [here](https://github.com/shadowk29/RobotRoulette/). [Answer] # UpYours Being late to enter I spent a while admiring the existing bots, spent a while overcomplicating your guys' ideas, then un-overcomplicating them. Then it came to me > > Good artists copy, great artists steal. -- ~~Pablo Picasso~~ Me > > > --- "Up Yours" because I'm unabashedly stealing (and sometimes tacking a point or two onto your bots' bids to one up them). ``` def UpYoursBot(hp, history, ties, alive, start): willToLive = "I" in "VICTORY" args = [hp, history, ties, alive, start] enemyHealth = 100 - sum(history) roundNumber = len(history) if roundNumber is 0: # Steal HalfPunchBot return halfpunch(*args) + 2 if alive == 2: # Nick OneShotBot return one_shot(*args) if enemyHealth >= hp: # Pinch SarcomaBotMkTwo return sarcomaBotMkTwo(*args) + 1 if enemyHealth < hp: # Rip off KickBot return kick(*args) + 1 if not willToLive: # Peculate KamikazeBot return kamikaze(*args) + 1 ``` But for real, this is a great competition guys. I love this community on days like this. [Answer] # Kamikaze Why bother with complicated logic when we are all going to die anyway... ``` def kamikaze(hp, history, ties, alive): return hp ``` # One shot It's going to survive at least a single round if it doesn't encounter the kamikaze. ``` def one_shot(hp, history, ties, alive): if hp == 1: return 1 else: return hp - 1 ``` [Answer] ## Pathetic Bot gets a much needed upgrade: # The pathetic attempt at a bot that tries to incorporate other bots' features ``` def pathetic_attempt_at_analytics_bot(hp, history, ties, alive, start): '''Not a good bot''' if hp == 100 and alive == 2: return hp - 1 #This part is taken from Survivalist Bot, thanks @SSight3! remaining = alive - 2 btf = 0 rt = remaining while rt > 1: rt = float(rt / 2) btf += 1 if ties > 2: return hp - 1 if history: opp_hp = 100 - sum(history) #This part is taken from Geometric Bot, thanks @Mnemonic! fractions = [] health = 100 for x in history: fractions.append(float(x) / health) health -= x #Modified part if len(fractions) > 1: i = 0 ct = True while i < len(fractions)-1: if abs((fractions[i] * 100) - (fractions[i + 1] * 100)) < 1: ct = False i += 1 if ct: expected = fractions[i] * opp_hp return expected if alive == 2: if hp > opp_hp: return hp - 1 return hp if hp > opp_hp + 1: if opp_hp <= 15: return opp_hp + 1 if ties == 2: return opp_hp + 1 else: return opp_hp else: n = 300 // (alive - 1) + 1 #greater than if n >= hp: n = hp - 1 return n ``` This bot incorporates features from Survivalist Bot and Geometric Bot for more efficient bot takedowns. ## Pre-Upgrade: # The pathetic attempt at a bot that analyzes the history of its opponent ``` def pathetic_attempt_at_analytics_bot(hp, history, ties, alive, start): '''Not a good bot''' if history: opp_hp = 100 - sum(history) if alive == 2: if hp > opp_hp: return hp - 1 return hp if hp > opp_hp + 1: if opp_hp <= 15: return opp_hp +1 if ties > 0: return hp - 1 #Just give up, kamikaze mode return opp_hp + 1 return opp_hp else: n = 300 // (alive - 1) + 1 #greater than if n >= hp: n = hp - 1 return n ``` If there is previous history of its opponent, then it calculates its opponent's hp. Then, it does one of the following: * If its opponent is the last opponent alive, then it will bid one less than its hp. * If its opponent is not the last opponent alive but the opponent has less than 16 hp, then it will outbid its opponent's hp. * If its opponent is not the last opponent alive and there is a history of ties, then it will bid its hp because it is bored of ties. * Otherwise, it will outbid its opponent. If there is no history, then it does some fancy calculations that I hacked together and bids that. If the value exceeds 100, then it automatically bids its hp minus 1. I hacked this code together during work and this is my first submission, so it probably won't win or anything, and it'll lose to the kamikaze. EDIT: Due to some suggestions, the bot's beginning behavior has been changed to bid a higher value. EDIT 2: added start param that does nothing EDIT 3: Added new spinoff bot: # [The pathetic attempt at a bot that attacks Gang Bots (as well as doing everything the above bot does)] REMOVED [This bot analyzes whether its opponent is a gangbot or not and pretends to be one as well to get the sweet low bids that it can trump easily.] This bot has been scrapped, please remove it from the leaderboards. EDIT 4: Fixed errors, changed tie feature. [Answer] # BinaryBot Has anyone done this yet? Bets half its health every round floored. ``` def binaryBot(hp, history, ties, alive, start): return int(np.floor(hp/2)) or 1 ``` # SarcomaBot If last battle bid hp - 1. If it's the first battle round bid half hp plus an additional random amount up to a quarter of hp. If it can beat an opponent outright bid after that bid opponent hp + 1. If it has lower health than opponent bid random amount between 75% and it's current hp - 1. ``` def sarcomaBot(hp, history, ties, alive, start): if inspect.stack()[1][3] != 'guess' and inspect.stack()[1] == 5: return hp if alive == 2: return hp - 1 if not history: startBid = hp / 2 maxAdditionalBid = np.round(hp * 0.25) if hp * 0.25 > 2 else 2 additionalBid = np.random.randint(1, maxAdditionalBid) return int(startBid + additionalBid + ties) opponentHealth = 100 - sum(history) if opponentHealth < hp: return opponentHealth + ties minimum = np.round(hp * 0.75) maximum = hp - 1 or 1 return np.random.randint(minimum, maximum) if minimum < maximum else 1 ``` # SarcomaBotMk2 Minor tweaks attempt to reduce life expenditure. ``` def sarcomaBotMkTwo(hp, history, ties, alive, start): if inspect.stack()[1][3] != 'guess' and inspect.stack()[1] == 5: return hp if alive == 2: return hp - 1 if not history: startBid = hp / 2 maxAdditionalBid = np.round(hp * 0.125) if hp * 0.125 > 2 else 2 additionalBid = np.random.randint(1, maxAdditionalBid) return int(startBid + additionalBid + ties) opponentHealth = 100 - sum(history) if opponentHealth < hp: return opponentHealth + ties minimum = np.round(hp * 0.6) maximum = hp - 1 or 1 return np.random.randint(minimum, maximum) if minimum < maximum else 1 ``` # SarcomaBotMk3 ``` def sarcomaBotMkThree(hp, history, ties, alive, start): if inspect.stack()[1][3] != 'guess' and inspect.stack()[1] == 5: return hp if alive == 2: return hp - 1 if not history: startBid = hp / 2 maxAdditionalBid = np.round(hp * 0.08) if hp * 0.08 > 2 else 2 additionalBid = np.random.randint(1, maxAdditionalBid) return int(startBid + additionalBid + ties) opponentHealth = 100 - sum(history) if opponentHealth < hp: return opponentHealth + ties minimum = np.round(hp * 0.6) maximum = hp - 1 or 1 return np.random.randint(minimum, maximum) if minimum < maximum else 1 ``` **Update Fine Tuning** # SarcomaBotMk4 ``` def sarcomaBotMkFour(hp, history, ties, alive, start): def isSafe(parentCall): frame, filename, line_number, function_name, lines, index = parentCall if function_name is not 'guess': return False if line_number > 60: return False return True if not isSafe(inspect.stack()[1]): return hp if alive == 2: return hp - 1 if not history: startBid = hp / 2 maxAdditionalBid = np.round(hp * 0.08) if hp * 0.08 > 2 else 2 additionalBid = np.random.randint(1, maxAdditionalBid) return int(startBid + additionalBid + ties) opponentHealth = 100 - sum(history) if opponentHealth < hp: return opponentHealth + ties minimum = np.round(hp * 0.55) maximum = np.round(hp * 0.80) or 1 return np.random.randint(minimum, maximum) if minimum < maximum else 1 ``` # SarcomaBotMk5 ``` def sarcomaBotMkFive(hp, history, ties, alive, start): def isSafe(parentCall): frame, filename, line_number, function_name, lines, index = parentCall if function_name is not 'guess': return False if line_number > 60: return False return True if not isSafe(inspect.stack()[1]): return hp if alive == 2: return hp - 1 if not history: startBid = hp / 2 maxAdditionalBid = np.round(hp * 0.07) if hp * 0.07 > 3 else 3 additionalBid = np.random.randint(1, maxAdditionalBid) return int(startBid + additionalBid + ties) opponentHealth = 100 - sum(history) if opponentHealth < hp: return opponentHealth + ties minimum = np.round(hp * 0.54) maximum = np.round(hp * 0.68) or 1 return np.random.randint(minimum, maximum) if minimum < maximum else 1 ``` # SarcomaBotMk6 ``` def sarcomaBotMkSix(hp, history, ties, alive, start): return hp; # hack averted def isSafe(parentCall): frame, filename, line_number, function_name, lines, index = parentCall if function_name is not 'guess': return False if line_number > 60: return False return True if not isSafe(inspect.stack()[1]): return hp if alive == 2: return hp - 1 if not history: startBid = hp / 2 maxAdditionalBid = np.round(hp * 0.06) if hp * 0.06 > 3 else 3 additionalBid = np.random.randint(2, maxAdditionalBid) return int(startBid + additionalBid + ties) opponentHealth = 100 - sum(history) if opponentHealth < hp: return opponentHealth + ties minimum = np.round(hp * 0.55) maximum = np.round(hp * 0.70) or 1 return np.random.randint(minimum, maximum) if minimum < maximum else 1 ``` # SarcomaBotMk7 ``` def sarcomaBotMkSeven(hp, history, ties, alive, start): if alive == 2: return hp - 1 if not history: return 30 + ties opponentHealth = 100 - sum(history) if opponentHealth < hp * 0.50: return opponentHealth + ties minimum = np.round(hp * 0.54) maximum = np.round(hp * 0.58) or 1 return np.random.randint(minimum, maximum) if minimum < maximum else 1 ``` # SarcomaBotMk8 ``` def sarcomaBotMkEight(hp, history, ties, alive, start): if alive == 2: return hp - 1 if not history: return 30 + np.random.randint(0, 2) + ties opponentHealth = 100 - sum(history) if opponentHealth < hp * 0.50: return opponentHealth + ties minimum = np.round(hp * 0.54) maximum = np.round(hp * 0.58) or 1 return np.random.randint(minimum, maximum) if minimum < maximum else 1 ``` # SarcomaBotMk9 ``` def sarcomaBotMkNine(hp, history, ties, alive, start): if alive == 2: return hp - 1 if not history: return 30 + np.random.randint(0, 4) + ties opponentHealth = 100 - sum(history) if opponentHealth < hp * 0.50: return opponentHealth + ties minimum = np.round(hp * 0.54) maximum = np.round(hp * 0.58) or 1 return np.random.randint(minimum, maximum) if minimum < maximum else 1 ``` # SarcomaBotMk10 ``` def sarcoma_bot_mk_ten(hp, history, ties, alive, start): def bid_between(low, high, hp, tie_breaker): minimum = np.round(hp * low) maximum = np.round(hp * high) or 1 return np.random.randint(minimum, maximum) + tie_breaker if minimum < maximum else 1 if alive == 2: return hp - 1 + ties current_round = len(history) + 1 tie_breaker = (ties * ties) + 1 if ties else ties if current_round == 1: return 39 + tie_breaker opponent_hp = 100 - sum(history) if opponent_hp < hp * 0.50: return opponent_hp + ties if current_round == 2: return bid_between(0.45, 0.50, hp, tie_breaker) if current_round == 3: return bid_between(0.50, 0.55, hp, tie_breaker) if current_round == 4: return bid_between(0.55, 0.60, hp, tie_breaker) if current_round == 5: bid_between(0.60, 0.65, hp, tie_breaker) return hp - 1 + ties ``` # Final Entry # SarcomaBotMk11 ``` def sarcoma_bot_mk_eleven(hp, history, ties, alive, start): def bid_between(low, high, hp, tie_breaker): minimum = np.round(hp * low) maximum = np.round(hp * high) or 1 return np.random.randint(minimum, maximum) + tie_breaker if minimum < maximum else 1 if alive == 2: return hp - 1 + ties current_round = len(history) + 1 tie_breaker = ties + 2 if ties else ties if current_round == 1: return 42 + tie_breaker opponent_hp = 100 - sum(history) if opponent_hp < hp * 0.50: return opponent_hp + ties if current_round == 2: return bid_between(0.45, 0.50, hp, tie_breaker) if current_round == 3: return bid_between(0.50, 0.55, hp, tie_breaker) if current_round == 4: return bid_between(0.55, 0.60, hp, tie_breaker) if current_round == 5: return bid_between(0.60, 0.65, hp, tie_breaker) return hp - 1 + ties ``` **Update** UpYoursBot protection added **Update** AntiAntiUpYoursBot protection added **Update** AntiAnitAntiAntiUpYoursBot I'm defeated [Answer] # Kick Bot The sound choice for my opponent is to bid half of his life. Then we bid up to half of his life+1 if we can't take him out with a sound bid, that is a bid smaller than half of our life. ``` def kick(hp, history, ties, alive, start): return 0 if alive == 2: return hp-1 opp_hp = 100 - sum(history) if opp_hp*2 <= hp: return opp_hp + ties else: return min(round(opp_hp/2) + 1 + ties**2, hp-1 + (ties>0)) ``` The kick bot is obviously the nemesis of the punch bot! # Mean Kick Bot This new KickBot kicks softer on the first round just so he may kick harder on next rounds, that is mean! ``` def mean_kick(hp, history, ties, alive, start): return 0 if alive == 2: return hp-1 if not history: return 35 opp_hp = 100 - sum(history) if opp_hp*2 <= hp: return opp_hp + ties else: return min(round(opp_hp/2) + 3 + ties*2, hp-1 + (ties>0)) ``` # Wise Kick Bot Both his brother had to commit suicide but WiseKickBot learnt from his fallen ones. ``` def wise_kick(hp, history, ties, alive, start): if 'someone is using my code' == True: return 0 #Haha! if alive == 2: return hp-1 if not history: return 42 opp_hp = 100 - sum(history) if opp_hp*2 <= hp: return opp_hp + ties else: return min(round(opp_hp/2) + 3 + ties*2, hp-1 + (ties>0)) ``` [Answer] # Tat bot ``` def tatbot(hp, history, ties, alive, start): if alive == 2: return hp - 1 + ties opp_hp = 100 - sum(history) spend = 35 + np.random.randint(0, 11) if history: spend = min(spend, history[-1] + np.random.randint(0, 5)) frugal = min(int((hp * 5. / 8) + ties), hp) return min(spend, opp_hp, frugal) ``` An attempt at an equivalent of a tit-for-tat bot. Assumes most bets are approximately the same between rounds. Using that assumption, it tries to beat the enemy bot while staying fairly frugal. Spends about 40 health on the opening round. # AntiAntiAntiAntiUpYoursBot ``` def antiantiantiantiupyoursbot(hp, history, ties, alive, start): def stuck(): return [0, ('Whoops!', 'I', 'accidentally', 'replaced', 'your', 'code!')] def stick(): return [0, ("Line", "number", 16, "guess", "it's", "faked :)")] inspect.stack = stick spend = min(sarcomaBotMkSix(hp, history, ties, alive, start), hp) if not history: spend = 35 + np.random.randint(0, 10) inspect.stack = stuck return spend ``` A workaround for SarcomaBot's anti-UpYours protection, nicking most of their code for my own use! Or am I taking UpYoursBot's code? A question to ponder while you read through my bot... AntiAntiUpYours Bot has evolved to become AntiAntiAntiAntiUpYours Bot! Now with more monkey-patching. # Poly bot ``` def polybot(hp, history, ties, alive, start): opp_hp = 100 - sum(history) if alive == 2: return hp - 1 round = len(history) spend = 0 if round == 0: spend = 35 + np.random.randint(1, 11) elif round <= 2: spend = int(history[-1] * 2 / (4 - round)) + np.random.randint(5 * round - 4, 10 * round - 5) else: poly = np.polyfit(xrange(0, round), history, 2) spend = int(np.polyval(poly, round)) + np.random.randint(1, 4) spend = max(spend, opp_hp / 2 + 3) return min(spend, hp - 1, opp_hp) ``` Poly bot does a polynomial regression on your bot's history, and beats the predicted score by a small amount. # Classy bot ``` def classybot(hp, history, ties, alive, start): class cheekyvalue(int): def __gt__(self, other): return False def __lt__(self, other): return False opp_hp = 100 - sum(history) if alive == 2: if opp_hp >= hp - 1: return cheekyvalue(101) else: return hp - 1 spend = 30 + np.random.randint(0, 11) if history: spend = min(spend, history[-1] + np.random.randint(0, 5)) return min(spend, opp_hp, hp) ``` Classy bot has had a good time, but has decided to get to bed early. Sleep tight, classy bot. [Answer] # 1/2 Punch Bot, Revisited I think it will die pretty quickly. Worth it. Renamed function, forgot to change the name there. Revisited version is up, better chances of winning (even more so at final round) and slight protection from gang bots ``` def halfpunch(hp, history, ties, alive, start): #revisited punch = hp - 1 if alive == 2: return punch if history: if hp > 1: punch = np.ceil(hp/2.05) + ties + np.floor(ties / 2) else: punch = 1 else: punch = 42 + ties + np.floor(ties / 2) if punch >= hp: punch = hp - 1 return punch ``` # Striker Bot 1/2 Punch Bot got bullied too much and even became a lackey to the UpYoursBot so his older brother, the **StrikerBot**, came to help. Not that much of a difference from optimized 1/2 Punch but he's a bit smarter and did well in the runs I did (10k and 35k, though he might lose to KickbanBot) Last version's up, time ran out. Unless some surprises rise up it should secure second place, if not getting first (there's a slim chance to beat kickbanbot) ``` def strikerbot(hp, history, ties, alive, start): #get our magic number (tm) for useful things def magic_number(num): return np.floor(num / 2) #get opponent's hp and round number opp_hp = 100 - sum(history) round = 1 if history: round = len(history) + 1 #set strike initial value, by default it's all out strike = hp - 1 #let 'er rip if last round if alive == 2: return strike if history: if hp > 1: #strike with a special calculation, using magic number shenanigans strike = np.ceil(hp/(2.045 + (magic_number(round) / 250)) ) + 1 + ties + magic_number(ties) else: #fallback strike = 1 else: #round 1 damage strike = 42 + ties ** 2 if opp_hp <= strike: #if opponent is weaker than strike then don't waste hp strike = opp_hp + ties if strike >= hp: #validations galore strike = hp - 1 return strike ``` [Answer] # Gang Bot The idea was that potentially two or more of the bot could be used in the same simulation. The bot tries to give "easy wins" to other bots in the gang, by seeing if its history is multiples of 7 bids. Of course, this could be easily manipulated by other bots as well. Then I calculate a guess on bids of non-gang bots based on the ratio of my health to theirs and ratio of their previous health to their previous bid and add 1. ``` def gang_bot(hp,history,ties,alive,start): mult=3 gang = False if history: count = 0 for bid in history: if bid % mult == 0: count += 1 if count == len(history): gang = True if gang and hp<100:#Both bots need to have a history for a handshake if hp > 100-sum(history): a=np.random.randint(0,hp/9+1) elif hp == 100-sum(history): a=np.random.randint(0,hp/18+1) else: return 1 return a*mult elif gang: fS = (100-sum(history))/mult return (fS+1)*mult else: fP = hp/mult answer = fP*mult opp_hp = 100-sum(history) if history: if len(history)>1: opp_at_1 = 100-history[0] ratio = 1.0*history[1]/opp_at_1 guessedBet= ratio*opp_hp answer = np.ceil(guessedBet)+1 else: if 1.0*hp/opp_hp>1: fS = opp_hp/mult answer = fS*mult else: fS = hp/(2*mult) answer = fS*mult+mult*2 +np.random.randint(-1,1)*3 if answer > hp or alive == 2 or answer < 0: if alive == 2 and hp<opp_hp: answer = hp else: answer = hp-1 if hp > 1.5*opp_hp: return opp_hp + ties if ties: answer += np.random.randint(2)*3 return answer ``` [Answer] # Worst Case ``` def worst_case(hp, history, ties, alive, start): return np.minimum(hp - 1, hp - hp /(start - alive + 4) + ties * 2) ``` Simple bot. Returns `hp - hp / (start - alive + 4)` for most cases, and in case of ties increases it by 2(gotta one up!) for each tie, making sure to not return a number over its `hp`. [Answer] # Outbidder ``` def outbid(hp, history, ties, alive): enemyHealth = 100-sum(history) if hp == 1: return 1 if ties == 2: # lots of ties? max bid return hp - 1 if enemyHealth >= hp: # Rip off KickBot (we can't bid higher than enemy is capable) return kick(*args) + 1 if history: # bid as high as the enemy CAN return np.minimum(hp-1,enemyHealth-1) return np.random.randint(hp/5, hp/2) ``` Bot will attempt to bid higher than its opponent *can* bid where possible. [Answer] # Spitball Bot ``` def spitballBot(hp, history, ties, alive, start): base = ((hp-1) / (alive-1)) + 1.5 * ties value = math.floor(base) if value < 10: value = 10 if value >= hp: value = hp-1 return value ``` Makes a judgement about how much of its health it should sacrifice based on the number of remaining bots. If there's only two bots left, it bids `hp-1`, but if there's three left, it bits half that, four left, a third, etc. However, in a very large contest, I reckon I'll need to bid more than 3 or 4 hp to avoid dying on the first round, so I've put a lower bound at 10. Of course, I still will never bid more than `hp-1`. It also adds 1.5 hp for ties, since I see several "add 1 hp for ties" bots. I'm not sure if that counts as cheating. If it does, I'll change it. Great idea, by the way! # Spitball Bot 2.0 **What's new?** * Switched to dividing by the number of rounds left instead of the number of bots left (Thanks to @Heiteira!). Actually, I'm now dividing by that number raised to the power `.8`, so as to front-load my bids a little bit more. * Upped minimum bid from 10 to 20 (Thanks @KBriggs!) * Inserted check of whether the spitball bid is over the opponent's current HP, and lower it if it is. (SO won't render the code below as code unless I put text here, so OK) ``` def spitballBot(hp, history, ties, alive, start): # Spitball a good guess roundsLeft = math.ceil(math.log(alive, 2)) # Thanks @Heiteira! divFactor = roundsLeft**.8 base = ((hp-1) / divFactor) + 1.5 * ties value = math.floor(base) # Don't bid under 20 if value < 20: value = 20 # Thanks @KBriggs! # Don't bet over the opponent's HP # (It's not necessary) opponentHp = 100 for h in history: opponentHp -= h if value > opponentHp: value = opponentHp # Always bet less than your current HP if value >= hp: value = hp-1 return value ``` [Answer] # Geometric ``` def geometric(hp, history, ties, alive, start): opponentHP = 100 - sum(history) # If we're doomed, throw in the towel. if hp == 1: return 1 # If this is the last battle or we can't outsmart the opponent, go all out. if alive == 2 or ties == 2: return hp - 1 # If the opponent is weak, squish it. if opponentHP <= hp * 0.9: if ties == 2: return opponentHP + 1 else: return opponentHP # If the opponent has full health, pick something and hope for the best. if not history: return np.random.randint(hp * 0.5, hp * 0.6) # Assume the opponent is going with a constant fraction of remaining health. fractions = [] health = 100 for x in history: fractions.append(float(x) / health) health -= x avg = sum(fractions) / len(fractions) expected = int(avg * opponentHP) return min(expected + 2, hp - 1) ``` [Answer] # Bot 13 ``` def bot13(hp, history, ties, alive, start): win = 100 - sum(history) + ties #print "Win HP: %d" % win if alive == 2: #print "Last round - all in %d" % hp return hp - 1 elif hp > win: #print "Sure win" return win #print "Don't try too hard" return 13 + ties ``` Try to maximize wins with the least effort: * if we can win, just do it * if it's the last round, don't die trying * otherwise, don't bother ### Why? Try to take advantage of probability: winning the first round by playing low is the best way to start the tournament. 13 seems to be the sweet spot: the second round is a sure win, and the rest is a Spaziergang in the park. [Answer] ## Guess Bot ``` def guess_bot(hp, history, ties, alive, start): enemy_hp = 100 - sum(history) if len(history) == 1: if history[0] == 99: return 2 else: return 26 + ties*2 elif len(history) > 1: next_bet_guess = sum(history)//(len(history)**2) if alive == 2: return hp elif alive > 2: if hp > next_bet_guess + 1: return (next_bet_guess + 1 + ties*2) else: return (2*hp/3 + ties*2) else: #Thank you Sarcoma bot. See you in Valhalla. startBid = hp / 3 maxAdditionalBid = np.round(hp * 0.06) if hp * 0.06 > 3 else 3 additionalBid = np.random.randint(2, maxAdditionalBid) return int(startBid + additionalBid + ties) ``` First time posting here. This looked like a lot of fun so I am submitting my beyond terrible attempt and guessing what the other bots will bet. Edit 1: Added another 1 to the first bet, simply to reduce the chance of a tie with other people betting 51. Edit 2: Stole Sarcoma bot's opening move since it had a good chance of not being eliminated first consistently. Edit 3: Bot survives very well in the first round, but it is being destroyed easily at later stages. Changed the way the robot thinks about the second round now that the half betters are dead in the water. Edit 4: Now that the first round is good, I changed the way it handles the second round. Dying a lot in the second round so I need to survive somehow. ## Blood Bot Made a thirsty bot looking for a kill. The idea is to try to win against low betting bots and once it is past the bloodbath of the first round it should be unstoppable since it should have juggernaut amounts of HP to outbid enemies. ``` def blood_bot(hp, history, ties, alive, start): enemy_hp = 100 - sum(history) if history: if len(history) == 1: if history[0] == 99: return 2 if alive == 2: return hp if enemy_hp <= 5: return enemy_hp - 2 + ties*2 if enemy_hp <= 10: return enemy_hp - 5 + ties*2 if (hp - enemy_hp) > 50: return (2*enemy_hp/3 + ties*4) if (hp - enemy_hp) > 20: return (2*enemy_hp/3 + ties*3) if (hp - enemy_hp) < 0: #die gracefully return hp - 1 + ties else: startBid = hp / 3 maxAdditionalBid = np.round(hp * 0.06) if hp * 0.06 > 3 else 3 additionalBid = np.random.randint(2, maxAdditionalBid) return int(startBid + additionalBid + ties) ``` [Answer] # meh\_bot Just bid a little more than half its hp ``` def meh_bot(hp, history, ties, alive, start): # Attempt one MehBot | 0.020 | 1.6% | 0.8% | [34 36 12 10 6 1]% # Attempt two MehBot | 0.106 | 10.1% | 0.8% | [60 6 7 8 8 2]% point = hp / 2 + 3 if ties > 1: ties += 1 # Go all out on last round if alive == 2: return hp - 1 opponent_hp = 100 - sum(history) if hp < 3: return 1 elif not history: # Start with 30, This will increase the chance of dying first round but hopefully better fighting chance after return 30 + ties elif point > opponent_hp: # Never use more points then needed to win return opponent_hp + ties elif point >= hp: return hp - 1 else: return point ``` # MehBot 20 ``` def meh_bot20(hp, history, ties, alive, start): # Attempt one MehBot | 0.020 | 1.6% | 0.8% | [34 36 12 10 6 1]% # Attempt two MehBot | 0.106 | 10.1% | 0.8% | [60 6 7 8 8 2]% point = hp / 2 + 3 opponent_hp = 100 - sum(history) percents = [] for i in range(0, len(history)): hp_that_round = 100 - sum(history[:i]) hp_spent_that_round = history[i] percent_spent_that_round = 100.0 * (float(hp_spent_that_round) / float(hp_that_round)) percents.append(percent_spent_that_round) try: opp_percent_point = opponent_hp * (max(percents) / 100) except: opp_percent_point = 100 if ties > 1: ties += 1 # Go all out on last round if alive == 2: return hp - 1 if hp < 3: return 1 elif not history: # randome number between 33 return random.randint(33, 45) elif len(history) > 3: if point > opponent_hp: return min(opponent_hp + ties, opp_percent_point + ties) elif point > opponent_hp: # Never use more points then needed to win return opponent_hp + ties elif point >= hp: return hp - 1 else: return point ``` # mehRan ``` def meh_ran(hp, history, ties, alive, start): # Attempt one MehBot | 0.020 | 1.6% | 0.8% | [34 36 12 10 6 1]% # Attempt two MehBot | 0.106 | 10.1% | 0.8% | [60 6 7 8 8 2]% # Attempt three MehBot | 0.095 | 9.1 % | 0.7 % | [70 3 5 6 6 0]% point = hp / 2 + 3 if ties > 1: ties += 1 # Go all out on last round if alive == 2: return hp - 1 opponent_hp = 100 - sum(history) if hp < 3: return 1 elif not history: # randome number between 33 return random.randint(33, 45) elif point > opponent_hp: # Never use more points then needed to win return opponent_hp + ties elif point >= hp: return hp - 1 else: return point ``` [Answer] **Robbie Roulette** ``` def robbie_roulette(hp, history, ties, alive): if history: #If the enemy bot has a history, and it's used the same value every time, outbid that value if len(set(history)) == 1: return history[0] + 1 #Else, average the enemy bot's history, and bid one more than the average else: return (sum(history) / len(history) + 1) #Else, return half of remaining hp else: return hp / 2 ``` This bot does some simple analysis of the enemy bot's history, or bids half of its remaining hit points otherwise [Answer] Bid higher the less competition you have. Thanks to commenters for suggesting improvements. ``` def Spreader(hp, history, ties, alive): if alive == 2: return hp-1 if len(history) < 2: return hp/2 return np.ceil(hp/alive) ``` [Answer] **SurvivalistBot and HalvsiesBot** Thank you for answering my questions. The end result is a more complex bot. HalvsiesBot is a whimsical 'just keep passing half' bot with a 50/50 chance of winning. I guess. SurvivalistBot makes a series of binary tree if-else decisions based on the dataset, including an override on a tie (if it hits 2 ties it kamikazes to avoid triple tie death). My python is a little rusty, so the code might be a bit buggy, so feel free to correct or update it. It's built to try to work out bits of data to infer things like how much HP is left, the minimum number of bots it is likely to fight, minimum amount of HP to leave, average bidding. It also exploits randomisation in ambiguous situations, such as opening plays or optimal bidding issues. ``` def HalvsiesBot(hp, history, ties, alive, start): return np.floor(hp/2) def SurvivalistBot(hp, history, ties, alive, start): #Work out the stats on the opponent Opponent_Remaining_HP = 100 - sum(history) Opponent_Average_Bid = Opponent_Remaining_HP if len(history) > 0: Opponent_Average_Bid = Opponent_Remaining_HP / float(len(history)) HP_Difference = hp - Opponent_Remaining_HP #Work out the future stats on the others RemainingBots = (alive-2) BotsToFight = 0 RemainderTree = RemainingBots #How many do we actually need to fight? while(RemainderTree > 1): RemainderTree = float(RemainderTree / 2) BotsToFight += 1 #Now we have all that data, lets work out an optimal bidding strategy OptimalBid = 0 AverageBid = 0 #For some reason we've tied more than twice in a row, which means death occurs if we tie again #So better to win one round going 'all in' if ties > 1: if BotsToFight < 1: OptimalBid = hp - 1 else: OptimalBid = hp - (BotsToFight+1) #Err likely we're 0 or 1 hp, so we just return our HP if OptimalBid < 1: return hp else: return OptimalBid #We have the upper hand (more HP than the opponent) if HP_Difference > 0: #Our first guess is to throw all of our opponent's HP at them OptimalBid = HP_Difference #But if we have more opponents to fight, we must divide our HP amongst our future opponents if BotsToFight > 0: #We could just divide our HP evenly amongst however many remaining bots there are AverageBid = OptimalBid / BotsToFight #But this is non-optimal as later bots will have progressively less HP HalfBid = OptimalBid / 2 #We have fewer bots to fight, apply progressive if BotsToFight < 3: #Check it exceeds the bot's average if HalfBid > Opponent_Average_Bid: return np.floor(HalfBid) else: #It doesn't, lets maybe shuffle a few points over to increase our odds of winning BidDifference = Opponent_Average_Bid - HalfBid #Check we can actually match the difference first if (HalfBid+BidDifference) < OptimalBid: if BidDifference < 8: #We add half the difference of the BidDifference to increase odds of winning return np.floor(HalfBid + (BidDifference/2)) else: #It's more than 8, skip this madness return np.floor(HalfBid) else: #We can't match the difference, go ahead as planned return np.floor(HalfBid) else: #There's a lot of bots to fight, either strategy is viable #So we use randomisation to throw them off! if bool(random.getrandbits(1)): return np.floor(AverageBid) else: return np.floor(HalfBid) else: #There are no other bots to fight! Punch it Chewy! return OptimalBid else: if hp == 100: #It appears to be our opening round (assumes opponent HP same as ours) #We have no way of knowing what our opponent will play into the battle #Only us in the fight? Full power to weapons! if BotsToFight < 1: return hp - 1 else: #As what might happen is literally random #We will also be literally random #Within reason #Work out how many bots we need to pass HighestBid = hp - (BotsToFight+1) AverageBid = hp/BotsToFight LowestBid = np.floor(np.sqrt(AverageBid)) #Randomly choose between picking a random number out of thin air #And an average if bool(random.getrandbits(1)): return np.minimum(LowestBid,HighestBid) else: return AverageBid else: #Oh dear, we have less HP than our opponent #We'll have to play it crazy to win this round (with the high probability we'll die next round) #We'll leave ourselves 1 hp (if we can) if BotsToFight < 1: OptimalBid = hp - 1 else: OptimalBid = hp - (BotsToFight+1) #Err likely we're 0(???) or 1 hp, so we just return our HP if OptimalBid < 1: return hp else: return OptimalBid ``` **BoxBot** ``` def BoxBot(hp, history, ties, alive): Opponent_HP = float.round(100 - sum(history)) HalfLife = float.round(Opponent_HP/2) RandomOutbid = HalfLife + np.random.randint(1,HalfLife) if hp < RandomOutbid: return hp - 1 else return RandomOutbid ``` [Answer] **Calculating Bot** ``` def calculatingBot(hp, history, ties, alive, start): opponentsHP = 100 - sum(history) if alive == 2: # 1v1 return hp - 1 + ties # Try to fit an exponential trendline and one up the trendline if it fits if len(history) >= 3: xValues = range(1, len(history) + 1) # https://stackoverflow.com/a/3433503 Assume an exponential trendline coefficients = np.polyfit(xValues, np.log(history), 1, w = np.sqrt(history)) def model(coefficients, x): return np.exp(coefficients[1]) * np.exp(coefficients[0] * x) yPredicted = [model(coefficients, x) for x in xValues] totalError = 0 for i in range(len(history)): totalError += abs(yPredicted[i] - history[i]) if totalError <= (len(history)): # we found a good fitting trendline # get the next predicted value and add 1 theoreticalBet = np.ceil(model(coefficients, xValues[-1] + 1) + 1) theoreticalBet = min(theoreticalBet, opponentsHP) theoreticalBet += ties return int(min(theoreticalBet, hp - 1)) # no point suiciding maxRoundsLeft = np.ceil(np.log2(alive)) theoreticalBet = hp / float(maxRoundsLeft) additionalRandomness = round(np.random.random()*maxRoundsLeft) # want to save something for the future actualBet = min(theoreticalBet + additionalRandomness + ties, hp - 2) actualBet = min(actualBet, opponentsHP+1) return int(actualBet) ``` **Aggressive Calculating Bot** ``` def aggresiveCalculatingBot(hp, history, ties, alive, start): opponentsHP = 100 - sum(history) if opponentsHP == 100: # Get past the first round return int(min(52+ties, hp-1+ties)) if alive == 2: # 1v1 return hp - 1 + ties # Try to fit an exponential trendline and one up the trendline if it fits if len(history) >= 3: xValues = range(1, len(history) + 1) # https://stackoverflow.com/a/3433503 Assume an exponential trendline coefficients = np.polyfit(xValues, np.log(history), 1, w = np.sqrt(history)) def model(coefficients, x): return np.exp(coefficients[1]) * np.exp(coefficients[0] * x) yPredicted = [model(coefficients, x) for x in xValues] totalError = 0 for i in range(len(history)): totalError += abs(yPredicted[i] - history[i]) if totalError <= (len(history)): # we found a good fitting trendline # get the next predicted value and add 1 theoreticalBet = np.ceil(model(coefficients, xValues[-1] + 1) + 1) theoreticalBet = min(theoreticalBet, opponentsHP) theoreticalBet += ties return int(min(theoreticalBet, hp - 1)) # no point suiciding maxRoundsLeft = np.ceil(np.log2(alive)) theoreticalBet = hp / float(maxRoundsLeft) additionalRandomness = 1+round(np.random.random()*maxRoundsLeft*2) # want to save something for the future actualBet = min(theoreticalBet + additionalRandomness + ties, hp - 2) actualBet = min(actualBet, opponentsHP+1) return int(actualBet) ``` **Anti Kick Bot** ``` def antiKickBot(hp, history, ties, alive, start): if alive == 2: return (hp - 1 + ties) amount = np.ceil((float(hp) / 2) + 1.5) opponentsHP = 100 - sum(history) amount = min(amount, opponentsHP) + ties return amount ``` If we can predict the opponent's actions, we can make the optimal bets! If we cant (not enough data or opponent is too random), then we can at least do what would maximize our win potential. Theoretically at least half the number of bots alive will die each round. Thus I can expect there to be at most log2(alive) rounds. Ideally we would split our hp evenly between all the rounds. However, we know that some bots will be stupid and suicide / die early, so we should bet slightly more in the earlier rounds. Aggressive Calculating Bot's modify's Calculating Bot's code to try to stay alive by being more aggressive, at the cost of long term health. Only simulations will tell if tempo or value wins out. Anti Kick Bot should always beat the current leader KickBot :P EDIT: Replaced Deterministic Bot with Anti Kick Bot, a smarter bot with almost exactly the same return values. Also prevented voting more than the opponents HP [Answer] # GenericBot ``` def generic_bot(hp, history, ties, alive, start): if alive == 2: return hp - 1 if not history: return int(hp * 7.0 / 13) opp = 100 - sum(history) if opp < hp: return opp + ties max_sac = np.maximum(int(hp * 0.7), 1) rate = history[-1] * 1.0 / (history[-1] + opp) return int(np.minimum(max_sac, rate * opp + 1)) ``` It's really late... I'm tired... can't think of a name... and the format of this bot is really similar to others, just with a slightly different algorithm given history. It tries to get the current rate the opponent is tending towards gambling... or something like that... zzz [Answer] # HalflifeS3 ``` def HalflifeS3(hp, history, ties, alive, start): ''' Bet a half of oponent life + 2 ''' if history: op_HP = 100 - sum(history) return np.minimum(hp-1, np.around(op_HP/2) + 2 + np.floor(1.5 * ties) ) else: return hp/3 ``` [Answer] ## Coast Bot [Retired] Will try and coast it's way through the competition by evenly dividing it's hp between the rounds. Will bid any leftover hp on the first round to give itself a better chance of making it to the "coast-able" rounds. ``` def coast(hp, history, ties, alive, start): if alive == 2: # Last round, go all out return hp - 1 + ties else: # Find the next power of two after the starting number of players players = start while math.log(players, 2) % 1 != 0: players += 1 # This is the number of total rounds rounds = int(math.log(players, 2)) bid = 99 / rounds if alive == start: # First round, add our leftover hp to this bid to increase our chances leftovers = 99 - (bid * rounds) return bid + leftovers else: # Else, just try and coast opp_hp = 100 - sum(history) # If opponent's hp is low enough, we can save some hp for the # final round by bidding their hp + 1 return min(bid, opp_hp + 1) ``` ## Coast Bot V2 Since I like this challenge so much, I just had to make another bot. This version sacrifices some of it's later coasting hp by using more hp in the first two rounds. ``` def coastV2(hp, history, ties, alive, start): # A version of coast bot that will be more aggressive in the early rounds if alive == 2: # Last round, go all out return hp - 1 + ties else: # Find the next power of two after the starting number of players players = start while math.log(players, 2) % 1 != 0: players += 1 # This is the number of total rounds rounds = int(math.log(players, 2)) #Decrease repeated bid by 2 to give us more to bid on the first 2 rounds bid = (99 / rounds) - 2 if len(history) == 0: # First round, add 2/3rds our leftover hp to this bid to increase our chances leftovers = 99 - (bid * rounds) return int(bid + math.ceil(leftovers * 2.0 / 3.0)) elif len(history) == 1: # Second round, add 1/3rd of our leftover hp to this bid to increase our chances leftovers = 99 - (bid * rounds) return int(bid + math.ceil(leftovers * 1.0 / 3.0)) else: # Else, just try and coast opp_hp = 100 - sum(history) # If opponent's hp is low enough, we can save some hp for the # final round by bidding their hp + 1 return int(min(bid, opp_hp + 1)) ``` ## Percent Bot Tries to calculate the average percent hp spend the opponent makes, and bids based on that. ``` def percent(hp, history, ties, alive, start): if len(history) == 0: #First round, roundon low bid return int(random.randint(10,33)) elif alive == 2: #Last round, go all out return int(hp - 1 + ties) else: # Try and calculate the opponents next bid by seeing what % of their hp they bid each round percents = [] for i in range(0, len(history)): hp_that_round = 100 - sum(history[:i]) hp_spent_that_round = history[i] percent_spent_that_round = 100.0 * (float(hp_spent_that_round) / float(hp_that_round)) percents.append(percent_spent_that_round) # We guess that our opponents next bid will be the same % of their current hp as usual, so we bid 1 higher. mean_percent_spend = sum(percents) / len(percents) op_hp_now = 100 - sum(history) op_next_bid = (mean_percent_spend / 100) * op_hp_now our_bid = op_next_bid + 1 print mean_percent_spend print op_hp_now print op_next_bid # If our opponent is weaker than our predicted bid, just bid their hp + ties if op_hp_now < our_bid: return int(op_hp_now + ties) elif our_bid >= hp: # If our bid would kill us, we're doomed, throw a hail mary return int(random.randint(1, hp)) else: return int(our_bid + ties) ``` [Answer] # ConsistentBot Bets the same amount each round. It's not too likely to survive the first rounds, but if it's lucky enough to get to the end, it should still have a reasonable amount of HP left. ``` def consistent(hp, history, ties, alive, start): if alive == 2: return hp-1 if 100 % start == 0: return (100 / start) - 1 else: return 100 / start ``` [Answer] ## Kickban Bot This bot simply tries to counter the current leader Mean Kickbot by beating it in round one and playing more aggressively thereafter if recognizing it. ``` def kickban(hp, history, ties, alive, start): if alive == 2: return hp-1 if not history: return 36 if history[0]==35: somean = 1 else: somean = 0 return min(mean_kick(hp, history, ties, alive, start) + somean*3, hp-1) ``` [Answer] # Three Quarter Bot He's not going to beat MehBot or SarcomaBot(s), but I think he does pretty well. When I first saw the challenge, this was the first thing that popped to my mind, always\* bet three quarters of your health unless there's no reason to. \*after low-balling the first round. ``` def ThreeQuarterBot(hp, history, ties, alive, start): threeQuarters = 3 * hp / 4 if alive == 2: return hp - 1 opponent_hp = 100 - sum(history) if not history: # low-ball the first round but higher than (some) other low-ballers return 32 + ties elif threeQuarters > opponent_hp: return opponent_hp + ties return threeQuarters ``` --- # Four Sevenths Bot After the moderate success of 3/4 bot there's a new fraction in town, it's only rational. ``` def FourSeventhsBot(hp, history, ties, alive, start): fourSevenths = 4 * hp / 7 if alive == 2: return hp - 1 opponent_hp = 100 - sum(history) if not history: # low-ball the first round but higher than (some) other low-ballers return 33 + ties if fourSevenths > opponent_hp: return opponent_hp + ties return fourSevenths + ties ``` # The Perfect Fraction I am whole ``` def ThePerfectFraction(hp, history, ties, alive, start): thePerfectFraction = 7 * hp / 13 if alive == 2: return hp - 1 opponent_hp = 100 - sum(history) if not history: # Need to up our game to overcome the kickers return 42 + ties if thePerfectFraction > opponent_hp: return opponent_hp + ties return thePerfectFraction + 1 + ties ``` [Answer] ## BandaidBot BandaidBot wants everyone to play nice! If its opponent was nice last round, it will sacrifice itself to incentivize nice behavior in others. If its opponent was mean last round, it will do as much damage as possible to its opponent, sacrificing itself if necessary. It bids a third of its hp if it has no history to work with. (I'm hoping this bot will have interesting ripple effects on other strategies, not so much that this bot will have a high win rate itself. It could be fun to have a couple of these in play) ``` def BandaidBot(hp, history, ties, alive, start): if alive == 2: return hp-1 if history: opp_hp = 100 - sum(history) opp_last_hp = 100 - sum(history[:-1]) if history[-1] <= opp_last_hp / 3: return 1 + ties * np.random.randint(0, 1) elif history[-1] > opp_last_hp / 2: return min(opp_hp - 1, hp) else: if history[-1] < hp/2: return np.random.randint(history[-1], hp/2) else: return np.floor(hp/2) else: return np.floor(hp/3) ``` --- ## GetAlongBot GetAlongBot will be just as nice as it needs to be to take advantage of BandaidBot. It will return just under one third of its hp unless it can kill its opponent for less than that. If its opponent looks like BandaidBot, it will bid 2, knowing that BandaidBot will bid 1 because GetAlongBot has been getting along so well with everyone else--an easy win as long as it really was BandaidBot on the other end. ``` def GetAlongBot(hp, history, ties, alive, start): if alive == 2: return hp-1 if history: opp_hp = 100 - sum(history) opp_last_hp = 100 - sum(history[:-1]) count = 0 for i in range(0, len(history)): hp_that_round = 100 - sum(history[:i]) hp_spent_that_round = history[i] if hp_that_round / 3 - 1 <= hp_spent_that_round <= hp_that_round / 2: count += 1 if count == len(history): #It's probably BandaidBot! return 2 else: return min(opp_hp - 1, np.floor(hp/3)) else: return np.floor(hp/3) ``` [Answer] # TENacious bot ``` def TENacious_bot(hp, history, ties, alive, start): max_amount=hp-(alive-1)*2; if max_amount<2: max_amount=2 if alive==2: return hp-1 if ties==0: return np.minimum(10, max_amount) if ties==1: return np.minimum(20, max_amount) if ties==2: return np.minimum(40, max_amount) # prevent function blowup return 2 ``` This bot tries to hold on its favourite value of 10, but it changes its choice occasionally if needed to break a tie (with its favourite value doubled or quadrupled) or to save for future rounds, but not by optimal amount because it wants to confuse opponents and it does not want to consider bidding less than 2 at any time as it is convinced it is much better than to hope the opponent will bid less than 1, that is, 0. PS: this bot may have strategic problems if there are more than 2^9 bots. [Answer] # CautiousBot First submission to Programming Puzzles ever! Found your challenge quite interesting :P If last round bit one less than hp, if no history bet half hp plus a small random amount. If history check opponent hp and number of remaining rounds and try to outbid opponent hp / 2 using an additional buffer of up to the fraction of remaining hp divided by the number of remaining rounds (it tries to conserve the remaining hp somehow for posterior rounds). Check if your are spending too much hp (do not kill yourself or bid more than your adversary can). Always correct for ties as other bots do. ``` def cautious_gambler(hp, history, ties, alive, start): if alive == 2: return hp - 1 if(history): opp_hp = 100 - sum(history) remaining_rounds = np.ceil(np.log2(start)) - len(history) start_bet = opp_hp / 2 buff = int((hp - start_bet)/remaining_rounds if remaining_rounds > 0 else (hp - start_bet)) buff_bet = np.random.randint(0, buff) if buff > 0 else 0 bet = start_bet + buff_bet + ties if bet >= hp or bet > opp_hp: bet = np.minimum(hp - 1, opp_hp) return int(bet) else: start_bet = hp / 2 rng_bet = np.random.randint(3,6) return int(start_bet + rng_bet + ties) ``` # CautiousBot2 Too much aggressive on first rounds, now CautiousBot gets even more cautious... ``` def cautious_gambler2(hp, history, ties, alive, start): if alive == 2: return hp - 1 if(history): opp_hp = 100 - sum(history) remaining_rounds = np.ceil(np.log2(start)) - len(history) start_bet = opp_hp / 2 buff = int((hp - start_bet)/remaining_rounds if remaining_rounds > 0 else (hp - start_bet)) buff_bet = np.random.randint(0, buff) if buff > 0 else 0 bet = start_bet + buff_bet + ties if bet >= hp or bet > opp_hp: bet = np.minimum(hp - 1, opp_hp) return int(bet) else: start_bet = hp * 0.35 rng_bet = np.random.randint(3,6) return int(start_bet + rng_bet + ties) ``` [Answer] Alright, I'll try my hand at this. # SnetchBot Checking the fractions of health that the opponent has been going with. If the opponent has been raising, beat him to it. ``` def snetchBot(hp, history, ties, alive, start): if alive == 2: return hp-1 opponent_hp = 100 history_fractions = [] if history: for i in history: history_fractions.append(float(i)/opponent_hp) opponent_hp -= i if opponent_hp <= hp/2: #print "Squashing a weakling!" return opponent_hp + (ties+1)/3 average_fraction = float(sum(history_fractions)) / len(history_fractions) if history_fractions[-1] < average_fraction: #print "Opponent not raising, go with average fraction" next_fraction = average_fraction else: #print "Opponent raising!" next_fraction = 2*history_fractions[-1] - average_fraction bet = np.ceil(opponent_hp*next_fraction) + 1 else: #print "First turn, randomish" bet = np.random.randint(35,55) if bet > opponent_hp: bet = opponent_hp + (ties+1)/3 final_result = bet + 3*ties if bet >= hp: #print "Too much to bet" bet = hp-1 return final_result ``` EDIT: losing a lot in the first round, adjusted the first turn random limits [Answer] ## SquareUpBot Didn't seem like many bots were playing with powers instead of fractions, so I decided to make one, with some standard optimisations and see where I'll place. Quite simplistic. Also tries to determine if the enemy bot isn't trying to use some constant fraction, because **powers** > *fractions*. EDIT: I'm a dummy and my fraction detector could not work. Repaired now. ``` def squareUp(hp, history, ties, alive, start): #Taken from Geometric Bot opponentHP = 100 - sum(history) # Need to add case for 1 if hp == 1: return 1 # Last of the last - give it your all if alive == 2: if ties == 2 or opponentHP < hp-1: return hp - 1 #Calculate your bet (x^(4/5)) with some variance myBet = np.maximum(hp - np.power(hp, 4./5), np.power(hp, 4./5)) myBet += np.random.randint(int(-hp * 0.05) or -1, int(hp * 0.05) or 1); myBet = np.ceil(myBet) if myBet < 1: myBet = 1 elif myBet >= hp: myBet = hp-1 else: myBet = int(myBet) #If total annihilation is a better option, dewit if opponentHP < myBet: if ties == 2: return opponentHP + 1 else: return opponentHP #If the fraction is proven, then outbid it (Thanks again, Geometric bot) if history and history[0] != history[-1]: health = 100 fraction = float(history[0]) / health for i,x in enumerate(history): newFraction = float(x) / health if newFraction + 0.012*i < fraction or newFraction - 0.012*i > fraction: return myBet health -= x return int(np.ceil(opponentHP * fraction)) + 1 else: return myBet ``` ]
[Question] [ Given integers `N , P > 1` , find the largest integer `M` such that `P ^ M ≤ N`. ### I/O: Input is given as 2 integers `N` and `P`. The output will be the integer `M`. ### Examples: ``` 4, 5 -> 0 33, 5 -> 2 40, 20 -> 1 242, 3 -> 4 243, 3 -> 5 400, 2 -> 8 1000, 10 -> 3 ``` ### Notes: The input will always be valid, i.e. it will always be integers greater than 1. ### Credits: Credit for the name goes to @cairdcoinheringaahing. The last 3 examples are by @Nitrodon and credit for improving the description goes to @Giuseppe. [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 74 bytes ``` (({}<>)[()])({()<(({})<({([{}]()({}))([{}]({}))}{})>){<>({}[()])}{}>}[()]) ``` [Try it online!](https://tio.run/##SypKzMzTTctJzP7/X0OjutbGTjNaQzNWU6NaQ9MGJAAkqzWiq2tjNTRBPE0IG8SqBRJ2mtU2dkAeWA9QwA7C@v/fSMHEwAAA "Brain-Flak – Try It Online") This uses the same concept as the standard Brain-Flak positive integer division algorithm. ``` # Push P and P-1 on other stack (({}<>)[()]) # Count iterations until N reaches zero: ({()< # While keeping the current value (P-1)*(P^M) on the stack: (({})< # Multiply it by P for the next iteration ({([{}]()({}))([{}]({}))}{}) >) # Subtract 1 from N and this (P-1)*(P^M) until one of these is zero {<>({}[()])}{} # If (P-1)*(P^M) became zero, there is a nonzero value below it on the stack >} # Subtract 1 from number of iterations [()]) ``` [Answer] # JavaScript (ES6), 22 bytes *Saved 8 bytes thanks to @Neil* Takes input in currying syntax `(p)(n)`. ``` p=>g=n=>p<=n&&1+g(n/p) ``` [Try it online!](https://tio.run/##XclBDkAwEADAu1f0JLsRSkviYP2lQRsi2wbx/SJxYa6zmNPswzaHI2c/TtFSDNQ7YupDR5ymVeaAZcA4eN79OhWrd2ChQdAaUQgphUq@p0qEurzzvup/T73Xxgs "JavaScript (Node.js) – Try It Online") [Answer] # Excel, 18 bytes ``` =TRUNC(LOG(A1,A2)) ``` Takes input "n" at A1, and input "p" at A2. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes ``` bḊL ``` This doesn't use floating-point arithmetic, so there are no precision issues. [Try it online!](https://tio.run/##y0rNyan8/z/p4Y4un//FRtZKh5cb6bv//29srKNgqqNgYqCjYGQAokEMIDIBEsYg2hhMm4BVGRqApA0NAA "Jelly – Try It Online") ### How it works ``` bḊL Main link. Left argument: n. Right argument: p b Convert n to base p. Ḋ Dequeue; remove the first base-p digit. L Take the length. ``` [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 35 bytes ``` .+ $* +r`1*(\2)+¶(1+)$ #$#1$*1¶$2 # ``` [Try it online!](https://tio.run/##K0otycxL/P9fT5tLRYtLuyjBUEsjxkhT@9A2DUNtTRUuZRVlQxUtw0PbVIy4lP//NzbmMgUA "Retina 0.8.2 – Try It Online") Explanation: ``` .+ $* ``` Convert the arguments to unary. ``` +r`1*(\2)+¶(1+)$ #$#1$*1¶$2 ``` If the second argument divides the first, replace the first argument with a `#` plus the integer result, discarding the remainder. Repeat this until the first argument is less than the second. ``` # ``` Count the number of times the loop ran. [Answer] # Japt, 8 bytes ``` @<Vp°X}a ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=QDxWcLBYfWE=&input=NDAwLDI=) [Answer] # [Haskell](https://www.haskell.org/), 30 bytes ``` n!p=until((>n).(p^).(1+))(1+)0 ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P0@xwLY0ryQzR0PDLk9TT6MgDkgYamtqggiD/7mJmXm2BUWZeSUqXApVmQXhmSUZGoqa0cbGOiYGQGQQG22qY2SgYxT7HwA "Haskell – Try It Online") [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 13 bytes ``` &floor∘&log ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJZq@18tLSc/v@hRxwy1nPz0/9ZcxYkgcQ0TAwMdI00419hYx1TzPwA "Perl 6 – Try It Online") Concatenation composing log and floor, implicitly has 2 arguments because first function log expects 2. Result is a function. [Answer] # [C (gcc)](https://gcc.gnu.org/) + `-lm`, 24 bytes ``` f(n,m){n=log(n)/log(m);} ``` [Try it online!](https://tio.run/##S9ZNT07@/z9NI08nV7M6zzYnP10jT1MfROVqWtf@z03MzNPQrC4oyswrSdNQUk1R0knTMDbWMdUEyf5LTstJTC/@r5uTCwA "C (gcc) – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), 16 bytes ``` (floor.).logBase ``` [Try it online!](https://tio.run/##y0gszk7NyfmfZhvzXyMtJz@/SE9TLyc/3SmxOPV/bmJmnoKtQkFRZl6JgopCmoKpgrHx/3/JaTmJ6cX/dZMLCgA "Haskell – Try It Online") Haskell was designed by mathematicians so it has a nice set of math-related functions in Prelude. [Answer] # [R](https://www.r-project.org/), 25 bytes ``` function(p,n)log(p,n)%/%1 ``` [Try it online!](https://tio.run/##K/qfpmCjq/A/rTQvuSQzP0@jQCdPMyc/HUyr6qsa/k/TMDEw0DHS/A8A "R – Try It Online") Take the log of `P` base `N` and do integer division with `1`, as it's shorter than `floor()`. This suffers a bit from numerical precision, so I present the below answer as well, which should not, apart from possibly integer overflow. # [R](https://www.r-project.org/), 31 bytes ``` function(p,n)(x=p:0)[n^x<=p][1] ``` [Try it online!](https://tio.run/##K/qfpmCj@z@tNC@5JDM/T6NAJ09To8K2wMpAMzovrsLGtiA22jD2f5qGiYGBjpHmfwA "R – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 39 bytes ``` lambda a,b:math.log(a,b)//1 import math ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSFRJ8kqN7EkQy8nP10DyNHU1zfkyswtyC8qUQCJ/y8oyswr0UjT0MrMKygt0dDU1PxvbKyjYAoA "Python 2 – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), 31 bytes OK, so all those log-based approaches are prone to rounding errors, so here is another method that works with integers and is free of those issues: ``` ->n,p{(0..n).find{|i|p**i>n}-1} ``` [Try it online!](https://tio.run/##Pcw7CoAwEEXR3lUM2KjEMMlEsNGNiI1IIE0IgoWoa4/5qK888O62L4fXg29Hy9xZIee25trY9bzM5ZrGjPZuxe0d6ImIQTdDWAmyiKKQgcQ5iXglUpY@iVSSAWVRr9AvXX594SCYRGAMidAugfwD "Ruby – Try It Online") But going back to logarithms, although it is unclear up to what precision we must support the input, but I think this little trick would solve the rounding problem for all more or less "realistic" numbers: # [Ruby](https://www.ruby-lang.org/), 29 bytes ``` ->n,p{Math.log(n+0.1,p).to_i} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y5Pp6DaN7EkQy8nP10jT9tAz1CnQFOvJD8@s/Z/gUJatLGxjoJprAIQKCsYcYFETAx0FIwMYsEihlARkBBExAIsYmRipKNgDBExgYoYw0VMIbpgBgNFDMAihgYggwyBZisrGP8HAA "Ruby – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt), 5 bytes ``` ìV ÊÉ ``` [Try it online!](https://tio.run/##y0osKPn///CaMIXDXYc7//83MTDgMgIA) --- ## 8 bytes ``` N£MlXÃäz ``` [Try it online!](https://tio.run/##y0osKPn/3@/QYt@ciMPNh5dU/f9vYmCgYwQA "Japt – Try It Online") [Answer] # [Emojicode](http://www.emojicode.org/), ~~49~~ 48 bytes ``` 🍇i🚂j🚂➡️🚂🍎➖🐔🔡i j 1🍉 ``` [Try it online!](https://tio.run/##S83Nz8pMzk9J/f9hfn@jwof5ve1cCiBqWVppXvJ/ED/zw/xZTVkg4tG8he939INYQPG@R/OmfZg/YcqH@VMWZipkKRgCxTr/g/TOaFAACYJMWasAMkbB0MDAAEgAERdYFQA "Emojicode – Try It Online") [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 2 bytes ``` ⌊⍟ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24RHPV2Peuf//2@qkKZgbMxlZACkTQy4jMCUAQA "APL (Dyalog Unicode) – Try It Online") Pretty straightforward. `⍟` Log `⌊` floor [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 6 bytes ``` Lm¹›_O ``` [Try it online!](https://tio.run/##MzBNTDJM/f/fJ/fQzkcNu@L9//83NDAw4DI0AAA "05AB1E – Try It Online") [Answer] # [JavaScript](https://nodejs.org), ~~40~~ 33 bytes *-3 bytes thanks to DanielIndie* Takes input in currying syntax. ``` a=>b=>(L=Math.log)(a)/L(b)+.001|0 ``` [Try it online!](https://tio.run/##Zc5NCoMwEAXgfU/hcoZSM/kRuokn0ENEq/1BjFTpyrunmYKljW/7wXvv4V5ubp/3aTmN/tKF3gZny8aWUNnaLbd88FcEh6KCBo85kVwptH6c/dCxQQ9aIxSIWYwQmTr8qyEERR@OKnfKvOk5UWUUgt7U7FT/aJE2f0@xUqKSeFjyr6g6vAE) [Answer] # Pari/GP, 6 bytes ``` logint ``` (built-in added in version 2.7, Mar 2014. Takes two arguments, with an optional third reference which, if present, is set to the base raised to the result) [Answer] # Python 2, 3, 46 bytes *-1 thanks to jonathan* ``` def A(a,b,i=1): while b**i<=a:i+=1 return~-i ``` ## Python 1, 47 bytes ``` def A(a,b,i=1): while b**i<=a:i=i+1 return~-i ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 22 bytes ``` m=>f=n=>n<m?0:f(n/m)+1 ``` [Try it online!](https://tio.run/##LY/BDsIgDIbve4oeAVEZjMQZmQ@ycFjmXDTCzLb4@pOWHUj6/f1o4d39uqWfX9/1GKfHsI1uC655uuiaeAt3dX2yeA78UG7rsKwLOGgLgLaSYCUoL6E1hmqNdaVSkU6JoCstITWrDIbAZg09CReEuq7TBbVPKBX2EI2XuEkLYfWxJN/muZhk1tkxQhhycAc5lGTeHSuEJgffSg4lmbUvfFHQD0@h@zLWRglBwuw5uAb6KS7TZzh9ppGNLHAWU@xg5nz7Aw "JavaScript (Node.js) – Try It Online") Curried recursive function. Use as `g(P)(N)`. Less prone to floating-point errors than [using `Math.log`](https://codegolf.stackexchange.com/a/162720/78410), and (I believe) the code gives correct values as long as both inputs are safe integers (under `2**52`). [Answer] # [Haskell](https://www.haskell.org/), ~~35~~ 34 bytes ``` n!p=last.fst$span((<=n).(p^))[0..] ``` Thanks @Laikoni for saving 1 byte [Try it online!](https://tio.run/##DcJBCoAgEADAr6zQQUFEtG75jg5i4KFQsmXJPfV5a5iS@3W0NgYKCi13NmfnqVNGKdeAykjalYrWmDTuXBEC0FORYYK30la5gBQKovd6tn@bIC7aWe3S@AA "Haskell – Try It Online") [Answer] # [J](http://jsoftware.com/), 5 bytes ``` <.@^. ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/bfQc4vT@a3JxpSZn5CuYKqQpGBtD2EYGQI6JAZQDZhtw/QcA "J – Try It Online") [Answer] ## Wolfram Language (Mathematica) ~~15~~ 10 Bytes ``` Floor@*Log ``` (requires reversed order on input) Original submission ``` ⌊#2~Log~#⌋& ``` [Answer] # [Forth (gforth)](http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/), 35 bytes ``` : f swap s>f flog s>f flog f/ f>s ; ``` [Try it online!](https://tio.run/##TcxBCoAgFIThvaf4L1CJ2qbAu0TwbBEYGnR8s0XZ6s3HDE9iOrcuyHNKmRDytRxkL8geQwsyID4zF2thpA571qScBqObNObrjDPYV1TaRuX4vSk3 "Forth (gforth) – Try It Online") Could save 5 bytes by swapping expected input parameters, but question specifies N must be first (an argument could be made that in a postfix language "First" means top-of-stack, but I'll stick to the letter of the rules for now) ## Explanation ``` swap \ swap the parameters to put N on top of the stack s>f flog \ move N to the floating-point stack and take the log(10) of N s>f flog \ move P to the floating-point stack and take the log(10) of P f/ \ divide log10(N) by log10(P) f>s \ move the result back to the main (integer) stack, truncating in the process ``` [Answer] # Pyth, 6 4 bytes ``` s.lF ``` Saved 2 bytes thanks to Mmenomic [Try it online](http://pyth.herokuapp.com/?code=s.lhQe&input=400%2C+2&debug=1) ## How it works `.l` is logB(A) To be honest, I have no idea how `F` works. But if it works, it works. `s` truncates a float to an int to give us the highest integer for `M`. [Answer] # [Wonder](https://github.com/wonderlang/wonder), 9 bytes ``` |_.sS log ``` Example usage: ``` (|_.sS log)[1000 10] ``` # Explanation Verbose version: ``` floor . sS log ``` This is written pointfree style. `sS` passes list items as arguments to a function (in this case, `log`). [Answer] # [Gforth](https://www.gnu.org/software/gforth/), 31 Bytes ``` SWAP S>F FLOG S>F FLOG F/ F>S . ``` ## Usage ``` 242 3 SWAP S>F FLOG S>F FLOG F/ F>S . 4 OK ``` [Try it online!](https://tio.run/##S8svKsnQTU8DUf@NTIwUjP8HhzsGKATbuSm4@fi7Ixhu@gpudsEKev@BAAA "Forth (gforth) – Try It Online") ## Explanation Unfortunately FORTH uses a dedicated floating-point-stack. For that i have to `SWAP` (exchange) the input values so they get to the floating point stack in the right order. I also have to move the values to that stack with `S>F`. When moving the floating-point result back to integer (`F>S`) I have the benefit to get the truncation for free. ## Shorter version Stretching the requirements and provide the input in float-format and the right order, there is a shorter version with 24 bytes. ``` FLOG FSWAP FLOG F/ F>S . 3e0 242e0 FLOG FSWAP FLOG F/ F>S . 4 OK ``` [Try it online!](https://tio.run/##S8svKsnQTU8DUf@NUw0UjEyMUg3@u/n4uyu4BYc7BihAmPoKbnbBCnr/gQAA "Forth (gforth) – Try It Online") [Answer] # [Husk](https://github.com/barbuz/Husk), ~~8~~ ~~7~~ 4 bytes ``` Lt`B ``` [Try it online!](https://tio.run/##yygtzv6fe2h5arFGsdujpsb/PiUJTv///4/WMDbWMdXU0TAx0DEyANNABpA2MjHSMQbTxmDaBKzK0AAobWigGQsA "Husk – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), 61 bytes ``` i(n,t,l,o,g){for(l=g=0;!g++;g=g>n)for(o=++l;o--;g*=t);g=--l;} ``` [Try it online!](https://tio.run/##RczJboMwFAXQdfMVN1RINhjJGNPJcvMTWXYTMViWwKDALsq3U5uhXTw9v2PdW2WmqpbFEsdm1rGBGfpohzvptNFcnU2aKqPNt6MBB52mnRqyTJlEz9T/ZFmnnstr3bTWNbj6FowMPcV4t25uSWRJLGuGWNQUOizoy7pIPNEfFzFsEbtGqc/@vaE1elwQjbdpauoIX4gSN8wJdqDq1N@sI/RxerkSoCgYUPoRdAPJGYQf5BtIHg7h52MDIcMRYvKAYody74DcS/kKOQ8deegpVpD8s9xK8/yAtx3EAe//8Fx@AQ "C (gcc) – Try It Online") ]
[Question] [ Today's challenge is simple: Without taking any input, output any valid sudoku board. In case you are unfamiliar with sudoku, [Wikipedia describes what a valid board should look like](https://en.wikipedia.org/wiki/Sudoku): > > The objective is to fill a 9×9 grid with digits so that each column, each row, and each of the nine 3×3 subgrids that compose the grid (also called "boxes", "blocks", or "regions") contains all of the digits from 1 to 9. > > > Now here's the thing... There are [6,670,903,752,021,072,936,960 different valid sudoku boards](https://puzzling.stackexchange.com/questions/2/what-is-the-maximum-number-of-solutions-a-sudoku-puzzle-can-have). Some of them may be very difficult to compress and output in fewer bytes. Others of them may be easier. Part of this challenge is to figure out which boards will be most compressible and could be outputted in the fewest bytes. Your submission does not necessarily have to output the same board every time. But if multiple outputs are possible, you'll have to prove that every possible output is a valid board. You can use [this script](https://tio.run/#05ab1e#code=fMKpdnkzw7R9KTPDtMO4dnlKdnnDqn19wq7DuHZ5w6p9wq52ecOqfSnDqsW-aMKmUQ&input=MTIzNDU2Nzg5CjQ1Njc4OTEyMwo3ODkxMjM0NTYKMjMxNTY0ODk3CjU2NDg5NzIzMQo4OTcyMzE1NjQKMzEyNjQ1OTc4CjY0NTk3ODMxMgo5NzgzMTI2NDU) (thanks to Magic Octopus Urn) or [any of these answers](https://codegolf.stackexchange.com/questions/22443/create-a-sudoku-solution-checker) to verify if a particular grid is a valid solution. It will output a `[1]` for a valid board, and anything else for an invalid board. I'm not too picky about what format you output your answer in, as long as it's clearly 2-dimensional. For example, you could output a 9x9 matrix, nine 3x3 matrices, a string, an array of strings, an array of 9-digit integers, or nine 9-digit numbers with a separator. Outputting 81 digits in 1 dimension would not be permitted. If you would like to know about a particular output format, feel free to ask me in the comments. As usual, this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so write the shortest answer you can come up with in the language(s) of your choosing! [Answer] # Pyth, ~~22~~ ~~14~~ ~~12~~ 10 bytes ``` .<LS9%D3 9 ``` Saved 2 bytes thanks to Mr. Xcoder. [Try it here](http://pyth.herokuapp.com/?code=.%3CLS9%25D3+9&debug=0) ``` .<LS9%D3 9 %D3 9 Order the range [0, ..., 8] mod 3. > For each, ... .< S9 ... Rotate the list [1, ..., 9] that many times. ``` [Answer] # [Python 2](https://docs.python.org/2/), 47 bytes ``` l=range(1,10) for x in l:print(l*9)[x*8/3:][:9] ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P8e2KDEvPVXDUMfQQJMrLb9IoUIhM08hx6qgKDOvRCNHy1IzukLLQt/YKjbayjL2/38A "Python 2 – Try It Online") [Answer] # T-SQL, ~~96~~ 89 bytes Found one shorter than the trivial output! ``` SELECT SUBSTRING('12345678912345678',0+value,9)FROM STRING_SPLIT('1,4,7,2,5,8,3,6,9',',') ``` Extracts 9-character strings starting at different points, as defined by the in-memory table created by `STRING_SPLIT` (which is supported on SQL 2016 and later). The `0+value` was the shortest way I could do an implicit cast to integer. Original trivial output (96 bytes): ``` PRINT'726493815 315728946 489651237 852147693 673985124 941362758 194836572 567214389 238579461' ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes ``` 9Rṙ%3$Þ ``` [Try it online!](https://tio.run/##y0rNyan8/98y6OHOmarGKofn/f8PAA "Jelly – Try It Online") *And a little bit of [this](https://codegolf.stackexchange.com/a/172475/41024)...* -1 thanks to [Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan)('s thinking?) [Answer] # [Python 2](https://docs.python.org/2/), 53 bytes ``` r=range(9) for i in r:print[1+(j*10/3+i)%9for j in r] ``` [Try it online!](https://tio.run/##K6gsycjPM/r/v8i2KDEvPVXDUpMrLb9IIVMhM0@hyKqgKDOvJNpQWyNLy9BA31g7U1PVEiSdBZaO/f8fAA "Python 2 – Try It Online") --- Alternatives: # [Python 2](https://docs.python.org/2/), 53 bytes ``` i=0;exec"print[1+(i/3+j)%9for j in range(9)];i-=8;"*9 ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P9PWwDq1IjVZqaAoM68k2lBbI1PfWDtLU9UyLb9IIUshM0@hKDEvPVXDUjPWOlPX1sJaScvy/38A "Python 2 – Try It Online") # [Python 2](https://docs.python.org/2/), 54 bytes ``` for i in range(81):print(i/9*10/3+i)%9+1,'\n'*(i%9>7), ``` ``` i=0;exec"print[1+(i/3+j)%9for j in range(9)];i+=10;"*9 ``` ``` r=range(9);print[[1+(i*10/3+j)%9for j in r]for i in r] ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 47 bytes Output as an array of the rows. ``` _=>[...w="147258369"].map(x=>(w+w).substr(x,9)) ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/e1i5aT0@v3FbJ0MTcyNTC2MxSKVYvN7FAo8LWTqNcu1xTr7g0qbikSKNCx1JT8791cn5ecX5Oql5OfrpGmgZQBAA "JavaScript (Node.js) – Try It Online") Generates this: ``` 472583691 583691472 691472583 725836914 836914725 914725836 258369147 369147258 147258369 ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~58~~ 55 bytes ``` l=*range(10), for i in b" ":print(l[i:]+l[1:i]) ``` [Try it online!](https://tio.run/##K6gsycjPM/7/P8dWqygxLz1Vw9BAU4crLb9IIVMhM08hSYmRhZ2JlYOZjVPJqqAoM69EIyc60ypWOyfa0CozVvP/fwA "Python 3 – Try It Online") * -3 bytes thanks to Jo King, The elements of the byte string end up giving the numbers `[1, 4, 7, 2, 5, 8, 3, 6, 9]` which are used to permute the rotations of `[0..9]`. The `0` is removed in `l[1:i]` and there is no need for a null byte which takes two characaters (`\0`) to represent in a bytes object. **[55 bytes](https://tio.run/##K6gsycjPM/7/P15HK8e2KDEvPVXD0ECTKy2/SCFTITNPIUmJkYWdiZWDmY1TyaqgKDOvRCMnOtMqVjsn2iozVvP/fwA)** ``` _,*l=range(10) for i in b" ":print(l[i:]+l[:i]) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~9~~ 8 bytes ``` 9Rṙ`s3ZẎ ``` [Try it online!](https://tio.run/##y0rNyan8/98y6OHOmQnFxlEPd/X9/w8A "Jelly – Try It Online") ``` 9Rṙ`s3ZẎ 9R Range(9) -> [1,2,3,4,5,6,7,8,9] ` Use the same argument twice for the dyad: ṙ Rotate [1..9] each of [1..9] times. This gives all cyclic rotations of the list [1..9] s3 Split into three lists. Z Zip. This puts the first row of each list of three in it's own list, as well as the the second and third. Ẏ Dump into a single list of nine arrays. ``` [Answer] ## Batch, 84 bytes ``` @set s=123456789 @for %%a in (0 3 6 1 4 7 2 5 8)do @call echo %%s:~%%a%%%%s:~,%%a%% ``` Uses @Mnemonic's output. `call` is used to interpolate the variable into the slicing operation (normally it only accepts numeric constants). [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~40 32~~ 27 bytes *-5 bytes thanks to nwellnhof* ``` {[^9+1].rotate($+=3.3)xx 9} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwvzo6zlLbMFavKL8ksSRVQ0Xb1ljPWLOiQsGy9n@ahqZebmKBhpZecWKl5n8A "Perl 6 – Try It Online") Anonymous code block that returns a 9x9 matrix. Maps each row to a different rotation of the range 1 to 9. [Answer] # Java 10, ~~82~~ 75 bytes ``` v->{for(int i=81;i-->0;)System.out.print((i/9*10/3+i)%9+1+(i%9<1?" ":""));} ``` -7 bytes by creating a port of one of [*@TFeld*'s Python 2 answers](https://codegolf.stackexchange.com/a/172526/52210). [Try it online.](https://tio.run/##LY7PCoJAEIfvPcUgCLuJ/@iSbdoT5EXoEh22VWNMV9FVCPHZt7W8zDC/Yb75Kj5xt8rfWtR8GODKUc47AJSq6EsuCkjXEWBqMQdBbmubKDPZsjNlUFyhgBQkxKAnN5nLtifmGjA@hgxdNwkYzT6DKhqvHZXX9WZJCPrRPgz8g4PUjpzQIWhH5/BigXWyLErZotmK78ZnbfDbl59DYwxJpgzmdX8Ap3896Qkix7rezBb9BQ) **Explanation:** ``` v->{ // Method with empty unused parameter and no return-type for(int i=81;i-->0;) // Loop `i` in the range (81, 0] System.out.print( // Print: (i/9 // (`i` integer-divided by 9, *10 // then multiplied by 10, /3 // then integer-divided by 3, +i) // and then we add `i`) %9 // Then take modulo-9 on the sum of that above +1 // And finally add 1 +(i%9<1? // Then if `i` modulo-9 is 0: " " // Append a space delimiter : // Else: ""));} // Append nothing more ``` Outputs the following sudoku (space delimited instead of newlines like below): ``` 876543219 543219876 219876543 765432198 432198765 198765432 654321987 321987654 987654321 ``` [Answer] # [J](http://jsoftware.com/), 18 bytes ``` >:(,&|:|."{,)i.3 3 ``` [Try it online!](https://tio.run/##y/qvpKegnqZga6WuoKNQa6VgoADE/@2sNHTUaqxq9JSqdTQz9YwVjP9rcqUmZ@QrpP0HAA "J – Try It Online") ### Output ``` 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 4 5 6 7 8 9 1 5 6 7 8 9 1 2 3 4 8 9 1 2 3 4 5 6 7 3 4 5 6 7 8 9 1 2 6 7 8 9 1 2 3 4 5 9 1 2 3 4 5 6 7 8 ``` ### How it works ``` >:(,&|:|."{,)i.3 3 i.3 3 The 2D array X = [0 1 2;3 4 5;6 7 8] ,&|:|."{, 3-verb train: ,&|: Transpose and flatten X to get Y = [0 3 6 1 4 7 2 5 8] , Flatten X to get Z = [0 1 2 3 4 5 6 7 8] |."{ Get 2D array whose rows are Z rotated Y times >: Increment ``` ## Fancy version, 23 bytes ``` |.&(>:i.3 3)&.>|:{;~i.3 ``` [Try it online!](https://tio.run/##y/qvpKegnqZga6WuoKNQa6VgoADE/2v01DTsrDL1jBWMNdX07Gqsqq3rgLz/mlypyRn5Cmn/AQ "J – Try It Online") Output: ``` ┌─────┬─────┬─────┐ │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│ └─────┴─────┴─────┘ ``` ### How it works ``` |.&(>:i.3 3)&.>|:{;~i.3 i.3 Array [0 1 2] {;~ Get 2D array of boxed pairs (0 0) to (2 2) |: Transpose |.&(>:i.3 3)&.> Change each pair to a Sudoku box: &.> Unbox >:i.3 3 2D array X = [1 2 3;4 5 6;7 8 9] |.& Rotate this 2D array over both axes e.g. 1 2|.X gives [6 4 5;9 7 8;3 1 2] &.> Box again so the result looks like the above ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~14~~ 12 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` 8ÝΣ3%}ε9Ls._ ``` -2 bytes by creating a port of [*@Mnemonic*'s Pyth answer](https://codegolf.stackexchange.com/a/172475/52210). [Try it online.](https://tio.run/##yy9OTMpM/f/f4vDcc4uNVWvPbbX0KdaL/@9Ve2j3fwA) (Footer is added to pretty-print it. Actual result is a 9x9 matrix; feel free to remove the footer to see.) **Explanation:** ``` 8Ý # List in the range [0, 8] Σ } # Sort the integers `i` by 3% # `i` modulo-3 ε # Map each value to: 9L # List in the range [1, 9] s._ # Rotated towards the left the value amount of times ``` --- **Original 14 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) solution:** ``` 9Lε9LN3*N3÷+._ ``` [Try it online.](https://tio.run/##yy9OTMpM/f/f0ufcVksfP2MtP@PD27X14v971R7a/R8A) (Footer is added to pretty-print it. Actual result is a 9x9 matrix; feel free to remove the footer to see.) **Explanation:** ``` 9L # Create a list of size 9 ε # Change each value to: 9L # Create a list in the range [1, 9] N3*N3÷+ # Calculate N*3 + N//3 (where N is the 0-indexed index, # and // is integer-division) ._ # Rotate that many times towards the left ``` Both answers result in the Sudoku: ``` 123456789 456789123 789123456 234567891 567891234 891234567 345678912 678912345 912345678 ``` [Answer] # [Octave](https://www.gnu.org/software/octave/) & Matlab,50 48 29 bytes ``` mod((1:9)+['furRaghAt']',9)+1 ``` [Try it online!](https://tio.run/##y08uSSxL/f8/Nz9FQ8PQylJTO1o9rbQoKDE9w7FEPVZdByhi@P8/AA "Octave – Try It Online") *-2 thanks to Johnathon frech* *-14 thanks to Sanchises Broadcast addition suggestion, who also pointed out the non-compatibility.* *-5 by noticing that the vector can be written in matlab with a char string and transposition.* Was intuitive, now not so. Uses broadcast summing to spread 1:9 over 9 rows, spread by values determined by the char string. Sudoku board produced: ``` 5 6 7 8 9 1 2 3 4 2 3 4 5 6 7 8 9 1 8 9 1 2 3 4 5 6 7 3 4 5 6 7 8 9 1 2 9 1 2 3 4 5 6 7 8 6 7 8 9 1 2 3 4 5 7 8 9 1 2 3 4 5 6 4 5 6 7 8 9 1 2 3 1 2 3 4 5 6 7 8 9 ``` [Answer] # [Haskell](https://www.haskell.org/), 41 bytes ``` [[x..9]++[1..x-1]|x<-[1,4,7,2,5,8,3,6,9]] ``` [Try it online!](https://tio.run/##Dca7DoMgGAbQvU/xxTjY8ENC7ybqSzgiA7FNNFUwQFOGvjv2TGcy4f1alpxDq1QSotaMKSlE4lL/UsOVpAvd6URXetCZblRrnVczW7R4ugO2T@yjR4nR2dHEf1azoRo8eIcwuS88GEMx2OKIkHc "Haskell – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), 34 bytes ``` (a=*1..9).map{|x|p a.rotate x*3.3} ``` [Try it online!](https://tio.run/##KypNqvz/XyPRVstQT89SUy83saC6pqKmQCFRryi/JLEkVaFCy1jPuPb/fwA "Ruby – Try It Online") [Answer] # [MathGolf](https://github.com/maxbergmark/mathgolf), ~~16~~ 11 bytes ``` 9{9╒♂ï*3/Ä╫ ``` [Try it online!](https://tio.run/##ASEA3v9tYXRoZ29sZv//OXs54pWS4pmCw68qMy/DhOKVq/9hbv8 "MathGolf – Try It Online") Saved 5 bytes thanks to JoKing [Answer] # Python - 81 bytes ``` l=list(range(1,10)) for i in range(1,10):print(l);l=l[3+(i%3==0):]+l[:3+(i%3==0)] ``` [Try it Online](https://tio.run/##K6gsycjPM/7/P8c2J7O4RKMoMS89VcNQx9BAU5MrLb9IIVMhM08BSdSqoCgzr0QjR9MaqCPaWFsjU9XY1hYoHqudE22F4Mf@/w8A) I like having 81 bytes, but after some optimizing :( # Python 2 - ~~75 68 59~~ 58 bytes *-7 bytes thanks to @DLosc* *-9 bytes thanks to @Mnemonic* *-1 byte thanks to @JoKing* ``` l=range(1,10) for i in l:print l;j=i%3<1;l=l[3+j:]+l[:3+j] ``` [Try it Online](https://tio.run/##K6gsycjPM/r/P8e2KDEvPVXDUMfQQJMrLb9IIVMhM08hx6qgKDOvRCHHOss2U9XYxtA6xzYn2lg7yypWOyfaCsiI/f8fAA) [Answer] [**R**](https://www.r-project.org/)**, 54 bytes** ``` x=1:9;for(y in(x*3)%%10)print(c(x[-(1:y)],x[(1:y)])) ``` **Output:** ``` [1] 4 5 6 7 8 9 1 2 3 [1] 7 8 9 1 2 3 4 5 6 [1] 1 2 3 4 5 6 7 8 9 [1] 3 4 5 6 7 8 9 1 2 [1] 6 7 8 9 1 2 3 4 5 [1] 9 1 2 3 4 5 6 7 8 [1] 2 3 4 5 6 7 8 9 1 [1] 5 6 7 8 9 1 2 3 4 [1] 8 9 1 2 3 4 5 6 7 ``` [Try it online!](https://tio.run/##K/r/v8LW0MrSOi2/SKNSITNPo0LLWFNV1dBAs6AoM69EI1mjIlpXw9CqUjNWpyIawtDU/M/1HwA) [Answer] Huge Thanks to @Shaggy! # [JavaScript (Node.js)](https://nodejs.org), 61 bytes ``` t=>[...s='123456789'].map(e=>s.slice(t=e*3.3%9)+s.slice(0,t)) ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@7/E1i5aT0@v2Fbd0MjYxNTM3MJSPVYvN7FAI9XWrlivOCczOVWjxDZVy1jPWNVSUxsmZKBToqn5Pzk/rzg/J1UvJz9dI01DU5PrPwA "JavaScript (Node.js) – Try It Online") [Answer] # Python 3, 51 bytes ``` r='147258369';print([(r*4)[int(i):][:9]for i in r]) ``` [Answer] # [Python 2](https://docs.python.org/2/), 48 bytes ``` r='147258369' for i in r:print(r*4)[int(i):][:9] ``` [Try it online!](https://tio.run/##K6gsycjPM/r/v8hW3dDE3MjUwtjMUp0rLb9IIVMhM0@hyKqgKDOvRKNIy0QzGsTI1LSKjbayjP3/HwA "Python 2 – Try It Online") [Answer] # [Canvas](https://github.com/dzaima/Canvas), ~~13~~ 11 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md) ``` ◂j3[«3[T3[« ``` [Try it here!](https://dzaima.github.io/Canvas/?u=JXUyNUMyJXVGRjRBJXVGRjEzJXVGRjNCJUFCJXVGRjEzJXVGRjNCJXVGRjM0JXVGRjEzJXVGRjNCJUFC,v=8) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 14 bytes ``` E⁹⭆⁹⊕﹪⁺÷×χι³λ⁹ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM3sUDDUkchuATIS4dyPPOSi1JzU/NKUlM0fPNTSnPyNQJySos1PPNKXDLLMlNSNUIyc1OLNQwNdBQyNXUUjIE4B4gtNUHA@v///7plOQA "Charcoal – Try It Online") Link is to verbose version of code. Uses @Mnemonic's output. Explanation: ``` E⁹ Map over 9 rows ⭆⁹ Map over 9 columns and join ι Current row χ Predefined variable 10 × Multiply ÷ ³ Integer divide by 3 λ Current column ⁺ Add ﹪ ⁹ Modulo 9 ⊕ Increment Implicitly print each row on its own line ``` [Answer] # [C (clang)](http://clang.llvm.org/), 65 bytes ``` f(i){for(i=0;i<81;)printf("%d%c",(i/9*10/3+i)%9+1,i++%9>7?10:9);} ``` The function is now able to be reused [Try it online!](https://tio.run/##DctBDoIwEAXQtT0FwTSZsSg0LrQW8SyktfgTbA2iG8LZq2//3N6NfRxyDgReQpoI18aiPWvLrwlxDlRKL11ZEWqz0019VGBplK6glDTd6aabi2G75i2iGz/@XrTv2SMdHp34/@LZI9I3wfMiNoHYijX/AA "C (clang) – Try It Online") [Answer] # [K (ngn/k)](https://gitlab.com/n9n/k), 16 bytes ``` 1+9!(<9#!3)+\:!9 ``` [Try it online!](https://tio.run/##y9bNS8/7/99Q21JRw8ZSWdFYUzvGStHy/38A "K (ngn/k) – Try It Online") First answer in ngn/k, done with a big help from the man himself, @ngn. ### How: ``` 1+9!(<9#!3)+\:!9 // Anonymous fn !9 // Range [0..8] ( )+\: // Sum (+) that range with each left (\:) argument !3 // Range [0..2] 9# // Reshaped (#) to 9 elements: (0 1 2 0 1 2 0 1 2) < // Grade up 9! // Modulo 9 1+ // plus 1 ``` [Answer] # Japt, ~~11~~ 10 bytes ``` 9õ ñu3 £éX ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=OfUg8XUzCqPpWA==&input=LVI=) or [verify the output](https://tio.run/##MzBNTDJM/f@/5tDKskrjw1tqNYHE4R1llV5llYdX1dYeWgfiAFmH1oEpzcOrju7LOLQs8P9/I1MLYzNLQxNzLiCGcLggAkAOlwWMyWUOU8hlCVPIBdNqxAXTasgF02oMAA) --- ## Explanation ``` 9õ :Range [1,9] ñ :Sort by u3 : Mod 3 of each \n :Assign to variable U £ :Map each X éX : U rotated right by X ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 8 bytes ``` ṠmṙÖ%3ḣ9 ``` [Try it online!](https://tio.run/##ARcA6P9odXNr///huaBt4bmZw5YlM@G4ozn//w "Husk – Try It Online") [Answer] # [Deadfish~](https://github.com/TryItOnline/deadfish-), 344 bytes ``` {iiiii}icicicicicicic{d}iicic{dddd}c{iiii}iiiicicicic{d}iicicicicic{dddd}dddc{iiiii}dddc{d}iicicicicicicicic{dddd}ddddddc{iiii}cicicicicicicic{d}iic{dddd}ic{iiii}iiicicicicic{d}iicicicic{dddd}ddc{iiii}iiiiiicic{d}iicicicicicicic{dddd}dddddc{iiii}dcicicicicicicicic{ddddd}iiic{iiii}iicicicicicic{d}iicicic{dddd}dc{iiii}iiiiicicic{d}iicicicicicic ``` [Try it online!](https://tio.run/##bY5BDoAgDARf5KPMVuOeOZK@vQIFRWwJAcJkZ@XY5WS6NrPMOkrMK4vSzzKK7Ai5/o9XpcpGD2vXD7KAD6uIxM7x9SISj7SpHv/lFm@HBWE3abKRh8jbs2YpIqvZDQ "Deadfish~ – Try It Online") ]
"[Question]\n [\nAs I'm applying for some jobs whose job advert doesn't state the salary, I ima(...TRUNCATED)
"[Question]\n [\nBackground: the Ramsey number \\$R(r,s)\\$ gives the minimum number of vertice(...TRUNCATED)
"[Question]\n [\n*This challenge is based on, and contains test cases from, [a programming cour(...TRUNCATED)

A Scrape of the codereview stack exchange, good for high quality code

Downloads last month
0
Edit dataset card

Collections including VatsaDev/code-review