text
stringlengths
180
608k
[Question] [ [1d version](https://codegolf.stackexchange.com/questions/100411/animate-finding-the-middle) Given a multidimensional array of positive integers where all dimensions are the same length, animate finding the centre of it. Simply output the array, then remove the first and last items of every array within it and output it, until the length of each dimension is less than 3 and can't have the first and last removed. For example, with this 2-dimensonal array: ``` [ [7, 2, 3, 6, 4], [2, 4, 9, 9, 8], [7, 3, 1, 9, 8], [9, 1, 7, 6, 9], [4, 3, 4, 8, 5] ] ``` You'd output the array, then remove the first and last of each to output this: ``` [ [4, 9, 9], [3, 1, 9], [1, 7, 6] ] ``` And finally output just this: ``` [ [ 1 ] ] ``` Output format can be as an array of multidimensional arrays, each array printed separately, etcetera. You may output a trailing empty list, and you don't have to output the original array. ## Testcases ``` [[[4, 6, 7], [1, 6, 8], [3, 3, 4]], [[9, 2, 8], [4, 9, 4], [6, 3, 9]], [[3, 7, 8], [4, 3, 6], [2, 8, 2]]] -> [[[4, 6, 7], [1, 6, 8], [3, 3, 4]], [[9, 2, 8], [4, 9, 4], [6, 3, 9]], [[3, 7, 8], [4, 3, 6], [2, 8, 2]]] [[[9]]] [[[6, 5, 9, 4], [8, 8, 5, 1], [9, 3, 1, 6], [1, 7, 7, 9]], [[8, 3, 7, 2], [6, 6, 9, 4], [5, 6, 8, 3], [2, 1, 9, 9]], [[4, 9, 6, 9], [6, 9, 3, 7], [3, 6, 8, 2], [7, 5, 8, 6]], [[8, 6, 2, 1], [3, 5, 9, 5], [2, 6, 1, 3], [3, 6, 3, 9]]] -> [[[6, 5, 9, 4], [8, 8, 5, 1], [9, 3, 1, 6], [1, 7, 7, 9]], [[8, 3, 7, 2], [6, 6, 9, 4], [5, 6, 8, 3], [2, 1, 9, 9]], [[4, 9, 6, 9], [6, 9, 3, 7], [3, 6, 8, 2], [7, 5, 8, 6]], [[8, 6, 2, 1], [3, 5, 9, 5], [2, 6, 1, 3], [3, 6, 3, 9]]] [[[6, 9], [6, 8]], [[9, 3], [6, 8]]] [[[[[5, 1, 6], [8, 2, 9], [9, 2, 4]], [[7, 1, 8], [1, 1, 5], [6, 9, 4]], [[3, 6, 6], [9, 9, 9], [4, 2, 5]]], [[[9, 9, 8], [7, 2, 7], [1, 2, 6]], [[3, 1, 8], [1, 7, 9], [6, 9, 2]], [[6, 6, 1], [6, 8, 8], [2, 5, 6]]], [[[9, 5, 3], [3, 6, 9], [8, 8, 7]], [[4, 6, 4], [8, 7, 9], [8, 6, 7]], [[2, 4, 1], [4, 5, 2], [8, 7, 8]]]], [[[[8, 1, 6], [1, 4, 4], [7, 6, 6]], [[9, 9, 9], [8, 1, 7], [9, 2, 4]], [[9, 5, 7], [1, 4, 8], [3, 8, 1]]], [[[3, 8, 1], [8, 7, 6], [1, 5, 7]], [[8, 5, 1], [7, 2, 1], [7, 1, 3]], [[1, 2, 6], [4, 3, 7], [1, 1, 1]]], [[[8, 1, 1], [7, 5, 2], [9, 3, 6]], [[2, 1, 5], [1, 3, 3], [5, 5, 2]], [[7, 6, 2], [9, 5, 7], [3, 8, 1]]]], [[[[5, 8, 9], [7, 2, 5], [3, 9, 7]], [[7, 8, 7], [3, 4, 1], [4, 1, 3]], [[3, 8, 6], [7, 7, 9], [8, 4, 8]]], [[[7, 5, 4], [8, 1, 7], [9, 9, 1]], [[1, 1, 8], [2, 3, 7], [9, 5, 4]], [[2, 2, 6], [8, 8, 2], [1, 3, 6]]], [[[7, 2, 7], [1, 7, 3], [8, 3, 9]], [[6, 1, 4], [8, 3, 8], [8, 9, 5]], [[5, 7, 2], [9, 7, 6], [1, 3, 4]]]]] -> [[[[[5, 1, 6], [8, 2, 9], [9, 2, 4]], [[7, 1, 8], [1, 1, 5], [6, 9, 4]], [[3, 6, 6], [9, 9, 9], [4, 2, 5]]], [[[9, 9, 8], [7, 2, 7], [1, 2, 6]], [[3, 1, 8], [1, 7, 9], [6, 9, 2]], [[6, 6, 1], [6, 8, 8], [2, 5, 6]]], [[[9, 5, 3], [3, 6, 9], [8, 8, 7]], [[4, 6, 4], [8, 7, 9], [8, 6, 7]], [[2, 4, 1], [4, 5, 2], [8, 7, 8]]]], [[[[8, 1, 6], [1, 4, 4], [7, 6, 6]], [[9, 9, 9], [8, 1, 7], [9, 2, 4]], [[9, 5, 7], [1, 4, 8], [3, 8, 1]]], [[[3, 8, 1], [8, 7, 6], [1, 5, 7]], [[8, 5, 1], [7, 2, 1], [7, 1, 3]], [[1, 2, 6], [4, 3, 7], [1, 1, 1]]], [[[8, 1, 1], [7, 5, 2], [9, 3, 6]], [[2, 1, 5], [1, 3, 3], [5, 5, 2]], [[7, 6, 2], [9, 5, 7], [3, 8, 1]]]], [[[[5, 8, 9], [7, 2, 5], [3, 9, 7]], [[7, 8, 7], [3, 4, 1], [4, 1, 3]], [[3, 8, 6], [7, 7, 9], [8, 4, 8]]], [[[7, 5, 4], [8, 1, 7], [9, 9, 1]], [[1, 1, 8], [2, 3, 7], [9, 5, 4]], [[2, 2, 6], [8, 8, 2], [1, 3, 6]]], [[[7, 2, 7], [1, 7, 3], [8, 3, 9]], [[6, 1, 4], [8, 3, 8], [8, 9, 5]], [[5, 7, 2], [9, 7, 6], [1, 3, 4]]]]] [[[[[2]]]]] [[[[1, 8, 1, 7, 8], [2, 6, 6, 2, 8], [9, 4, 2, 3, 3], [1, 9, 5, 8, 5], [6, 3, 9, 2, 2]], [[8, 2, 5, 5, 3], [3, 3, 8, 6, 6], [3, 3, 5, 6, 6], [4, 2, 5, 3, 6], [2, 2, 5, 5, 4]], [[4, 4, 1, 9, 7], [4, 3, 4, 3, 8], [3, 7, 1, 7, 7], [1, 2, 7, 5, 6], [5, 6, 5, 4, 6]], [[7, 8, 9, 7, 2], [9, 4, 9, 9, 2], [3, 1, 9, 2, 9], [3, 5, 8, 4, 7], [3, 3, 5, 9, 9]], [[5, 6, 2, 4, 3], [2, 9, 6, 6, 1], [6, 8, 2, 9, 7], [5, 2, 1, 8, 4], [7, 7, 9, 6, 1]]], [[[2, 2, 8, 1, 6], [3, 6, 9, 9, 9], [9, 7, 6, 8, 7], [9, 6, 3, 5, 6], [9, 1, 8, 5, 6]], [[2, 4, 2, 7, 3], [8, 9, 8, 7, 1], [1, 6, 1, 8, 4], [9, 9, 8, 8, 2], [5, 5, 7, 9, 5]], [[6, 4, 3, 1, 2], [6, 4, 4, 7, 6], [7, 7, 6, 1, 3], [8, 7, 1, 4, 7], [4, 7, 1, 1, 2]], [[1, 7, 7, 5, 3], [7, 8, 4, 1, 1], [8, 5, 7, 5, 3], [6, 9, 1, 9, 6], [5, 9, 7, 3, 1]], [[6, 3, 7, 1, 5], [1, 9, 4, 8, 2], [9, 6, 5, 9, 5], [2, 9, 4, 4, 6], [8, 3, 6, 7, 4]]], [[[2, 4, 7, 7, 8], [4, 2, 9, 4, 8], [5, 4, 2, 1, 3], [1, 6, 8, 1, 1], [4, 7, 4, 9, 5]], [[4, 9, 1, 3, 7], [3, 3, 7, 6, 4], [4, 6, 7, 4, 5], [7, 3, 2, 7, 6], [5, 5, 7, 9, 3]], [[7, 6, 7, 4, 1], [8, 3, 4, 7, 3], [1, 9, 9, 2, 4], [2, 7, 2, 8, 1], [5, 1, 4, 8, 8]], [[3, 5, 4, 8, 2], [1, 2, 7, 4, 5], [1, 7, 2, 2, 9], [8, 4, 2, 1, 4], [4, 9, 2, 3, 5]], [[1, 1, 9, 7, 8], [4, 8, 1, 7, 5], [3, 5, 2, 2, 7], [8, 6, 3, 2, 1], [6, 9, 9, 1, 3]]], [[[2, 8, 5, 5, 6], [6, 3, 4, 6, 4], [2, 3, 5, 7, 9], [2, 6, 1, 1, 2], [6, 4, 9, 8, 5]], [[8, 4, 7, 2, 1], [6, 5, 4, 8, 7], [7, 8, 3, 6, 8], [2, 2, 4, 7, 2], [2, 3, 6, 4, 4]], [[5, 2, 8, 4, 8], [6, 7, 2, 8, 7], [8, 2, 1, 9, 2], [2, 1, 1, 7, 2], [9, 6, 1, 5, 2]], [[3, 2, 9, 2, 2], [9, 4, 5, 1, 2], [9, 1, 6, 3, 7], [8, 8, 7, 1, 8], [3, 4, 8, 9, 6]], [[8, 6, 1, 6, 9], [1, 9, 6, 9, 4], [6, 6, 6, 9, 6], [2, 5, 3, 6, 5], [6, 6, 9, 5, 7]]], [[[2, 4, 3, 6, 1], [6, 8, 2, 8, 8], [5, 2, 9, 7, 7], [1, 3, 5, 6, 2], [5, 3, 5, 7, 9]], [[5, 3, 8, 8, 5], [2, 7, 5, 3, 7], [2, 5, 1, 6, 6], [5, 7, 1, 4, 2], [5, 1, 4, 5, 2]], [[1, 6, 2, 5, 3], [3, 8, 1, 9, 4], [3, 9, 6, 7, 1], [8, 5, 3, 7, 1], [3, 8, 8, 1, 4]], [[3, 1, 2, 1, 9], [5, 7, 1, 4, 2], [1, 8, 5, 7, 3], [2, 5, 8, 2, 1], [9, 9, 6, 9, 7]], [[4, 8, 3, 5, 6], [5, 6, 4, 2, 3], [2, 5, 3, 1, 6], [2, 9, 4, 9, 4], [4, 6, 8, 2, 2]]]] -> [[[[1, 8, 1, 7, 8], [2, 6, 6, 2, 8], [9, 4, 2, 3, 3], [1, 9, 5, 8, 5], [6, 3, 9, 2, 2]], [[8, 2, 5, 5, 3], [3, 3, 8, 6, 6], [3, 3, 5, 6, 6], [4, 2, 5, 3, 6], [2, 2, 5, 5, 4]], [[4, 4, 1, 9, 7], [4, 3, 4, 3, 8], [3, 7, 1, 7, 7], [1, 2, 7, 5, 6], [5, 6, 5, 4, 6]], [[7, 8, 9, 7, 2], [9, 4, 9, 9, 2], [3, 1, 9, 2, 9], [3, 5, 8, 4, 7], [3, 3, 5, 9, 9]], [[5, 6, 2, 4, 3], [2, 9, 6, 6, 1], [6, 8, 2, 9, 7], [5, 2, 1, 8, 4], [7, 7, 9, 6, 1]]], [[[2, 2, 8, 1, 6], [3, 6, 9, 9, 9], [9, 7, 6, 8, 7], [9, 6, 3, 5, 6], [9, 1, 8, 5, 6]], [[2, 4, 2, 7, 3], [8, 9, 8, 7, 1], [1, 6, 1, 8, 4], [9, 9, 8, 8, 2], [5, 5, 7, 9, 5]], [[6, 4, 3, 1, 2], [6, 4, 4, 7, 6], [7, 7, 6, 1, 3], [8, 7, 1, 4, 7], [4, 7, 1, 1, 2]], [[1, 7, 7, 5, 3], [7, 8, 4, 1, 1], [8, 5, 7, 5, 3], [6, 9, 1, 9, 6], [5, 9, 7, 3, 1]], [[6, 3, 7, 1, 5], [1, 9, 4, 8, 2], [9, 6, 5, 9, 5], [2, 9, 4, 4, 6], [8, 3, 6, 7, 4]]], [[[2, 4, 7, 7, 8], [4, 2, 9, 4, 8], [5, 4, 2, 1, 3], [1, 6, 8, 1, 1], [4, 7, 4, 9, 5]], [[4, 9, 1, 3, 7], [3, 3, 7, 6, 4], [4, 6, 7, 4, 5], [7, 3, 2, 7, 6], [5, 5, 7, 9, 3]], [[7, 6, 7, 4, 1], [8, 3, 4, 7, 3], [1, 9, 9, 2, 4], [2, 7, 2, 8, 1], [5, 1, 4, 8, 8]], [[3, 5, 4, 8, 2], [1, 2, 7, 4, 5], [1, 7, 2, 2, 9], [8, 4, 2, 1, 4], [4, 9, 2, 3, 5]], [[1, 1, 9, 7, 8], [4, 8, 1, 7, 5], [3, 5, 2, 2, 7], [8, 6, 3, 2, 1], [6, 9, 9, 1, 3]]], [[[2, 8, 5, 5, 6], [6, 3, 4, 6, 4], [2, 3, 5, 7, 9], [2, 6, 1, 1, 2], [6, 4, 9, 8, 5]], [[8, 4, 7, 2, 1], [6, 5, 4, 8, 7], [7, 8, 3, 6, 8], [2, 2, 4, 7, 2], [2, 3, 6, 4, 4]], [[5, 2, 8, 4, 8], [6, 7, 2, 8, 7], [8, 2, 1, 9, 2], [2, 1, 1, 7, 2], [9, 6, 1, 5, 2]], [[3, 2, 9, 2, 2], [9, 4, 5, 1, 2], [9, 1, 6, 3, 7], [8, 8, 7, 1, 8], [3, 4, 8, 9, 6]], [[8, 6, 1, 6, 9], [1, 9, 6, 9, 4], [6, 6, 6, 9, 6], [2, 5, 3, 6, 5], [6, 6, 9, 5, 7]]], [[[2, 4, 3, 6, 1], [6, 8, 2, 8, 8], [5, 2, 9, 7, 7], [1, 3, 5, 6, 2], [5, 3, 5, 7, 9]], [[5, 3, 8, 8, 5], [2, 7, 5, 3, 7], [2, 5, 1, 6, 6], [5, 7, 1, 4, 2], [5, 1, 4, 5, 2]], [[1, 6, 2, 5, 3], [3, 8, 1, 9, 4], [3, 9, 6, 7, 1], [8, 5, 3, 7, 1], [3, 8, 8, 1, 4]], [[3, 1, 2, 1, 9], [5, 7, 1, 4, 2], [1, 8, 5, 7, 3], [2, 5, 8, 2, 1], [9, 9, 6, 9, 7]], [[4, 8, 3, 5, 6], [5, 6, 4, 2, 3], [2, 5, 3, 1, 6], [2, 9, 4, 9, 4], [4, 6, 8, 2, 2]]]] [[[[9, 8, 7], [6, 1, 8], [9, 8, 8]], [[4, 4, 7], [7, 6, 1], [7, 1, 4]], [[8, 4, 1], [5, 7, 5], [9, 1, 9]]], [[[3, 7, 6], [6, 7, 4], [3, 2, 7]], [[3, 4, 7], [9, 9, 2], [7, 2, 8]], [[2, 7, 4], [7, 2, 2], [4, 2, 1]]], [[[5, 4, 8], [8, 3, 6], [2, 4, 7]], [[7, 2, 8], [2, 1, 9], [1, 1, 7]], [[4, 5, 1], [1, 6, 3], [8, 7, 1]]]] [[[[9]]]] ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~47~~ 44 bytes ``` #//.l_:>(Print@l;#0/@#[[2;;-2]]~Check~#&@l)& ``` [Try it online!](https://tio.run/##7VhNayNHEL3rVwg5LAnIcbqnPyPWCJI9BHJI4twGEYzQxiJay9haWNjs/nVnuuvjdW/2nBAiMHimp6ar6tWr1zV6c3u62725Pe23t8@vXz5fXF19ffjt2@svf3rc35/Wh9XFN1fri3G0q9Wl3Ww@fne32/7x8eLF@vDVi@ef3@53p/X3x3H2fr88fpi/nN@cptd@/2X3cLjd7sbFuLi8Xvy4fzqNi836sL/frWb7yerX46t3D4@7p6f98X69X82On67RNjcPh/1pPC4Xs8VmNXu1vTsW4xrYOC28bu7o/9X6qAvL98XfknZ69e70eLs9jV/cbB/3D6cf7h/enujJtPlsCnK1Wi7ml9ezxZ/l35yWNh82z@M4uuU8LOdxs5yPpl6mcjks59Of25TrMS/nltcn61zWp8tQTTKZTFcRJtNdKJflrendzWZT3f5j3oqnXP6Xi@lNj31SNZoWTLnL9W3DG5i6bVQ3qT6NZU@KIGAfT9FPFuza1Gf8JgVezPlNchQ52cCRTnexBpNKBOIzVAAM21Lsnr2E6mjAPgRKwfd/kysnKu6S0mbAymRE1R9L9JJ0qt4yo2GVcrGaJMbFcAiCgFAu8C6Zsyf22WJNNvwkca4WRLea89C5ih1qlkwIfCPJsLWt8ITGle/Ayah41MIEMCHCJKhJgYBdubqhhXVBkXyVhYY3jjeNDInAn@HBcOodyhRyxC7S@@UF8SW3GoZ49Rp0w@kI@kRmSzURyFUgImqrrhLfKjMt2iQoPsIGU9cH7gev1SIU5FUP4nNWDCERPyNoz2ZZ84pcPFpv6oK8Bm4f2qUpqaN6VV@UjPt7KXKNiPEx4NUAE6/VsoAwoYWNoKOuGpZHxie1Wk1d7LCe@LJ2ejXxEJ7c1ZwOBcjbuZnPzXxu5v96M1MnW7quN4YAxlRHp3/AJJgrKhZloxGECuGbAbEaWeUWNVrTXAw6h0ULHgtOXmmGSt3DaSs6mYEiWOkACE1SPGJBNSJ3vY5Uvr4VWsbkDj6arTIvDOJVdG8QBByopmNU1noQjg7zWxZ4G12yyMdTI9LODT35FaYLIdOoySBDY4YsRxkAhZNBEecFI0NqaFXMdgTMtAXHa2Q0lPCyWAixqVyxpWWQAhmMuFTI2PVgM3QmqaJDnWnBKMV0jBaKRamHgfD5zoIwokIKFwipQVs6yDTeCBbRIYEc4dOBOUtKAQ0a6jauKZqTkBMInyHhXvA36LQgdTaAwbXoOslp6IgYcWg5DYXjpXwt8G@LNrRyHKGfSTotdjIgJxPBEJWYvK0R5JIKr@/A1PZ0gJt2sZ0qW8ifE6@DgmBUFICtyppHv1robJKGsOjFrFg2RUuiQQFa14wEVrpKThH9fOrpnlkvRR6d5CnOFZcIMg/4ULeiJKJRVh47lUcv8AujQlOSiMnNQNishBo7dpv2aB6EqLaTR48UCbUAEiaVDeiyE5XtvkENpi6jn7P45UE/hwOGN0rbd1/LNNa0nTZ8RmYTOs0KXyIOSY8ZxHdlFXQH0ToPwntkbQWUgMZSHbNdS/hWx4Iefc3MAxgGwSV2wjZgQeMy7aBttNifjUXlP@J48oKUgbqHdrhywsv@OOUJoauRQdH0PG0EKcm8gG@M8zByHkbOw8h5GDkPI@dh5DyMnIeRf2UYqZNIBksDeJNb9XA4ECKqG9u0ExTLo/tZ9Ztf6iL6OQJmq3kOcNWMAdxMelxGnNLSG6xV4sqjGVM32rj2xzOLJjdoBtOi7rsjuD0lgWC5@gs "Wolfram Language (Mathematica) – Try It Online") Prints the steps, one per line. Includes a final empty list if the input has even length ``` # starting from input, //. until a fixed point is reached: l_:>(Print@l; ) output current value #0/@#[[2;;-2]] &@l recursively take its middle on every level ~Check~# or unchanged if length<2 (this also handles recursion base case) ``` --- **43 bytes**, non-competing ``` {#}//.l_:>{#0/@#[[2;;-2]]~Check~#&@@l}⋃l& ``` [Try it online!](https://tio.run/##7VhNayNHEL3rVwg57EmO0z39GWEjSPYQyCGJcxuGYIQ2FtFaxtbCguO95Jh/mT/inen6eN2bPSeECAzu6anuqn716nWN3t4cb7dvb467zc3Lm8uXp7Pni4sv9798ffV09tXF@qzv7Wp1bofhwze3281vH85erdf757/@/GP/6uXHd7vtcf3toZ897ZaH5/nl/Pr4sLv79aft/f5ms@0X/eL8avH97vHYL4b1fne3Xc12o9XPh9fv7x@2j4@7w916t5odPp2jba7v97tjf1guZothNXu9uT1Mxj@Mr479wIOL9RtMjsP55eX8MKjVbPk0uV3Shq/fHx9uNsf@i@vNw@7@@N3d/bsjvRl9zMZYV6vlYn5@NVv8Pv2b09TwPLz0fe@W87Ccx2E5700ZpmnYLefjnxumcZ@Xc8vzo3We5sdhKCaZTMZRhMn4FKbhtGpcOwxDcfuPeZs85en/NBhXeuyTitE4YaanXFYb3sCUbaO6SeVtnPakCAL28RT9aMGuTXnHKynwyZxXkqPIhw0c6fgUSzBpikB8hgKAYVuK3bOXUBx12IdAmfD935yVDyruktKmw8xoRNnvp@jl0Kl4y4yGVcrFYpIYF8MhCAJCucC7ZD49sc9O1mTDbxKf1YLoVs/cNa5ig5olEwLfyGHY2hZ4QuXKN@BkZDxqYgKYEGES1GSCgF25sqGF9YQi@ZomKt443jQyJAJ/hgfDR29QppAjdpHanxaIL3nUMMSr16ArTkfQJzJbiolArgIRkVt1lfhRmWlRJkHxETaYMt9xPXjNFqEgSz2Iz6diCIn4GUF7Nst6rsjJo/kqLzhXx@VDu1QpdZSv4osO4/6eilwiYnwMeNXBxGu2LCBMKGEj6KiriuWR8Um1VlMVO8wnHpZKLyYewpObnNOlAHk7FfOpmE/F/F8vZqpkS@PyYAhgdHV0@wd0grmgYpE2akEoEb5qEIuRVW5RoVXFxaBzWDThMeFkSdVU6h5OS9FJDxTBSgdAqJPiFguqEbnqtaXyZVWoGZMb@Ki3yjzRiVfRvU4QcKCatlFZ80E4OvRvWeCtdMniPJ4KkXau6MlLmC6ETKUmnTSNGbIcpQEUTgZFnCeMNKmhVjHbEDDTFhyvkdZQwstiIcSmdMWalkESZNDiUiJjU4NV05kkiw55pgmjFNM2WigWJR8GwucbC8KIEilcIKQ6Lekg3XglWESHBHKETxvmLEcKKNBQtnFV0pyEnED4DAn3gr9BpQXJswEMrkbXyZm6hogRl5bTUDheOq8F/nXSulqOI/QzSaXFRgbkZiIYohKTtzWCXFLh9Q2YWp4OcNMutlFlC/lz4rVTEIyKArBVWfOoVwudTVIQFrWYFcsqaUk0KEDrqpbASlXJLaKfTy3dM@ulyKOTc4pzxSWCzB0@1K0oiWiUlddO5dEL/MKoUKUkonMzEDYrocaG3aa@mjshqm3k0eOIhFoACZPKBnTZico236AGXZfRz1n88qCfwwHNGx3bN1/L1NbUldZ9RmYTKs0KXyIuSY8exDdpFXQ70ToPwnuc2gooAYWlOmabkvC1jgW9@qqeBzB0gktshK3DhMZl6kbbaLI/G4vKf8T15AUpA3UPdXPlhJftdcodQpMjg6TpfVoJUpJ@Ad8Yp2bk1IycmpFTM3JqRk7NyKkZOTUj/0ozUjqRDJYG8CbX6uFwIURkN9bHTlAsj@pn1a9@qYuo5wiYrZ6zg6uqDeBi0usy4paW2mCtElcexZia1sbVP55ZFLlBMZgadd9cwfUtCQSn0Uc "Wolfram Language (Mathematica) – Try It Online") Returns the lists in reverse order. I don't expect this is allowed, but it's an interesting variation. [Answer] # [APL(Dyalog Unicode)](https://dyalog.com), 17 bytes [SBCS](https://github.com/abrudz/SBCS) ``` {h↓⍵↓⍨-h←×⍴⎕←⍵}⍣≡ ``` [Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=q8541Db5Ue9WMLlCF8ibcHj6o94tj/qmAplAidpHvYsfdS4EAA&f=bVY7rlUxDNzK6R5I9xX5OtkCBRSUV7dlE4gOPYHQQ1Ag0SIaNsAGWMpZCefEHk8CT7pFbo4T2@PxxG/3z9/2hy939/f3d/un92@2Z/vD1/3x5/7xx/P9w/fj64vXr15u@@Pvd39@bXfX6zVftnrZ5HbZrmEs27lMl@345du5vvbLFm3/sO7n/rGsw6SrybESmhz/6rk8Tx1nb7fb3fB1HCm8oI2vx0Y4//VxLNjJMO4Tv7@Nr3Jepq4r7yka9mFhPsP4Zic14tPcTqojsSyrhXj8kxFMOyOAzzoyD2arsRfzUoejxHsUDUv1eoaFbNq4plua0YGVYdIs4WB3IzUAW@2WbmkpxvG0Vhv70iyJyHJGTyYtrmSBI6qJohpsv5l1HHnXyVVZsu4spTjilSUWmlQ3OSEwV3lcGGndbvB1bkyEyHapGCTgZqeHYKkvKGvIwlvA8PMAfOGvhwGvxYOeyCrkhRgNhgkg9zYQ1tZdNfvrlIvkf3V8wIYw9pMRvXi1FAUcLWS0ZWUQKqM7gy5m1j0vseLp/lQX5pWsL/SWqaRZ6zV8aTL5/1L0EZHhE8irRJPi1YqEsLE3A9BxVxPLxfBpsyJpe2buN1uOFh4mhYrSl5qr9LGXg6JKjdP2r9TFPqCIrJVqkKJfJrkcRtEJpd01dZQhbbHoRuFGxpFJYv2O7P2XIYJCKmaioFJqGkupEGt119QyTtWZJn3BTMW120aCV4hdAgKZ/HId7V4ExTFTwDvgncQoMp@i3ac3T5y0I8YRRWaSkIRXo1OLBS8AiFgdcdsIeKXqLF1xYV3XKyzegLcB4XVYgM1aLpm5WFGgwDdOCylL402vTkMVM@usG8Ep5u8oKCaoR6DalcVCMdJCgguKVPI@rniOJ5VSOjSSo/77YnakVNmVdVyTp6JlhNxI@E7dLsA/sNMq6hwIQ57RzcgpLUQUvlTZQ7F4Nd9I/OeipVmDhaLZ0GmyyACeI4VBnJh2bQByzdW2LGB6e2bCrbfERYojNS/Da3IQgosCsXVZK@zXSHFtaIjIXuyO5VS0Bg2q1LppDojoKjwdPj@tdO@ml5DHjDzh3HERkjlxbI1QEmhUxOfs8lgAPxhVp5IIx7VAYYsIVRZ2h/k9TiBqXOSxMEVFrZKEzWWDupyhsssQGjhqBZ9nOYf7PFw5sWnaZRmXdZaZOy09IbONnRbBF@HLWDh4lKWsQDdB6woJX5h1BCiVjeU6FpeWKLOOVX/6pkGHMCTgIouwJW54XGGeroMX@8lYXP6Fz1MBUoHqXueJKoOX63NqE8JSo8Ci@Xs6CVLDvHDMIn8B&i=AwA&r=tio&l=apl-dyalog&m=dfn&n=f) A dfn submission which prints each iteration. Input is a multidimensional array. -14 from ovs. [Answer] # [Ruby](https://www.ruby-lang.org/), 57 bytes ``` f=->x{x*0==0?x:x[1..-2].map(&f)} g=->h{p h h[2]&&g[f[h]]} ``` [Try it online!](https://tio.run/##lVfdThZBDL3nKb5wQQA/CfM/Y4I@yLoXaAKYqCFGE4zh2XF32tMzo96YcLE7X3fanp6elm8/Pvx8ebm7ef326dfT5fXNzfW7pzdPi7u6eu3Xqy@3j@dndxfPJ/ebwcOvx8PDycPi17Oz@@VueVjX55fHb5@@fj/cX328/fz5fFmWeDzk46Gsx8Pi@mPdH8PxsP3FdX9e2vHg9Xyzbvv59pi7SROT7anQZHvL@@P@1fbtuq4XJyfi@PT919NXp4fL00t3/Wp72V7xE2Park50VPst24Hb31q/3qkH1/0Wi6P2X8vuVELMvCdJepuFxub6b/qlZLab65fiqCgaWVPZ3koPpu4RwGfuCDm1ldiTesndUeA9gtp/QrLs4SPr2t01hcNboUo3qQqM0xgAAQqV9Zam6UvN/G4tNvpL1WQ96eEt6TC5KhNsXkwEfafnVa19xycPrtKETmPJi1UmkwqFJtlMdgjUVewXelrXFb72g4E4US8tCgm43ujBaeoTyhJy4S3omP0D@MKrhQGvyYIeSF3In6J06SaA3NqqsLbmquqrUdOzT7LhAza4fh60IZJVS1DAp4nM16wUQmF@Y9BJzZrlVbR4cj7UhXkF7R@5ZShplHp1X5JM/LsUrUek@DjyKtAkWbU8IazsYQd0zNXA8qL41FHhpI0jz6s@9lbvJonK06aai5RKz/9f1zvBn@oqgpKpyK2D5llVUTWpUxqEuht5o5704dB7WhONWg4SDyI@GcTd7ojWqRGyWkjaSLxEnFW1KSpFRcFUOvWv8kioNqErct30IMArZDEAgUgmmjI3K5fgGDkSGuAdZMsznyR9KjcP7NVPlE2CzCA2AXOoUbULZgoomw1xPXCYe3kUOT/xs8kVGq/DtEF4DRbgvZSrjKzNKJDj1JRClqlFhzlWUcXIOsuBM4rZZAbFCurhqItpshCMpJDggiAVrOMzBvygZ0KHSnLkP2dwQ0qZ/Zv7NXEoWkTIlYRvVPgE/B07LaPOjjDEEd2InMJExMKZFi0UjVfy9cR/LFoY1bpQXis6rUwygMElMBQjpl7rgFw1XU4TmNaekXDLLX4SbU91jPAaDARnokBsTdYS@9VThisawrMXm2E5FK1CgzK1btgYPLoKQ8Y2spnuTfUS8hiRJ5wbLoVkDlyYPZQEGuXxczR5TIAfjMpDSQoXO0dh8wi1TOx24@QOIKqf5DExRUEtk4TVZIO6HKGy01rruJQ525D5H4Bt2Jm7naSdpgVctp6x08I/ZLay0zz4UjhDE1eUNJUV6AZoXSLhE7P2ACWzsUzH/NQSadSxbKNvWIkIQwAuZRK2wAOLy417uLNi/zMWk//C8ZSAlKO653H3iuDlPE51Q5hq5Fg0m6eDIFXsC9vW8vIb "Ruby – Try It Online") [Answer] # [Pip](https://github.com/dloscutoff/pip) `-xp`, ~~25~~ ~~24~~ 22 bytes ``` W@<P@ggM:{0*a?fM@<Saa} ``` Takes the input array as a command line argument; outputs each step on a separate line. Gives an empty list at the end for even-size test-cases, as permitted. [Attempt This Online!](https://ato.pxeger.com/run?1=PY-9CsIwFIXfJaNQMEnz5y3YFygIDg4hQ5YWtwwKBfFJXAQRJ1ffxbfxJA2S5SP3nO8mt0c6ppdnzZxYuD_Pp7Gxn0Pf7fppGjaX9Spux6Hv9jFel2HNfN-eee81KXLUBvKWLJiDHEnipEGcDI4LQMwlWAA16dpRINyDBBquJlsQEiWZXQYkSzK3DbZY2BenJlF2yvIOVUwaLlk7MjvD_2c_) ### Explanation This is for a somewhat more straightforward 23-byte version. The 22-byte version works the same way, except that the main program manipulates `g` (the list of all command-line args--in our case, a singleton list) instead of `a` (the first command-line arg). This ends up saving a byte because Pip's function-call syntax is a bit verbose. ``` W@<Paa:({...}a) ; a is 1st cmdline arg (evaluated, thanks to -x flag) W ; While... a ; Current array P ; Printed (in list format, thanks to -p flag) @< ; Minus its last element ; ...is truthy (nonempty list), loop: ( ) ; Call {...} ; This function (see below) a ; With argument a a: ; Assign the result back to a {0*a?fM@<Saa} ; Recursive function to strip one hypercube layer: a ; The function argument 0* ; Times 0 (either 0 for integer a, or list of 0s for list a) ? ; If truthy, the argument is a nonempty list: Sa ; Argument minus its first element @< ; Minus its last element fM ; Map this function recursively to each remaining element ; Else, the argument is an integer: a ; Return it unchanged ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 18 bytes Anonymous tacit prefix function. ``` {⍵(⊢↓↓⍨∘-)×⍴⎕←⍵}⍣≡ ``` [Try it online!](https://tio.run/##fVa7qmVFEM39ipONwpmgn9Udm6iBgtfscIIBGZMBTUWMhIsOnEER0VRNDAQT/QH9k/0j1727atXq1qtwuezdp3Y9Vq1aXc8@efH0w0@fvfj4o4eHz7bbH69vL3/a7r89/m6/bF/@8PSNv77fbr9vr77b7r/ef/98u/28ffXjw/Px@mp7@cV2@3U3@PO3tN1/s5vdvf/m/v@Dt96@e3h@Oo6G/X70zt177z65XC75fKrnk1zPp0sYj@14TOfT/pevx/Oln0/Rznfrfpzvj3WYdDXZn4Qm@1s9Ho@v9m@v1@uT1x6PvjspdNmG/X4Qjrc@HAXzFUYE8Yht/CqHe02m0k/RQnYLyyKM3@xLreEwty81kFjd1ZLe32Qk044MELMOLILZau7FotQRKNGP4vOfxV@ORFFfG467FR4dfBkmzSAIFg3FAvxqXroVqn2Ih7Xa2C/NyopsefTy0hJKFoCimijOwc6bWceBRJ1ClQWHzuaK96Cy6UKT6iYHBBYqD4eR1u2KWMfBRJFsTsUgAX87IwQrfUFZUxZ6wRQcHyAWXj0NRC2e9ERfIVPEiDFMALmPirC3HqrZq5MwciKq4wM2hHGejPrFu6Uo4NNCjltVBqFyvDPpYmbd6xJrnp5PfWFdySZFvUwtzdqvEUuLyf9uRR8ZGT6BvEo0Kd6tSAgbpzUAHQ81sVwMnzarlg5s5nmzxzHUw6RQY/rSc5XH/5vuoDhTGVUiKtW0D3Aiu6c6pf0ok8gOo@gU03mbZsywt@z0oPAg45NJmN1H9onMEEohOTNxUbk1HaZ4iA2/624ZX9WZOH1BUQW420FCVMhfAgKZjHOt7d4WxTFT5DvgneQpsp6i86ieJ5baJ8YaRWYSlYSbpVOdBbcEqFkdcTsIuMnqLGZx4WFXF5ZvwP2B9DoswG9tl8zsrGhQ4D2ojZRlFKebqaGLmX3Wg@AU87sWFBP0I1D/ymKhGGkjwQVFKvlkV1zZk24pHRrJUf95q3aUVDmndbjJU9MyUm4kfKeSF@AfOGkVfQ6EIc/oZtSUFiIK767sqVi@Wm8k/nPT0qzKQhltmDRZZAAXlMIgTkxzG4Bcc/0tC5g@nplwq5e4iHOkCmZETQ5CcFEgti5rhfMaKbcNAxE5i92xnJrWoEGVWjdtBhFThcvEd6yV7t30EvKYUSeCOy5CMicuuxFKAo2K@Dm7PBbAD0bVqSXCBS5Q2CJSlYXdYb6hE4gaF3ksLFFRqyRhc9mgLmeo7LKoBi5fwXdebu@@M1fucFp2WVZq3W7mSUuPyGzjpEXwRXhXFq4iZWkr0E3QukLCF1YdAUrlYLmOxWUkyqxj1a@@afUhDAm4yCJsiQeeV5j37eDNfjQXl3/h9VSAVKC613nHyuDlep3ahrD0KLBpfp9OgtSwL@zbyd8 "APL (Dyalog Unicode) – Try It Online") `{`…`}⍣≡`  apply lambda until stable  `⎕←⍵` print the argument  `⍴` get its shape  `×` signum of that (gives list with one 1 per dimension)  `⍵(`…`)` apply the following tacit function with the argument as left argument:    …`∘-` negate the right argument (the number of elements to drop, so they'll be dropped from the rear     `↓⍨` drop that many elements from the left argument   `⊢↓` drop right-argument elements from that [Answer] # Python + NumPy, 74 bytes --> 64 bytes (@DLosc) ``` def x(a): if len(a):print(a);x(a[(slice(1,-1),)*len(a.shape)]) ``` [Try it online!](https://tio.run/##bVZdb9swDHzvr9BjMngFJFFfHfZLgjwEW4oGaFMjyYDl12e2yCPtoUXQxrR0Io/HU8f77e3zHB@nj/HzcnPnPx/j3R2u7jw@HdzP6c/z4XI53De76ccPrg5u@l2mL/vB7cLgcv8ECbTBUX@K02cOTIunWOob0xzI/V3ri8J@juxqf0j90zfFvqYyuAWSBQhbogTCAoMYlnounECRTbHHomQbeyVcT5FsQ39KAstHpr4rM2zpmbW@LFjNjYsSWI8SmwSYAZJztJ55F8Mm8EhCQuhvmV4vzDFTqCf1J24KzYHSk2qyhXGFGe4byMzIt0kBpceqADNCNBoajklKQ0Cni@TLpFSmVMjMq/QaVlQhitvFKSeGzWiQlzUcIE7RimRkHMxdJOszB7xKTHpsEivoh5dsK3LBCuaIGwktMFOxsyvZqoaSyZ2sxAYBNVkRsIIEtrKIOwwtmkZIuZrgBVuyIfQ/Gt3VKmIAWrJLqCmuhMh8kmzK2JeEqIg@5/@bFnUkdJO3msjE4XVA5BwGFGEKrAdzlWEjJg9k6niS0c0omLS6YAX1NBhSUi14tBLcqq0lm1eGLQKbwYM3cQiXi6ZVeFA2ryNjN2CqiuQboOS13Jv4JeyRUCcOV16KiZlVVM0NyTwq4DWpPSbQD0XlRUtQdVArExQPohbq9kyXNi2Yv6s9JiuRWcsmwqq2Yb5McNmsJGTsa6Yo7gNJ@hkBXAkJZSdbwddRWU9a/MJmq01agF5wS@htBB9btBXsRnhdMsEnqzqAlGyDpT4WViORlj6W9eoTqip6RBJoGMeFsUULaF5etSB@y0Bf5qL2X@x6SmDKm7tnuZ5gN3V1jyRoMKxQol1OanJtZUgV/y/s99vH7@Or@7s5bF/ckzu9uvfjeX4YL6fzbfryY3q121zfT7@OGz9899th@60veb6@HcbjdgKYNz/@AQ "Python 3 – Try It Online") Thank's @DLosc for removing the return. Nice spot. [Answer] # JavaScript, 53 bytes ``` f=a=>[a,...g(a)+''&&f(b)] g=a=>b=a.map?.(g).slice(1,-1)??a ``` ``` f=a=>[a,...g(a)+''&&f(b)] g=a=>b=a.map?.(g).slice(1,-1)??a console.log(JSON.stringify(f([[[4, 6, 7], [1, 6, 8], [3, 3, 4]], [[9, 2, 8], [4, 9, 4], [6, 3, 9]], [[3, 7, 8], [4, 3, 6], [2, 8, 2]]]))) console.log(JSON.stringify(f([[[6, 5, 9, 4], [8, 8, 5, 1], [9, 3, 1, 6], [1, 7, 7, 9]], [[8, 3, 7, 2], [6, 6, 9, 4], [5, 6, 8, 3], [2, 1, 9, 9]], [[4, 9, 6, 9], [6, 9, 3, 7], [3, 6, 8, 2], [7, 5, 8, 6]], [[8, 6, 2, 1], [3, 5, 9, 5], [2, 6, 1, 3], [3, 6, 3, 9]]]))) console.log(JSON.stringify(f([[[[[5, 1, 6], [8, 2, 9], [9, 2, 4]], [[7, 1, 8], [1, 1, 5], [6, 9, 4]], [[3, 6, 6], [9, 9, 9], [4, 2, 5]]], [[[9, 9, 8], [7, 2, 7], [1, 2, 6]], [[3, 1, 8], [1, 7, 9], [6, 9, 2]], [[6, 6, 1], [6, 8, 8], [2, 5, 6]]], [[[9, 5, 3], [3, 6, 9], [8, 8, 7]], [[4, 6, 4], [8, 7, 9], [8, 6, 7]], [[2, 4, 1], [4, 5, 2], [8, 7, 8]]]], [[[[8, 1, 6], [1, 4, 4], [7, 6, 6]], [[9, 9, 9], [8, 1, 7], [9, 2, 4]], [[9, 5, 7], [1, 4, 8], [3, 8, 1]]], [[[3, 8, 1], [8, 7, 6], [1, 5, 7]], [[8, 5, 1], [7, 2, 1], [7, 1, 3]], [[1, 2, 6], [4, 3, 7], [1, 1, 1]]], [[[8, 1, 1], [7, 5, 2], [9, 3, 6]], [[2, 1, 5], [1, 3, 3], [5, 5, 2]], [[7, 6, 2], [9, 5, 7], [3, 8, 1]]]], [[[[5, 8, 9], [7, 2, 5], [3, 9, 7]], [[7, 8, 7], [3, 4, 1], [4, 1, 3]], [[3, 8, 6], [7, 7, 9], [8, 4, 8]]], [[[7, 5, 4], [8, 1, 7], [9, 9, 1]], [[1, 1, 8], [2, 3, 7], [9, 5, 4]], [[2, 2, 6], [8, 8, 2], [1, 3, 6]]], [[[7, 2, 7], [1, 7, 3], [8, 3, 9]], [[6, 1, 4], [8, 3, 8], [8, 9, 5]], [[5, 7, 2], [9, 7, 6], [1, 3, 4]]]]]))) console.log(JSON.stringify(f([[[[1, 8, 1, 7, 8], [2, 6, 6, 2, 8], [9, 4, 2, 3, 3], [1, 9, 5, 8, 5], [6, 3, 9, 2, 2]], [[8, 2, 5, 5, 3], [3, 3, 8, 6, 6], [3, 3, 5, 6, 6], [4, 2, 5, 3, 6], [2, 2, 5, 5, 4]], [[4, 4, 1, 9, 7], [4, 3, 4, 3, 8], [3, 7, 1, 7, 7], [1, 2, 7, 5, 6], [5, 6, 5, 4, 6]], [[7, 8, 9, 7, 2], [9, 4, 9, 9, 2], [3, 1, 9, 2, 9], [3, 5, 8, 4, 7], [3, 3, 5, 9, 9]], [[5, 6, 2, 4, 3], [2, 9, 6, 6, 1], [6, 8, 2, 9, 7], [5, 2, 1, 8, 4], [7, 7, 9, 6, 1]]], [[[2, 2, 8, 1, 6], [3, 6, 9, 9, 9], [9, 7, 6, 8, 7], [9, 6, 3, 5, 6], [9, 1, 8, 5, 6]], [[2, 4, 2, 7, 3], [8, 9, 8, 7, 1], [1, 6, 1, 8, 4], [9, 9, 8, 8, 2], [5, 5, 7, 9, 5]], [[6, 4, 3, 1, 2], [6, 4, 4, 7, 6], [7, 7, 6, 1, 3], [8, 7, 1, 4, 7], [4, 7, 1, 1, 2]], [[1, 7, 7, 5, 3], [7, 8, 4, 1, 1], [8, 5, 7, 5, 3], [6, 9, 1, 9, 6], [5, 9, 7, 3, 1]], [[6, 3, 7, 1, 5], [1, 9, 4, 8, 2], [9, 6, 5, 9, 5], [2, 9, 4, 4, 6], [8, 3, 6, 7, 4]]], [[[2, 4, 7, 7, 8], [4, 2, 9, 4, 8], [5, 4, 2, 1, 3], [1, 6, 8, 1, 1], [4, 7, 4, 9, 5]], [[4, 9, 1, 3, 7], [3, 3, 7, 6, 4], [4, 6, 7, 4, 5], [7, 3, 2, 7, 6], [5, 5, 7, 9, 3]], [[7, 6, 7, 4, 1], [8, 3, 4, 7, 3], [1, 9, 9, 2, 4], [2, 7, 2, 8, 1], [5, 1, 4, 8, 8]], [[3, 5, 4, 8, 2], [1, 2, 7, 4, 5], [1, 7, 2, 2, 9], [8, 4, 2, 1, 4], [4, 9, 2, 3, 5]], [[1, 1, 9, 7, 8], [4, 8, 1, 7, 5], [3, 5, 2, 2, 7], [8, 6, 3, 2, 1], [6, 9, 9, 1, 3]]], [[[2, 8, 5, 5, 6], [6, 3, 4, 6, 4], [2, 3, 5, 7, 9], [2, 6, 1, 1, 2], [6, 4, 9, 8, 5]], [[8, 4, 7, 2, 1], [6, 5, 4, 8, 7], [7, 8, 3, 6, 8], [2, 2, 4, 7, 2], [2, 3, 6, 4, 4]], [[5, 2, 8, 4, 8], [6, 7, 2, 8, 7], [8, 2, 1, 9, 2], [2, 1, 1, 7, 2], [9, 6, 1, 5, 2]], [[3, 2, 9, 2, 2], [9, 4, 5, 1, 2], [9, 1, 6, 3, 7], [8, 8, 7, 1, 8], [3, 4, 8, 9, 6]], [[8, 6, 1, 6, 9], [1, 9, 6, 9, 4], [6, 6, 6, 9, 6], [2, 5, 3, 6, 5], [6, 6, 9, 5, 7]]], [[[2, 4, 3, 6, 1], [6, 8, 2, 8, 8], [5, 2, 9, 7, 7], [1, 3, 5, 6, 2], [5, 3, 5, 7, 9]], [[5, 3, 8, 8, 5], [2, 7, 5, 3, 7], [2, 5, 1, 6, 6], [5, 7, 1, 4, 2], [5, 1, 4, 5, 2]], [[1, 6, 2, 5, 3], [3, 8, 1, 9, 4], [3, 9, 6, 7, 1], [8, 5, 3, 7, 1], [3, 8, 8, 1, 4]], [[3, 1, 2, 1, 9], [5, 7, 1, 4, 2], [1, 8, 5, 7, 3], [2, 5, 8, 2, 1], [9, 9, 6, 9, 7]], [[4, 8, 3, 5, 6], [5, 6, 4, 2, 3], [2, 5, 3, 1, 6], [2, 9, 4, 9, 4], [4, 6, 8, 2, 2]]]]))) ``` [Answer] # [Python 3](https://docs.python.org/3/), 75 bytes ``` f=lambda x:[x]+(x[2:]and f(q(x))) q=lambda x:0!=x*0and[*map(q,x[1:-1])]or x ``` [Try it online!](https://tio.run/##bVbLbtwwDLz3K9ybnbpAJFGvBfIlhg8bBIsWaDa7QQ7O12@9Ioe0gwRGENPSiBwOR7l8fvx5O4fb7fT07/j6/HLslsO0zL/6ZfKH@Xh@6U79tV@GYfhxtRWPP5@Wh8f16/Twerz013GZ3OG3m4f57b1bbpf3v@eP/tRP648buzJ26@@8/jGP3eTHLrXHS6COHbW3sD73wLp4jcW2Md4DqX2rbZGf75GptJfYnrYptDWFwS0QLUDYEiTgNxjEsNRy4QSybAotFiTb0CrherJk69tbFFg@MrZdiWFzy6y2Zd5qrlyUwDqUWCXADJCco/XcdzFsBI8kJPj2lel1whwzhXpie@Om0D2QW1JVtjCuMMN9A5kJ@VYpILdYEWBGCEZDxTFRafDodJZ8mZTClAqZaZdexYoiRHG7OOXIsAkNcrKGA8QpWpGMjIO5i2R95oBTiUmPTWIZ/XCSbUEuWMEccSOhBWYqNHYlW9VQNLmTlVghoCorPFaQwBYWcYOhTdMIKRcTvGBLNoT@B6O7WEUMQFt2CTWFnRCZT5JNCfuiEBXQ5/S1aUFHQjc5q4lMHE4HRM5hQBGmwDowVxg2YPJApo4nGd2MgkkrG1ZQT4UhRdWCQyvBrdpatHll2CywCTw4E4dwuWlagQcl8zoydj2mKku@Hkrey72KX8IeCXXicOUlm5hZRcXckMyjPD6T2mME/VBU2rQEVXu1MkFxIGqjbsd0adO8@bvaY7QSmbVkIixqG@bLBJdNSkLCvmqK4j6QpJ8QwJUQUXa0FXwd5f2khW9sttikeegFt4TeRvCxTVvBboDXRRN8tKo9SEk2WOpjfjcScetjSa8@oaqgRySBinHcGFuwgOblVAvitwz0bS5q/9mupwimnLl7kusJdlN290iEBv0OJdjlpCZXd4ZU8P/CPA/D7T8 "Python 3 – Try It Online") -7 bytes + fixed thanks to DLosc [Answer] # [Wolfram Language](https://www.wolfram.com/wolframscript/), ~~34~~ 32 bytes ``` #~ArrayPad~-1&~FixedPointList~#& ``` [Try it online!](https://tio.run/##bVZNaxtBDL3nV5im5LRlme@ZQ6E9tFDoITS9tT2YxG4XGic4W0gJ9l9P15KetBtqluCVZzRPT09vcrsef21u1@NwvX7evn0@P77f79d/L9c3xzfu4vhxeNzcXN4Nu/Hz8DAezy@eX19d74f78dPu/s94Ne6H3c@@/3r34fF@v3l4GO52fb/t@y/Ddvt78@28e/V99@rHRd9fTgvH/t20/2n6uG5Vu9X0t0xfDt3qyXerTI@XQOtWkd7C9JwC0@Iplmjj2Wr6pFM004JGK/3hFHmq9JLooZ2B1lQ@wQKpozQajdgXJOBniSLnjoSKoRTZRFkC/RAEfKDCuLwi4D29JcmdCE2iXZQg8wGFgDZa642HxjVKboeKmwSIFa4myomokbZy7gSCoxDj6Vfm3QmblIUpRI2J3rhl8RQoBK/JPk4ubHFXpSKGkQG/ST2FYlWyc5pg1DScxV3uQI2HIorAZ6Iqcy0s5wVQOpd5qRT1Uk9CBYlzZ7TPyRoORFpm1RSAdwaBGx1NDxxwqkeRgeCAKLnRLCYnqRIkEgRCQ6@hmSZoCoNV8Cq4ZKMSreIGtTVZ4QVNQ5lZIHC/Cgle@xqlAhZ3hDgg3SrgInQSrBnVCuQscU57lBIZTFhIl4mOsjNjcxLyAqSQraWgpp0gYJx0p7MSo4nI6XDJYaCmqJ7lAAdKK@cOmF@wrEMe5w7F7fc2r3XGFMprsLqkmnGm3Rnz6prJRp9zF8mdwY0zEZ1Jr6k31tcKd8tmpdFo9xhLzEAzp3YvR4UnMakFR5QNGMSVzmKxGWDJVXPcaO7n8XNUC0afPQaoygHaMDDh1SkllQN5nMAmwzGP2ldvV4pacLKKmcn8QrZVvchugQg7z0pMls3MprPmcKuiVJMRwFWUQEWyFW0m@@W8hoWpV1BTzc/b4nYKM7s1m9T22w3CN2lVH4FjSSpvNufswk0zm/SLcUpzm8y4cPlKFQ4r2hgl0DDUM98MFlCElMWpcMTdOdt/UTmMRLELMplmIebWWbuKGlldXGIJqvXzarSNzvqqF/zM6ir@nzkc/gE) * `ArrayPad[array,-1]` negatively pad 1 element on every side regardless the dimension of `array`. * `FixedPointList[f, x]` applies function `f` on `x` repeatedly, until a fixed-point of `f` is reached. The result is collected in a `List`, extra code (`Grid[...]`) is needed for aesthetic view. Example for Notebook environment: ``` {{7, 2, 3, 6, 4}, {2, 4, 9, 9, 8}, {7, 3, 1, 9, 8}, {9, 1, 7, 6, 9}, {4, 3, 4, 8, 5}} // #~ArrayPad~-1&~FixedPointList~#& // Grid[#,Dividers->{False,Center},Alignment->Left]& ``` [Answer] # [BQN](https://mlochbaum.github.io/BQN/), 20 bytes[SBCS](https://github.com/mlochbaum/BQN/blob/master/commentary/sbcs.bqn) ``` ×∘≠¨⊸/×∘≢⊸(-∘⊣↓↓)⍟⊒˜ ``` [Run online!](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAgw5fiiJjiiaDCqOKKuC/Dl+KImOKJouKKuCgt4oiY4oqj4oaT4oaTKeKNn+KKksucCgpGwqggPuKNnygxLcuc4omhKeKImOKAokpzwqgg4p+oCiJbW1s0LDYsN10sWzEsNiw4XSxbMywzLDRdXSxbWzksMiw4XSxbNCw5LDRdLFs2LDMsOV1dLFtbMyw3LDhdLFs0LDMsNl0sWzIsOCwyXV1dIgoiW1tbNiw1LDksNF0sWzgsOCw1LDFdLFs5LDMsMSw2XSxbMSw3LDcsOV1dLFtbOCwzLDcsMl0sWzYsNiw5LDRdLFs1LDYsOCwzXSxbMiwxLDksOV1dLFtbNCw5LDYsOV0sWzYsOSwzLDddLFszLDYsOCwyXSxbNyw1LDgsNl1dLFtbOCw2LDIsMV0sWzMsNSw5LDVdLFsyLDYsMSwzXSxbMyw2LDMsOV1dXSIKIltbW1tbNSwxLDZdLFs4LDIsOV0sWzksMiw0XV0sW1s3LDEsOF0sWzEsMSw1XSxbNiw5LDRdXSxbWzMsNiw2XSxbOSw5LDldLFs0LDIsNV1dXSxbW1s5LDksOF0sWzcsMiw3XSxbMSwyLDZdXSxbWzMsMSw4XSxbMSw3LDldLFs2LDksMl1dLFtbNiw2LDFdLFs2LDgsOF0sWzIsNSw2XV1dLFtbWzksNSwzXSxbMyw2LDldLFs4LDgsN11dLFtbNCw2LDRdLFs4LDcsOV0sWzgsNiw3XV0sW1syLDQsMV0sWzQsNSwyXSxbOCw3LDhdXV1dLFtbW1s4LDEsNl0sWzEsNCw0XSxbNyw2LDZdXSxbWzksOSw5XSxbOCwxLDddLFs5LDIsNF1dLFtbOSw1LDddLFsxLDQsOF0sWzMsOCwxXV1dLFtbWzMsOCwxXSxbOCw3LDZdLFsxLDUsN11dLFtbOCw1LDFdLFs3LDIsMV0sWzcsMSwzXV0sW1sxLDIsNl0sWzQsMyw3XSxbMSwxLDFdXV0sW1tbOCwxLDFdLFs3LDUsMl0sWzksMyw2XV0sW1syLDEsNV0sWzEsMywzXSxbNSw1LDJdXSxbWzcsNiwyXSxbOSw1LDddLFszLDgsMV1dXV0sW1tbWzUsOCw5XSxbNywyLDVdLFszLDksN11dLFtbNyw4LDddLFszLDQsMV0sWzQsMSwzXV0sW1szLDgsNl0sWzcsNyw5XSxbOCw0LDhdXV0sW1tbNyw1LDRdLFs4LDEsN10sWzksOSwxXV0sW1sxLDEsOF0sWzIsMyw3XSxbOSw1LDRdXSxbWzIsMiw2XSxbOCw4LDJdLFsxLDMsNl1dXSxbW1s3LDIsN10sWzEsNywzXSxbOCwzLDldXSxbWzYsMSw0XSxbOCwzLDhdLFs4LDksNV1dLFtbNSw3LDJdLFs5LDcsNl0sWzEsMyw0XV1dXV0iCiJbW1tbMSw4LDEsNyw4XSxbMiw2LDYsMiw4XSxbOSw0LDIsMywzXSxbMSw5LDUsOCw1XSxbNiwzLDksMiwyXV0sW1s4LDIsNSw1LDNdLFszLDMsOCw2LDZdLFszLDMsNSw2LDZdLFs0LDIsNSwzLDZdLFsyLDIsNSw1LDRdXSxbWzQsNCwxLDksN10sWzQsMyw0LDMsOF0sWzMsNywxLDcsN10sWzEsMiw3LDUsNl0sWzUsNiw1LDQsNl1dLFtbNyw4LDksNywyXSxbOSw0LDksOSwyXSxbMywxLDksMiw5XSxbMyw1LDgsNCw3XSxbMywzLDUsOSw5XV0sW1s1LDYsMiw0LDNdLFsyLDksNiw2LDFdLFs2LDgsMiw5LDddLFs1LDIsMSw4LDRdLFs3LDcsOSw2LDFdXV0sW1tbMiwyLDgsMSw2XSxbMyw2LDksOSw5XSxbOSw3LDYsOCw3XSxbOSw2LDMsNSw2XSxbOSwxLDgsNSw2XV0sW1syLDQsMiw3LDNdLFs4LDksOCw3LDFdLFsxLDYsMSw4LDRdLFs5LDksOCw4LDJdLFs1LDUsNyw5LDVdXSxbWzYsNCwzLDEsMl0sWzYsNCw0LDcsNl0sWzcsNyw2LDEsM10sWzgsNywxLDQsN10sWzQsNywxLDEsMl1dLFtbMSw3LDcsNSwzXSxbNyw4LDQsMSwxXSxbOCw1LDcsNSwzXSxbNiw5LDEsOSw2XSxbNSw5LDcsMywxXV0sW1s2LDMsNywxLDVdLFsxLDksNCw4LDJdLFs5LDYsNSw5LDVdLFsyLDksNCw0LDZdLFs4LDMsNiw3LDRdXV0sW1tbMiw0LDcsNyw4XSxbNCwyLDksNCw4XSxbNSw0LDIsMSwzXSxbMSw2LDgsMSwxXSxbNCw3LDQsOSw1XV0sW1s0LDksMSwzLDddLFszLDMsNyw2LDRdLFs0LDYsNyw0LDVdLFs3LDMsMiw3LDZdLFs1LDUsNyw5LDNdXSxbWzcsNiw3LDQsMV0sWzgsMyw0LDcsM10sWzEsOSw5LDIsNF0sWzIsNywyLDgsMV0sWzUsMSw0LDgsOF1dLFtbMyw1LDQsOCwyXSxbMSwyLDcsNCw1XSxbMSw3LDIsMiw5XSxbOCw0LDIsMSw0XSxbNCw5LDIsMyw1XV0sW1sxLDEsOSw3LDhdLFs0LDgsMSw3LDVdLFszLDUsMiwyLDddLFs4LDYsMywyLDFdLFs2LDksOSwxLDNdXV0sW1tbMiw4LDUsNSw2XSxbNiwzLDQsNiw0XSxbMiwzLDUsNyw5XSxbMiw2LDEsMSwyXSxbNiw0LDksOCw1XV0sW1s4LDQsNywyLDFdLFs2LDUsNCw4LDddLFs3LDgsMyw2LDhdLFsyLDIsNCw3LDJdLFsyLDMsNiw0LDRdXSxbWzUsMiw4LDQsOF0sWzYsNywyLDgsN10sWzgsMiwxLDksMl0sWzIsMSwxLDcsMl0sWzksNiwxLDUsMl1dLFtbMywyLDksMiwyXSxbOSw0LDUsMSwyXSxbOSwxLDYsMyw3XSxbOCw4LDcsMSw4XSxbMyw0LDgsOSw2XV0sW1s4LDYsMSw2LDldLFsxLDksNiw5LDRdLFs2LDYsNiw5LDZdLFsyLDUsMyw2LDVdLFs2LDYsOSw1LDddXV0sW1tbMiw0LDMsNiwxXSxbNiw4LDIsOCw4XSxbNSwyLDksNyw3XSxbMSwzLDUsNiwyXSxbNSwzLDUsNyw5XV0sW1s1LDMsOCw4LDVdLFsyLDcsNSwzLDddLFsyLDUsMSw2LDZdLFs1LDcsMSw0LDJdLFs1LDEsNCw1LDJdXSxbWzEsNiwyLDUsM10sWzMsOCwxLDksNF0sWzMsOSw2LDcsMV0sWzgsNSwzLDcsMV0sWzMsOCw4LDEsNF1dLFtbMywxLDIsMSw5XSxbNSw3LDEsNCwyXSxbMSw4LDUsNywzXSxbMiw1LDgsMiwxXSxbOSw5LDYsOSw3XV0sW1s0LDgsMyw1LDZdLFs1LDYsNCwyLDNdLFsyLDUsMywxLDZdLFsyLDksNCw5LDRdLFs0LDYsOCwyLDJdXV1dIgrin6k=) `...⍟⊒˜` Iterate 0 to length-1 times, collecting the results: `×∘≢⊸(-∘⊣↓↓)` Drop the outer face. `×∘≠¨⊸/` Remove empty arrays from the output. Calculating the length of the output to avoid the last step is a byte longer: ``` ×∘≢⊸(-∘⊣↓↓)⍟(↕·⌈2÷˜≠) ``` [Run online!](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAgw5fiiJjiiaLiirgoLeKImOKKo+KGk+KGkynijZ8o4oaVwrfijIgyw7fLnOKJoCkKCkbCqCA+4o2fKDEty5ziiaEp4oiY4oCiSnPCqCDin6gKIltbWzQsNiw3XSxbMSw2LDhdLFszLDMsNF1dLFtbOSwyLDhdLFs0LDksNF0sWzYsMyw5XV0sW1szLDcsOF0sWzQsMyw2XSxbMiw4LDJdXV0iCiJbW1s2LDUsOSw0XSxbOCw4LDUsMV0sWzksMywxLDZdLFsxLDcsNyw5XV0sW1s4LDMsNywyXSxbNiw2LDksNF0sWzUsNiw4LDNdLFsyLDEsOSw5XV0sW1s0LDksNiw5XSxbNiw5LDMsN10sWzMsNiw4LDJdLFs3LDUsOCw2XV0sW1s4LDYsMiwxXSxbMyw1LDksNV0sWzIsNiwxLDNdLFszLDYsMyw5XV1dIgoiW1tbW1s1LDEsNl0sWzgsMiw5XSxbOSwyLDRdXSxbWzcsMSw4XSxbMSwxLDVdLFs2LDksNF1dLFtbMyw2LDZdLFs5LDksOV0sWzQsMiw1XV1dLFtbWzksOSw4XSxbNywyLDddLFsxLDIsNl1dLFtbMywxLDhdLFsxLDcsOV0sWzYsOSwyXV0sW1s2LDYsMV0sWzYsOCw4XSxbMiw1LDZdXV0sW1tbOSw1LDNdLFszLDYsOV0sWzgsOCw3XV0sW1s0LDYsNF0sWzgsNyw5XSxbOCw2LDddXSxbWzIsNCwxXSxbNCw1LDJdLFs4LDcsOF1dXV0sW1tbWzgsMSw2XSxbMSw0LDRdLFs3LDYsNl1dLFtbOSw5LDldLFs4LDEsN10sWzksMiw0XV0sW1s5LDUsN10sWzEsNCw4XSxbMyw4LDFdXV0sW1tbMyw4LDFdLFs4LDcsNl0sWzEsNSw3XV0sW1s4LDUsMV0sWzcsMiwxXSxbNywxLDNdXSxbWzEsMiw2XSxbNCwzLDddLFsxLDEsMV1dXSxbW1s4LDEsMV0sWzcsNSwyXSxbOSwzLDZdXSxbWzIsMSw1XSxbMSwzLDNdLFs1LDUsMl1dLFtbNyw2LDJdLFs5LDUsN10sWzMsOCwxXV1dXSxbW1tbNSw4LDldLFs3LDIsNV0sWzMsOSw3XV0sW1s3LDgsN10sWzMsNCwxXSxbNCwxLDNdXSxbWzMsOCw2XSxbNyw3LDldLFs4LDQsOF1dXSxbW1s3LDUsNF0sWzgsMSw3XSxbOSw5LDFdXSxbWzEsMSw4XSxbMiwzLDddLFs5LDUsNF1dLFtbMiwyLDZdLFs4LDgsMl0sWzEsMyw2XV1dLFtbWzcsMiw3XSxbMSw3LDNdLFs4LDMsOV1dLFtbNiwxLDRdLFs4LDMsOF0sWzgsOSw1XV0sW1s1LDcsMl0sWzksNyw2XSxbMSwzLDRdXV1dXSIKIltbW1sxLDgsMSw3LDhdLFsyLDYsNiwyLDhdLFs5LDQsMiwzLDNdLFsxLDksNSw4LDVdLFs2LDMsOSwyLDJdXSxbWzgsMiw1LDUsM10sWzMsMyw4LDYsNl0sWzMsMyw1LDYsNl0sWzQsMiw1LDMsNl0sWzIsMiw1LDUsNF1dLFtbNCw0LDEsOSw3XSxbNCwzLDQsMyw4XSxbMyw3LDEsNyw3XSxbMSwyLDcsNSw2XSxbNSw2LDUsNCw2XV0sW1s3LDgsOSw3LDJdLFs5LDQsOSw5LDJdLFszLDEsOSwyLDldLFszLDUsOCw0LDddLFszLDMsNSw5LDldXSxbWzUsNiwyLDQsM10sWzIsOSw2LDYsMV0sWzYsOCwyLDksN10sWzUsMiwxLDgsNF0sWzcsNyw5LDYsMV1dXSxbW1syLDIsOCwxLDZdLFszLDYsOSw5LDldLFs5LDcsNiw4LDddLFs5LDYsMyw1LDZdLFs5LDEsOCw1LDZdXSxbWzIsNCwyLDcsM10sWzgsOSw4LDcsMV0sWzEsNiwxLDgsNF0sWzksOSw4LDgsMl0sWzUsNSw3LDksNV1dLFtbNiw0LDMsMSwyXSxbNiw0LDQsNyw2XSxbNyw3LDYsMSwzXSxbOCw3LDEsNCw3XSxbNCw3LDEsMSwyXV0sW1sxLDcsNyw1LDNdLFs3LDgsNCwxLDFdLFs4LDUsNyw1LDNdLFs2LDksMSw5LDZdLFs1LDksNywzLDFdXSxbWzYsMyw3LDEsNV0sWzEsOSw0LDgsMl0sWzksNiw1LDksNV0sWzIsOSw0LDQsNl0sWzgsMyw2LDcsNF1dXSxbW1syLDQsNyw3LDhdLFs0LDIsOSw0LDhdLFs1LDQsMiwxLDNdLFsxLDYsOCwxLDFdLFs0LDcsNCw5LDVdXSxbWzQsOSwxLDMsN10sWzMsMyw3LDYsNF0sWzQsNiw3LDQsNV0sWzcsMywyLDcsNl0sWzUsNSw3LDksM11dLFtbNyw2LDcsNCwxXSxbOCwzLDQsNywzXSxbMSw5LDksMiw0XSxbMiw3LDIsOCwxXSxbNSwxLDQsOCw4XV0sW1szLDUsNCw4LDJdLFsxLDIsNyw0LDVdLFsxLDcsMiwyLDldLFs4LDQsMiwxLDRdLFs0LDksMiwzLDVdXSxbWzEsMSw5LDcsOF0sWzQsOCwxLDcsNV0sWzMsNSwyLDIsN10sWzgsNiwzLDIsMV0sWzYsOSw5LDEsM11dXSxbW1syLDgsNSw1LDZdLFs2LDMsNCw2LDRdLFsyLDMsNSw3LDldLFsyLDYsMSwxLDJdLFs2LDQsOSw4LDVdXSxbWzgsNCw3LDIsMV0sWzYsNSw0LDgsN10sWzcsOCwzLDYsOF0sWzIsMiw0LDcsMl0sWzIsMyw2LDQsNF1dLFtbNSwyLDgsNCw4XSxbNiw3LDIsOCw3XSxbOCwyLDEsOSwyXSxbMiwxLDEsNywyXSxbOSw2LDEsNSwyXV0sW1szLDIsOSwyLDJdLFs5LDQsNSwxLDJdLFs5LDEsNiwzLDddLFs4LDgsNywxLDhdLFszLDQsOCw5LDZdXSxbWzgsNiwxLDYsOV0sWzEsOSw2LDksNF0sWzYsNiw2LDksNl0sWzIsNSwzLDYsNV0sWzYsNiw5LDUsN11dXSxbW1syLDQsMyw2LDFdLFs2LDgsMiw4LDhdLFs1LDIsOSw3LDddLFsxLDMsNSw2LDJdLFs1LDMsNSw3LDldXSxbWzUsMyw4LDgsNV0sWzIsNyw1LDMsN10sWzIsNSwxLDYsNl0sWzUsNywxLDQsMl0sWzUsMSw0LDUsMl1dLFtbMSw2LDIsNSwzXSxbMyw4LDEsOSw0XSxbMyw5LDYsNywxXSxbOCw1LDMsNywxXSxbMyw4LDgsMSw0XV0sW1szLDEsMiwxLDldLFs1LDcsMSw0LDJdLFsxLDgsNSw3LDNdLFsyLDUsOCwyLDFdLFs5LDksNiw5LDddXSxbWzQsOCwzLDUsNl0sWzUsNiw0LDIsM10sWzIsNSwzLDEsNl0sWzIsOSw0LDksNF0sWzQsNiw4LDIsMl1dXV0iCuKfqQ==) [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 12 bytes ``` ẉ&{ċbk↰ᵐ|ℕ}↰ ``` Outputs one array per line. Includes an empty array for even-length inputs. [Try it online!](https://tio.run/##SypKTM6ozMlPN/r//@GuTrXqI91J2Y/aNjzcOqHmUcvUWiDz///o6GgzHQVTHQVLHQWTWB2FaAsdBQuwgCGIBxQ1BjJ1FMxAPCBtDkaWsSAuSK0xmG8E4gLNMUOYYwrmgVSAeEZgQyzhOk3AHJByqE6IReYgnjFMJ9hUc7BjLEAugNkJlDWCus8Y5nZTqC1mYIuMEeYYg@2MBQA "Brachylog – Try It Online") ### Explanation ``` ẉ&{ċbk↰ᵐ|ℕ}↰ ẉ Write the input to stdout with a trailing newline & And, with the input { } Apply this predicate to remove one hypercube layer: ċ The input must be a list b Remove the first element k Remove the last element ↰ᵐ Map the current predicate recursively to each remaining element | Or, if that definition fails, try this one: ℕ The input is a nonnegative integer (return it unchanged) ↰ After removing a layer, call the outer predicate recursively The recursion continues until the predicate fails ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 20 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` Δ=DdΔ€`}\N>"妨"צ.V ``` Will always output a single trailing empty list. [Try it online](https://tio.run/##ZVI7TsVADLxK9OoIaZP9FlBRU9KESICgoKKgpuEMT@IGTxS0XCD0OQQXCfHYXq/0Unmd8Yw99uvbw@PL87atx8vrp/X49/F9/353c3VYf5bT8nX4/VxOF7fbNtEX@s71XZz7bsp9N/RdobAg9DPFUwIkU@wQBgrjDq2QcacQloI8WDxYwswY@QOehD9JKAcqVZ5GKgkPSw0MiZByks@CJh2wVKn9OdKDWysyYCZVYDzyXvLJILFCyAKR8iAcDJ1n1aKEWuhQ4WXEWOdqTGF0OnOZW07GkqV7KlAtfdY2VDXUpjMezlzW0JEhgKjlPNdoqq6RyvLkYh2@AB@rP3oNDnkYHgSttxOtVAe0qcTCgESxpoPASp0ryfI43@zF5mLaKCzNSj3vC1o8jD9fRUFH4o@zuxoNEuq2BrOQr2owF2Ij1Vx5En8yQKVes7NuRlHN6CYwJKBULWx2PqKb/fsH) or [verify all test cases](https://tio.run/##XVa9bpQxEOx5iuhqC8m/ayNBGhoa6Gg@TgIEBQ0gJUFKkYZniMQbRBS08ABHn4fgRYJ3drwXyBXx@Wc9Ozuzvk9nb95@eH/3Zffs4@eL80cnu9PL8GD34uJ8fjubX8Pl3e3146fvbq//fP3x@urV8ye725@Hm8P33e9vh5uHL@@uDr9O77Ztk5BCDi2UfdhSKGHMT59jmbOR4zFHMveMOS5zvoQe6n4fTub5Mudlzsf5X/dmXZ9r2zyVMKMxNXqbKwMreUbrjNVwbw9pz4AtVB7oek2IAKBgGq6R@bEwPWighNCNZ6rCCBlBFb7tVAgGX/dlAM7YmZBqnaPGmG3CjlhXHBWR2oyVeQZJGNRtXmewZiCE15wte5krHYAjghhAy77hzAA8ZSEpm7q0HdlPZDURWPZ44okkrGjyETMdO2Y0PcN41YEPUiqkpJFk4UrjiqogAlcFPR3VYsD5bRWi4LwgG6v3YKQI7EcuFIXwjGlk7mFAG9stFrcSxyq@sCCCIuiKsWL6EXK84nWMraiJ0mnMyyoxo4CTih1Wq8a9ldIwfJaximMQR8XqIEIBmzqzGFsIMwSlZxa7BRwGOK6S@cXT0NuQV2QFM1cqGUzMuFOy0bJivKUVQV7dfaayLZzp@D/gW81JmPFiHa51YccAdETTYArrBAX9IuPMgHHq8vZcSaycanApD1zgFh1XjqF697/tL1RmgXXFu02magSYli8EOjfLz7OsstZkeHbWzxJORyActLZWRBzTahQVmRY2kBHueysRU1U96vlVX@yxWmgmyyHwHD0BnqmWgSZS2QMimlxz5yWv4tD9uD2iAdmN6BBUgXImXtMGpiIborIorsHVwBCRmReMI2tmjdVqJmAn0pfV5zUfZdFY15wylduCVadSF4UIR2j32ugAqkZFzn4DzRlvBfd3KmOwU1QwEqm3Fpa7dXfxzAtwZa@nsLcVuwO3K9ZERhZv2d0vdHCH3sT1bT1MsYtVFqfRx9TPcHr1bE2VhSzoieTuT/RiQcxM5NGUzrzNc5UKTfR1h14SdTgsV@etwzmNHiz@kmfL0Z@voy4GX@8NuMQjWx7C@me@5ylYbRKjQln0SgqddWrkR/gWRrou4WZxLUTvuRlVTu7TSoSaXWMtuzmA7i9w9vGZjnzToj3u/I1hPwUa30HFW/0HAl4W11v@x9udeoPL2WOsW5nTFp@WeYYHK5VRiTchi0aNmdOSK6a605r1vvXSEHtGHuKuyxzbXdF/PUTj9787rI8IO1dFTpH9ovmLVVDZY99EN3euInmzvrkc1K2vz7@/). **Explanation:** ``` Δ # Continue looping until the result no longer changes: = # Print the current multi-dimensional matrix with trailing newline # (without popping) # (which will use the implicit input in the first iteration) DdΔ€`}\N> # Determine the depth of this multi-dimensional matrix: D # Duplicate it d # Transform each inner integer to a 1 (with a >=0 check) Δ # Inner loop until the result no longer changes: €` # Flatten one level down }\ # After the inner loop: discard the result N> # Push the last 1-based index instead (0-based index + 1) "妨"× # Repeat "妨" that many times as string ¦ # Remove the leading "ε" .V # Evaluate and execute it as 05AB1E code: ε # Map over each inner list: ¦ # Remove the first item ¨ # As well as the last item ``` It'll always output an additional trailing empty list, because `Δ` will loop an additional time to determine if the list isn't changing anymore. The determination of the depth of the multi-dimensional matrix (`DdΔ€`}\N>`) is taken from [this answer of mine](https://codegolf.stackexchange.com/a/240671/52210). Minor note: `"妨"×` cannot be `…妨×` or `…娦×`, because the `¦¨`/`¨¦` will be interpret as [dictionary words](https://codegolf.stackexchange.com/a/166851/52210) `"ink"`/`"keys"` respectively: [try it online](https://tio.run/##yy9OTMpM/f//UcOyc1sPLTu04vB0HS4IZ8WhZUDO//8A). [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 188 bytes ``` ;{:G` (\[)(\d+|\[((\[)|(?<-4>])|[^][])+(?(4)^)]),(?=(\d+|\[((\[)|(?<-7>])|[^][])+(?(7)^)]),)|(?<=,(\d+|(?(10)^)\[((])|(?<-10>\[)|[^][])+])),(\d+|\[((\[)|(?<-13>])|[^][])+(?(13)^)])(?=]) $1 ``` [Try it online!](https://tio.run/##ZVbLTl0xDNzzHa10j0gl8nRSCiz5iMNBrdQuuumi6q78O7XHk1xuWXFIHGc8nnHu7x9/fv769nr78fT49fX27@fHr1enp307PX2/fnnaT/b9cnr48qncH9vL/nzsx3Z9ejiV7Xk7tnB6uHsXKZeR4pHYuwuI1tV4o8t26vBD8ebezvPYsW3hXd6YLxPHjMwK4diuPsTX133fS2hBjrBH/dv1bw45lEM/9hESVkoYuhL2pjsDOzkId3Jo@lfjQjqO40rztVAZ33W1hqhfQ@MiIqOeFGbpwfIkZG48Uw1FyMgZdc0jDYFGINJyCXA23Bp20Vu6ZvecTVFH7BuOikxNc2WeQQ1AuuttjkrzILtV7LWL7nTgjcjh@Lz2hjMD6IyDpBHYwloHokROE3HllU9WHQk7VnvESkeEZrMzzFcX7kFGhYw0cizcadzRCpCv6NnEiH4wof43@1BwXlCNd3swUwT2MxeGQnjGFaIxTOjffovnrcQxey/sh6AHtuOsuHqEHM98Hd/e00TlNNblndAs4KQiwnvVGFupDMfnFZs2BnFU7A4iFLBpK5OxiTBDT3ZmslvAoSU0ZOWCp2G3oa7IDmbuVDKYWHGnYqNXxXxTK4K6@nKZqbZwpeOv6dl2Kn0zFuvw7NR1DABHMA2W6Ag3sTp9Zi6jpk5j605i40yCU3igApfYd@U3RL/M7/GFwiwwrrDBheDN6jA/bSGQuRtez7LJ1pKxijPbD3xn5HSTZuAubJ3bfJAWq7RwfIzw1lqJmKrJ0c7P9iLGW2GVTIPAcrQEaKZYBkZI5QiIGHFtGS@tJg6Lx@0R48dvxICgCIwzWS1tYCpyHBqLsiQ4xxcysvKC78ie@Vj1ngnYibRlXetWj7HorFtNmcJtwbtTqYtChCO0N0N0AFWjIHXcQHLOW8H9ncoYHBQVjETqrYVpbosuq/ICXHn1Uzjait@B2w1rIiOTt7zMLzRwh95k6dtHmGEX7yxOY4yZnWH0uqp1VRayYCfSMn@iFQtyZiKPrnTW7Z6rVGiirTv0kqjD4bUu3jqc0@jBOdRxA0ePP15nXQx41n1agqzMXoew/5mPeQrem8SsUBa9kkJnnxr5ET6Fka5LuFmWFuIauRldTsunlQitusZedncA3V/g7PMjHfmkRX/a@QPDfwg0PoOGt66fB3hYlt7yhbc79QaXc8b4tHKnTT698gwPViqjEm9CFY0ac6elpZi6nNZ89s2Hhtgz6pDlusxvvyuuHw/R@f3vDp8jwslVUVPkvGjrwSro7HluYpovriJ587k5HdR9rh/HPw "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: ``` ;{:G` ``` Output the contents of the buffer before every iteration, but don't double-output the last iteration. ``` (\[)(\d+|\[((\[)|(?<-4>])|[^][])+(?(4)^)]),(?=(\d+|\[((\[)|(?<-7>])|[^][])+(?(7)^)]),)| ``` Match the first element in the array or one of its inner subarrays, as long as that array has at least three elements. The leading `[` is captured as that's slightly golfier than a lookbehind. The first element is matched normally and the second element is matched with a lookahead as if it's a subarray then we'll want to match the first element in the subarray. .NET balancing groups are used to ensure that whole subarrays are matched. Alternatively: ``` (?<=,(\d+|(?(10)^)\[((])|(?<-10>\[)|[^][])+])),(\d+|\[((\[)|(?<-13>])|[^][])+(?(13)^)])(?=]) ``` Match the last element in the array or one of its inner subarrays, as long as that array has at least three elements. The penultimate element is matched with a lookbehind which is subtly different as it matches from right to left so `]`s increase the balancing group depth and `[`s decrease it. Here a lookahead is slightly golfier than capturing the trailing `]`. ``` $1 ``` Keep the leading `[` before the first element if that's what we matched. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 66 bytes ``` W¬⁼θυ«≔∨υθθ⟦⭆¹θ⟧≔IIθυ≔⟦υ⟧ηFη«F‹²Lκ«≔⟦⟧ζWκ⊞ζ⊟κF⮌✂ζ¹±¹⊞κμ»Fκ¿⁺⟦⟧λ⊞ηλ ``` [Try it online!](https://tio.run/##bVZNb9swDD2nv8JHG8gO@rSEnYZht64LtmPQQ1C4cdCsaeKkAzr0t2eWyCfaQwO3jSnyiXyknvrQb04Ph83@ev3T7/ZdVd8dzvW342WzH@rjsro0TVP9vVl8GYbd9rn@caovy@rYpJ/PN4vVafd8rte/zuPf7ffNS63Swn1a4oCvm@FMv45Nk@BkaX25X1Z9MjweTlXd533o@203DLVeVrfd8/bc10@cxKKEjpFvKXKx4Kyfmmp1Gfr6bVmtDi8pIq9mtJ/da3cauvrXfvfQJY8xy7tuuzl3tWoSdI58Wla/c9A7shgxd49VvdpfhrzjHq59@j66vt@8X6/r9BkRQ8Ztxy@j63pM3udHsyEuK5vfzPgkw@g82lwOdMng81rMTvo@WdYhv7j85CCTfQKBi8GJwSLEsEFPMCzB2pwLJdBykMk2w9maXAnV03K2Or85hqUtXY7yBNvmzGJ201JzpKIYVqHEyAZiwPI@pZ4URbAOPFomQedVolcxc8QU6nH5jZpik6HNSUUOIVxmhvoGMj3yjVxAm22BgQnBCA0R27hCg0anW86XSAlEKZPpZ@lFeAQmitpFKTuC9WiQYh8yWEpRiiRkbExdtNJnMqgyYtxjGbEW/VCcbUAu8CCOqJGYBWLKZHY52zJDTsbdSokRAxTZQ8PDMmygIc4wdtI0i5SDDDxjczYW/TdCd5CKCMBO2bWoycwGkfi0HOQR55gogz77/5tmypEoQUpqsjIcqhwQ3ocAeTAZVoG5QLAGJw9kluNphW5CwUkLE1ZQT4QguTILCq0Et0XWnJxXgm0Z1oMHJcPBXE6aFqBBXrTOCrsap6rlfDUmeT7ukfUS8mhRJzYvvLQyzDRFQdTQikZpLNsijw70Y6L8pCWoWhcpYxQFoibTrYiu0jQt@l7k0UmJxJqXIQxFNkSXLVTWFxI84qJMFPXBcvoeBlwJDmU78aDrqJ2fNPOBzAY5aRrzglui3EbQsUlbwa6B1jkZeCdVa5Di5WAVHdOzI@GmOubL1cdUBfTIsiHiOE6EzYih5KXKLLDeEtCHuRT5b@V6cmBKibp7vp4gN2F2jzjMoJ6hGLmcisjFmSAF/L8wfq6fXvf/AA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` W¬⁼θυ« ``` Repeat until the array stops changing. ``` ≔∨υθθ ``` Except on the first run, use the new array in place of the original. ``` ⟦⭆¹θ⟧ ``` Pretty-print the array on its own line. ``` ≔IIθυ ``` Deep clone the array. (Unfortunately adding `0` or multiplying by `1` doesn't work because those operators only vectorise once.) ``` ≔⟦υ⟧ηFη« ``` Start processing the array and all of its subarrays. ``` F‹²Lκ« ``` If this array has at least three elements, then... ``` ≔⟦⟧ζWκ⊞ζ⊟κ ``` ... remove the elements of the array into a temporary array, and... ``` F⮌✂ζ¹±¹⊞κμ ``` ... push all of the elements of the temporary array except the first and last back to the array. ``` »Fκ¿⁺⟦⟧λ⊞ηλ ``` Push all subarrays of the current array to the list of arrays to be processed. [Answer] # [Python 2](https://docs.python.org/2/), 68 bytes ``` def f(L):L>f<map(f,L)<L.pop(0)+L.pop() L=input() while[f(L)]:print L ``` [Try it online!](https://tio.run/##bVbtittADPzfp/DPhJrS3ZX247j2CfwGIT8KvXCBNmdKSunTp/ZKI9nlDnPY8mosjWZnM/@9v77d4uPx/eUyXA7T8Wn6enn@@W0@XMbp@Dx9mt/mw@fjR7k5fpi@XG/z7/ty9@f1@uPltKacn@Zf19t9mB6P0/IXxqGOw/K/LDfncTjFccj9ihpo40D9KS3XGlgWLzHuibwGcn/X@qJ4XiOn2h@4Xz0p9TVVwD3AHiCkJA3EDQYJLPVapICiSanHklabeifST9FqY39ihZVPcs/KAlt6Za0vi95zk6YUNqDFpgFhgPQ71s@aJbAMHklJiP2t0BuUOWEK/XB/kqHQGii9qKYpgqvMyNxAZka9TRsoPVYVWBCS09DwGTYaIiZdtF4hpQqlSmbeldewoipRMi4pmQU2Y0BB10iApERvUpDxYZki@ZwlEExiOmOXWME8glZbUQtWCEcySGhBmEqdXa3WNMQud/IWGwTUdEXEClLYKiLuMLQZGqHk6oJXbK2GMP/kdFfvSABoyy6hp7QTovBJmpSRx0pUwpzz/0NLtiUsKXhP5OIItkH0OwKowlTYAOaqwCbsPJBp25OcbkHBTqsbVtBPgyGxaSFglODWbI19vwpsUdgMHoKLQ7ncDK3Cg7J7HTm7EbuqaL0RSt7Lvalfwh4JfeLjxktxMYuKqrshuUdFvCazRwb9UFTejARdR7MyRQkgaqPuIHTZ0KL7u9kje4vCWnYRVrMN92WCy2YjISOvuaJkDqTlZwRwJDDaZl8hx1HZ77T0js1W32kResEpYacRfGwzVrCb4HXsgmfvOoKU7BvLfCzutgRvfSzb0adUVcyINNCwHTfGljxgdQXTgvqtAL1bi9l/8eOJwVRwd896PMFu6u4cYWgw7lCSH05mcm1nSBW/F87nfw "Python 2 – Try It Online") A program taking input from STDIN and output to STDOUT. Doesn't output the initial array. Terminates with error. ]
[Question] [ Find what is the distance for a given string to its closest palindrome of the same length. For this task I decided to give the characters further away from the string's center more weight (think of it as contributing more torque), proportional to their distance to the center. Let's define the palindrome distance for a string \$s\$ as the sum of all products of the absolute difference of the corresponding pairs, equally spaced from the string's centre, and their distance to the center. \$D\_p=\displaystyle\sum\_{i=1}^{d}\left(d-i+1\right)|s\_i-s\_{l-i+1}|\$ where \$l\$ is the length of \$s\$ and \$d = \left\lfloor\frac{l}{2}\right\rfloor\$ Since the middle character doesn't contribute anything to the sum, \$d\$ for strings with odd length \$l\$ is equal to \$d\$ for strings with length \$l-1\$. ## Task Given string \$s\$ with length > 1 find \$D\_p(s)\$ ## Input One of the following: * a string; * a list of characters; * a list of numbers. ## Output An integer - the palindrome distance of the input string. ## Test cases ``` "aa" -> 0 "bab" -> 0 "abca" -> 1 "cbade" -> 6 "hello" -> 21 "code-golf" -> 45 "neveroddoreven" -> 0 "Neveroddoreven" -> 224 ``` ## Winning criteria The shortest code in bytes in every language wins. # [Sandbox](https://codegolf.meta.stackexchange.com/a/19363/75681) [Answer] # [Haskell](https://www.haskell.org/), 50 bytes ``` u#(a:b)|c:d<-reverse b=u+(abs(c-a)+u)#d u#_=u (0#) ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/v1RZI9EqSbMm2SrFRrcotSy1qDhVIcm2VFsjMalYI1k3UVO7VFM5hatUOd62lCvdVsNAWfN/SWpxiW20oY4RGFrGcuUmZubZpuRzKSgUFGXmlaikK4CU/AcA "Haskell – Try It Online") Look ma! No multiplication! (or division) ## Explanation Rather than explain what this answer *does* which I think would only be confusing, I think I will give an abridged explanation how I came to this answer. First off Haskell is a recursive language, so we want to phrase this in a recursive way. This is pretty easy to do, if we have a list ``` [ a , d... , c ] ``` Then we take the "palindrome distance" of the middle bit `d` and add on `abs(a-c)*(div(length d)2)`. If it is anything else the answer is zero. Now getting the last element is a little hard in Haskell, but getting the first is dead simple. So one way to get the last element is to reverse the list and get the first one. In order to get the middle we then have to reverse that back to the original order. Our first breakthrough is to realize that when you reverse a string its "palindrome distance" doesn't change. So we don't have to reverse the middle part back to its original order since computing on the reversed order will give the correct result anyway. ``` f(a:b)|c:d<-reverse b= ... ``` So all in all our code is: ``` f(a:b)|c:d<-reverse b=f d+abs(a-c)*div(length d)2 f _=0 ``` Ok but `length` and `div` are kind of costly. The number of steps left is really just the thing we are looking for so what if we used that to help us. ``` f(a:b)|c:d<-reverse b,(k,n)=(k+abs(a-c)*n,n+1) f _=(0,1) g=fst.f ``` Well that didn't help, but we are onto something here. Multiplication is just repeated addition, so what we really want is to add `abs(a-c)` once for each remaining iteration. So why don't we keep track of the numbers we want to add and just keep adding them on the way down. ``` u#(a:b)|c:d<-reverse b=sum u+(abs(c-a):u)#d u#_=sum u g=([]#) ``` So here we have this extra argument `u` which is just the list of all the absolute differences so far. And each iteration we add the sum of these to the result of the next iteration. This way each difference gets added as many times the number of steps from the center, in essence multiplying it by its distance from the center. Of course since we are only ever asking `u` for its sum we don't actually need to separate the values we can just keep track of the running sum to save some bytes. ``` u#(a:b)|c:d<-reverse b=u+(abs(c-a)+u)#d u#_=u g=(0#) ``` And this gives us the final code. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 8 bytes -1 byte thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen) for reminding me that input can be taken as lists of integers. ``` Âα2äθā*O ``` [Try it online!](https://tio.run/##yy9OTMpM/X@4/f/hpnMbjQ4vObfjSKOW////yfkpqbrp@TlpAA "05AB1E – Try It Online") **Commented:** ``` # implicit input: a list of codepoints  # push codepoints and codepoints reversed α # take the (element-wise) absolute difference 2ä # split into 2 pieces # the last one will be shorter for odd lengths θ # take the last piece ā # length-range: [1, ..., length] (doesn't pop the TOS) * # multiply element-wise O # take the sum ``` [Answer] # [R](https://www.r-project.org/), ~~50~~ 47 bytes *Edit: -3 bytes thanks to Giuseppe by using `%*%` operator to calculate inner product of vectors, rather than summing the product of elements as separate operations* ``` abs((rev(x<-scan())-x)[(y=sum(x|1)/2):1])%*%1:y ``` [Try it online!](https://tio.run/##lZHBSgMxEIbP5imGltJEXGyWKmV1vXvxpCcVmU1m7UKalCRbtqjPvqaI6GFd6eG/DHzzf8z4vscqcO5px7vrLCi0XIisE498X4Z2w7t3Kc5zUchnMTudyWLfy8US5EKmrL4iJWMKI58/2blgbAqa6sYSYIC6tSo2zkJ0EP0e0BiIFGKmMFBgWzSN1d5t6EU3IaJVVH4jvBNv7ORHblSKfaRa6yIVQN2WVAxg0kJwNdh2U5EPZxAcKGd35OMvBWjsQW1NjYeHWK9gh6alULBQThAnV13Zpum9u7WRBwFTyG4WQ9rJ74BUWB3NYKWGi@QIpCrUNEhdjlBrMsYNUvlomdOUvTpTD6LLixHUUjq409qlH5I9@jZ3/@N5vvxrAes/AQ "R – Try It Online") Accepts list of numbers. Un-golfed code: ``` x=scan() # x is vector of numbers y=sum(x|1)/2) # y is half the length of x sum( # return the sum of... abs( # the absolute values of... (x-rev(x)) # the differences between each element of x # and the same elements reversed... [y:1] # at positions y..1 # (so only the first half, backwards)... *1:y)) # multiplied by 1..y ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~74~~ \$\cdots\$ ~~52~~ 51 bytes Saved ~~6~~ 7 bytes thanks to [AZTECCO](https://codegolf.stackexchange.com/users/84844/aztecco)!!! Saved ~~9~~ a whooping 15 bytes thanks to [Dominic van Essen](https://codegolf.stackexchange.com/users/95126/dominic-van-essen)!!! ``` f(s,l)int*s;{l=l>1?l/2*abs(*s++-s[l-=2])+f(s,l):0;} ``` [Try it online!](https://tio.run/##bVFda4MwFH3vr7gIhcQP2rp2sFm7h7HX/YEqI4mxFVJtjQxZ8be7m@hsCwua3Htybs7hXhEchOj7nGhf0aJsXB1dVax2qze1CF3GNXG15wV6r4I4TKk3EF@XUdcjG06sKAmF6wxwiSOrXWikbr70PoUYrg5jjg8OZ9wcjAubCs4yaYKjVKqySJXJ4FCp3CSl/JZ1lWVVjUFpkM9HpIusnNGX7VmKRmaD3NIH/FY@PPsQ4rHeWCAM12PJ4LAezSXtR5i0L@/4b4zMXf5kRGxJXtVAjFRRZrLFumU0hlvQxY@scvJngi5GwJ2QCDzPsv96dHOh8a2xV5aRRhPBzAE43hthl54YtkmQ8XGEqEt0UytZEk29FaW3SnQ7mB2NwjaGiWrN0IlrF98Xphno4VEfd4n41N9/LOJ@QUpOuH/TuPNyrpGUEydx5jpxINjBPAMMzUi1DxcfB3GJY5ne@6@lJHwEulnX/wI "C (gcc) – Try It Online") Port of my [Python 3 answer](https://codegolf.stackexchange.com/a/211941/9481). [Answer] # JavaScript (ES6), ~~61~~ 57 bytes Expects a list of ASCII codes. ``` f=a=>1/a?0:(a.length>>1)*Math.abs(a.shift()-a.pop())+f(a) ``` [Try it online!](https://tio.run/##bc7BbsIwDAbgO08RcUpAdWkFHCa107Tz9gKIg5MmDVMWV03E63ce6qaC8Cny59/xF14xmfEy5CJSZ6fJNdi0VYmvuxeJEGzss2/bSm0@MHtAnbib/MVlqQqEgQap1NZJVFO2KYtGJNG0wlBMFCwE6qWTJwBIZ/jGQZqbgvE4vvN/b7yGa7X6Dcs14lqJZZWl2M2mUd/jwlCb@yRbNZvR2Nklsh1n8zYEerD6P8j3FT0F9zfAuD/MGO3VjtR1NPIj8sTims8nVtf76Qc "JavaScript (Node.js) – Try It Online") ### How? This is a pretty straightforward recursive implementation that removes the first and the last entry from the list at each iteration, computes the absolute value of their difference and applies the weight \$\lfloor L/2 \rfloor\$, where \$L\$ is the length of the list before the items are removed. The halting criterion `1 / a` is truthy if either: * `a[]` is empty, in which case `1 / a == Infinity`. This happens when the length of the input list is even. * Or `a[]` is a singleton integer, which happens if the length of the list is odd. We can safely stop the recursion without any other calculation because a single character is a palindrome and we already have the final result at this point. [Answer] # [Python 2](https://docs.python.org/2/), ~~57~~ 54 bytes A recursive function that takes input as a list of integers. ``` f=lambda l:l>[]and len(l)/2*abs(l[0]-l[-1])+f(l[1:-1]) ``` [Try it online!](https://tio.run/##VY1NCoMwEIX3PcXskrTaVulK0CP0AsHF5K8WxkSiFIp4dpu462q@972BN32XIfh6311LOCqDQA11skdvgKznJG71GdXMSd77kmRZ9eLiUqqajLsLEWZ4e2CIrACmUOWDSh9RKzQ2w2CJwmGCseUrkMvB24@NwZgQE/hsnv@mOQHoCVqQIRquBeQ9nffmPlVTfPuFs7XpqscGZQfrxq7pZcSFzwU4richxP4D "Python 2 – Try It Online") The last part could also be `abs(l[0]-l.pop())+f(l[1:])` at the same length. --- # [Python 2](https://docs.python.org/2/), 57 bytes A slightly longer approach without recursion. ``` lambda l:eval(len(l)/2*'+len(l)/2*abs(l.pop(0)-l.pop())') ``` [Try it online!](https://tio.run/##VY1LCsJAEET3nqJ3M61J/OAqEI/gBdRFzycqdKaHSRBEPHvMRBBc9atXDRWfw03Cbmyb88jUGUfAtX8Qa/ZBM653S7X6IZlecxUl6g2WX0BUOLaSoId7AEWkClCGTD5k7BytIecz3DyzzEacL6/CbQ7BP3wS5yRNELI5/pt6AWAjNHCS5LRFyHs27/WXqYrpHgatXvVhu39DeYDXW1XTS0eD7gtotY2IOH4A "Python 2 – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 22 bytes ``` IΣE∕θ²×⁻L∕θ²κ↔⁻℅ι℅§⮌θκ ``` [Try it online!](https://tio.run/##VYvBCsIwEER/pccV2otXT0UvgkVRf2BN1nYxTTTZBP9@DWIPDgwMzHtmwmgCOtVTZC@wxSRwyTMM@IQdF7YEr7ZZr9rmyjMlGNjnBAfyo0x/QCUetf0tBZeFfuAxWvbogOu17F723tIbzlQopqp/1SUbVRMsdWNwd@2K@wA "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a string (halving a string is golfier than halving an array). Explanation: ``` θ Input string ∕ ² First half E Map over characters κ Current index ⁻ Subtracted from L∕θ² Length of half of string × Multiplied by ↔⁻ Absolute difference of ℅ ℅ Ordinals of ι Current character and § Character at κ Current index in ⮌ Reversed θ Input string Σ Take the sum I Cast to string Implicitly print ``` Alternative approach, also 22 bytes: ``` IΣE⮌∕⮌θ²×⊕κ↔⁻℅ι℅§⮌∕θ²κ ``` [Try it online!](https://tio.run/##XUw5DsIwEPwK5UYiDS1VBE2KCAR8wNgDrOKsE1/i98YUoWCkkebS6Jfy2ilbytmzRDqoEOmaJhrUTBdk@AA6cmaDn12a7WZXeeMJgXrRHhMkwtBY0@4enE0RNLCkQCdvWJQlrtWqu9iLwfv/f/ne1tnYrNiXop1B@3T2UdpsPw "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` θ Input string ⮌ Reversed ∕ ² "First" half ⮌ Reversed i.e. last "half" E Map over characters κ Current index ⊕ Incremented × Multiplied by ↔⁻ Absolute difference of ℅ ℅ Ordinals of ι Current character and § Character at κ Current index in ⮌ Reversed ∕θ² First half of input string Σ Take the sum I Cast to string Implicitly print ``` [Answer] # [TECO](https://en.wikipedia.org/wiki/TECO_(text_editor)), 53 Bytes 1. Q-register A has the initialisation code. ``` *:ga $$ j0uaz-1ub0uu0uw$$* ``` 2. Q-register M adds it all up. The result remains in Q-register W. ``` :gm$$ z/2<0ua0a-(qba)%a"L-qaua'qa%u%w$c-2%b>$$* ``` 3. An Example to calculate the \$D\_p\$ of “Neveroddoreven”: kill the whole buffer, insert your word, initialise registers A,B,U, and W and jump to the beginning of the buffer; then iterate z/2 times, accumulating into register W; finally show the numeric content of register W. ``` hkiNeveroddoreven$mamm$$ *qw=$$ 224 * ``` 4. The complete program, and its length. ``` *ht$$ j0uaz-1ub0uu0uwz/2<0ua0a-(qba)%a"L-qaua'qa%u%w$c-2%b>*z=$$ 53 ``` 5. The test cases. ``` "aa" -> 0 "bab" -> 0 "abca" -> 1 "cbade" -> 6 "hello" -> 21 "code-golf" -> 45 "neveroddoreven" -> 0 "Neveroddoreven" -> 224 ``` This shows a TECO session of inserting each test word into the emptied edit buffer, then calling the macros of Q-registers A and M, and finally showing the \$D\_p\$ that was accumulated in the numeric Q-register W. ``` *hkiaa$mammqw=$$ 0 *hkibab$mammqw=$$ 0 *hkiabca$mammqw=$$ 1 *hkicbade$mammqw=$$ 6 *hkihello$mammqw=$$ 21 *hkicode-golf$mammqw=$$ 45 *hkineveroddoreven$mammqw=$$ 0 *hkiNeveroddoreven$mammqw=$$ 224 ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 21 bytes ``` {+/|⍵×⍳≢⍵}(⌈2÷⍨⍴)↓⊢-⌽ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///v1pbv@ZR79bD0x/1bn7UuQjIrNV41NNhdHj7o94Vj3q3aD5qm/yoa5Huo569/9MetU141Nv3qKv5Ue8aoNyh9caP2iY@6psaHOQMJEM8PIP/pykAWaHOwQrqiYnqXAheUmISMjcxKRlFOjkpMSUVWSAjNScnX10BWUl@Sqpuen5OGopoXmpZalF@Skp@EZCRhyLlhyoFAA "APL (Dyalog Unicode) – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~55~~ 52 bytes ``` f(a,z)char*a;{z=z/2?z/2*abs(*a++-a[z-=2])+f(a,z):0;} ``` [Try it online!](https://tio.run/##ZY5BboMwEEX3nMKyFMmGQU1cUilBtDfoBdouhrEhkShGNqkqIs5OTSxWXdie5z9vNJS3RMvSCIRJ0gVdiuV9qqYn9RZOirUXKWZZjh9TXqkvmcXO876cFyseAsG1H9n0uJ28J2xwoWwE33lWvbKdZsDE@sjPngNBIyhMACfLZE5W6RuvPRPBHG6jF9yPwW9X1Rl/68ZVN7@DodFoyYNlBUfkoGAfocaaw/NGWFMICzhEpBq14XCEl8gX03V2ZbU1WG3y1nYNhxMUx/jZmx/jrNbWhSJsfSi28e//E6WKkCXJvPwB "C (gcc) – Try It Online") * Saved a bit stealing from @Noodle9 and rearrangements ``` f(a,z)char*a;{z= - function tacking a C-string pointer and its length and returning trough eax register. z/2? - if not in the centre : f(a+1,z-2) > recursively call with pointer moved and length decreased +abs(*a-a[z-1])*(z/2) - add value of pairs :0;} > else initialize r to 0 ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 7 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ạṚŒHṪḋJ ``` A monadic Link accepting a list of integers which yields an integer. **[Try it online!](https://tio.run/##ASgA1/9qZWxsef//4bqh4bmaxZJI4bmq4biLSv9Pw4f//yJjb2RlLWdvbGYi "Jelly – Try It Online")** ### How? ``` ạṚŒHṪḋJ - Link: list of integers, A e.g. (Abracadabra) [65,98,114,97,99,97,100,97,98,114,97] Ṛ - reverse (A) [97,114,98,97,100,97,99,97,114,98,65] ạ - absolute difference (vectorises) [32,16,16,0,1,0,1,0,16,16,32] ŒH - split in two (1st part longest, if any) [[32,16,16,0,1,0],[1,0,16,16,32]] Ṫ - tail [1,0,16,16,32] J - range of length (of A) [1,2,3,4,5,6,7,8,9,10,11] ḋ - dot-product 273 (= 1×1+0×2+16×3+16×4+32×5+0×6+...0×11) ``` [Answer] # [Husk](https://github.com/barbuz/Husk), ~~14 12~~ 11 bytes *-2 thanks to Wheat Wizard pointing out you can take input as a list of codepoints* *and -1 thanks to HP.Wiz showing that ≠ does absolute difference not just inequality* ``` ΣFoz*ŀ½Sz≠↔ ``` [Try it online!](https://tio.run/##yygtzv7//9xit/wqraMNh/YGVz3qXPCobcr///@VkvNTUnXT83PSlAA "Husk – Try It Online") ### Explanation ``` Sz≠ Zip absolute difference the list from ↔ The reverse of the list ½ Split the list into two halves (with the longer being the first) F Reduce by o ŀ Converting the first half to range(1, length) z* And zip multiplying with the second half Σ Finally sum the absolute values ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 53 bytes ``` f@_:0=0 f[a_,b___,c_]:=Abs[a-c]⌈Length@a?b/2⌉+f@b ``` [Try it online!](https://tio.run/##VYtBC4IwGIbv/gyFLilJR8FaeI0I6iYyvm3fnKAbrNEl8lzgr/SPLOet0/s8D7wDOIUDuI6D95LQIi/zSNZAU0YpTTltivLEHjVkvJmnzxl16xSBI9vt5@m7lYT5q@20q5PsIAm5m0qBBe7QVkYgSZrNeOOgx1cUA8RpFDNgYYDxVTkDgQEU9r1Zy/LLWtPLIBqfaI0Qxi6gQ7n8l@jtfw "Wolfram Language (Mathematica) – Try It Online") Takes a list of integers. `Length@a?b` saves one byte over `Tr[1^{a,b}]`/`Length[a.b]` thanks to `PatternTest`'s high precedence. [Answer] # [Python 3](https://docs.python.org/3/), 59 bytes ``` f=lambda l:len(l)>1and len(l)//2*abs(l.pop(0)-l.pop())+f(l) ``` [Try it online!](https://tio.run/##XY9LbsMgFEXnXsWTJ0BrNzFxGymSs4RuIM2ArxOJggWkUmV57S4mldWU0X3nXPFg@I4XZ3fzrDvDPrlkYA5GWWzIsWFWwj1vNvSJ8YDNy@AGvCX1PRDyrJOdowoxQAe4gHRwyVhZwZZUvyNn/GFmXCyFZgWCM6kSeVvJRRnjEqF/Sk6qundGJ9y@rtiqL@WdlM6nYB/2vP9XlLZJksIvb0UfN7pvBaogp2aHSKGdh1ApuFrIfzrkm2Kqn5yXWBBYGmLx4Zxdn5zGkeRh8FcbsUblGKYS6iOM/QSjP/Vdp84TIvMP "Python 3 – Try It Online") [Answer] # [J](http://jsoftware.com/), 24 bytes ``` +/@(#\.@]*|@-)&(,~inv)|. ``` [Try it online!](https://tio.run/##XY09C4MwEED3/IrDgklajfWjHQJCaKFTcehcBz@itogBQSfpX7daksEOB8d7j7v3bDFcQcwBgwNH4Mu4DK6P@20@eILsnkyk@0m41CbO59WNdGIzRcmFgdar9CyfCofZJPw1YuDp0iFUxwwqQUJ74BQhWTRqPc@hBpxleAvyLNfEN0lemOisUZFnpdQsMF0j21ZpGJ1MqUrp1qqt/t50cpS9KkvVL0tnTgWR1slWz18 "J – Try It Online") Takes input as list of integers. Another one of those interesting problems that is unexpectedly difficult to express tersely in J. I tried a few approaches and this is my best attempt. ## how * `(...)|.` The whole phrase is a hook, which means the original input and that input reversed `|.` will be passed as the left and right arguments, respectively, to the phrase in parentheses. * `(...)&(,~inv)` The compose conjunction `&` transforms both arguments with the specified verb, in this case `,~inv`. + `,~inv` is the inverse of the verb that doubles a list by self-appending `,~`. The inverse of that operation is to take the first half of the list, and it happens to "round down" for odd lists, which is what we want here. * `#\.@]*|@-` Multiply `#\.@]` element-wise by `|@-` + `|@-` subtract the two list arguments element-wise and take the absolute value `|`. These are the "distances". + `#\.@]` produces, eg, `4 3 2 1` if the lists have length 4. It does this by taking the suffix lengths `#\.` of the right argument `]`. We could have used the left argument just as well here. * `+/@` Sum the result --- For comparison, the APL solution converted into J is 25 bytes: ``` >.@-:@#(1#.]*&|#\)@}.]-|. ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/7fQcdK0clDUMlfVitdRqlGM0HWr1YnVr9P5rcnGl2@oppDloGKuVWgF5qckZ@SCdVgrpCuqJieqoAkmJSVARQ5iSpGSYIjOoUHJSYkoqVMwIpi4jNScnHypoYgpTmZ@Sqpuen5OGZk1eallqUX5KSn4RkJEHM8rIBCrthyr9HwA "J – Try It Online") ]
[Question] [ # Challenge : Given a string split at specific positions and capitalize the first character of the given word. Capitalize the first word's first char if and only if it was already capitalized # Input : A string `s` and a character `c`. # Ouput : The string with each occurrence of `c` replaced with the first char capitalized # Examples : ``` STRING(s) CHARACTER(c) RESULT Hello_world _ HelloWorld me,no,like , meNoLike you-got-it - youGotIt Am^I^clear ^ AmIClear go!full!caps ! goFullCaps weird&but&tRue & weirdButTRue ProbleM1fixed1no 1 ProbleMFixedNo !prob!!lem!s!Olved!! ! ProbLemSOlved ``` --- # Note : * Given input will always be valid. i.e : The first will always be a string with at least one instance of the character to replace at. The second will always will be a single character. * The length of the input string will be greater 4. * There will be at least one occurrence of the character to split at. * The input is guaranteed to contain only letters and the separator (Thanks @Arnauld) * Separator is anything that is not an alphabet (a-z / A-Z) (suggested by @Dennis) --- # Winning criteria : This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest code in bytes for each language wins. --- 1. Thanks to @JonathanAllan for pointing out two mistakes. [Answer] # [Python 3](https://docs.python.org/3/), 63 bytes ``` lambda s,c:''.join(map(min,s,s[0]+s.title()[1:])).replace(c,'') ``` [Try it online!](https://tio.run/##Lc@9TsMwFIbhmVyFvcS2cCIitkgd2GBAINbSVKlzUgzHP7IdSq8@xJj1eXU@6fhr@nD2fp3JjryvOJrTNJIoVc9Y@@m05Wb03Ggro4z7u8NtbJNOCFzsu/4gRBvA46iAK8mYWGcXtmOiiLaEVxVnj4DojhcXcGKSsCMTclMD0jqJ@gsyyoJXtzRnlxqdMjYFH8zwNCiEMWQcCp4dnRdEqkYfM9PCF9Bhqk9LqtPb8rdcl/Aa3AnhuZv1D0yddTl1JVG/NUoRDI30Bb9hov@LVSX66sYHbROfeX5KiPUX "Python 3 – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~61~~ ~~53~~ 55 bytes *-8 bytes thanks to Dennis!* ``` f(s,c)char*s;{for(;*s;putchar(*s++))if(*s==c)*++s&=95;} ``` [Try it online!](https://tio.run/##FYyxCoAgFAB/JRzKp72xIcS5j4gGeWA5lNGzIaJvN92O4zjClShnL7knoM1dis3r4yVNgfNOVUnFWgMEX8BaAqU1t3YczJd3Fw4Jb60anhcr8Ik3TjFhSMLUa4cdlPAH "C (gcc) – Try It Online") [Answer] # JavaScript (ES6), ~~58~~ 56 bytes *Saved 2 bytes thanks to @l4m2 / @Downgoat* Takes input in currying syntax `(s)(c)`. ``` s=>c=>s.replace(u=/./g,x=>u=x==c?'':u?x:x.toUpperCase()) ``` [Try it online!](https://tio.run/##Zc9La8JAFIbhfX@Fk4UmkAtuhYlYwVawtvRCd0qcnIS0k5wwF01/fToTrG3Hs3154Dsf2TGTTFStihrMoS9oL2nKaCpjAS3PGPiaJnFShh1NNe0oZfPJZKbn3ayLFb61LYhlJsEPgp5hI5FDzLH0C9@7B85xf0LBcy/wvb0XBKPLJclo6O823ziyhrDBkFefYGH4D1pZwxY3prruC3VUoooqZV105Uy/Q7VWrlvUu/WOcciEdbsrt6jXS1tdVyIpNOeEZa20kvyVxpW4MnlpqitPUIl8fNBqrJ718OX41xo59FutXk117ZPAA4eHaVF1kE8btHr6o40995XNW3Q1aU0mhENNJHnkR8gJuWw/6w3UL0PqvwE "JavaScript (Node.js) – Try It Online") ### Commented ``` s => c => // given s and c s.replace(u = /./g, x => // initialize u to a RegExp; replace each character x in s with, u = // and update u to: x == c ? // if x is the separator: '' // an empty string : // else: u ? // if u is not an empty string: x // x unchanged : // else: x.toUpperCase() // x capitalized ) // end of replace() ``` [Answer] # [APL (Dyalog Classic)](https://www.dyalog.com/), 22 bytes ``` {⍵~⍨1(819⌶@(⍵=¯1⌽⊢))⍺} ``` [Try it online!](https://tio.run/##Lc6xSsNAHMfxPU/RLPm3kKDZVChYC2pAHERwSzmTSzh68V@SC6VIXRTB2kgXH0Cnbk46CC4@yv9F4j8xNxzH5/sbTsy0Fy@ExtSLtCgKFdX08qqQHje7dcL3LVWfd1Rt/f6ev0/rr8M@w/D3w6f1D63eBwOqvpd1bbopPb3l/KTVfbLD5QBwCvT8AIlQGhh4ki8tOJVa42SOuY6hxwcmYP7xqjULMuneoKvVVLaDHri8yOQ5njVkwQJLL0XjKdN1jzvjCZrAcB9lYRBGWoq86yH3URaMW7IgRTsptbYjMSuaBdjcUzxmGzdkwVyqPHauS@OYi5J/AQ4vWjwqzWVDfw "APL (Dyalog Classic) – Try It Online") [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg) `-p`, 19 bytes ``` s:g[<:!L>(.)]=$0.uc ``` [Try it online!](https://tio.run/##BcHBCsIwDADQe/6iIENhHZ48DBW8Key0qziZXSzFbCltw/Dnje9FTHRQza2/H1vTnbfN7nHa7Btxqlck4ufKiSaYsV64pvBB@LJYz8WGApd5uA2OcEzg2byFyLgxZlgxpKl6SalKL/jjWAIvWW38Aw "Perl 6 – Try It Online") [Answer] # [sed 4.2.2](https://www.gnu.org/software/sed/) (-r), 21 ``` s/[^a-z]+(.)?/\u\1/gi ``` I tried `\W` instead of `[^a-z]`, but unfortunately that doesn't match `_`. [Try it online!](https://tio.run/##DctLDsIgEADQPaegG6JxkHgC485u3VoxWEZCnHYaPmn08KJv/zL61rK5Wqc/t91mvz2aoQ4HE2JrZyTi@8qJvJgQZgaKLwQJ4s1VBy46FpBanCbb25HQJZBWBO6elagb3ZJBdmLFmLx61KLKpf63@vJSIs@56fQD "sed 4.2.2 – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes ``` Œt⁸1¦«⁸ḟ ``` [Try it online!](https://tio.run/##DYo7DoJAFAD7PcW@hgpi9gh2WhiNnQ2Ez4OsPlwCi0ipR/ACdlpoZSxI7DAeBC6ybjOTTGaLRK0xv4seT53ob/3DeuiuZvi8h@41np/f@8RyY8zMripoVEkJD1iO7l65JHfIXdaq2suU9qTmHpvm/tyPCcOS@yxTkNZEEIdFxYE1KMvEiWrt6HWN3GGrUkWEC5HKIyZir7hgUNgGQJhDBUs6YAIc/g "Jelly – Try It Online") ### How it works ``` Œt⁸1¦«⁸ḟ Main link. Left argument: s (string). Right argument: c (character). Œt Title case; capitalize the first character of each word. ⁸1¦ Replace the first character of the result with the first character of s. «⁸ Take the character-wise minimum of the result and s. Note that uppercase letters have lower code points than lowercase ones. ḟ Filterfalse; remove all occurrences of c. ``` [Answer] # [Octave](https://www.gnu.org/software/octave/), ~~83~~, ~~66~~, 64 bytes Saved 2 bytes thanks to Luis Mendo. `upper` instead of `toupper`. ``` @(s,c,k=upper(s(i=find(s==c)+1)))[strsplit({s(i)=k,s}{2},c){:}]; ``` [Try it online!](https://tio.run/##JczNisIwFEDhvW/RTZNgWqjLGQLOblwI4nawUtMbCb32lvyoQ@mzdzJk@x04pEP3hNWouq7XPfdSy0HFaQLHPbfK2LHnXiktto0Q4scH5ye0gc@pCjVIv8y7RWoxfyyXz9Vw9g2IdH2Rw55JdmVik/ABciSJdoBkMtsvxepOobIhSZXt69EeWo3QuWRttjsVJiIWupt80iLrC6zry1sMZTjH/2uZ/eTohnBsjH1D34yUSsPE@gc "Octave – Try It Online") Wow, that's probably the messiest piece of Octave-code I've ever written! This uses two of the tricks posted in [this](https://codegolf.stackexchange.com/q/163105/31516) tips question, namely Argument list, and cell arrays. ### Explanation: **Argument list input:** ``` @(s,c,k % An anonymous function that may take three input variables, s, c, k % where the third argument has the default value: k=upper(s(i=find(s==c)+1)) ``` `k` is here the first character in `s` after each separator `c`, converted to upper case. The index of each capitalized character is stored in `i`. **Cell array body:** We create a cell array with two elements, one were we say that all i'th characters should be substituted by its counterpart in `k`, and the other one with `s`, that is now already updated. We index this using `{2}` so that we only get the whole, modified string back. This is fed to `strsplit`, which splits it into cells at the separator character. We convert it to a comma-separated list using `{:}`, and concatenates it back to a string using square brackets `[]`. Apologies if that didn't make any sense to you... It barely makes sense to me :P [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 20 bytes ``` T`lLp`LL_`[\W\d_]+.? ``` [Try it online!](https://tio.run/##DcjBCoJAEADQ@/zFHJIgDfyC6FSBUkTQIdNVd5Sl0ZF1N@vrt97xWXJmrMNqfVDhpjibVJZV6lHcC109N9tdCEdilmoRyxoGikeJ2bwIvuKTXlxiHOyH8lS2TLWFXrDzzNjW0wwLGaujxrvIXT3BxUrDlKed@ZBORwGc/oPINOCMZ36TRvwB "Retina 0.8.2 – Try It Online") Takes the string only, separator optional. All non-alphabetic characters are deleted but any following alphabetic character is uppercased. Previous 34-byte version accepted arbitrary input: ``` T`l`L`(?=.*(.)$)\1+. (?=.*(.)$)\1 ``` [Try it online!](https://tio.run/##TcjBCoJAEADQ@/zFQImWCvsBEZ0qKIroGLrqjrI0urLuZn391rHje5acHqqwjPcy3CXLk4y3m3wV58kieYh1Dv@EEA7EbMrZWFYl9JQOJmX9pBQ@xmedcZl2Gez64lg0TJUtoDPYemZsqnFCmElbFdXeRe7mKYKrNTXTWbT6TUoMRgCOv0Jk6nHCC79IIX4B "Retina 0.8.2 – Try It Online") Link includes test suite. Assumes the input consists of the string and character concatenated together. Explanation: The first stage transliterates all characters immediately following occurrences of the end character from lower to upper case and the second stage then deletes all occurrences of the end character. For both solutions, using a right-to-left match instead of a `+` also works. [Answer] # [Röda](https://github.com/fergusq/roda), ~~57~~ 54 bytes *-3 bytes thanks to [Cows quack](https://codegolf.stackexchange.com/users/41805/cows-quack)* ``` {(_/`\Q$_`)|{pull;[upperCase(_[:1]),_1[1:]]if[#_1>0]}} ``` [Try it online!](https://tio.run/##LZBda4MwFIbv8ysSN4qCZfO2w0FX6Fbouk/YhVprNXZh0RM0rhs9/naX2J2L8D4PJ28gDRTZcCLUTElnIY2Hk5te7eKXy3Tn4Ul1Ut5EnVK8WWQtd9NoFiSenwZRMEsSUUYXaXB7nfT90BNSZaKm565WSaFpy1XoxDE6FGkJDc18uvdpTgsYl@yorv10rffsjmvPHOo80yaoRtTazerWpw4NqWOu2uSaYG2YewY9xzt31@1YWkDNST88cCkhPUIjC0xxpA8LpOJ@Db4UXxx9rPgG1iaSX@imB9BToXGKBu5BrzSZV9vVNpc8a3CL82q1sJEcgJXmW1ieqRYZHmBpaGGAHLloism@0xP92nGc4CjuOv1ukDw3sJf8MSjFDy@CGjDAf7W0ZgOEKcOMSV6xlj3Jb14w84BdWvPqbRR/ "Röda – Try It Online") Explanation: ``` { (_/`\Q$_`)| /* Pull two strings and split the first with the second */ { pull; /* Pull one string and print it */ /* For each string _1 in the stream: */ /* If _1 is not empty: */ [ /* Print: */ upperCase(_[:1]), /* The first character capitalized */ _1[1:] /* The rest of characters */ ]if[#_1>0] /* End if */ } } ``` [Answer] # [V](https://github.com/DJMcMayhem/V), 6 ~~7~~ bytes *1 byte saved by not using argument* ``` ÓÁˆ/õ± ``` [Try it online!](https://tio.run/##K/v///Dkw42HOvQPbz208f//3FSdvHydnMzs1P86AA "V – Try It Online") The program takes in the text as input and the char as an argument. Hexdump: ``` 00000000: d3c1 882f f5b1 .../.. ``` This is a simple substitution. Uncompressed, it looks like the following ``` :s/\A(.)/\u\1/g ``` Perform a global substitution in which `\A`, a non-alphabetic character, followed by a character `(.)` is replaced with uppercased `\u` first capture group `\1` [Answer] # Scala, 83 bytes ``` def f(s:String)={val w=s.split("[^a-zA-Z]");w(0)+w.tail.map(_.capitalize).mkString} ``` [Try it online!](https://tio.run/##bdBBT4MwFMDx@z7FKwcCWSHuqpkJNz0sGr1pZCnwWOoetKFlzC377Fj1MNbZU5N/fq/pM6UgMariE0sLKyFbwL3FtjKQaQ3H2VhhDXVkbl9tJ9tNvDzuBMGwNKnRJG0UvOciOWTJ20cQ3w3RTTwfUiskpY3Q0TothZZWkDxgnDbbvxmnEUC7i6U2Ch6QSK0H1VEFHNbwe5b3EMDcPTvNQRzPJrBB3ipOcovcQfDhJHvwS/XJRtlEWg7JNTxnz2VN/piXhKLjkF@7c/bcRrG6J2JuFYYD8900e3JA2VVh0dvQvvTum@GlvMyefe5UQbha1HKP1cKtYnFh/exppl1njLBhhj3RDivGJvq//DPhNH4D) Explanation: ``` def f(s: String) = { // takes a String "s" as input val w = s.split("[^a-zA-Z]"); // split on non-alpha chars w(0) + w.tail.map(_.capitalize).mkString // upper case first letter of all words except first one and join array into a String } // ``` [Answer] # [Red](http://www.red-lang.org), 87 bytes ``` func[s c][b: split s c prin b/1 foreach w next b[if w <>""[w/1: uppercase w/1 prin w]]] ``` [Try it online!](https://tio.run/##Tc2xasMwEAbgPU9x8uDJJng1pdCtHUpLViEFSzqlImdLyFKdEPrsrtJC6@0/vrv7I5r1gIaLne1XmyfNZ9CCqx7mQC5BmSBEN4Had2B9xEF/wAITXhIo7mzJD49VxZd910MOAaMeZoQy/p4tQoj1nhJYuD0jkT8uPpL5gupY7f5kxGbyDbkzFmg2cPW5PfnUulSgreBfnkYpX6TUhEMsJuUWT57ZTMT0EOaCbPNxQRdNrXKq0yHf6@rt4Xv0ivC1s@6Cppt88W7rLJQFxghHNrM3@kTD2E/B@g0 "Red – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 9 bytes ``` ¡ćsvyćusJ ``` [Try it online!](https://tio.run/##MzBNTDJM/f//0MIj7cVllUfaS4u9/v9X4ypPzSxKUVNLKi1RKwkqTQUA "05AB1E – Try It Online") **Explanation** ``` ¡ # split the string on the char ć # extract the head of the resulting list s # swap the head to the bottom of the stack vy # for each string y in the rest of the list ću # extract the head and capitalize it s # swap it below the rest of the string J # join everything to one string ``` [Answer] # PHP, ~~91~~ 83 bytes ``` $a=explode($argv[2],$argv[1]);echo array_shift($a);foreach($a as$i)echo ucfirst($i); ``` Run with `-r`. Was 2 bytes shorter using split instead of explode, but ^ test fails due to regex. -8 thanks to [Med](https://codegolf.stackexchange.com/users/41036/med) [Answer] # LaTeX, 97 bytes ## The function ``` \def~#1#2{{\seq_set_split:Nnn~{#2}{#1}\seq_map_function:NN~"}}\def"{\let"\text_titlecase_first:n} ``` ## Complete document with test cases ``` \documentclass[preview,border=3.14]{standalone} \ExplSyntaxOn \catcode`\~13 \catcode`\"13 \def~#1#2{{\seq_set_split:Nnn~{#2}{#1}\seq_map_function:NN~"}}\def"{\let"\text_titlecase_first:n} \ExplSyntaxOff \begin{document} ~{Hello_world}_ ~{me,no,like}, ~{you-got-it}- ~{Am^I^clear}^ ~{go!full!caps}! ~{weird&but&tRue}& ~{ProbleM1fixed1no}1 ~{!prob!!lem!s!Olved!!}! \end{document} ``` ## Results (in PDF) [![enter image description here](https://i.stack.imgur.com/n5uEC.png)](https://i.stack.imgur.com/n5uEC.png) [Answer] # [R](https://www.r-project.org/), 64 bytes Pure regular expression solution using <https://www.regular-expressions.info/replacecase.html>. Unfortunately separators can be underscores so I couldn't use `\w` to capture letters. Improved version taking advantage of gsub's ignore.case parameter to save on `[a-zA-Z]`. Correction thanks to <https://codegolf.stackexchange.com/users/95126/dominic-van-essen>, who has a 25% shorter solution in the comments. ``` function(s,c)gsub('[^a-z]([a-z]?)([a-z]*)','\\U\\1\\E\\2',s,T,T) ``` [Try it online!](https://tio.run/##jdBbS8MwGIDhe3/FUqEHSQr1XmUOp4U5RSteLHb0kJZi0m@0iVP/fE1q54WzsgYSCO/DF9p0xVlXqDqTFdRuizOvbFXqOqs4IZ8v7srsF973eeI52KH0idKA0itKTx3c4ghHXle41g3jHNZbaHhuYWtteceT3x8h5HzSd88mO9opf6f8A9UHKL8E6VdyDA1Mh9cgQ2mQYLgGzKtXhi2zxpVgS1jobhhF9CjSjyIHjpqKOIwzzpJGo/gfNBXhzGQGlYAKxTnKkk2rGRr9FyXMdTfTmWFbVjW5nSppywfFNLT3Yc/68FLJSGcG3jeQcnYbFNU7y4MaNA32aC@Hcm7CJRiLNvoKIc4EatEdf2M5@uPJP3jBxGNfdV8 "R – Try It Online") <https://codegolf.stackexchange.com/users/95126/dominic-van-essen> 's solution, with an extra character removed (by using `?` for optional): # [R](https://www.r-project.org/), 47 bytes ``` function(s,c)gsub("[^a-z]+(.)?","\\U\\1",s,T,T) ``` [Try it online!](https://tio.run/##jdDdSsMwFMDxe59iiVBaTAp9AJU5mBbmFK14Ye3ox2kppj2jTZz68jUJnRfOypK75P/jhHRDeT6Uqs1lja3bs9yrepW59CVJ@dfrmet7l5TROH6K44CynkUs8obSpTcgBG522IlC32@odzr7vTjnFzPbPZvsZK/8vfKPVJ@o/AqlX8spNDIdXqMMpUENsBaZqN@AUbOnVQNrXOluHMX1KG5H8SNHzZskTHIBaadR8g@aN@HCZAZVSEolBMnTba8ZmfyLCpe6W@jMsB3UXeFkSjryQYGGziG0zIZXSkY6M/C@w0zAbVDWH1AELWoaHFArx3JpwjUaS7b6iBABDenJnXiHgvzx5B@8gubRVsM3 "R – Try It Online") [Answer] # [Pinecone](https://github.com/wmww/Pinecone), 314 bytes ``` s:String.input;p:String.input;k:IntArray:s.len;k.set:0,-1;o:"";n:1;i:0|i<s.len|i:i+1@((s.sub:i,i+1)=p?(k.set:n,i;n:n+1))k.set:n,s.len;i:1|i<n+1|i:i+1@(x:k.get:i-1;y:k.get:i;x:x+1;j:s.sub:x,y;e:1|e<256|e:e+1@((j.sub:0,1)=e.ascii?(e<96?(o:o+(e.ascii)+(j.sub:1,(j.len)))|(o:o+(e-32).ascii+(j.sub:1,(j.len))))))print:o ``` This was extremely fun.... [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal), 5 bytes ``` /ḣǐJṅ ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%2F%E1%B8%A3%C7%90J%E1%B9%85&inputs=.%0Ahello.world&header=&footer=) [Answer] ## Groovy, 43 bytes, 45 bytes ``` s.replaceAll(/\$c(.)/){it[1].toUpperCase()} ``` [Try it online](https://tio.run/##TZDRasIwFIbv@xRRRFtoK7sdOHCFbcLYxdjYRa2SpWkXlnhKkk6k9Nm7k1jR3JyQ7/t/yKk1wN9pGEpekYoyYcmK5AEhubknixcuJeyPoGW5iAkeho97vOoL/PKsiC8JxeMDxFL88nPAJ@IxofgbvDp09U/QJjXYRNgbPxl9hM9gN/bGX6vdZsckp/rG343@Wm0yj65@DZOqlXLCaGN8wvmT0a/hCVnm0DVx5EKX8@/Wzu17637hEvMx4eFjaz8cKoogcGsrQdjQoBiRDltMqnkjKeNrKcPldsbCNFpGnbD5XZFa@GwarjNqeBj1QR8Efukpp@yHdESR5AErqDFc23OxSrFapVi@WuHUiBstDlYeyDSfdYj7mLjJ@gLT/qr7KVYPwz8). Test suite included excluding the last item as it lacks the separator char `c`. [Answer] # Go, ~~138~~ ~~92~~ 87 bytes Dropped 46 bytes thanks to [@Dennis](https://codegolf.stackexchange.com/users/12012/dennis)' title case idea. ``` func f(s,d string){p:=Split(s,d);Print(p[0]+Replace(Title(Join(p[1:]," "))," ","",-1))} ``` [Try it online!](https://tio.run/##bdBNa8MwDAbgc/wrbB2CzZyxXFt22G0bjJVut64paaIEU3@ROOtG6W/P4vQ2chGSeITgbd3oy@pUtkhNqSwhynjXBcpJck@hMQHmpg@dsm0PRBDSDLaaMRf0QpKGwzNq7Q5n1@kaJIUDCJJspoPA4cvGYTIGpXVSqxNGIpfIrxuy1oVMhUiyJfJkipei0lh2kRRL5Iyqq9PjENKwHeZn6RLbdO6o8S1v1A/WuXUR5kuQ@UkyptGwnr3rb6wZi5j9x9dxTqbhvazpLTBx8avHD69ViEuxvnG/e9jfbdHrskL@qYJG/uqmOP0uX@0lUBAiVgkgs1yI6zj@AQ) [Answer] # [Husk](https://github.com/barbuz/Husk), 10 bytes ``` ΣΓ·:mΓo:ax ``` [Try it online!](https://tio.run/##yygtzv7//9zic5MPbbfKPTc53yqx4v///4r/FQuK8pMUFXNScxWLFf1zylJTFBUB "Husk – Try It Online") ### Explanation ``` ΣΓ·:mΓ(:a)x -- example inputs: 'x' "abxbcxcdxdex" x -- split on character: ["ab","bc","cd","de"] Γ -- pattern match (x = head) (xs = tail) and do.. ·: -- | construct list (x:xs) but with the second argument do.. m -- | | map (eg. "bc") Γ( ) -- | | | pattern match on first character ( a) -- | | | | upper-case it (: ) -- | | | | and join again -- | | | : "Bc" -- | | : ["Bc","Cd","De"] -- : ["ab","Bc","Cd","De"] Σ -- concatenate: "abBcCdDe" ``` [Answer] # [F# (Mono)](http://www.mono-project.com/), 122 bytes ``` let f(s:string)c=s|>Seq.mapi(fun i x->if i>0&&s.[i-1]=c then Char.ToUpper(x)else x)|>Seq.where((<>)c)|>Seq.toArray|>String ``` [Try it online!](https://tio.run/##bc9RT8IwFAXgd39Fu8SxJQzk1cgSJEFJEI1gfDBCxrgbje3ubDuBxP8@7yYPwNjDku2c7zRNTKAwwxJzyNhsbyyoUoJliWdujdUiS/24b37DGXx3VJQLLykyJtguCEXCRHjjuqbzIYLeZz9mdkMbw02kO3N8y3PQ3s4HaYDt/P@B7QY0eN5d6MeHPxYHWkd7@qjPKnN62yRjzvXAYV7CnEeQEpdb1HLtsNay5bOTp9tldeO9Klw1tIJ2hm0pvoBw@xxXWsEUJ5Q37R6LIEUbCEs2uGSp8YB2bJt2oBbjRSwh0mQXl@xAjYdV3rQp8qSQksdRbkjzM002xREVhpQ39RaEXrurwrr2tahu7Z540nXjvrBzypv@ReNKwlMvETtY9zKkhd7RAvlDY1QVpthc4DkVOJeguOHP8gfWnB/d47AwATWrw7L8Aw "F# (Mono) – Try It Online") [Answer] # Java 10, 141 bytes ``` s->c->{var r=s.split("\\"+c);var r=a[0],t;for(int i=0;++i<a.length;r+=t.isEmpty()?"":(char)(t.charAt(0)&~32)+t.substring(1))t=a[i];return r;} ``` [Try it online.](https://tio.run/##jZBRSyMxEIDf/RXJPtSE3Q3t@XZrKyKKPsgd@qitpNm0ps4mSzKpV6T@9RqvhT040IVAwsx8M/lmJdeyXNUvOwUyBHIrjX07IiSgRKPIKmVFRANiEa1C46y4OjxO79Ebuyy@rLl4ll4q1L4g@/LJhCgy3oVyosrJ21p64sdBhBYMsuzxMcsVr/ZR@TCcFlgtnGfGIjHjYZXn5lQK0HaJz5XPxyhMuGxa3DB@lmU/mUrTOEPxeZ8jG/LB@8kPnqMIcR7@jmcjzjG1NtPKa4zeEl9td1USTqeNc0jOB/W1MzVp0jrY/ucPUyL552oIud8E1I1wEUWbUgiWKSHbFjYsu9YA7unVeagzfggePx1zXn2LNrqwrgDzojuy6EVuXCyXDkuDHVn2Is@b2c1MgZa@I2e9yKWjiwhAlWxDx9Je7Ks2vh7MIw7wLv5jO@hF//ZuDvp2tDB/dD2yruNHvXjapgaUgm5ooL9grWtK/zfYHm13Hw) **Explanation:** ``` s->c->{ // Method with String and character parameters and String return-type var r=s.split("\\"+c); // Split String by character (with potential regex char) var r=a[0], // Result-String, starting at the first item t; // Temp-String to reduce bytes for(int i=0;++i<a.length;// Loop in the range [1, length_of_array) r+= // After every iteration: append the result-String with: t.isEmpty()? // If the current item empty: "" // Append nothing : // Else: (char)(t.charAt(0)&~32) // Capitalize the first character +t.substring(1)) // And append the other characters as is t=a[i]; // Set `t` to the current String-item of the array return r;} // Return the result-String ``` [Answer] # [R](https://www.r-project.org/), 87 bytes ``` g<-function(s,x,z=strsplit(s,x,T)[[1]])cat(z[1],capwords(z[-1]),sep="") example(chartr) ``` [Try it online!](https://tio.run/##jZFRb9owEIDf8yscV0Kx5ETKXlsm0Qo2JEqnwbSHCqqQXEI0J7ZiZ9Aifjs7uxRBKVPtSLGt77s7n5vd1XRZaoKfWQLJ2zo1paxxkxgC66RSAoJ0mTSmYSSDvKxBk6CWhiA0HT4wz0sTtZJNpslNePADzYk2TZka0iWD3mjSZ2TjERxIn4KMqEQbCIxslYIm0O3CmnVhY8T4McadeTo2Lt8J/IVdkzIPXvMyYqSQKxuQERAaiN5@FOdoaFBYLaWcpFKIRKGDW5zMeTpRSjzb8FqJ0rgr2sUrxLi9Gie/Jv1o3LvvT/DYL3VUt0IEdVKBxkIY87a74iY8atOav3SPQq75lD0@xrMZSxMTvOCKv/UXd2E8YxzL7FLKvHevs8tP@hpFEdsU7ndtQ1GPsq2XB/Q7CCGfMKLIKKdPlF2dNSIMw6/Ecb8tdrCiNyv6pPUs26iQJirNJWmvIfhNmqGxUgW8llyUf4BTOy9bFYzlCLl9qhBThS5V@MlUvWo@nKcCkgal@X@kXjW8s5iVCunn@Kg@votGzb/Yi0IOkLtDzGorKJuss2hNx/xsAcXOueg0B962ZoqYFX80ciHgPs7LNWRxLVGNz1Rn7smBBcfSur7CI98XUPnafxB/IfM/KPkgj6CaOGr3Dw "R – Try It Online") Uses [this trick](https://codegolf.stackexchange.com/a/144559/80010) can can not be properly executed in TIO so I simulated it. We need the `T` otherwise one of the test cases fails. [Answer] # [Stax](https://github.com/tomtheisen/stax), 11 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` óKo{cplòüö\ ``` [Run and debug it](http://stax.tomtheisen.com/#p=a24b6f7b63706c9581945c&i=_%0AHello_world%0A%0A,%0Ame,no,like%0A%0A-%0Ayou-got-it%0A%0A%5E%0AAm%5EI%5EClear%0A%0A%21%0Ago%21full%21caps%0A%0A%26%0Aweird%26but%26tRue%0A%0A1%0AProbleM1fixed1no%0A%0A%21%0A%21prob%21%21lem%21s%21Olved%21%21&m=1) **Explanation** ``` /BsF1:/s^s|dl # Full Program, unpacked, Implicit Input / # Split on substrings (Split input with symbol to split on) B # Remove first element from array. Push the tail of the array, then the removed element. s # Swap first two elements of stack F # Start for loop 1:/ # Split array at index; push both parts. s^s # Swap first two elements of stack, capitalize character, swap first two elements |dl # Get length of stack, listify that amount (entire stack), implicit output of array ``` There's a few parts I would really like to fix somehow. I can get it down to about 8 bytes, but it fails on the last test case >.< [Answer] # [Ruby](https://www.ruby-lang.org/) `-pl`, 36 bytes ``` $_.gsub!(/[^a-z]+(.|$)/i){$1.upcase} ``` [Try it online!](https://tio.run/##DchLDoIwEADQfW8xCSEQ@YQjuNOF0bg1QgoMpHFgmn5E/Fzd6ls@49s1hKgpRutbSMpLLfPndZMU7ygtVfqKqsLrTlr8hLBDIm4WNtSLCbOZM1I3FCv7fGSXKye2U72vO0JpxMgweCLopLZiQWX6uPUudmeP4mS4JTxUg3pgX80sQP8HgHACC0e6Yw/wZe0Uzzbkmn4 "Ruby – Try It Online") Takes only the string without second argument. Uses the block version of `gsub!` method because with common `gsub! x,y` syntax `$1` is not readily filled with match data. `|$` in regex is necessary for the test case with separator in the end. [Answer] # [Python 3](https://docs.python.org/3/), 77 bytes ``` o=[] for x in s.split(c): o.append(chr(ord(x[0])-32)+x[1:]) print(''.join(o)) ``` [Try it online!](https://tio.run/##BcFBCsMgEADAu68QL9mlRtrmFvAl4iGoRYu4okLs6@1M/Y1I5VhdixhyJnlTy16O0IdgTgspFmlj2YcanzwV3lWvOQ1weHJSV62heHCxATUP0zwt7scbH9O8ToustlQGbJv6UipAiGv9AQ "Python 3 – Try It Online") This assumes that the string is ASCII encoded and assumes that `s` and `c` are preloaded variables containing the input. ``` for x in s.split(x) #loop through items in the string s split by x o.append( #add the following to c chr( #turn the following number into a character ord( #turn the following character into a number x[0] #the first character in string x )-32 #subtract 32 from this number +x[1:] #add everything past and including the second character in string x ``` This solution works on the fact that in ASCII encoding, [lowercase letters are positioned 32 entries after capitalised letters](http://www.asciitable.com/) Edit: i just realised that this also capitalises the first character in the string, which it shouldn't. but i'm quite proud of my nonsense, so i'll leave this up if that's allowed [Answer] # [Pip](https://github.com/dloscutoff/pip), 23 bytes ``` Ya^by@0AL(UC@_.@>_M@>y) ``` might be shorter with regex substitution. [Try it online!](https://tio.run/##K8gs@P8/MjEuqdLBwNFHI9TZIV7PwS7e18GuUvP///@5qTp5@To5mdmp/3UA "Pip – Try It Online") [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 45 bytes ``` ""<>MapAt[Capitalize,##~StringSplit~All,2;;]& ``` [Try it online!](https://tio.run/##JcxBa4MwGIDhe/9FIuQUGe7arSiD0R7KytxNtKT66UK/mJB@rttK/esuI9fnhdco@gSjSLdq6Z8Xzp82e@UKql6U06RQ/4JMkrkkr8ehdKhpLhDl43pdi@UQkKoPG2uVyN3oJnq13tTiIU/STZ/nSS3mslXjfFvd@BYQ7fFqPXZc8iO/y4AG5Ggl6jMEk9F@7JQOllJNQdJohWl2TYugfLAm2mBZPyGyVrlLUBb1Ctp34jSRoPfp/yqiH7w9IeyzXn9Dl402lCwW5kJiDMGwC3vDL@gYi7/VffkD "Wolfram Language (Mathematica) – Try It Online") ]
[Question] [ # Task Given integers `x` and `y` which are both at least `2`, find the smallest positive number whose `y`-th power is divisible by `x`. # Example Given `x=96` and `y=2`, the output should be `24` since `24` is the smallest positive `n` satisfying `n^2 is divisible by 96`. # Testcases ``` x y output 26 2 26 96 2 24 32 3 4 64 9 2 27 3 3 ``` # Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Solution with lowest byte-count wins. # References * `y=2`: [OEIS A019554](http://oeis.org/A019554) * `y=3`: [OEIS A019555](http://oeis.org/A019555) * `y=4`: [OEIS A053166](http://oeis.org/A053166) * `y=5`: [OEIS A015052](http://oeis.org/A015052) * `y=6`: [OEIS A015054](http://oeis.org/A015053) [Answer] # [Brachylog](http://github.com/JCumin/Brachylog), ~~19~~ ~~17~~ ~~16~~ ~~15~~ 12 bytes *2 bytes saved thanks to @LeakyNun.* ``` :[I:1]*$r=#> ``` [Try it online!](http://brachylog.tryitonline.net/#code=OltJOjFdKiRyPSM-&input=Wzk2OjJd&args=Wg) ### Explanation ``` Input = [X, Y] :[I:1]* Get a list [X*I, Y] (I being any integer at this point) $r= Get the first integer which is the Yth root of X*I #> This integer must be strictly positive This integer is the Output ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ÆE÷ĊÆẸ ``` [Try it online!](http://jelly.tryitonline.net/#code=w4ZFw7fEisOG4bq4&input=&args=OTY+Mg) or [verify all test cases](http://jelly.tryitonline.net/#code=w4ZFw7fEisOG4bq4CsOnL-KCrOKBuDsiRw&input=&args=WzI2LCAyXSwgWzk2LCAyXSwgWzMyLCAzXSwgWzY0LCA5XSwgWzI3LCAzXQ). ### How it works ``` ÆE÷ĊÆẸ Main link. Arguments: x, y ÆE Yield the exponents of x's prime factorization. ÷ Divide them by y. Ċ Ceil; round the quotients up to the nearest integer. ÆẸ Return the integer with that exponents in its prime factorization. ``` [Answer] ## JavaScript (ES7), 32 bytes ``` f=(x,y,i=1)=>i**y%x?f(x,y,i+1):i ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` R*%⁸i0 ``` [Try it online!](http://jelly.tryitonline.net/#code=Uiol4oG4aTA&input=&args=OTY+Mg) or [verify all test cases](http://jelly.tryitonline.net/#code=Uiol4oG4aTAKw6cv4oKs4oG4OyJH&input=&args=WzI2LCAyXSwgWzk2LCAyXSwgWzMyLCAzXSwgWzY0LCA5XSwgWzI3LCAzXQ). ### How it works ``` R*%⁸i0 Main link. Arguments: x, y R Yield range from 1 to x inclusive. * Raise each to power y. %⁸ Take modulo of each with base x. i0 Find the 1-based index of the first occurence of zero, returns. ``` [Answer] # Python 3, ~~60~~ ~~43~~ 39 bytes *Thanks to @LeakyNun and @Sp3000 for help* ``` f=lambda x,y,i=1:i**y%x<1or-~f(x,y,i+1) ``` A function that takes input via argument and returns the output. **How it works** The function uses recursion to repeatedly check integers `i`, starting with `i=1`, until one satisfying the required condition, here `i**y%x<1`, is found. This is achieved by taking the logical `or` of the condition and the result of the expression for `i+1` incremented, which here is `-~f(x,y,i+1)`. This expression continuously evaluates as `False` until a satisfying value `j` is found, at which point it evaluates to `True` and recursion stops. Since these are respectively equivalent to `0` and `1` in Python, and the function has repeatedly been adding `1` via the incrementing part, the function returns `(j-1)*False + True + (j-1)*1 = (j-1)*0 + 1 + (j-1)*1 = 1 + j-1 = j`, as required. [Try it on Ideone](http://ideone.com/CqdRnk) [Answer] ## Haskell, 31 bytes ``` x#y=[n|n<-[1..],mod(n^y)x<1]!!0 ``` Usage example: `96#2` -> `24`. Direct implementation: try all integers `n`, keep those that meet the condition and pick the first one. [Answer] # 05AB1E (10 bytes) ``` >GN²m¹ÖiNq ``` [Try it online](http://05ab1e.tryitonline.net/#code=PkdOwrJtwrnDlmlOcQ&input=OTYKMg) * `>` Reads the first argument, increments it, and pushes it on the stack * `G` pops the stack (`a`) and starts a loop that contains the rest of the program where `N` takes on the value `1, 2, ... a - 1`. * `N²m` pushes `N` and the second entry from the input history, then pops them both and pushes the first to the power of the second. * `¹` pushes the first entry from the input history onto the stack. * `Ö` pops the previous two stack entries, then pushes `a % b == 0` on the stack. * `i` pops that from the stack. If true, it executes the rest of the program; otherwise, the loop continues. * `N` pushes `N` on the stack. * `q` terminates the program. When the program terminates, the top value of the stack is printed. [Answer] # [MATL](http://github.com/lmendo/MATL), 9 bytes ``` y:w^w\&X< ``` [Try it online!](http://matl.tryitonline.net/#code=eTp3XndcJlg8&input=OTYKMg) ### Explanation ``` y % Take x and y implicitly. Push x again % STACK: x, y, x : % Range from 1 to x % STACK: x, y, [1, 2, ..., x] w % Swap % STACK: x, [1, 2, ..., x], y ^ % Power, element-wise % STACK: x, [1^y, 2^y, ..., x^y] w % Swap % STACK: [1^y, 2^y, ..., x^y], x \ % Modulo, element-wise % STACK: [mod(1^y,x), mod(2^y,x), ..., mod(x^y,x)] % A 0 at the k-th entry indicates that x^y is divisible by x. The last entry % is guaranteed to be 0 &X< % Arg min: get (1-based) index of the first minimum (the first zero), say n % STACK: n % Implicitly display ``` [Answer] # [Actually](http://github.com/Mego/Seriously), ~~12~~ 11 bytes Many thanks to Leaky Nun for his many suggestions. Golfing suggestions welcome. [Try it online!](http://actually.tryitonline.net/#code=OylS4pmA4oG_4pmAJTBAw611&input=MgoyNQ) ``` ;)R♀ⁿ♀%0@íu ``` Original 12-byte approach. [Try it online!](http://actually.tryitonline.net/#code=MVdY4pSCMeKVluKVnOKBvyVXWOKVnA&input=MjUKMg) ``` 1WX│1╖╜ⁿ%WX╜ ``` Another 12-byte approach. [Try it online!](http://actually.tryitonline.net/#code=d-KUrGkp4pmAL-KZgktA4pmA4oG_z4A&input=MgoyNQ) ``` w┬i)♀/♂K@♀ⁿπ ``` A 13-byte approach. [Try it online!](http://actually.tryitonline.net/#code=a-KVlzJg4pWcaWHigb8lWWDilZNO&input=MjUKMg) ``` k╗2`╜iaⁿ%Y`╓N ``` **Ungolfing:** First algorithm ``` Implicitly pushes y, then x. ; Duplicate x. ) Rotate duplicate x to bottom of the stack. R Range [1, x] (inclusive). ♀ⁿ Map a**y over the range. ♀% Map a**y%x over the range. 0@í new_list.index(0) u Increment and print implicitly at the end of the program. ``` Original algorithm ``` Implicitly pushes x, then y. 1WX Pushes a truthy value to be immediately discarded (in future loops, we discard a**y%x) | Duplicates entire stack. Stack: [y x y x] 1╖ Increment register 0. ╜ Push register 0. Call it a. ⁿ Take a to the y-th power. % Take a**y mod x. W If a**y%x == 0, end loop. X Discard the modulus. ╜ Push register 0 as output. ``` Third algorithm ``` Implicitly pushes y, then x. w Pushes the full prime factorization of x. ┬ Transposes the factorization (separating primes from exponents) i Flatten (into two separate lists of primes and exponents). ) Rotate primes to the bottom of the stack. ♀/ Map divide over the exponents. ♂K Map ceil() over all of the divided exponents. @ Swap primes and modified exponents. ♀ⁿ Map each prime ** each exponent. π Product of that list. Print implicitly at the end of the program. ``` Fourth algorithm ``` Implicitly pushes x, then y. k╗ Turns stack [x y] into a list [x, y] and saves to register 0. 2 Pushes 2. ` Starts function with a. ╜i Pushes register 0 and flattens. Stack: [x y a] a Inverts the stack. Stack: [a y x] ⁿ% Gets a**y%x. Y Logical negate (if a**y is divisible by x, then 1, else 0) ` End function. ╓ Push first (2) values where f(x) is truthy, starting with f(0). N As f(0) is always truthy, get the second value. Print implicitly at the end of the program. ``` [Answer] # R, ~~61 bytes~~, ~~39 bytes~~, ~~37 bytes~~, 34 bytes I'm still a newbie in R programming and it turns out this is my first function I create in R (**Yay!**) so I believe there's still room for improvement. ``` function(x,y){for(n in 2:x){if(n^y%%x==0){cat(x,y,n);break}}} ``` Online test can be conducted here: [RStudio on rollApp](https://www.rollapp.com/app/rstudio). --- **Major progress:** ``` function(x,y){which.max((1:x)^y%%x==0)} ``` `which.max` works because it returns the highest value in a vector and if there are multiple it will return the first. In this case, we have a vector of many FALSEs (which are 0s) and a few TRUEs (which are 1s), so it will return the first TRUE. --- **Another progress:** ``` function(x,y)which.max((1:x)^y%%x==0) ``` Finally, it beats out the answer using Python by two bytes. **:)** **Another progress: (Again!)** ``` function(x,y)which.min((1:x)^y%%x) ``` --- Many thanks to [Axeman](https://stackoverflow.com/users/4341440/axeman) and [user5957401](https://codegolf.stackexchange.com/users/58162/user5957401) for the help. [Answer] # dc, ~~23~~ 22 bytes *Thanks to Delioth for his tip about input methods, saving a byte* ``` sysxz[zdlylx|0<F]dsFxp ``` Uses the stack depth operator `z` for incrementing the test case directly on the stack, and the modular exponentiation operator `|` for, well, modular exponentiation. Repeat testing until remainder is not greater than zero. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/), 8 bytes ``` Lsm¹%0k> ``` **Explanation** ``` L # range(1,x) inclusive sm # each to the power of y ¹% # each mod x 0k # find first index of 0 (0-based) > # increment to 1-based ``` [Try it online](http://05ab1e.tryitonline.net/#code=THNtwrklMGs-&input=OTYKMg) [Answer] # [Perl 6](http://perl6.org), ~~26~~ 25 bytes ``` ~~{first \* \*\*$^y%%$^x,1..$x}~~ {first * **$^y%%$^x,1..*} ``` ## Explanation: ``` # bare block with two placeholder parameters 「$^y」 and 「$^x」 { # find the first value first # where when it 「*」 is taken to the power # of the outer blocks first parameter 「$^y」 * ** $^y # is divisible by the outer blocks second parameter 「$^x」 %% $^x, # out of the values from 1 to Inf 1 .. * } ``` [Answer] # Mathematica, 36 bytes ``` (i=1;While[n=i++;Mod[n^#2,#]!=0];n)& ``` [Answer] # [Dyalog APL](http://goo.gl/9KrKoM), 11 [bytes](http://meta.codegolf.stackexchange.com/a/9429/43319) Translation of [this](https://codegolf.stackexchange.com/a/90577/43319). ``` 0⍳⍨⊣|(⍳⊣)*⊢ ``` `0⍳⍨` find the first zero in `⊣|` the division remainders when *x* divides `(⍳⊣)*` the integers one through *x*, raised to the power of `⊢` *y* [TryAPL online!](http://tryapl.org/?a=f%u21900%u2373%u2368%u22A3%7C%28%u2373%u22A3%29*%u22A2%20%u22C4%20f/%A8%2826%202%29%2896%202%29%2832%203%29%2864%209%29%2827%203%29&run) [Answer] ## PowerShell v2+, 48 bytes ``` param($x,$y)(1..$x|?{!(("$_*"*$y+1|iex)%$x)})[0] ``` Takes input `$x` and `$y`. Constructs a range from `1` to `$x`, then uses `Where-Object` to filter those numbers. The filter takes the string `"$_*"` (i.e., the current number with an asterisk) and uses string-multiplication to concatenate those `$y` times, then tacks on a final `1` at the end, then pipes that to `iex` (short for `Invoke-Expression` and similar to `eval`). This takes the place of `[math]::Pow($_,$y)`, since PowerShell doesn't have an exponentiation operator, and is two bytes shorter. That's fed into the modulo operator `%` with `$x` -- thus, if it's divisible, this will be `0`, so we encapsulate that in parens and take the Boolean-not `!(...)` thereof. Thus, if its divisible, it'll be included by this filter, and all other numbers will be excluded. Finally, we encapsulate the resultant numbers in parens `(...)` and take the `[0]` index. Since the range entered sorted `1..$x`, this will be the smallest. That's left on the pipeline and printing is implicit. ### Test cases ``` PS C:\Tools\Scripts\golfing> (26,2),(96,2),(32,3),(64,9),(27,3)|%{($_-join', ')+' -> '+(.\smallest-positive-number-divisor.ps1 $_[0] $_[1])} 26, 2 -> 26 96, 2 -> 24 32, 3 -> 4 64, 9 -> 2 27, 3 -> 3 ``` [Answer] ## PHP, ~~55~~ 33 bytes ``` $i=1;while($i**$y%$x)$i++;echo$i; ``` [Answer] # Perl, ~~29~~ 26 bytes Includes +3 for `-p` (not +1 since the code contains `'`) Run with the input on STDIN ``` power.pl <<< "96 2" ``` `power.pl`: ``` #!/usr/bin/perl -p / /;1while++$\**$'%$`}{ ``` [Answer] # Pyth, 9 bytes ``` AQf!%^THG ``` A program that takes input of a list of the form `[x, y]` on STDIN and prints the result. [Try it online](https://pyth.herokuapp.com/?code=AQf%21%25%5ETHG&test_suite=1&test_suite_input=%5B26%2C2%5D%0A%5B96%2C2%5D%0A%5B32%2C3%5D%0A%5B64%2C9%5D%0A%5B27%2C3%5D&debug=0) **How it works** ``` AQf!%^THG Program. Input: Q AQ G=Q[0];H=Q[1] f First truthy input T in [1, 2, 3, ...] with function: ^TH T^H % G %G ! Logical not (0 -> True, all other modulus results -> False) Implicitly print ``` [Answer] # PHP 59 bytes Sorry, but I can't test this from my mobile. **:)** ``` function blahblah($x,$y){ for($i=0;1;$i++){ if(!$i^$y%$x){ return $i; } } } ``` Golfed ``` function b($x,$y){for($i=0;1;$i++){if(!$i^$y%$x)return $i;} ``` ]
[Question] [ # Task Your task is to print or output all **positive** numbers in which every multi-digit substring in its decimal representation is also prime. If the number has at least 2 digits, this would imply that the number itself also needs to be prime. # Example * `6197` is in the sequence because every multi-digit substring in `6197` is prime, namely: `61`, `19`, `97`, `619`, `197`, `6197` (itself). * Note that `6` is not a prime but `6197` is still in the sequence because `6` is not a multi-digit substring of `6197`. * `8` is also in the sequence because every multi-digit substring in `8` is prime. There is no multi-digit substring in `8`, so this is a case of [vacuous truth](https://en.wikipedia.org/wiki/Vacuous_truth). # Specs * [Standard loopholes](http://meta.codegolf.stackexchange.com/q/1061/48934) apply, except that you are **allowed** to hardcode the output or store information related to the output in your program. * The numbers in the output can be in **any order**. * The numbers in the output are **allowed** to have duplicates. * You may use **any separator**, if you choose to print instead of output. * You are **allowed** to prefix and/or postfix output if you choose to print instead of output. * The separator and the prefix and the postfix may **not** contain any digits (U+0030 to U+0039). # Full list (58 items) ``` 1 2 3 4 5 6 7 8 9 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 113 131 137 173 179 197 311 313 317 373 379 419 431 479 613 617 619 673 719 797 971 1373 3137 3797 6131 6173 6197 9719 ``` # Reference * [OEIS A131648](http://oeis.org/A131648) (incomplete list) --- As always, please feel free to address in the comments anything I should clarify. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 18 bytes ``` 9719⟦₁{sᶠℕ₁₀ˢṗᵐ&}ˢ ``` [Try it online!](https://tio.run/##ATQAy/9icmFjaHlsb2cy//85NzE54p@m4oKBe3PhtqDihJXigoHigoDLouG5l@G1kCZ9y6L///9a "Brachylog – Try It Online") So...am I ready for the ["bounty"](https://codegolf.stackexchange.com/questions/90042/print-output-all-positive-numbers-in-which-every-multi-digit-substring-in-its-de?rq=1#comment219535_90042)? :D [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), ~~15~~ 13 bytes Code: ``` 4°GN§ŒD9›ÏpP– ``` Explanation: ``` G # For N in range 1, 4° # 10000 N # Push N § # Convert that to string Œ # Get all substrings D9›Ï # Keep all substrings that are greater than 9 p # Check each of them if they are prime P # Product – # If 1, print N ``` Uses the **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=NMKwR07Cp8WSRDnigLrDj3BQ4oCT&input=) (might take a few seconds). [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), ~~18~~ ~~17~~ ~~15~~ ~~16~~ 15 bytes ``` ℕ₁<l4&≜sᶠ{Ḋ|ṗ}ᵐ ``` [Try it online!](https://tio.run/##ATgAx/9icmFjaHlsb2cy/@KGsOKCgSbhuoniiqX/4oSV4oKBPGw0JuKJnHPhtqB74biKfOG5l33htZD//w "Brachylog – Try It Online") -1 byte after a discussion with Fatalize inspired me to just see what happens if I swap the `l` and the `<` around. This predicate [generates](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/10753#10753) the output through the input variable, so long as the output variable is left unconstrained. Since duplicates are allowed, each number is generated with multiplicity equal to 2 to the power of the number of its digits which are prime numbers. ``` ℕ₁ The input variable is a natural number < less than l4 some number with length 4 (maximized as 9999). &≜ Assign a number to the input, and assert that sᶠ every substring of it { | }ᵐ is either ṗ a prime number Ḋ or a single digit. ``` Older versions: ``` {≜ℕsᶠ{Ḋ!|ṗ}ᵐ&}ᶠ⁵⁹b 7^₅⟦₁{sᶠ{Ḋ|ṗ}ᵐ&}ˢ 8ḟ⟦₁{sᶠ{Ḋ|ṗ}ᵐ&}ˢ ∧8ḟ>?ℕ₁≜sᶠ{Ḋ|ṗ}ᵐ ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog/), 18 bytes Another Brachylog solution. I couldn't get it *shorter* than Erik The Outgolfer's Brachylog solution; it's the exact same length, but approaches the generation from the opposite direction. ``` {≜ℕ{sℕ₁₀}ᶠṗᵐ&}ᶠ⁵⁹b ``` Looks like Unrelated String has beaten this by many a character, whom I congratulate. Explanation: ``` {≜ℕ Brute force all nonnegative integers to find any that match the constraints {s Create a predicate that finds all subsequences of digits of said integer ℕ₁₀ Constrains those subsequences to be >= 10 }ᶠ Finds all possible values of that predicate: all multi-digit subsequences ṗᵐ Apply a primality constraint to all of those subsequences & Make the predicate output the input integer rather than a prime subsequence }ᶠ⁵⁹ Find the first 59 results (all of the puzzle's solutions, and zero) b Remove the first element of the list, i.e. 0 ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/v/pR55xHLVOri4HEo6bGR00NtQ@3LXi4c/rDrRPUQMxHjVsfNe5M@v//v1@or5NrUDAA) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 17 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` DẆṖÐfḌÆP€Ạ ³²RÇÐf ``` My first Jelly answer! Saved 3 bytes thanks to [@Leaky Nun](https://codegolf.stackexchange.com/users/48934/leaky-nun)! [Try it online](http://jelly.tryitonline.net/#code=ROG6huG5lsOQZuG4jMOGUOKCrOG6oArCs8KyUsOHw5Bm&input=) Explanation: ``` DẆṖÐfḌÆP€Ạ The helper link, which checks if a given number satisfy the conditions. DẆ Convert the argument to a list of its digits and get all its substrings. ṖÐf Remove all lists of length 1. ḌÆP€Ạ Convert back each element to an integer and check if all of them are prime. ³²RÇÐf Main link. ³² Create a 100 and square it, which gives 10000. R Create a list from 1 to it. ÇÐf Filter out all the elements where the helper link gives false. ``` [Answer] # Java 8, 182 bytes ``` v->{for(int n=0;++n<1e4;)if(P(n)>0)System.out.println(n);}int p(int n){for(int i=2;i<n;n=n%i++<1?0:n);return n;}int P(int n){return n>99?p(n)*p(n%100)*p(n%1000)*P(n/10):n<10?n:p(n);} ``` Port of [*gastropner*'s C (gcc) answer](https://codegolf.stackexchange.com/a/160625/52210), so make sure to upvote his answer! [Try it online.](https://tio.run/##PVDLasMwELz3K/YSkGriyKWXWH58QUIg0EvpQVXkolRZC1l2KcHf7q6dJiBpV8PMajRnNaj1@fQ9aae6DnbK4vUJwGI0oVHawH6@AgytPYFmb3MZuCRspE1rDwglTMO6ujZtYCQELIVMEiwy8yq5bdiBIa8EP/520VzSto@pD8RzSLgc5SzxNyF/zLDli7QFSixxZZOkyGqREzuY2AcElONMOtxVd7jabmtPU5/pWGVCPBrqyMUmEzwnX6LG3C@PTwC@/3RWQxdVpLL880IpsGMkk1/vH4rfEkDzs8TDeIqpZtg795/DOP0B) **Explanation:** ``` // Loop in range [1,10000), and print any primes corresponding to the challenge description v->{for(int n=0;++n<1e4;)if(P(n)>0)System.out.println(n);} // Checks if the given integer is a prime (return unchanged input if prime, 0 if not) int p(int n){for(int i=2;i<n;n=n%i++<1?0:n);return n;} // Recursive method that checks if every part of length 2+ is a prime, or is below 10 int P(int n){return n>99?p(n)*p(n%100)*p(n%1000)*P(n/10):n<10?n:p(n);} ``` [Answer] ## PowerShell v2+, ~~107~~ 104 bytes ``` 1..10+(11..1e4|?{($x=11..($i=$_)|?{"$i"-match$_}).count-eq($x|?{'1'*$_-match'^(?!(..+)\1+$)..'}).count}) ``` *Warning: Kinda Slow* Loops from `11` to `1e4` (i.e., `10000`) and pulls out numbers using the `Where-Object` selector (`|?{...}`). The clause is two components -- the first loops from `11` up to the current number and uses `Where-Object` to pull out those numbers that form a substring of the current number (via the `-match` regex operator). We store those substrings in `$x`. The second portion loops through `$x` and uses `Where-Object` to pull out all primes using the [prime regex](https://codegolf.stackexchange.com/a/57636/42963). We then take the `.count` of both and the check is actually whether those are `-eq`ual. For example, `971` will have `$x = (71,97,971)` and each of those are prime, so `3-eq3` is `$TRUE` and thus `971` will be selected. That result is array-concatenated with a range `1..10`. The resulting array is left on the pipeline and output is implicit, with a newline between elements by default. [Answer] # [Japt](https://github.com/ETHproductions/japt), 15 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` L²õs f_ã fÅe_°j ``` [Test it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=TLL1cyBmX%2bMgZsVlX7Bq) [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~144~~ ~~142~~ ~~140~~ ~~136~~ ~~134~~ 132 bytes -2 thanks to Kevin Cruijssen. -2 thanks to ceilingcat ...And inspired by that, we can get another 2 bytes from that for loop. Also shamelessly nicked the rather better prime checker from Kevin Cruijssen's [answer](https://codegolf.stackexchange.com/a/160628/75886) for another -4. ``` p(n,i){for(i=2;i<n;)n*=n%i++||n<10;i=n;}P(n){n=p(n)*(n<99||p(n%100)*p(n%1000)*P(n/10));}f(n){for(n=1e4;--n;)P(n)&&printf("%d\n",n);} ``` [Try it online!](https://tio.run/##LYxLCsJAEAWvIoGE7nxwRtyEnrmDB3Aj0ZFe@Awhu0zOHnvAXfGoV9PwnqbjmAm98pa@C2m8iAYIo42otetyRvBONEL2G4E3RNO5JYRxzNm49s5x@wcjs87eMcueil@qiP51lWGwbmk0zbwo1kRV/byj6mHuYcPp81CQXagMPw "C (gcc) – Try It Online") [Answer] # Malbolge Unshackled (20-trit rotation variant), 2,5254e7 bytes or 1,9809e7 bytes Size of this answer exceeds maximum postable program size (eh), so the code is [located in my GitHub repository](https://github.com/KrzysztofSzewczyk/codegolf-submissions/raw/master/90042-a.mb) (note: Don't copy the code using CTRL+A and CTRL+C, just rightclick and click "Save destination element as..."). ## How to run this? This might be a tricky part, because naive Haskell interpreter will take ages upon ages to run this. TIO has decent Malbogle Unshackled interpreter, but sadly I won't be able to use it (limitations). The best one I could find is the fixed 20-trit rotation width variant, that performs very well. To make the interpreter a bit faster, I've removed all the checks from Matthias Lutter's Malbolge Unshackled interpreter. ``` #include <malloc.h> #include <stdio.h> #include <stdlib.h> #include <string.h> const char* translation = "5z]&gqtyfr$(we4{WP)H-Zn,[%\\3dL+Q;>U!pJS72Fh" "OA1CB6v^=I_0/8|jsb9m<.TVac`uY*MK'X~xDl}REokN:#?G\"i@"; typedef struct Word { unsigned int area; unsigned int high; unsigned int low; } Word; void word2string(Word w, char* s, int min_length) { if (!s) return; if (min_length < 1) min_length = 1; if (min_length > 20) min_length = 20; s[0] = (w.area%3) + '0'; s[1] = 't'; char tmp[20]; int i; for (i=0;i<10;i++) { tmp[19-i] = (w.low % 3) + '0'; w.low /= 3; } for (i=0;i<10;i++) { tmp[9-i] = (w.high % 3) + '0'; w.high /= 3; } i = 0; while (tmp[i] == s[0] && i < 20 - min_length) i++; int j = 2; while (i < 20) { s[j] = tmp[i]; i++; j++; } s[j] = 0; } unsigned int crazy_low(unsigned int a, unsigned int d){ unsigned int crz[] = {1,0,0,1,0,2,2,2,1}; int position = 0; unsigned int output = 0; while (position < 10){ unsigned int i = a%3; unsigned int j = d%3; unsigned int out = crz[i+3*j]; unsigned int multiple = 1; int k; for (k=0;k<position;k++) multiple *= 3; output += multiple*out; a /= 3; d /= 3; position++; } return output; } Word zero() { Word result = {0, 0, 0}; return result; } Word increment(Word d) { d.low++; if (d.low >= 59049) { d.low = 0; d.high++; if (d.high >= 59049) { fprintf(stderr,"error: overflow\n"); exit(1); } } return d; } Word decrement(Word d) { if (d.low == 0) { d.low = 59048; d.high--; }else{ d.low--; } return d; } Word crazy(Word a, Word d){ Word output; unsigned int crz[] = {1,0,0,1,0,2,2,2,1}; output.area = crz[a.area+3*d.area]; output.high = crazy_low(a.high, d.high); output.low = crazy_low(a.low, d.low); return output; } Word rotate_r(Word d){ unsigned int carry_h = d.high%3; unsigned int carry_l = d.low%3; d.high = 19683 * carry_l + d.high / 3; d.low = 19683 * carry_h + d.low / 3; return d; } // last_initialized: if set, use to fill newly generated memory with preinitial values... Word* ptr_to(Word** mem[], Word d, unsigned int last_initialized) { if ((mem[d.area])[d.high]) { return &(((mem[d.area])[d.high])[d.low]); } (mem[d.area])[d.high] = (Word*)malloc(59049 * sizeof(Word)); if (!(mem[d.area])[d.high]) { fprintf(stderr,"error: out of memory.\n"); exit(1); } if (last_initialized) { Word repitition[6]; repitition[(last_initialized-1) % 6] = ((mem[0])[(last_initialized-1) / 59049]) [(last_initialized-1) % 59049]; repitition[(last_initialized) % 6] = ((mem[0])[last_initialized / 59049]) [last_initialized % 59049]; unsigned int i; for (i=0;i<6;i++) { repitition[(last_initialized+1+i) % 6] = crazy(repitition[(last_initialized+i) % 6], repitition[(last_initialized-1+i) % 6]); } unsigned int offset = (59049*d.high) % 6; i = 0; while (1){ ((mem[d.area])[d.high])[i] = repitition[(i+offset)%6]; if (i == 59048) { break; } i++; } } return &(((mem[d.area])[d.high])[d.low]); } unsigned int get_instruction(Word** mem[], Word c, unsigned int last_initialized, int ignore_invalid) { Word* instr = ptr_to(mem, c, last_initialized); unsigned int instruction = instr->low; instruction = (instruction+c.low + 59049 * c.high + (c.area==1?52:(c.area==2?10:0)))%94; return instruction; } int main(int argc, char* argv[]) { Word** memory[3]; int i,j; for (i=0; i<3; i++) { memory[i] = (Word**)malloc(59049 * sizeof(Word*)); if (!memory) { fprintf(stderr,"not enough memory.\n"); return 1; } for (j=0; j<59049; j++) { (memory[i])[j] = 0; } } Word a, c, d; unsigned int result; FILE* file; if (argc < 2) { // read program code from STDIN file = stdin; }else{ file = fopen(argv[1],"rb"); } if (file == NULL) { fprintf(stderr, "File not found: %s\n",argv[1]); return 1; } a = zero(); c = zero(); d = zero(); result = 0; while (!feof(file)){ unsigned int instr; Word* cell = ptr_to(memory, d, 0); (*cell) = zero(); result = fread(&cell->low,1,1,file); if (result > 1) return 1; if (result == 0 || cell->low == 0x1a || cell->low == 0x04) break; instr = (cell->low + d.low + 59049*d.high)%94; if (cell->low == ' ' || cell->low == '\t' || cell->low == '\r' || cell->low == '\n'); else if (cell->low >= 33 && cell->low < 127 && (instr == 4 || instr == 5 || instr == 23 || instr == 39 || instr == 40 || instr == 62 || instr == 68 || instr == 81)) { d = increment(d); } } if (file != stdin) { fclose(file); } unsigned int last_initialized = 0; while (1){ *ptr_to(memory, d, 0) = crazy(*ptr_to(memory, decrement(d), 0), *ptr_to(memory, decrement(decrement(d)), 0)); last_initialized = d.low + 59049*d.high; if (d.low == 59048) { break; } d = increment(d); } d = zero(); unsigned int step = 0; while (1) { unsigned int instruction = get_instruction(memory, c, last_initialized, 0); step++; switch (instruction){ case 4: c = *ptr_to(memory,d,last_initialized); break; case 5: if (!a.area) { printf("%c",(char)(a.low + 59049*a.high)); }else if (a.area == 2 && a.low == 59047 && a.high == 59048) { printf("\n"); } break; case 23: a = zero(); a.low = getchar(); if (a.low == EOF) { a.low = 59048; a.high = 59048; a.area = 2; }else if (a.low == '\n'){ a.low = 59047; a.high = 59048; a.area = 2; } break; case 39: a = (*ptr_to(memory,d,last_initialized) = rotate_r(*ptr_to(memory,d,last_initialized))); break; case 40: d = *ptr_to(memory,d,last_initialized); break; case 62: a = (*ptr_to(memory,d,last_initialized) = crazy(a, *ptr_to(memory,d,last_initialized))); break; case 81: return 0; case 68: default: break; } Word* mem_c = ptr_to(memory, c, last_initialized); mem_c->low = translation[mem_c->low - 33]; c = increment(c); d = increment(d); } return 0; } ``` ## Performance notes The application ran about 40 minutes on my machine, producing HEX numbers of the sequence. I stopped it around an hour of calculations, and it finished on 0x11. Note this answer differs from my other one, because this one actually calculates the numbers, and it can be made so it calculates them indefinitely. The application allocates the spinup buffer, that is around 7 gigabytes big, so better prepare your free RAM. # Alternative variant Alternative variant uses around 2 gigabytes of memory less, but produces the output in form of ASCII characters (0 = ASCII(0x0), 10 = newline, etc...), and is available [here](https://github.com/KrzysztofSzewczyk/codegolf-submissions/raw/master/90042-b.mb). It doesn't compete though, due to challenge requirements [Answer] # [Python 3](https://docs.python.org/3/), 118 bytes ``` r=range(9720) for n in r[1:]:all(all(l%k+9//l for k in r[2:l])for l in(n%10**(i%5)//10**(i//5)for i in r))and print(n) ``` [Try it online!](https://tio.run/##JYpLCoRADAX3niKbhkQX8YOIDXOSwUXDzGhjiBLczOlbWxcPqqi3/49l0y4le1nQ@Yvj0NZU/DYDhahg78ZPPohgnri1GpkFcl@f3nqZKLtcjuqauiwxup6YH2Tu7x7vP1HQD@wW9UCllE4 "Python 3 – Try It Online") ### Explanation Warning: no actual strings involved in this solution. ``` r=range(9720) for n in r[1:]: # For each positive integer up to 9720 all( ... for l in(n%10**(i%5)//10**(i//5)for i in r)) # Check for all its substrings all(l%k ... for k in r[2:l]) # If it is either prime +9//l # Or smaller than 10 and print(n) # Then print ``` [Answer] # Ruby, 81 + 8 = 89 bytes +8 bytes for `-rprime`. ``` puts (?1..?9*4).select{|m|(r=2..m.size).all?{|i|r.all?{|j|m[i-2,j].to_i.prime?}}} ``` See it on repl.it: <https://repl.it/CniR/2> [Answer] # [Perl 6](http://perl6.org), ~~47 44~~ 43 bytes ``` ~~for 1..9719 {all(m:ex/..+/).Int.is-prime&&.say} put grep {is-prime +all(m:ex/..+/):},1..9719~~ put grep {is-prime +all m:ex/..+/:},1..9719 ``` ## Explanation: ``` # print the values space separated, with trailing newline put # that match grep -> $_ { # call the method 「.is-prime」 ( that is what 「:」 is for ) # (autothreaded) is-prime # convert following to numeric (autothreaded) + # a junction of all( # all substrings 2 characters or greater $_ ~~ m :exhaustive / . .+ / ) # needed to indicate that 「is-prime」 is a method call : }, # in this Range 1..9719 ``` [Answer] ## C#, ~~261~~ ~~249~~ 247 bytes *Saved 12 bytes thanks to Leaky Nun* ``` ()=>{Action<int>w=System.Console.WriteLine;int i=0,n,j,k,p,m,b;for(;++i<10001;){n=(i+"").Length;if(n<2)w(i);else{b=1;for(j=1;++j<=n;)for(k=0;k+j<=n;){p=int.Parse((i+"").Substring(k++,j));if(p%2<1)b=0;for(m=3;m<p;m+=2)if(p%m<1)b=0;}if(b>0)w(i);}}}; ``` This compiles to a `Func<List<int>>`. The formatted version looks like: ``` () => { Action<int> w = System.Console.WriteLine; int i = 0, n, j, k, p, m, b; for (; ++i < 10001;) { n = (i + "").Length; if (n < 2) w(i); else { b = 1; for (j = 1; ++j <= n; ) for (k = 0; k + j <= n; ) { p = int.Parse((i + "").Substring(k++, j)); if (p % 2 < 1) b = 0; for (m = 3; m < p; m += 2) if (p % m < 1) b = 0; } if (b > 0) w(i); } } }; ``` [Answer] # [Swift 4](https://developer.apple.com/swift/), 144 bytes ``` let p={n in !(2..<n).contains{n%$0<1}} print((1...971).filter{$0<10||p($0)&&($0<100||p($0/10)&&p($0%100))}+[1373,3137,3797,6131,6173,6197,9719]) ``` [Try it online!](https://tio.run/##LYzBCsIwEETvfkWEtmQxrFkjDYH6JeJBpIVAWUMb8JDm22MqXoZ5b2DWj5/itZR5jCLcEgvP4igviAMDvt4cn57XxG2jB8r5EBbPUUpCRGcJcPJzHJe0r3rbgmw0dJ384Z/PtKu9tdUB5NOdjDXK1FTGOqt6MlSjup4q1l/3gFK@) ## Explanation ``` let p={n in !(2..<n).contains{n%$0<1}} // Helper function p, tests if a number is prime print((1...971).filter{ // Print every number n in the range 1 to 971 $0<10 // that is less than 10 ||p($0)&& // or a prime and ($0<100 // is less than 100 or ||p($0/10)&&p($0%100))} // n/10 and n%100 are primes +[1373,3137,3797,6131,6173,6197,9719]) // Print the four digit numbers ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 130 bytes if i can assume infinite stack `i*i<=n&&` can be removed and `i*i>n` turns to `i>=n` which reduces the code by 9 bytes and maybe convert main function to recursive : <https://tio.run/##LYpBDoIwEEX33AMyAxVbXUmccgX2xkWDRYeQaSPqyrvXkrj5ef/lze7j1vHJ8bWTcPMpTQRMWjm6XJFs0/DZ@EM/ASunBmCsKtfG9/rIiJ0rIoEoJpNbKXPdx@1jx5akGEiytqdNYp2nNFr/wR@xHkD2Rn81dpLGIGtYfLuEO0yAmH4> (119 bytes) ``` _=>eval(`for(a=[i=1];++i<1e4;)P(i)&&a.push(i)`)||a p=(n,i=1)=>i*i<=n&&n%++i?p(n,i):n%i P=n=>n>9?p(n)*p(n%100)*p(n%1e3)*P(n/10|0):n ``` [Try it online!](https://tio.run/##LYtBDoIwEEX33IOmg4ptdKMw9QrsjZEGi44h0waUFXevJXHz8/Ly/tvOdupGCp8d@4eLPcY7GjfbQba9H6XFK6G@VZsN1dodK2gkgRC2DN/plbCFZbFZQMnb1AEaKqhGFoLzdLmE1cOZc8oaZDRsTquDIk2ulfqDO0DRSN5rtahUx87z5AdXDv4pewkQfw "JavaScript (Node.js) – Try It Online") [Answer] # [Malbolge](https://github.com/TryItOnline/malbolge), 1361 bytes Simple and boring version. Displays numbers from the highest. ``` D'`r^"!=[YG3yUCvA-csNqp-nJ$HYFgDC#AbQ,|*)\rwvutm3kSonmlkdihg`&dc\aZ_X|V[ZYXQPt7SRQPOHGkKJIHG@d>=<A:98\}|:981U5.-2+0/.'K%$#G!E}e#z!~}v<]yxwpun4rkj0nmfN+ihaf_^$\a`_XW{>=YXWVONrLKPINGkE-IBAe(>=<;_?>=}|:3W1w543,P0).-&J*)(!E}|B"!~}|{zyr8potml2jongfkjibg`&d]\"`_XW{>=YXWVONr54JIHMFj-,HGF?>b%A@?87[;:981w543,P0).-&J*j(!EfeB"!~}_u;yrqpun4rqpihmlkjihg`&d]\"`_X|\[ZYXQuUNMLQJnH0LKJIBAe(>=<`#"8\<5Y9270T43,Pqp.-&J$)"!~D|#"y~}|u;s9qvotsrk1inglkdihg`&d]\"Z~XWVUZYXQu87SLKo2NGFjDIHGF?>bBA#"8\6;:981Uv.32+*)Mnm%$)('~D|{A!xwv{zyr8vXnsrkjoh.fNdchg`ed]#aC_^WVz=YXQPt7SRQPOHGkK-IHGF?>bBA#"8\6;:981Uv.32+*)Mnm%*#"F&%$#cy?}v<]\xwpun4rqSonmf,diha'eG]#a`_X|V[ZYXWPt76LKoIHGLEiCHGFED=aA:?>7[;:981w/4-,PO)o'&J*j(!E%edz@~}_u;yxqpo5mrqpoh.f,jibgf_%]\[!_XW{[ZYXQu87SLKo2NGFjJIHAF?c=BA@?>=<5Y38765.-Q10)o'&J*j(!E%e{z@~}|{ts9qpotsrk1oQglkd*)gIed]#DZ_^]VzZYRQuONMRKJnNGLEJCgG)(D=aA:?>=<;4X816/43,P0).-&+$H('gf|Bcb~w|u;yxwYutmrqj0nmleMib(fH%cba`_X|VUZYXWPt7SRQPOHGkEDIHG@dDC<;@?8\6|:32V0T43,+O)o'&J*)('&}C{"yxwv<tyr8vun4Ukpoh.fN+c)gIed]#DZ_^]VzTSRWPtTSLQJnH0LKJIBAe(>=BA@987[;:381Uv.32+*)Mnm%$)('~D${"y?}_uzyxqpo5srqSonmf,jihgfeG]#a`_X|V[ZYXWPt76LKo2NGFjJIH*)ED=a;@?>76;4X816/43,P*).',%I)('~Ded"y~}|u;srqvo5mlqpih.fN+cba`&d]\aZ~^]VUZSwWPUTSLpJ2NGLEiCHGFED=a;:?>7<5YX876v43,+O).-,+$H('&feBz!x}v{zsr8punsrk1inglkdihg`&d]\"Z~X]V[ZSwQVUTMRKo2NGFjDIHGF?>b%A@?87[;{921U5.3210)M-,%k#(!EfeB"y~}v{zyr8% ``` [Try it online!](https://tio.run/##hZTZcqJQFEW/xQEVBaM4t1NwwpFoDI4YRzCKgqJiVMyvp88F7UpSqeqX@7hq19r73PV4NVFWc@HzM@ccqa9WS7LfZQInLqvR5HTHbjekXLYXu4V5LmujJw1Cd@O8etQO@3VAairyeiXNFm/zkWM25ce9YUdv9XvdTqO@jzSfG/WnIiNVyqUi8zhLJRP0n1iUv@rw@rmQl6Q8vgevs4LZbYwlfxVsZ8vHVUsMTu/HzUEOqtLSJ69F1rN4G4vDVzs/Hg077Usq2e20W0@sWq3USywj5clShhZcQI8P06kk0ANt/zEUDBB1H@4lHWU37gK6nrECXb@cT2p0o@zXK2qpyHNRWi4mKPuAt36nh4KQulZYkkSRKaRTE4x@TEcj/TjK/o2@BLooGPThIX5St0b27WbxBmaWphmTrvOGmQPH1qqNslz0VcHMLfvIZo3yiVA3RkV8L4i@3SC6HQduTrdZT5D9EN/Ftpqy36mSfyHP/3kHeu8DUnMGPRppVisKxTKFZa5kZs/QiB42snOaN0B53HhNXmN23OUE@oW2vB81w4zWkYG@VN68IjubAl2YDWzj7PC13Tonf7RK/ofutlkLDuh2ekqjVvlbq1u0GZGA7GOnwAB9dN9MG@hhyA7can6RBXo@lxzTf9Kpu/eHIEnUn3DFefOOCbPzo@n9fbtRQmvwjrITqFVxiA34vgW12v9pBrqlC@lpMgOtgv1QNxCNhGGRDb/vK/2C6PplD943pnelgby78XkJmcn1hq@D1rnXfW4cntjac6Uss5C9nJ0zuOuWHXYZ7ET94Yd/m/HYiy7nXNQz08nHUUfZj124JnWL9r4SaouJSyxi04lphruZuXvP54xrymUTcVgkH4a9Uy1jM56bGWjVcc1erMDVEnvUKnjnJMMM65l@z/7SfAb6S/PnIsFMzNh74LfN2IGeBu9n0/vu3irau/h7q3fvbhy1CtlTkfAXM27c6ySwkkEXZve9q7D30HqFrsnIDk7Q3se9D8jO9ZrHdp2D7JsyxX7dTBxtBlrtQKuaacZLEoZ3B9zq2fJ@hb3v4Cc4yL9f0wCyN4@NFvcCrX6/pvtPcIlR6BcLULCZGklgku32E0B285qwz8@/ "Malbolge – Try It Online") [Answer] # TI-83/84 BASIC, 124 Bytes ``` For(A,1,E4 DelVar Nint(log(A→P Ans→Q While Ans For(I,0,Q-Ans 10^(P+1 AnsfPart(iPart(A/10^I)/Ans→S min(Ans={2,3,5 If S≥7 and fPart(.5S min(remainder(S,3+2cumSum(not(binompdf(int(.5√(S)),0 N+not(Ans→N End P-1→P End If not(N Disp A End ``` Loops over the first 10k integers. Sets up a counter in N to check each substring prime, and int(log(A retrieves one less than the number of digits in the current number. We then set that number aside in a second variable so we can step P down through each length substring at least 2 digits. 10^... and AnsfPart(iPart(,,, generate the current substring to check for primality, then the following 3 lines do the primality check to 1 or 0 in Ans. If the substring is not prime, we increment N, and after all the substrings are checked if N is still 0 we print the current number. Possibly some tweaking could be done to increase the efficiency of the primality check toward this test? I'm just glad I found an algorithm in fewer bytes than storing the output directly in TI-83 formatting! [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 194 bytes ``` r=range s=str l=lambda _:len(s(_)) [*map(print,[t for t in r(1,10**4) if all(all(int(x)%b for b in r(2,int(x))) for x in [s(t)[i:j+1] for i in r(l(t)) for j in r(i,l(t)) if l(s(t)[i:j+1])>1])])] ``` [Try it online!](https://tio.run/##Tc3BCsIwDIDh@54iFyGZPTj1IMJ8kSKjw007sq6kPcynr916kZDLxx/iv/GzuMvNS0rSinHvoQptiFJxy2buXwa6Ow8OA3ZEla5n49GLdVHpCOMiEME6EGxUc6rrK4EdwTDjtrnClQ793vWlO6uiRLuum@qAkbS9T8fmuastLWcu2VTAqkL5B@PfET3y5knpBw "Python 3.8 (pre-release) – Try It Online") [Answer] # [PHP](https://php.net/), 135 bytes ``` for(;++$n<1e4;$p||print"$n ")for($p=$i=0;$i<$l=strlen($n);$i++)for($j=1;$j++<$l-$i;$p|=$k)for($k=($m=substr($n,$i,$j))-1;$k&&$m%$k--;); ``` [Try it online!](https://tio.run/##JYzBCoMwEETv/QyZSsIaqNBbsvRfCpYm0XSJevPf0xUvc5h5b@QrLbxE8/OrxhOhhHF6eshxSI1l61BunT1HCCPywyMGzLxudZ6KQbFaEF1E4tEjESngEM8TRr6mzAYLr/tbRbUGxAHJWqdC7nssd2TnvPWt/QE "PHP – Try It Online") ``` for(; // level 1 loop on ++$n<1e4; // all numbers from 1 to 10,000, $n is current number $p||print"$n\n" // at the end of loop for each number, print $n if all multi digit sub strings were prime ($p=0) ) for( // level 2 loop on each digit of $n $p= // $p is a flag for all sub string primes and is set to 0 for each new $n $i=0; // $i is position of current digit (and sub string start position) $i<$l=strlen($n); // $l is the total digits count in $n $i++ // increment $i by one ) for( // level 3 loop to create sub strings $j=1; // $j is length of sub string, we only care about multi digit sub strings so it starts from 1 $j++<$l-$i; // continue the loop as long as $j has not reached last digit and increment it by one $p|=$k // THIS IS RUN AFTER LOOP LEVEL 4: update $p flag based on value of $k // $p will be left at 0 only if all of the sub strings are prime (if $k is always 0) ) for( // level 4 loop to check each sub string to be prime $k=( // $k is set to current sub string minus 1 $m=substr($n,$i,$j) // $m is current sub string )-1; // $k && $m%$k--; // as long as $k is more than 0 and $m%$k is not zero, decrement $k by one and continue // a prime number will only get a 0 remainder, when $k gets to 1 // so $k will be 0 for primes and more than 0 for non-primes ); ``` ]
[Question] [ In a standard dice (die) the numbers are arranged so that opposite faces add to seven. Write the shortest possible program in your preferred language which outputs a random throw followed by 9 random tippings. A tipping is a quarter turn of the dice, e.g. if the dice is facing 5, all possible tippings are 1,3,4 and 6. Example of desired output: > > 1532131356 > > > [Answer] ## Ruby, 44 ``` c=0;10.times{$><<c=([*1..6]-[c,7-c]).sample} ``` I found the [\*1..6] trick by lucky experimenting. [Answer] ### GolfScript, 26 chars ``` 0{(.6,5@--\-.,rand=).}10*; ``` A slight more compressed version of [Joey](https://codegolf.stackexchange.com/users/15/joey)'s, basically working around the issue with zero-indexing. [Answer] ## JavaScript (71 characters) You may need to replace `print` with `alert` or something else, depending on your JavaScript environment. ``` for(C=L=T=0;C++<10;print(L=T))while(!(T-L&&T+L-7))T=Math.random()*6+1|0 ``` [Answer] ## GolfScript, 28 ``` 0:|;{7,[0|7|-]-.,rand=:|}10* ``` [Answer] **Bash** ``` #/!bin/bash f=`expr $RANDOM % 6` f=`expr $f + 1` printf "$f" for ((i=0; i<9; i++)) do ((bad=7-$f)) next=`expr $RANDOM % 6` next=`expr $next + 1` while [ $next -eq $bad ] || [ $next -eq $f ] do next=`expr $RANDOM % 6` next=`expr $next + 1` done printf "$next" f=$next done ``` sample code: <http://ideone.com/CCfro> [Answer] ### Bash: 97 94 92 90 89 87 Heavily golfed from Aman ZeeK Verma's answer: ``` for((i=10,f=0;i--;))do for((n=f;n==f||n+f==7;f=RANDOM%6+1))do : done printf $f done ``` <http://ideone.com/QiuTx> NB arguably it can be shrunk by 5 chars by changing the first line to `for((;i++<10;))` but that makes assumptions which aren't always valid. It would work ok in ideone but someone running it from a shell could have `i` or `f` exported to something non-zero. [Answer] ## R, 56 52 ``` for(i in 0:9)cat(F<-sample(setdiff(1:6,c(F,7-F)),1)) ``` [Answer] ### Bash with only one loop: 100 99 98 96 ``` for((i=10,f=RANDOM%6+1;i--;))do printf $f ((n=RANDOM%4+1,m=f<4?f:7-f,f=n<m||++n<7-m?n:n+1)) done ``` <http://ideone.com/XrZO7> The key idea is that to pick a random number in [1,x] which isn't equal to y you can pick a random number in [1,x-1] and then increment if it's >= y. For this problem we want a random number in [1,6] which isn't equal to f or 7-f. We have to do the two tests in order min(f,7-f), max(f,7-f). Assuming an initially empty environment could save 2 chars by not initialising i and changing the loop condition to `i++<10` [Answer] ## Windows PowerShell, 45 ``` -join(0..9|%{($d=1..6-ne(7-$d)-ne$d|random)}) ``` Pretty trivial, actually. I generate a list of possible dice rolls `1..6` and then select only those not equal to seven minus the last roll and then only those not equal to the last roll. From the remaining list I then select a random item and assign it to `$d`. Since `$d` is initially treated as `0` it rolls a normal die the first time. Test script: ``` for($i=0;$i-lt20;$i++){ $o=@(./tipping.ps1) if ($i-gt0-and$o-eq$o2) { throw "Must have random output" } if ($o.count-ne1) { throw "Must only have one line of output" } if ($o[0]-match'[^1-6]'){ throw "Invalid characters" } if($o[0].length-ne10){ throw "Wrong length: $($o[0].length)" } $r=[char[]]($o[0])|%{$_-48} for ($x=1;$x-lt$r.count;$x++){ if ($r[$x-1]+$r[$x]-eq7) { throw "Not a tipping: $($r[$x-1]) and $($r[$x])" } } $o2=$o } ``` History: * 2011-02-18 11:57 (61) First attempt. * 2011-02-18 11:58 (45) I don't need to generate the first number separately. [Answer] ## J This should work but unfortunately J's random generator gets stuck after the 3rd iteration: ``` a=:>:i.6 f=:a#~1-(+&(a=])7&-) ((,(?4)&{@f@(_1&{))^:9)>:?6 ``` `6 4 5 4 5 4 5 4 5 4` [Answer] ## Ruby ### 66 characters ``` (0..9).reduce([]){|m|m<<((1..6).to_a-[d=m[-1]||0,7-d]).shuffle[0]} ``` [Answer] ## J, 30 characters ``` >:(?@4:{(i.6)-.],5&-)^:(<10)?6 ``` `6 2 3 5 4 2 4 1 3 6` Explanations (read from right to left): * `?6` returns a random number between 0 and 5 * `^:(<10)` applies a function 9 times, accumulating the results along the way. The function is: * `?@4:{(i.6)-.],5&-` + `] , 5&-` returns an array of the input number and its complement to 5 (we're handling 0-based numbers currently, so the sum of opposite faces is 5) + `(i. 6) -.` removes them from the full set of integers 0 to 5. We're left with all valid positions after a single tipping operation from the input position. + `?@4: {` picks one of those at random. * `>:` increments the whole sequence to bring the figures back to the 1 to 6 interval. [Answer] # TI-BASIC, ~~38~~ 34 ``` For(I,1,9 Ans→X Repeat Ans≠X and Ans≠7-X randInt(1,6 End Disp Ans End ``` Boring solution, but it's shorter than the previous revision. I take advantage of the fact that on a fresh calculator, `Ans` is initialized to zero. [Answer] ## GS2, 16 bytes ``` 16 2f 25 08 41 20 17 30 16 2f 31 31 25 09 19 32 ``` Here's how it works ``` 16 2f 25 # make range from 1 to 6 and push random element 08 # start block 41 # duplicate top of stack twice 20 17 30 # negate top of stack and add 7 16 2f # push range from 1 to 6 31 31 # do set-wise difference with each of the two previous numbers 25 # push a random element from the list 09 # end block 19 32 # repeat block 9 times ``` [Answer] ## QBasic (71 characters) The two newlines are necessary and included in the character count as one character each. ``` RANDOMIZE:FOR I=0TO 9 1N=INT(RND*6)+1:IF L=N OR L+N=7THEN 1 ?N:L=N:NEXT ``` [Answer] # Java 8, 130 bytes ``` v->{int d=(int)(Math.random()*6+1),i=10,p;String r=""+d;for(;i-->0;r+=d)for(p=d;p==d|p+d==7;d=(int)(Math.random()*6+1));return r;} ``` [Try it here.](https://tio.run/##dZA/b8MgEMX3fIpTJqhj54@UdqBk65gslbpUHSiQhBQDgsNqlfqzuzjOWgl0upPu3e@9i@hE7YN2F/U1SCtSgr0w7joDMA51PAqp4TC2AK8YjTuBJG/eKOgoK9O@/PISCjQSDuCAw9DVu2vZBsVJKZTsBZ6bKJzyLaEPj9WaLgxfrxaB3SUjn88rxY4@EmbqerdiseKKjn3gigXO1W@oFOdP7H9NyqLGHB1E1g9s4gr50xauO143crfFHpnuvn@AoJO35RJevrXMqAHPGo7ZSTTewWYLaFqdAD2cNELyrYYk2mA1RJ2yxXTbH1FHy8UXA/PMN9tSququXrL7SajbxmdsQjmN1hHXSOKytfQW5BRlP@uHPw) As full program with verbose main-method this would be **178 bytes** instead: ``` interface M{static void main(String[]a){int d=(int)(Math.random()*6+1),i=10,p;String r=""+d;for(;i-->0;r+=d)for(p=d;p==d|p+d==7;d=(int)(Math.random()*6+1));System.out.print(r);}} ``` [Try it here.](https://tio.run/##dYyxDoIwFEV/pWFqLRBYdGief8DEaBxeeKDF0DblSWKQb68YZ6eTm5x7Rlyw8KF3Iz1Sso77OGDXi2adGdl2YvGWxITWyZajdbfLFdW6e4JA7lCyQb6XER35SarDUdcqt1BXeTC/g4iQZZrM4KM0tijOlYkaSH13ADIBgN5BE8DJ/G8q075m7qfSP7kMe5dlVGbbUvoA) Semi-port of [*@AmanZeeKVerma*'s Bash answer](https://codegolf.stackexchange.com/a/963/52210). **Explanation:** ``` v->{ // Method with empty unused parameter and String return-type int d=(int)(Math.random()*6+1), // Random dice-roll 1-6 i=10, // Counter-integer, starting at 10 p; // Temp integer to store new side String r=""+d; // Result-String, starting at the first dice-roll for(;i-->0; // Loop (1) 10 times: r+=d) // After every iteration, append the result with a random side for(p=d; // Set the new side to the current side p==d // Loop (2) as long as the new side and current side are the same |p+d==7; // or as long as both combined are exactly 7: d=(int)(Math.random()*6+1) // Set the new side to a random side 1-6 ); // End of loop (2) // End of loop (1) (implicit / single-line body) return r; // Return the result-String } // End of method ``` [Answer] ## MATLAB 58 bytes ``` a=randi(6) for i=1:9;b=1:6;b([a,7-a])=[];a=b(randi(4)) end ``` [Answer] # [><>](https://esolangs.org/wiki/Fish), 71 bytes I'm glad I could showcase ><>'s `x` code-pointer randomization as I don't recall seeing it here. ``` a&0 v /2v 1x3v >x< << 6x4v \5v ~ :{:/ ^?=} :{:/ ^?=7+} :~$<^&;!?:-1&n ``` You can try it on [this online interpreter](http://fishlanguage.com/playground) (paste code, submit, start). [Answer] # [R](https://www.r-project.org/), 67 bytes ``` c(3,5,1,4,2,6)[(sample(1:6,1)+cumsum(sample((-2:2)[-3],9,T)))%%6+1] ``` [Try it online!](https://tio.run/##K/r/P1nDWMdUx1DHRMdIx0wzWqM4MbcgJ1XD0MpMx1BTO7k0t7g0FyaooWtkZaQZrWscq2OpE6KpqamqaqZtGPv/PwA "R – Try It Online") There is [a golfier R answer](https://codegolf.stackexchange.com/a/15991/80010) but this I think is a different approach from the answers submitted so far. ``` c(3,5,1,4,2,6) #A dice and its facets (sample(1:6,1) #Initial dice roll +cumsum(sample((-2:2)[-3],9,T))) #9 tippings in c(-2,-1,1,2) %%6+1 #converts to values in [0,6] [ ]# ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 23 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` 6LΩUTFX?6LʒDXÊsX+7Ê*}ΩU ``` Can definitely be golfed, but I'm currently not seeing it.. [Try it online.](https://tio.run/##MzBNTDJM/f/fzOfcytAQtwh7M59Tk1wiDncVR2ibH@7SqgUK//8PAA) **Explanation:** ``` 6LΩ # Pick a random value from the range [1,6] # i.e. [1,2,3,4,5,6] → 3 U # Save this random value in variable `X` TF # Loop 10 times: X? # Print `X` without newline to STDOUT 6Lʒ } # Create a range [1,6] again, and filter it by: DXÊ # Check if the current value is not equal to `X` # i.e. 1 and 3 → 1 (truthy) # i.e. 3 and 3 → 0 (falsey) sX+ # Sum the current value with `X` # i.e. 1 and 3 → 4 # i.e. 3 and 3 → 6 7Ê # And check if it's not equal to 7 # i.e. 4 and 7 → 1 (truthy) # i.e. 6 and 7 → 1 (truthy) * # If both checks are truthy, keep it in the filtered list # i.e. 1 and 1 → 1 (truthy) # i.e. 0 and 1 → 0 (falsey) Ω # Pick a random value from the filtered list # i.e. [1,2,5,6] → 1 U # And save it in variable `X` for the next iteration of the loop ``` ]
[Question] [ A [**Hankel matrix**](https://en.wikipedia.org/wiki/Hankel_matrix) is a square matrix in which each ascending skew-diagonal from left to right is constant, e.g.: $$\begin{bmatrix} a & b & c & d \\ b & c & d & e \\ c & d & e & f \\ d & e & f & g \end{bmatrix}.$$ Given a sequence of integers \$\{a\_n\}\$, we can construct a sequence of Hankel matrices \$\{H\_n\}\$, where \$H\_n\$ is the \$n\times n\$ Hankel matrix whose \$(i,j)\$ entry is \$a\_{i+j-1}\$ (1-indexed). The **Hankel transform** of \$\{a\_n\}\$ is defined as the sequence of determinants of the matrices \$\{H\_n\}\$, i.e. \$\{\det(H\_n)\}\$. For example, the fourth Hankel matrix of the Catalan numbers \$\{1,1,2,5,14,42,132,\dots\}\$ is $$H\_4 = \begin{bmatrix} 1 & 1 & 2 & 5 \\ 1 & 2 & 5 & 14 \\ 2 & 5 & 14 & 42 \\ 5 & 14 & 42 & 132 \end{bmatrix},$$ and the determinant of \$H\_1\$, \$H\_2\$, \$H\_3\$, and \$H\_4\$ are all \$1\$. The Hankel transform of the Catalan numbers is therefore \$\{1,1,1,1,\dots\}\$. ## Task Given a finite sequence of integers \$\{a\_n\}\$, output its Hankel transform \$\{\det(H\_n)\}\$. The length of the input sequence is always an odd number. If the length of the input sequence is \$2n-1\$, then the length of the output sequence should be \$n\$. Input and output can be in any reasonable format, e.g., a list, an array, a polynomial, a function that takes \$i\$ and returns the \$i\$th term (0-indexed or 1-indexed), etc. You may also take the input sequence and an integer \$i\$, and output the \$i\$th term (0-indexed or 1-indexed) of the output sequence. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins. ## Testcases ``` [1,1,2,3,5,8,13] -> [1,1,0,0] [0,1,2,3,4,5,6,7,8] -> [0,-1,0,0,0] [1,0,-1,0,1,0,-1,0,1] -> [1,-1,0,0,0] [1,2,5,14,42,132,429,1430,4862] -> [1,1,1,1,1] [1,2,5,15,51,188,731,2950,12235] -> [1,1,1,1,1] [1,2,6,20,70,252,924,3432,12870] -> [1,2,4,8,16] [1,1,2,4,10,26,76,232,764,2620,9496] -> [1,1,2,12,288,34560] ``` [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 10 bytes Anonymous tacit infix function taking 1-indexed \$i\$ as left argument and the sequence \$\{a\_n\}\$ as right argument. ``` ⌂det∘↑⊣↑,/ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn//1FPU0pqyaOOGY/aJj7qWgwkdfT/pz1qm/Cot@9RV/Oj3jWPerccWm8Mku6bGhzkDCRDPDyD/xsqpCkY6hjqGOmY6Bga6BiZ6Zib6RgZGwEpEyDPyEDH0sTSjMuIOGXGxCkzIU6ZKXHKzIhSBgA "APL (Dyalog Extended) – Try It Online") `,/` sliding windows in \$\{a\_n\}\$ of size \$i\$ `⊣↑` take the first \$i\$ of those `∘↑` combine those lists as rows into a matrix, then… `⌂det` compute the determinant [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes ``` ṡḣṛÆḊ ``` [Try it online!](https://tio.run/##TY4tDgIxEEY9NyH5SNrp9M8hEVyAbFZiyF4Ai0CsRJGgCALDAbaWhYOUi5TZLARMp/P6vuls1k2zLSWnc@4uOZ36fe7aslw82v46f@1u9/Q85HScrkqpKg0NgoFFgDY1JpX6EBbm4BEGqKEwG47fZcQklmYwSZqkROmMAgdHf4KFlY9CgDdCopU4kbFfw4EUvAJZQiSGYZmlKXg1GoPD0CLIQiLLq3csncQiR1fXbw "Jelly – Try It Online") Port of [Adám's APL answer](https://codegolf.stackexchange.com/a/260326/85334), so go upvote that. Sequence on the left, index on the right. ``` ḣṛ First i ṡ overlapping length-i slices of the sequence. ÆḊ Determinant. ``` [Answer] # Excel, ~~104~~ ~~99~~ 86 bytes *With thanks to **JvdV** for the 18-byte save.* ``` =MAP( SEQUENCE(ROWS(A1#)/2+1), LAMBDA(r,MDETERM(INDEX(A1#,SEQUENCE(,r)+SEQUENCE(r)-1))) ) ``` Input is spilled range `#A1`. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 4 bytes ``` lẎÞḊ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJs4bqOw57huIoiLCIiLCI0XG5bMSwxLDIsNCwxMCwyNiw3NiwyMzIsNzY0LDI2MjAsOTQ5Nl0iXQ==) Takes 1 based index and then the sequence. Port of [*@Adàm*'s APL answer](https://codegolf.stackexchange.com/a/260326/52210). ``` l # overlapping groups of length i Ẏ # take first i ÞḊ # determinant ``` [Answer] # [R](https://www.r-project.org), ~~46~~ 42 bytes *Edit: -4 bytes thanks to [@Dominic van Essen](https://codegolf.stackexchange.com/users/95126/dominic-van-essen).* ``` \(v,i)det(t(matrix(v,sum(v|1)+1,i)[1:i,])) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=fVFLTsMwEBXbnCJSNza8CHv8iVMpXKRkUUFTKrVV1aYRSNyETUHiItwCTsMkITStBPLCnjfvM7ZfXreHtzJ_31dlEj4vb0WNhbyfVaISq2m1XTwysNuvRP2s5ZXm3kSPFyik7BRfFx-luBMaGgQHbWEJ2pCElfEouYl19Edf9_1onjep61wsZ-t59SBqDpLXJHfTzWb5JPR4jRJ1Xsto_mtl2CywkZSjmF0mDaqgipaifiiWSR4pQs9SSFpaT2yKFjkejobn1JP5ecu4Mgo2eBpO0a4TjYNjKASkhpHMcQqRcf-IPEghVSBHyMjCWE7UFFJ1FPEIzQv4YvAqFppFfGU2YEXqLVdsldnMD-MaMxBPZKzzqui-8nDo9m8) Takes input as vector `v` of the sequence and index `i`. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~64~~ ~~52~~ 49 bytes ``` Det@Take[HankelMatrix@#,,]~Table~{,Length@#/2+1}& ``` [Try it online!](https://tio.run/##DcexCsIwEADQ3d8ouHhgc4ZIK8INDg6Kgt3E4SyJDW0ilBsqpf312OnxAktjA4uvOd2co8cvCg9lWX/DYeWO6WSFKm7t88yxtd2VpfcDZQCvueJ3Z@cRLjZ@pKFsixs1rdO991HI0ahAAYIGlQMa2BvAHS7oZZhDoQszpT8 "Wolfram Language (Mathematica) – Try It Online") Thanks to @alephalpha ana @att! [Answer] # [Factor](https://factorcode.org) + `math.matrices.extras`, 35 bytes ``` [ [ clump ] keep head determinant ] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=ldG9asNADAdwuvop_pC5xjk7dj4ga-jSJXQKHg5bTkzi8-XuDAnGT9LFS7Plgdqnqaj9ADUCCYnfIunzUcjM1ab_ebl_7N_ed2tIa-vM4mjqRpfqiDMZRRdYujakMrKopDv5nEzJnU83Z6SFNuTcXZtSOWw8r_VatJhzCESYBxAxkhgiFFwi7kSAVbSK0THp_o_FFBxOwdEUvJiC4xEHfzhkvuBZguW4T_fVuOJ1-T074IDs0lQaKV-dNE4kc-TkyFSlknzZdKDPYvjStpIa_jDr-6H-Ag) Port of Adám's [APL answer](https://codegolf.stackexchange.com/a/260326/97916). [Answer] # [Wolfram Language(Mathematica)](https://www.wolfram.com/wolframscript/), ~~72~~ 54 bytes Saved 18 bytes thanks to the comment of @alephalpha [Try it online!](https://tio.run/##bY69awJBEMV7/w3BJk9uZ3b2qwhYpExhkU5SrLLqcXoB2U68f/0yBxFjSDNf7/cec871WM65trs8jvvXt1I363ypbW2/@s0cHehz@MhdGbqpb09luHZ4L/2hHlfzhl/othj3qyuBwLBwiCB7a5r1pe3rTBXzo4hqHgHxt0gwWE7lMTzLrC4SCGsqa0u6WQOJnv8BHZw@EiOC1UtyGsds3V/Sgw2CATtGYoEVzSaOwTyTEysgBfVxNSkVvOim9iTJ3@nxGw) ``` f=Det[Partition[#,k,1]~Take~k]~Table~{k,Length@#/2+1}& ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~36~~ ~~34~~ 30 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) *Given a list of integers \$\{a\_n\}\$ and integer \$i\$, outputs its \$i^{th}\$ Hankel transform \$\det(H\_{n,i})\$* **(30 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage))** ``` ŒIùI£ā<sUœε©2.ÆíÆ.±Xε®Nèè}«P}O ``` [Try it online](https://tio.run/##AU0Asv9vc2FiaWX//8WSScO5ScKjxIE8c1XFk861wqkyLsOGw63Dhi7CsVjOtcKuTsOow6h9wqtQfU///1sxLDEsMiw1LDE0LDQyLDEzMl0KMw) or [verify all test cases](https://tio.run/##VY69SgNBFIVfJaQ@hpk7/ySYxlLURjGELSIGSaNFILBFCpt9gOQR0kREwcLCdse0PoQvsh7DYrCZuec75/48zCc3s2mzKE@u7o77p4vRsNuZ3N92usOS1Xe1YjVqdqsyf5T15vNxML/crb/e6yfp5Sq/5KpXv11Tv57lbd4u6@eL5XmDZjzW0BA4aAsr0EYKtMyQRhIC1QJL5BEQ9yGFo9/nUOzpv2H8EpVRsNHLwXdwXBIjgiFJjs0ixrUBD1EICuIESSyM5SQtMai/4yw0fd7CLM3gLRW7kk2@KH4A). *Given a list of integers \$\{a\_n\}\$, outputs its Hankel transform \$\{\det(H\_n)\}\$* **(~~36~~ 34 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage))** ``` gÅÉε£ŒN>ùā<sUœε©2.ÆíÆ.±Xε®Nèè}«P}O ``` Inspired by [*@Adàm*'s APL answer](https://codegolf.stackexchange.com/a/260326/52210), but without any matrix builtins available.. [Try it online](https://tio.run/##yy9OTMpM/f8//XDr4c5zWw8tPjrJz@7wziONNsWhRycDBVYa6R1uO7z2cJveoY0RQP46v8MrDq@oPbQ6oNb///9oQx1DHSMdUx1DEx0TIx1DY6NYAA) or [verify all test cases](https://tio.run/##VY6/agJBEMZfRaw/ZXd29h@G2KQMMY0hQa5QkJAqxUHgiits7gH0EWwMkkAKC9vb2PoQeZHLRI6Izex8v@@b2XnNp7OXefNWDLudn2rZ6Q6Lm4fm@Xpwe9w9HZZ52hf1@ntxlY8Pq@Oufqd@qtJHqvr116Poz7u0SZuy3t6Xo6ZEM5loaBAsNIMJ2lCGlhmhQYgA1QIW5OARTiGF3l85Nyd6sUyeKMoocHB09i2sfBICvBESrQwTGdsGHEjBK5AlRGIYlk2aglf/xzG0@HKLZMX0jkXJVOTosuwX). **Explanation (of the program with list output):** Step 1: Create a list of matrices from the input-list: ``` g # Push the length of the (implicit) input-list ÅÉ # Pop and push a list of odd numbers <= this input-length ε # Map over each odd value: £ # Keep the first value amount of items from the (implicit) input-list Œ # Get all sublists of that list N> # Push the (0-based) map-index, and increase it by 1 ù # Only keep the sublists of that length ``` [Try just this first step online.](https://tio.run/##yy9OTMpM/f8//XDr4c5zWw8tPjrJz@7wzv//ow11DHWMdEx1DE10TIx0DI2NYgE) Step 2: Get the determinant of each matrix, which [I've done before in 05AB1E](https://codegolf.stackexchange.com/a/202866/52210) for the [*Determinant of an Integer Matrix* challenge](https://codegolf.stackexchange.com/q/147668/52210): ``` ā # Push a list in the range [1, matrix-length] (without popping) < # Decrease it by 1 to make the range [0, matrix-length) sU # Swap to get the matrix again, and pop and store it in variable `X` œ # Get all permutations of the [0, matrix-length) list ε # Inner map over each permutation: © # Store the current permutation in variable `®` (without popping) 2.Æ # Get all 2-element combinations of this permutation í # Reverse each inner pair Æ # Reduce it by subtracting .± # And get it's signum (-1 if a<0; 0 if a==0; 1 if a>0) X # Push the matrix from variable `X` ε # Map over each of its rows: ® # Push the current permutation of variable `®` Nè # Get the value in the permutation at the current map-index è # And use that to index into the current matrix-row }« # After the map of rows: merge it together with the signum list P # And take the product of this entire list }O # After the map of permutations: sum all values ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~54~~ 46 bytes ``` ≔…⁰ηη⊞υ⟦⟧Fη≔ΣEυE⁻⎇﹪λ²⮌ηηκ⁺κ⟦μ⟧υI↨E⮌υΠEι§θ⁺λμ±¹ ``` [Attempt This Online!](https://ato.pxeger.com/run?1=NY-_TsNADMZ3nuLUyZFcKTlCoOpUmBiCqsIW3XCk1yTq5QL3p4JnYekAglfqxKvga4Ily_psfz_LHz91K209SH08fgW_m9-cflfOdY2BjTSNghRZm8RcXqyDayEgqwSJ3WAZtAmblh9DD6V8ieNYys4EB0_KGmnfoRy2QQ-gkXFCbdRBWadgxCLbU641re8J3YuEAlmI92xnPNxJ5-FWkiGC_80hmixxa3_ud8hW_t5s1Ru8Tjg61ycj7UE10ivIolp-uufaTc9-V7P5Qc_ECaoqwww55pilyAu8LpBfcio5KZ7iIl8UAq_E6PsD "Charcoal – Attempt This Online") Link is to verbose version of code. Takes the sequence and index as inputs. Explanation: ``` ≔…⁰ηη⊞υ⟦⟧Fη≔ΣEυE⁻⎇﹪λ²⮌ηηκ⁺κ⟦μ⟧υ ``` Generate all of the permutations of `[0..i)`. This is based on my answer to [1 to N column and row sums](https://codegolf.stackexchange.com/q/254768/) but tweaked to alternate between even and odd permutations. ``` I↨E⮌υΠEι§θ⁺λμ±¹ ``` For each permutation, add each element to its index and use that to index into the original sequence, then take the alternating sum of products, which is the determinant of the Hankel matrix as required. Previous 54-byte version: ``` ≔⟦EηEη§θ⁺ιλ⟧θFθ¿⊖LιFE⊟ιEι×Φμ⁻πλ⎇ν¹×X±¹⁺Lιλκ⊞θκ⊞υ⊟⊟ιIΣυ ``` [Try it online!](https://tio.run/##PU/LasNADLz3K3TUggqx67qEnEJLodAWQ3szOSyOYi9Zr@3ddR9f78qOU12ERqOZUdVoX3XaTtM@BFM7LN90jw3B2vbxxR35BweCwo4BDYFVUgeCQe1uTp0HHBSYE@ATV55bdpGP@Mqujg0aYcLCmeWKrhfkIi06n6blgM/GRvbYCmycGPSLgWzZO@1/0REkV27RfQv1nWsdGRO1Rvr3Wi/PaikoxtDMuc9qB2wDX4BRrrprFiUvFN64iI86RPwYWxxncJrKMqGEUsoo2VCa00NO6V0qLZMp3dA22@YHuj9Mt1/2Dw "Charcoal – Try It Online") Link is to verbose version of code. Takes the sequence and index as inputs. Explanation: ``` ≔⟦EηEη§θ⁺ιλ⟧θ ``` Construct the Hankel matrix `Hᵢ`. ``` Fθ¿⊖LιFE⊟ιEι×Φμ⁻πλ⎇ν¹×X±¹⁺Lιλκ⊞θκ⊞υ⊟⊟ιIΣυ ``` Calculate its determinant using the following algorithm: * Remove the last row and iterate over its elements. (This was the golfiest out of the first and last row and column, the ease of removing the last row making up for the slightly more complicated parity calculation.) * For each element, create a new matrix by also removing its column, and multiply the first row of it with the element, but with the sign changed according to the parity of the element's original position. * Take the sum of the determinants of the resulting trivial matrices. [Answer] # JavaScript (ES10), 152 bytes *-1 thanks to [@tsh](https://codegolf.stackexchange.com/users/44718/tsh)* ``` f=(a,b=[D=m=>q=+m||m.reduce((s,[v],i)=>s+(-1)**i*v*D(m.flatMap(([,...r])=>i--?[r]:[])),0)])=>1/D(b.map((_,y)=>b.map(_=>a[y++])))?[q,...f(a,[...b,0])]:[] ``` [Try it online!](https://tio.run/##hdBbb4IwGAbg@/0KL1t4qW0ppyXojbf7BQ0xqLCwiCg4ExP/O/s6d8g2t9GL8h148oan8lQO677ZH4Ndt6nGsc5ZiVVuF3mbzw65314ureirzfO6YmyAPRVoeD4bfBYo7nmNd/IWrBX1tjw@lHvGLIQQfUErTRDMbV/c24JzSO5aarpgK9G6vSXO1LgWy3xW2rPv0yKf24MTakph6V5BFtwZ47rbDd22EtvukdXMSihohDCIECNBSh9PfjzT6YQ2AwXpTnH3DXH91@Hnyw3GIeovRFMGZWA0VKjpyqgKJUwa6w/uiryd34wIEU3TFElInSyiPFqH0TvyvxFDSyQSOtLItEFoKJDSaSK/GpQSKVR8A7kOFRn0W8kjIIkNVSRnJosd9B7E2dCUNzRRLIvxBQ "JavaScript (Node.js) – Try It Online") ## Commented ### Determinant function ``` D = m => // m[] = matrix +m || // if m[] is a non-zero singleton, return it m.reduce(( // otherwise, for each row: s, // given the accumulator s [v], // and the first value v i // of the i-th row ) => // s + // add to s (-1) ** i * v // either v or -v depending on the parity of i * // multiplied by D( // the result of a recursive call: m.flatMap( // for each row: ([, ...r]) => // remove the first value of each row i-- ? [r] // and remove the i-th row entirely : [] // ) // end of flatMap() ), // end of recursive call 0 // start with s = 0 ) // end of reduce() ``` ### Wrapper function ``` f = ( // f is a recursive function taking: a, // a[] = input list b = [0], // b[] = vector, initially of size 1 q = D( // q = determinant of: b.map((_, y) => // the Hankel matrix built by iterating twice b.map(_ => // over the vector b[] a[y++] // and setting each cell at (x, y) to a[x + y] ) // ) // ) // ) => // 1 / q ? // if q is defined: [ q, // append q ...f( // followed by the result of a recursive call: a, // pass a[] unchanged [...b, 0] // add a dummy item to b[] ) // end of recursive call ] // : // else: [] // stop ``` [Answer] # [Julia 0.7](http://julialang.org/), 26 bytes ``` a*i=det(a[(s=1:i)'.+.~-s]) ``` [Try it online!](https://tio.run/##dVDLToUwEN3zFU1c2F4PpJ2@4Cb4I4QFEbxiCJpL3frrOKA36MJ00TnT8@jM68c0dnFdu9NY90OSXSOX2pxHdV88FJ/50qo1DUtaRC2arDEwIFh4lDC2xZ3IH8Xe1dBt1uifd8eMgIjyRtHId87O2qodHsVh9YdH7GMcHHEa8VUxshquDPQ7fD@HwMMzLktEy53Ksz@R9f8pAkgjapAnVORgHWcZKqM@FBy@jRza2w4cDCt4RlYzPQbHiH0qV4X2yNmMQPwV63zgmdrs@e0qEm/ze6vv13FO0yxlghLFSUhzfpp6OQ3zJb3IpEBKKTHM/foF "Julia 0.7 – Try It Online") Accepts sequence `a` and `i`th term. [Answer] # [J](http://jsoftware.com/), ~~11~~ 10 bytes *-1 byte thanks to [@Bubbler](https://codegolf.stackexchange.com/users/78410/bubbler)!* ``` [-/ .*@{.[\ ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/o3X1FfS0HFSiY/5rcqUmZ@QrGCqkKRjqGOoY6RjrmOpY6BgaQ8SNcIgb4xA3wRD/DwA "J – Try It Online") Input format from [Adàm's APL answer](https://codegolf.stackexchange.com/a/260326/31957), but the form, although basically equivalent to his answer, was discovered independently when I wrote the below answer to work with only a sequence as input. # [J](http://jsoftware.com/), ~~28~~ 27 bytes *-1 byte thanks to [@Bubbler](https://codegolf.stackexchange.com/users/78410/bubbler)!* ``` ([-/ .*@$[\)"{~1+i.@>.@-:@# ``` [Try it online!](https://tio.run/##XY5NigJBDIX3c4rQCj3q67IqlfprGGkQXM1qtj3gQhR14wEEr95GcGjHRZLKy5dXOQ@VqQ/01VJNIEutRmNo/fO9GT77Zklm3k3731l1vbnFyXQr0zVtNxlmH/vd8UIHcnBgeARkOP@n2qcqqkck5BG32D7S@BhHrLQTCKsTaynaeQvJkd@ggKAf54zkVSlBbZh9eKUi2CJZcGAUFnhRT8c52f@nC5xCeqQuKJGiaKerRUoc7g "J – Try It Online") The novel bit in this approach is doing more work! :P ``` ([-/ .*@{.[\)"{~1+i.@>.@-:@# -: half @# the input size >.@ rounded up i.@ range [0, ^) 1+ range [1, ^] this gives us all the valid matrix sizes ( )" ~ (equivalent to Adàm's answer) applied at { equiv. 0 _ every possible matrix size and the entire input sequence ``` ]
[Question] [ Given a pattern and a ragged list of positive integers, your task is to decide whether the pattern matches the ragged list. The pattern is also represented by a ragged list. But in addition to positive integers, it may contain a wildcard value. Here is the rule for matching: * A positive integer matches the same positive integer. * The wildcard matches anything: either a positive integer, or a ragged list. * A ragged list matches a ragged list if they have the same length, and each pair of items at the same position matches. For example, if we write the wildcard as `0`, then the pattern `[0, [4, [5], 0]]` matches the ragged list `[[1, 2, [3]], [4, [5], [6, [7]]]]`: here the first `0` matches `[1, 2, [3]]`, while the second `0` matches `[6, [7]]`. Note that the wildcard cannot match a subsequence of more than 1 items in a ragged list. You may choose any fixed value as the wildcard, as long as it is consistent. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins. This is [decision-problem](/questions/tagged/decision-problem "show questions tagged 'decision-problem'"). You may use your language's convention for truthy/falsy, or use two distinct, fixed values to represent true or false. ## Testcases Here I use `0` to represent the wildcard. The input here are given in the order `pattern, ragged list`. Thanks @pxeger, @pajonk, @DLosc, @Deadcode for providing some interesting testcases. ### Truthy ``` [], [] [0], [1] [1, 0], [1, [2, 3]] [1, 0], [1, [[2, 3]]] [1, [2, 0], 4], [1, [2, 3], 4] [0, [4, [5], 0]], [[1, 2, [3]], [4, [5], [6, [7]]]] ``` ### Falsy ``` [1], [] [0], [] [[]], [] [[]], [3] [[4]], [4] [0], [1, 2] [1, 0], [1] [0], [[1], [2]] [1, 0, [2, 3]], [1, [2, 3]] [1, [0, 2], 4], [1, [2, 3], 4] [[0], [4, [5], 0]], [[1, 2, [3]], [4, [5], [6, [7]]]] ``` [Answer] # [Elixir](https://elixir-lang.org/), 1 byte ``` = ``` Yes, Elixir's equality/pattern match operator functions exactly as requested when input is provided as plain code with wildcards indicated by underscore`_`. The output is by presence/absence of error (passed = match, error = no match, see the [Test Suite](https://tio.run/##nVDBasJAEL3vVwzrRWEjqGm9VC@lBU8e2tsyLJKMNhBMmd1I/Po4mxWtBy89DLz35s3jMVRXXcV93wfywcMKrBp9cxt@zkpbjBy1EegGPEtkZuDKDdi5gQXe9EgdGsgf91FIOaLkMi8YfYMpusRkJeXP0r7KLBGH6NHnrvaxkU0nixRm80Tzh46Sdq95K/ikrovu53Wtw38UVqj2DUMHbxmkv5aNAgh8FgCCAN6bkqZ02tXOB66Oh3E3SYvNdvrbyoX@aouCvNeiMvmiJaBsfV9/MDes4w0dSyXTXwA "Elixir – Try It Online") Since validity of this way of taking input has been questioned in comments, here is also the conventional function doing the same, with all the boilerplate counted in code... # [Elixir](https://elixir-lang.org/), 28 bytes ``` &Code.eval_string&1<>"="<>&2 ``` [Try it online!](https://tio.run/##nVDBaoQwEL3nK4YsSAtZwV3bXtTL0kJPPbS3YQiLxlaQdUliWb/eJkZZWWgPPUzIe/Pm5U1U21waPdb5GB26SsXq@9hKY3Vz@oySrOA5z4poN1plrIEckG0@dG@/BoYciQvwJwmPZIDJghMBCyUAdwL2tGp5QpKA9EYyMbOh41JXD@SlQeeFTofOa9XFR1dPROGBzcuxNVNAnKf2iyWmM5Pepna26@DXxL8uIP3InwugpH@twIjVnQa8iIEg20L4/KpjAFYP4QJQx3dOcA8TeH2Lz70T8fe@LJUx3LFambJXoLbFtf2sdae5n1GnirkafwA "Elixir – Try It Online") [Answer] # [Haskell](https://www.haskell.org), 44 bytes ``` W#_=1 p#a|p==a=1 L(h:p)#L(f:r)|h#f>0=L p#L r ``` [Attempt This Online!](https://ato.pxeger.com/run?1=tVLLSsNAFAWX-YpDo5BAItbWB4FkIxUqoYIVspAgQzJtgmkyTifFRf_ETTfiN9WvcZJJY-sDunF17j13ztwzh3l9T8j8iWbZan2TzljBBa6KXPAiOx68RJSJtMi1mAiCOzKd0hguAiwxwjAXEn08KD7UEFOeLtJ8isHzWykm9uXaCvRHt6sxnSyZ6xJZ-kbiMFP3jYnDzWWiT7wT1wfTfXCl-TgQDEcgck9ERJTAoAuSlURQGAw6iAnPA-OpXH_PS2rCiIp8LnDYkNckm1M4DsbFjLZPgO1heAvDNLUZSXN5e1xoqOyHclsFqguadoRuw8jKwhZtKTy1ZAa9cPvQhg_Catb_S6KGzbpm1G_wLKzkjXIjrpV1I_f9IqiL8wYvwrA2xUoxFtzP0bFtu9O63H1tVbU2e19kZbDl-z-jqT3t5PMtlf3SCtQ9e6dVm_ifxNTnW60UfgI) More readable: ``` W # _ = True p # a | p == a = True L (h:p) # L (f:r) | h # f = L p # L r ``` Uses a custom sum type for ragged list, where `W` represents a wildcard: ``` data Ragged = W | N Int | L [Ragged] deriving Eq ``` As I understand it, I don't have to include that type definition in my score? Maybe `deriving Eq` is not allowed, in which case it can be manually instantiated for only 1 byte more: ## [Haskell](https://www.haskell.org), 45 bytes ``` W==_=1>0;N p==N a=p==a;L p==L a=p==a;_==_=1<0 ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m708I7E4OzUnZ8FN-5TEkkSFoMT09NQUBVuFcIUaBT8Fz7wSIO2jEA0Rj-XKzCsuScxLTlVwLYSpLc9ILUpVqF5aWpKma3FTN9zWNt7W0M7A2k-hwNbWTyHRFkglWvuAeD4wXjxYkY0BRNMtpuZartzEzDygvSn5XAoKBUWZQItVQBbHKtjagmlU4XCYuJ-CIZoUUERHAVleB0Ib6QA9ZByLTTVMPjwWpMYEp16ILJpLoEpMoLRpLMgcmBEwU8BGgDlAF2DRAWaYQWnz2FiIM0tLgkuKfPIUlHR1dZUw3I0jaEAiCB8YY8qC_IBQgOEfFN8D3Y01eNHClMTADocYTHpgg91HowCHpMUFCyA0AA) Although now I'm not sure if I have to include the instance declaration in my score. More readable: ``` W == _ = True N p == N a = p==a L p == L a = p==a _ == _ = False ``` [Answer] # [tinylisp](https://github.com/dloscutoff/Esolangs/tree/master/tinylisp), ~~71~~ ~~81~~ ~~70~~ 79 bytes Being a language whose syntax is entirely made of ragged lists, you'd expect tinylisp to be good at parsing them, and it indeed doesn't do that bad of a job at it. ``` (d F(q((A B)(i(a(e A 0)(e A B))0(i(a(e()B)(e(v B)B))1(a(F(h A)(h B))(F(t A)(t B ``` Takes two lists as arguments, and outputs falsy (zero) if they match, or truthy (positive int) if they don't. Edit +10 bytes: @DLosc pointed out that my code actually failed for some cases containing an empty list as an element. Edit -11 bytes: @DLosc suggested `(e(v A)A)` for the troublesome conditional, and indeed it does work, and saves a byte off my original size. Edit +9 bytes: Two more fixes for problems pointed out by alephalpha and DLosc, changing `(e(v A)A)` to `(e(v B)B)` and adding a test if `B` is nil to the second if, I think this actually works perfectly now [Try it online!](https://tio.run/##lVHLboNADLzzFT6OpR6AkPYMB/6DJhsFKbyyJlK@nnp5BorUdGXt2jMj22tLXj5vua27DmdK0QAxJYwcGQzF5HP/JMz@gIGVNXgopGCgUIorxayXxhqIC4SSjsfj4az5CQ3JvZXr0yGnqihMKSNCYqzQKbPGflDVSt2KFvaQemBng9sQfCbuncA5MxwQQjrwTC7hi8R/nx743yVUE22yDMDSICEiHFmlk1CVIcHVGyl8Er54kx@8dKD@9L9pcpfsZleD64G9udWVzSV/GCrb4tvclw9M2df97qIa9fbS0GDBrmxHudFN9GGNRzMR7Xelo9uu6Z1V6xrCP1flqvx3Wd0P "tinylisp – Try It Online") [Answer] # [R](https://www.r-project.org), ~~111~~ ~~110~~ ~~104~~ 82 bytes *Edit: -22 bytes thanks to [@Giuseppe](https://codegolf.stackexchange.com/users/67312/giuseppe).* ``` f=\(p,l,`+`=is.list,`-`=length)`if`(+p,+l&-p==-l&&all(mapply(f,p,l)),!p|!+l&&p==l) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGCpaUlaboWN4PSbGM0CnRydBK0E2wzi_VyMotLdBJ0E2xzUvPSSzI0EzLTEjS0C3S0c9R0C2xtdXPU1BJzcjRyEwsKcio10nSAWjU1dRQLahSBKtSAKnI0ISbfYnJLTizRUAopKi3JqIzJU9LkStMAma6hqQOh4AIGmjoKYIYhQsxQRwEhDKWNdBSMNfErQVaHrBAmDtJggtVckDjCRVAZEyhtqgnSqolsCVCzEZRvDJdBVg9mmEFpc02wg7jAQRKT55aYU4wSJoYwDQg3QLkIO1AkTBB2YgtIoONQAwolCAmGKywQjIgLLlTLqRxokOQES7AA) Straightforward recursion. [Answer] # [Python 2](https://docs.python.org/2/), 34 bytes ``` f=lambda p,a:a+a!=p+p>0<map(f,p,a) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m728oLIkIz_PaMGCpaUlaboWN5XSbHMSc5NSEhUKdBKtErUTFW0LtAvsDGxyEws00nSAgpoQlbcYX6Skpim4aWglalpxKZQUVVopFKWWlBblKaSBxBTyixRCikpTuRRSK5JTC0rgsm6JOcWpXAVFmXklQN3RsToK0bGaCL4BSMAQWcRQRwEiCMRGOgrGsWiSIEGQAhMURSA-srFAcRMgNo0FKQapBCkFqow2BvNgctFmQGweG4uwRElXV1cJzX3IJpvqYAgZogtEg-0wRhEygdiL6Xegs9C9D_c5vmAwAGkkEAwQK0gMCEiEw5IIAA) Outputs via presence or absence of an error. If there's no error, the pattern matches. If there is an error, the pattern doesn't match. ~~-16~~ -13 bytes thanks to @loopy walt [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~65~~ ~~63~~ ~~57~~ 56 bytes ``` ~(L$`^.+ \n$&$ _ (\d+|<((?<_><)|(?<-_>>)|\d|,)+(?(_)^)>) ``` [Try it online!](https://tio.run/##lY4xDsIwDEX3nCJDQYkakAoBhkbpBdhgc10XqQwsHRAbhasHp60qkLowWP62n@1/vz5u7SULC3Wqc3GupYLnC3VNzjkf3uqY1NU6FWWbLBNBQpVN2jmlCkfe6Y7zirzXXdl0RqeqUKQr7XUIgLkEFEAxZywyIwdtJGyM3OLQi5rQSPszizXvcmk5dhiZCESCAeDtrxnsOQ6I/cnxL/T8NirbSzuZ4ROjn8nKjC@K2LwvIPzb2Qc "Retina – Try It Online") Takes two newline-separated `<>`-wrapped lists but link is to test suite that deletes spaces, splits on semicolons and converts other types of brackets for convenience. Uses `_` to represent the wild card. Edit: Saved ~~6~~ 7 bytes thanks to @Deadcode pointing out that I don't need to use `[]`-wrapped lists or support spaces. Explanation: ``` ~(` ``` Evaluate the result of the transformations below on the original input. Since they result in a single line, this makes Retina attempt to match the input against the result. ``` L$`^.+ \n$&$ ``` Take only the first line of the input and wrap it in `\n` and `$` so that it will match against the second line of the input. ``` _ (\d+|<((?<_><)|(?<-_>>)|\d|,)+(?(_)^)>) ``` Replace each `_` with a match against either a non-negative integer or a list, using a .NET balancing group to ensure that the list is properly balanced. A named capturing group `?<_>` is used here because .NET allows capturing groups to be reused in this way and it's golfier than calculating the capturing group number. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 13 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ßȯŒḊ?"ḣL{ ç⁹⁼ ``` A dyadic Link that accepts the pattern (with `0` as the wildcard) on the left and the potential match on the right and yields `1` for a match or `0` for no match. **[Try it online!](https://tio.run/##y0rNyan8///w/BPrj056uKPLXunhjsU@1VyHlz9q3Pmocc//w8v1HzWt@f8/Ojo6VkchOjaWSyc62gDENISwDXUUIFwgNtJRMI6FC4O4ICkTFGkQH2IIUMQEiE1jQcpAakCKgGqijcE8mFy0GRCbx4IAF9hkhDuiwQqNoRwTiDZkJwLNQ7gS7kDsrjUAKcbpWoiBpLo3FgA "Jelly – Try It Online")** ### How? ``` ßȯŒḊ?"ḣL{ - Helper Link: pattern P; potential A " - P zip A applying: ? - if... ŒḊ - ...condition: depth (of element of P) ß - ...then: call this Helper Link (with element of P and element of A) ȯ - ...else: (element of P) logical OR (element of A) L{ - get length of P ḣ - head (the zip result) to index (length of P) ç⁹⁼ - Link: pattern P; potential A ç⁹ - P Helper Link A ⁼ - equals A? ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 56 bytes ``` ¹≔⟦A⟧θFθ«≔§ι⁰η≔§ι¹ζ¿⁼⁺ηυη¿∧⁼⁺ζυζ⁼LηLζFLη⊞θEι§λκ⎚¿∧η¬⁼ηζ⎚ ``` [Try it online!](https://tio.run/##bZDLasMwEEXX9VfMcgQq2OlrkZUpXQSS4L3wQiRKZCLk2JJCcOm3qyPXKhQqGD3m3OFedNByPPTSxNiMnfVYsXVRO9edLYqNvQaPrOUwUPfUj4ADg8/iYRHUfmOP6o4dh5Jx0CT6B1WEpoS6E@DHEKRx2JjgUHMI8xiDhGp7/IOnHzxRLe2tsmevUVNnuU6Mhudgv4xBE5zGgcNOXpN/jmI4XEi@BmWcgnej5Ij5lf0p0r73OYZO7skhi4uvGIUQJQfxTPVCP1O2tAlRcVjR@TS/MhOvVG/tvOLjzXwD "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a pair of two ragged lists with `0` indicating a wildcard and outputs a Charcoal boolean, i.e. `-` for matching, nothing for mismatching. Explanation: ``` ¹ ``` Start by assuming that the lists match. ``` ≔⟦A⟧θFθ« ``` Start a breadth-first search of the lists. ``` ≔§ι⁰η≔§ι¹ζ ``` Extract the corresponding sublists that are being searched. ``` ¿⁼⁺ηυη ``` If the pattern list element is a sublist, ... ``` ¿∧⁼⁺ζυζ⁼LηLζ ``` ... then if the list element under test is a sublist of the same length, then... ``` FLη ``` ... for each pair of elements of the sublists... ``` ⊞θEι§λκ ``` ... push the corresponding pair to the search list. ``` ⎚ ``` If the element under test wasn't a sublist of the same length then clear the canvas. ``` ¿∧η¬⁼ηζ⎚ ``` Otherwise, when the pattern element isn't a sublist, then if it is truthy but not equal to the element under test then clear the canvas. Support for zeros by using empty strings as wildcard is possible at a cost of 2 bytes: ``` ¹≔⟦A⟧θFθ«≔§ι⁰η≔§ι¹ζ¿⁼⁺ηυη¿∧⁼⁺ζυζ⁼LηLζFLη⊞θEι§λκ⎚¿∧⁺ηω¬⁼ηζ⎚ ``` [Try it online!](https://tio.run/##bY7NasMwEITP9VMsOa1AhTj9O@RkSg6BJPgufBCJEpkKObakNrj02dWVaxUKFayknW@XmaOWw7GTJsZ6aK3Hkq2Lyrn2YlFs7TV4ZA2HntRzNwD2DD6Lu3mg8lt7UjdsOSwZB01D/6CS0JhQewbc9EEah7UJDjWHMK0xSKiypz94/MEj1SzvlL14jZqU@TsyWp6C/TIGdXAaew57eU3@OYrh8Ebja1DGKXg1Sg6Yu@yfc32QxaHzOY9OMZJV3iq@YhRCLDksFhzEI9VTk5qG7iSLksOKnodJyFw8U70004n37@Yb "Charcoal – Try It Online") Link is to verbose version of code. [Answer] # [Ruby](https://www.ruby-lang.org/), 57 bytes ``` f=->t,a{a!=t&&t&&t.zip(a).map{|r|[f][t.size^a.size][*r]}} ``` [Try it online!](https://tio.run/##lU/bisIwEH3PV4wiYktb0HbXp@7j/sQwQtRkKbilpOmDt2@vmdTWCygIOWTOzMmZHNOs922r8/jHRvIoR7mdTvkkh6KaySD5l9XxZE6oCW1SFwe1kv4iDA2dz@1EQw5abJWG31koAwGwVn9F6W6AicZQki@Nso0pwZpGCWb1xhfDQMtdzQ1VbgVDVM4PKQKkoKvLYsd03vN5BH3LYRFBSncjbnTj7EHC/GboupnDF3ViVrLUKTH1rJ/it8OSyK9obA3jOI7H1233v0T/LB1o1tk8h3A7HnMMEV7l8ZrFuzy9@ceJ2gs "Ruby – Try It Online") Uses `nil` as filler. (`false` will also work) Ports @pxeger's Python answer. [Answer] # Regex (Perl / PCRE), ~~63~~ ~~60~~ ~~56~~ 53 bytes ``` ((_?)(\2.)?(?=.* (\4?(?(?=\2)\3|(\d+,?|{(?5)*})))))+ ``` [Try it online!](https://tio.run/##jZBPb4JAEMXvfIqJbsKubkUQ24QViQntoQd7qEeSDbXYmOCfghyadfvV6ayowaaHcpnfvrcz@4Z9VuTjuiozeH59mQswFKeHNAjiarPPCgGbLyBYVL5bpjkQR@AxnMSzxWyqrdWuoGQdDsVkKrC6TMF6hQpT@2K9PUAn2XaEBpJDCGX1Vh7wuuR3LndZ9mlMiFr6EB0GARApLMBBQC9ejp5psZXNFElxGskxCMI3lBjJSbbOh4DmUUobwyGFwyJ7UVRZAGAH9lOal4g2ExrnN5fNHC3l4zyWsqZURowm3oBFNAoHPYsmPhJy4rFkdKTJe59HR0WjMetpZr6@VdddMG/AMi2z0rKUxr@lLSVNdRFc3iBXHh/pG6FRThKi1Nxv3cQDTuHK52qs0TQWeh5X2HOR1T1XD9rMsLpwWvCaw20Hwar0DYwM@Sf0r3G518p3UZEw0Tn5eYtfC2FO74/02P/f/D8 "Perl 5 – Try It Online") (Perl) [Try it on regex101](https://regex101.com/r/ZpjUWM/11) (PCRE) The wildcard is `_` and the delimiter between the pattern and the ragged list is a newline. This regex works by going through the pattern one character at a time; any character other than `_` must be matched with the identical character in the pattern, and `_` is matched with any positive integer or ragged list. This is done while cumulatively building up a backreference of the full ragged list, as each piece of it is matched. Due to the optimization of requiring the input to be well-formed, only the ragged lists matched with `_` need to be checked for matched brackets. The regex uses `{` and `}` (curly braces) as its brackets to avoid having to `\`-escape them. Similarly, spaces must not be present in the input. #### Explanation `(` ... `)+` Match what is inside any nonzero number of times. `(_?)(\2.)?` Consume the current pattern character. If it is `_`, set `\2` to contain it. Otherwise, set `\2` to be empty and `\3` to contain the character. Note that the latter can also happen if the character is `_`, but this cannot lead to a subsequent match, because `_` cannot be in the input ragged list. `(?=.*` ... `)` Process the input ragged list in a lookahead, so that outside this lookahead, the input pattern can still be processed picking up where it left off. The `.*` skips over what remains of the input pattern, and the newline skips over the newline delimiter. `(\4?(?(?=\2)\3|(\d+,?|{(?5)*})))` Validate that the appropriate section of the input ragged list matches the current character of the input pattern, capturing the entire portion of it matched so far (starting from its beginning) in `\4`. `\4?` If this is the first character being processed, `\4` will be unset, and this will consume zero characters of the input ragged list. Otherwise, this can either match with what `\4` has been set to, or match an empty string. Since the regex is designed only to work on well-formed input, it will in practice always match `\4` (the portion of the input ragged list already matched) when it is set, skipping to the appropriate part of the input ragged list to match against the corresponding current input pattern character. The unoptimized version of this would be `(?(4)\4)` or `\4?+`. `(?(?=\2)` ... `|` ... `)` If `\2` matches (without consuming it), match against the first part, otherwise match against the second part. `\2` will contain `_` if that (a wildcard) is the current pattern character, otherwise it will be empty. Since well-formed input can never contain `_` in the input ragged list, `\2` will only match if the current pattern character is *not* a wildcard. `\3` Match against the current non-wildcard character. `(\d+,?|{(?5)*})` Match any single positive integer or ragged list. Balancing of opening and closing braces is done here using recursion; `(?5)` recursively calls the entire expression above. Since the input is assumed to be well-formed, we can get away with the optimization of not enforcing that there is an integer directly before and after every comma. `‍` Once the entire input pattern has been processed, the newline delimiter is skipped, enforcing that the entire input pattern has been matched against. There is no need to anchor at the beginning or end of the input string, because as long as the input is well-formed (with balanced braces), there is no way that the entire input pattern can be matched without also matching the entire input ragged list. # Regex (.NET), 71 bytes ``` (?<=(.)+);(?<-1>\1|(?<=(?=\1)_.*)(\d+|<((<)|(?<-4>>)|\d|,)+(?(4)^)>))+$ ``` [Try it online!](https://tio.run/##jY/BToNAFEX3fMWEkjBPhqZQ1KQM0yYm7ty5K7UhZSokCA3Q1LRl6wf4if4IPsZWaoyJq3fn3nl3zmyKnSyrRGZZa5TBvJTP8nUxmeRyR2dmS6c8oEOwwEdlOyJ0jsqaBqEDy@EV0DC2jpxSDl1ge0LAMYyPDCw6pR48gQCwjNacMf2ueNmkmYx18I19MPLXRSmjVUKNjKQ5MdJ8s63hoBGSrqmxh8OuTGtpJ0VVN3jfwaB3iJ0XiJiluSRGpnYIFtl41HViR3mM9ny0UMZAB9L1/lWgk4@3d2JQ1VEOH6J6lcgK6wD3zMdyK82GyKySeLqPcJoN6NjXaE07IF1OVlElK03jwudC40scDk6HKcW4y8bi8vxlKAflUjCvv4caGxj3GL8WmGGCkcs4bpxdfsP4regatAFRSN8ETo@Ag4uLOe6E1ynvDMncHuvkoUCQE@4J/ecnkM79jYzL/4XGAvWSespB5xM "PowerShell – Try It Online") The wildcard is `_` and the delimiter between the pattern and the ragged list is `;`. The brackets are `<` and `>`. This regex works by capturing the input pattern character by character in reverse, pushing it onto the Balanced Group stack of Group 1. Then the input ragged list is tested against this by popping the stack in a loop, and for each popped character, matching directly against it if possible, and otherwise, checking if the popped character is `_`, and if it is, matching against any ragged list with balanced brackets. #### Explanation `(?<=(.)+);` Push the input pattern onto the Group 1 stack, one character at a time in reverse order, then skip to the input ragged list. `(?<-1>` ... `)+$` Pop the Group 1 stack in a loop, executing the following for each popped character, and then assert that the end of the string (and thus the end of the input ragged list) has been reached. `\1|(?<=(?=\1)_.*)(\d+|<((<)|(?<-4>>)|\d|,)+>)` What to execute for each character popped from the Group 1 stack. `\1` If the character matches, consume it. This can never happen if the character is `_`, because a well-formed input ragged list can't contain that. `|` Otherwise, execute the following. `(?<=(?=\1)_.*)` Assert that the pattern character is `_`. `(\d+|<((<)|(?<-4>>)|\d|,)+(?(4)^)>)` Match either a single positive integer, or a ragged list with balanced brackets. `(<)` - push an opening bracket onto the Group 4 stack `(?<-4>>)` - pop an entry from the Group 4 stack, and match a closing bracket `\d|,` - match a numeral or comma `(?(4)^)` - assert that the Group 4 stack is empty (literally, assert that if the Group 4 stack is not empty, we're at the beginning of the input string) [Answer] # Python3, 114 bytes: ``` T=type f=lambda x,y:len(x)==len(y)and all(a==0 or(T(a)==T(b)and(f(a,b)if list==T(a)else a==b))for a,b in zip(x,y)) ``` [Try it online!](https://tio.run/##lY/PCsIwDMbP@hQ5NtDD5uYfhL7FbqWHDjcs1K7MHZwvPxOHwjZRPISS3/cl6Rf77tyE7BDbYShU18dqXStvL@XJwk32R18FcUOl@O3RhhNY74VVKoGmFYWwpBWiZEXUwsoSXQ3eXTvGFit/rYDcJWLdtEA6uAB3FwUtRxxi60JHg9pI0AZx/QYJk3SCUgkjpdpIyMxcZcqOfOLifrKZhJxqa9jNVvaSVWfP7qXpHdXemNmZxU/1cyqbsnxc9SESnVqkegf6mi7h0V/pxit/51sNDw) [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 6 bytes ``` MatchQ ``` [Try it online!](https://tio.run/##jY4xDsIwDEXn5hqVmMyQNMAE6gWQqBgRiqKIqh3aAWUz7tVTpyUtA0J4sd63v/0765tHZ33rbKiP4Wy9a6pweba9v@XbU12W@X0zXJ3tBxRIGdcrQwKBMoGZCFBBQTRLEj5F0IvMbCLzkEkBsgVQA@647QEPxDUdTarhBbF@ltFaJMI4RL2gpvmt@p3tzd8TGnb/kzDeXjMKCiM "Wolfram Language (Mathematica) – Try It Online") Built-in. Uses `_` as a wildcard. Input `[list, pattern]` or `[pattern][list]`. --- Non-built-in: ### [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 33 bytes ``` ##=!=0&&Or@@#0@@@Check[{##},]& ``` [Try it online!](https://tio.run/##jY49CsJAEIVr9xaysNUImx@1iix4ABXLkGIJCQmSFGGtxk1r6VE9wjpJTGIh4jTD92bezKu0KbJKmzLVLo8c59EykkIcGqW4VErtiyy9xMi5fT7ukAh3upaZUcemrE3MV7uc9hLRnlNdt8jQLqhuC7TA0BtB9gToQ2DtIHnwKUI4ycSyYxoS@YBkAQwB19Q2gFtL1R8dVUkLbP7sddZgJOyGGE4Y2uGt/zvbm78nlOT@J2F3e87IrHsB "Wolfram Language (Mathematica) – Try It Online") Uses `0` as a wildcard. Input in any order. Returns `False` if they match, or `Null` otherwise. ### [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 23 bytes ``` ##=!=0&&#0@@@({##})& ``` [Try it online!](https://tio.run/##jY7PCoJAEMbP@hTlghRMsP6pDmEs9AJFR/Egi6KEBmGnab127FF7BJvV1A4RzWX2981@M18RV1lSxFUu4yYNGsaCacBtm3EhxAwZU8/HfW43h2ueVGJ/ycsqZIvtLkvkKUyFYBuLzDKzwCrPk@4ZRXZ9lHFZo4nKoLoZqMBEpwfeEqALnlKd5MCnCP4gE3PNNCRyAckC6AMuqa0A14qqXdqrnD6Y42VHW72eUA/RH9BX3Vn3d7Y3f0/Iyf1PQr17zGiq5gU "Wolfram Language (Mathematica) – Try It Online") Uses `0` as a wildcard. Input in any order. Returns by error presence/absence. [Answer] # [Factor](https://factorcode.org/) + `match`, 7 bytes ``` (match) ``` [Try it online!](https://tio.run/##pZGxCsIwEIb3PMWNOii0jQqKXcXFRZxESggtllIbkixy9Nlj0tY2auliIAn35b@7/FzGuK6kuZyPp8MWmFIVV1Ayze8gWC4XsuJFqkHIVOunkPlDw44QJGAXQg372F1dmLxB0KPAhwghRDYcHh1xAvorol5ZtBHCylIn7qROHNqzqehJENZ2bxrqevXNvn6LQ6kRFHmQDpiOmQ0/7PYup2wnLmnadtviL@s1XImZNeOcmxtk7YDjkglQmvFiaV4 "Factor – Try It Online") [Answer] # [Pip](https://github.com/dloscutoff/pip) `-x`, 25 bytes ``` aN[0b]|$&0*g&a#=b&$&fMZab ``` Takes the pattern and the list as command-line arguments in Pip list syntax, using `0` as the wildcard value. Outputs `1` for truthy, empty string or `0` for falsey. [Attempt This Online!](https://ato.pxeger.com/run?1=m724ILNgWbSSboVS7IKlpSVpuhY7E_2iDZJia1TUDLTS1RKVbZPUVNTSfKMSkyDyUGU3LaOVog2sFaJNgNg01lrBIDZWSUdBKTra0FrBCChmHBuLJBttBsTmsUAAtwgA) Or, [verify all test cases](https://ato.pxeger.com/run?1=m724ILNgWbSSboBS7MLqpaUlaboWOxP9og2SYmtU1Ay00tUSlW2T1FTU0nyjEpMg8rcYK2sVfEMVormsrRVCikpLMiqtuBSio2OtFaJjY0EsAxDTEMI2tIbwrKONrI1j0cWgglBRIA8oYYKkHsiBmGgdbWIdbRoLlAfJAqWNrKOBOmHC0WbW0eaxYJOAjnJLzClOhTjKEM1VEGZ0LDrbGMoxAfNMkP1hbYTqaiQ5kPHRRghfQT2J6V-gB4yw-wxkENF-i4XEwIIFEBoA). ### Explanation This is a recursive full program. The `-x` flag evaluates the program's arguments, which allows us to take lists as inputs. ``` aN[0b]|$&0*g&a#=b&$&fMZab ; a is 1st arg (pattern); b is 2nd arg (list) ; g is list of both args; f is main function [0b] ; List containing 0 and b aN ; Is a in that list? (I.e. is a 0 or does a equal b?) | ; If that result is truthy, return it; if not: 0*g ; 0 times g (applies to ints, maps over lists) $& ; Fold on AND (truthy iff both elements are truthy): ; - If a or b is an int (and we know they're not equal ; because we already checked), we get a falsey result ; - If a or b is an empty list (and we know they're not ; both empty because we already checked), that's falsey ; - Otherwise, both are nonempty lists and we get truthy & ; If that result is falsey, return it; if not: a#=b ; Are a and b the same length? & ; If that result is falsey, return it; if not: f ; Apply the main function recursively MZab ; to corresponding items from a and b $& ; Fold on AND (truthy iff all elements are truthy) ``` ]
[Question] [ Let's begin with a thought experiment. You have a clock and a timer, in which you start the timer when the clock shows exactly `hh:mm.00`. * Clock: The clock employs 24-hour time. So the range of `hh` is `0<=h<23`. (Because `23` inputs are unsolvable, you aren't required to handle that) * Timer: It starts exactly on `00.00`. The number to the right of `.` isn't milliseconds; it's seconds. What you need to do is to find out when the two numbers represented by clock time (hh:mm) is respectively equal to the timer time (mm.ss); e.g. 13:24 is "respectively equal" to 13.24. There can potentially be more than one time. ## An example Say the input is `1:59`. ``` Clock: 1:59 Timer: 0.00 (The timer just started) ... Clock: 1:59 Timer: 0.59 (59 seconds later...) ... Clock: 2:00 Timer: 1.00 (As the timer's second section rounds up to the minute section, the clock time gets incremented by a minute. And the 59 minutes in the clock section gets rounded up to the hour section, hence the 2:00.) ... Clock: 2:00 Timer: 1.59 (59 seconds later...) ... Clock: 2:01 Timer: 2.00 (The timer minute gets rounded up, as the clock time increments by a minute) ... Clock: 2:01 Timer: 2.01 (Now the clock time is "respectively equal" to the timer time) ``` Therefore you need to output `2:01` for the `1:59` input. ## Examples [Here](https://tio.run/##fVHdCsIgFL7fU5zulHZxLIoKfIdeIZZjknPhHD2@uWQ6w/JC8Ps9B@XgXAsXDr2w3XAnnRlr6KUe6wr8sbIXZqaVHC3BGpB@8EYNzSPi0RTIVyeVIMG64UEb4lLkzV4nS1i9vAijW0ajSLZkxXB@xBRQSEH6m8XUgVkHpEWWnOX1NU0210pTmCvPA/xTh6kOC3XhNsJORoeFKlq18x8czhSeRmqrtAd8yx7XwK6gyIG9B06ZxXtYBJx7Aw) is a sample program I use to check my test cases. ``` 0:59 -> 0:59 (or 1:00, if your answer supports that) 1:30 -> 1:31 2:59 -> 3:02 1:59 -> 2:01 3:58 -> 4:02 22:01->22:23 ``` ## Specifications * Although in the test cases, the input is taken as `hh:mm`, you can nevertheless take input in a list, e.g. `[hh,mm]`, or any format suitable for your answer. * You can output the time in the format `[mm,ss]`. * You *could* start two physical timers, but you need to optimize their speed somehow. Your code running all of the test cases must terminate in 60 seconds. * You are allowed to take input/output as base 60. * You don't need to handle unsolvable inputs. I.e. The hour section in the clock will never be `23`. * If you find more than one time for a specific test case, you can output any of them. [Answer] # [Raku](https://github.com/nxadm/rakudo-pkg), ~~14 12~~ 11 bytes ``` 0+|*/.98334 ``` [Try it online!](https://tio.run/##VVDbboJAFHzfrziNtNlFWfYiFJbidzRRJCaAmogaaI2G@u30LNCHPmzmzJzLTPZaNqewrx/wVkEKvZj/uD6PI62XfUKsvEe5w8KpsXDy11Aklh1SJ4fieIOJF6lzmFN8Ts3@dFTdUKBaWBU3nwCzrjo27Rd0znbnUbRzdn4oWIrnnguQnLtPQtrdAypqQrGufbop5mxjBvDXW5VljF8vp0d9KSgu8qa8lU1bQnVp4HQ8l20yrO@b8gpdRZ2cwUsKe1uggeB8uKv0QocZSwiZDWZTptzHOU8y@MAoQoaxfp9SJWMqqYPIlzqSowsV418xfv4uyv/XxpZewgpcfNNksID1p58BxaNxHLP7HVTSCxPE4OEQIpFGC0sQJVFTRxuhsDMSZYQk2gSRJUvbUVbyVghKE6WNDpHgRPwL "Perl 6 – Try It Online") Since we know the bounds of the input, we can substitute a constant operation and a floor on the input in base 60. That number by the way is around `1358/1381`, which is the maximum the input differs from the output in base 60. There may be a smaller constant, or at least a smaller way to represent it. For reference, the shortest constant you can multiply by, rather than divide, is `1.01694`. [Answer] # [Python 3.8](https://docs.python.org/3.8/), ~~40~~ 36 bytes ``` lambda h,m:(d:=h+(h+m)//60,(d+m)%60) ``` [Try it online!](https://tio.run/##PYzBCoMwEETv@Yq5iEnd4iZB0YD9kl4sQRQaFfHSr0@jpV7evFmWWT/7uMy2Wbc4oMMzvvvw8j1GCk56142FHIugyrJmkj5ZVrOKw7KlDwRMMyRT1SqC1GT5SHP1X1qqmvNuSCsngHWb5l3mGRvvDuD@wFVyZJDHNuE2nKKUikyoWqEJloX5e6JNbERaBusv "Python 3.8 (pre-release) – Try It Online") [Answer] # [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), ~~11~~ 9 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py) ``` +α_╙╟/+╟% ``` Port of the approach used in [*@ovs*' Python answer](https://codegolf.stackexchange.com/a/207200/52210). Input as two loose integers. Output as a pair. [Try it online.](https://tio.run/##y00syUjPz0n7/1/73Mb4R1NnPpo6X18bSKj@/2@gYGrJZahgbMBlBGEBCWMFUwsuIyMFQwA) **Explanation:** ``` + # Add the two (implicit) inputs together: h+m α # Wrap two items in a list, which will use the (implicit) first input: [h,h+m] _╙ # Duplicate it, and pop and push the maximum: h+m ╟/ # Integer-divide it by 60: (h+m)//60 + # Add it to both values in the list: [h+(h+m)//60,h+m+(h+m)//60] ╟% # Take modulo-60 on both: [(h+(h+m)//60)%60,(h+m+(h+m)//60)%60] # (after which the entire stack joined together is output implicitly as result) ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~13~~ 10 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ηO¤60÷+60% ``` Port of the approach used in [*@ovs*' Python answer](https://codegolf.stackexchange.com/a/207200/52210). I/O as a pair of integers. [Try it online](https://tio.run/##yy9OTMpM/f//3Hb/Q0vMDA5v1zYzUP3/P9pQx9QyFgA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9WGfKoYYOXutXhvfZKCo/aJiko2Ve6/D@33f/QEjODw9u1zQxU/0OU6B3eq/M/OtpAx9QyVifaUMfYAEgZwXhgyljH1AIkaKRjYBgbCwA). **Explanation:** ``` η # Get the prefixes of the (implicit) input-pair: [h,m] → [[h],[h,m]] O # Take the sum of each inner list: [h,h+m] ¤ # Push the last item (without popping): h+m 60÷ # Integer-divide it by 60: (h+m)//60 + # Add it to both values: [h+(h+m)//60,(h+m)+(h+m)//60] 60% # Take modulo-60 on both: [(h+(h+m)//60)%60,((h+m)+(h+m)//60)%60] # (after which the result is output implicitly) ``` [Answer] # [R](https://www.r-project.org/), 42 bytes ``` function(h,m)c(t<-(h*60+m)/59,60*t%%1)%/%1 ``` [Try it online!](https://tio.run/##ZYxBDoIwEEX3nGIS06TFMUxbSyTRM3gEgw2mRAsJLeevVt0Aq7947/0pxd5308230bouXNJjHmzsx4E79MLyeD5wV9a096IyDdZURsakYBWTy5ITmkbADvLCfY4gkQj6AO0rjHB9Fktdoqasf1aukPo/aSS1qX5IIa0rjeaU0XFbqax/M4VKF@kN "R – Try It Online") Version 2: -3 bytes thanks to clarification that we don't need to output the **first** match when the timer & clock show the same numbers. So this version outputs the second match for an input of `0:59` (in other words, `1:00`instead of the first match at `0:59`), and similarly for all other outputs that can end with `:59` or `:00`. # [R](https://www.r-project.org/), Version 1: ~~49~~ 45 bytes ``` function(h,m)c(t<-(h+m/60)*6/5.9,60*t%%1)%/%1 ``` [Try it online!](https://tio.run/##ZctBCsIwEIXhfU9RkEBSRzOZmGChnkUkVNJFWqjj@aPRbtqu3uJ/35x5SP18Tw8OsX/d8vM9Bh6mUUZIKkjuTjIek/aoGq/duQWPDQthlNDCrLFEcK2qD3XZap0MWCzpu2aTaFEWkHbqnwhwqyy4a0mXvaJy/zECslX@AA "R – Try It Online") Outputs the **first** timer-clock match (so, always a match ending `0:59` instead of a subsequent match ending `:00`). This exploits the floating-point rounding of `*6/5.9` to slightly less than `*60/59`, but using the same number of characters. This effectively gives us a floor-like result that rounds-down exact integers in the output (the desired behaviour). Using `*60/59` gives an exact floating-point result and so doesn't do this. ~~(Frustratingly, though, it still isn't as short as simply porting ovs's approach for [43 bytes](https://tio.run/##ZctBCoMwEIXhvacQSmCCI04mVVqoZyklKHGRCBrPH411o67ewD/fFMPguunrfsHYbm5jv3gThtGDRScN@E9pC7CFk1VDCH47hGhIikqoMwXC@i3zR542OyeFmlLaVl0SH0oj8U39EyNdlcb6ldLzrji974yRdRZX)).~~ Version 2 (above) is shorter. [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 69 bytes ``` \d+ $* ^ $' +`:1{60} 1: (1*):1*: $.1:$1 :(1{60})?(1{10})*(1*) :$#2$.3 ``` [Try it online!](https://tio.run/##K0otycxL/K@q4Z7wPyZFm0tFiyuOS0WdSzvByrDazKCWy9CKS8NQS9PKUMuKS0XP0ErFkMtKAyylaQ@kDYG0FkgBl5WKspGKnvH//wZWppZAbcYGXEYQFpAwtjK14DIysjIwBAA "Retina 0.8.2 – Try It Online") Link includes test cases. Uses @ovs' formula. Explanation: ``` \d+ $* ``` Convert to unary. ``` ^ $' ``` Duplicate the input, which effectively sums the two values together. ``` +`:1{60} 1: ``` Add a sixtieth of the sum to the first value. ``` (1*):1*: $.1:$1 ``` Delete the remainder of the sum, convert the first value to decimal, and also add it to the second value (still in unary). ``` :(1{60})?(1{10})*(1*) :$#2$.3 ``` Convert the second value modulo sixty to two decimal digits. [Answer] # [Japt](https://github.com/ETHproductions/japt), 11 (10?) [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Port of Jo's Raku solution ``` ì60'*1.0#©4 ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=7DYwJyoxLjAjqTQ&input=WzEsNTldCi1R) This *might* work for 10 but I haven't fully tested it: ``` ì60'*6/5.9 ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=7DYwJyo2LzUuOQ&input=WzEsNTldCi1R) ``` ì60'*1.0#©4 :Implicit input of integer array ì60 :Convert from base-60 '* :Multiply by 1.0#©4 : 1.01694 :Implicitly convert back to base-60 and output ``` [Answer] # Javascript, ~~43~~ 42 bytes ``` h=>m=>[~~(h+(i=h+m)/60)%60,~~(61*i/60)%60] ``` Port of the approach used in [*@ovs*' Python answer](https://codegolf.stackexchange.com/a/207200/52210). Input: two integers, output: List of [mm,ss] [Try it online.](https://tio.run/##y0osSyxOLsosKNEts/ifZvs/w9Yu19Yuuq5OI0NbI9M2QztXU9/MQFPVzEAHKGZmqJUJ5cb@T87PK87PSdXLyU/XSNMwMtLUMNTU/A8A) [Answer] # [JavaScript (V8)](https://v8.dev/), ~~28~~ 26 bytes ``` h=>m=>[h+=h+m>59,(h+m)%60] ``` Based off of [SomoKRoceS' JavaScript answer](https://codegolf.stackexchange.com/a/207215/96347) Input: two integers, output: List of [mm,ss] [Try it online!](https://tio.run/##dc7RCoIwFMbx@55iBMGGGsezFjrZXiS6ENEsNEPN118Hq4uxutp38zv/3cqlnKrx@piTJXONca2xvbGnNjJt1FuVx5xesTvC2VXDfRq6et8NF75loFXOEsveY6ynZzfrbcwazkBwlQtRbHyRagmroJH6IhVcQijw25Aa0Bf4r/ERqCFs/BJSq2wVh6AhSWSBwPU0CRooPYH0K@qIwr0A "JavaScript (V8) – Try It Online") [Answer] # [J](https://www.jsoftware.com/indexno.html), 23 bytes Based on [Jo King's Raku answer](https://codegolf.stackexchange.com/a/207201/9486). Input and output is in the form of 2-vectors. ``` <.@(1.01694&*)&.(60&#.) ``` Explanation: ``` &.(60&#.) NB. Under base 60, (1.01694&*) NB. multiply by the magic number, <.@ NB. then floor the result. ``` [Try it online!](https://tio.run/##y/r/P03B1krBRs9Bw1DPwNDM0kRNS1NNT8PMQE1ZT/N/SWpxSTFIgYGCqaWCtYKhgrEBkDKC8cCUsYKpBUjQSMGQqyi1uDQHokUjTU3PTlPJUAFsCBdXanJGvkINUFzDRt3TLyA0RF1TQQciCWRAxP1DQ2ASUJM0/wMA "J – Try It Online") ]
[Question] [ # The task Given an image as input, your task is to do the following: 1. Resize the image so it is **At least** 2 times smaller, but still has the same width/height ratio by taking every second (if resized to 2x) pixel in both horizontal and vertical directions and using those in the pixel art image. Example: ``` a 4x4 image [abcd ,efgh ,ijkl ,mnop] When resized to 2x will become one of the following: [ac [bd [eg [fh ,ik] ,jl] ,mo] ,np] ``` 2. Each RGB pixel in the newly resized image must be converted to a 3-bit color, so there are 8 different possible colors: ``` Red (255,0,0) Green (0,255,0) Blue (0,0,255) Light Blue (0,255,255) Magenta (255,0,255) Yellow (255,255,0) White (255,255,255) Black (0,0,0) ``` An image of the colors: [![3bit colors](https://i.stack.imgur.com/M9YOx.jpg)](https://i.stack.imgur.com/M9YOx.jpg) 3. And output the resulting image. # Input Your input may be: 1. An image 2. A path to the inputting image # Output Can be: 1. An image 2. A path to the outputting image # Rules * The inputting image will not be larger than 2048x2048 and will always be at least 256x256 * The outputting image must be at least 64x64 * When changing pixels, the original pixel **must** be converted to the closest (euclidean) pixel in the 3-bit scheme, no randomization * You may hardcode how much you resize the image if you want to * When submitting your answer, please include the following: 1. Your byte-count in the title 2. Your code 3. An pair of images, one original of your choice and the other being the "pixel-art" from that image * This is code-golf, so lowest byte count for each language wins. # Test cases [![flower](https://i.stack.imgur.com/ugw3d.jpg)](https://i.stack.imgur.com/ugw3d.jpg) [![flower](https://i.stack.imgur.com/wX1B7.png)](https://i.stack.imgur.com/wX1B7.png) (2x resize) [![tracer](https://i.stack.imgur.com/cZimB.jpg)](https://i.stack.imgur.com/cZimB.jpg) [![tracer](https://i.stack.imgur.com/DaZgq.png)](https://i.stack.imgur.com/DaZgq.png) (2x resize) [Answer] # Sledgehammer, ~~22~~ 17 bytes I noticed I'm no longer winning for some reason and made a minor IO golf ``` ⢟⢡⡂⠴⠒⢂⢜⠧⣘⡨⡏⣻⢈⠯⣧⠼⡫ ``` Corresponding Mathematica code: `Export[".bmp",ImageAdjust[Import[#]~Downsample~2, 9!]]&` . Takes input from the file with name specified in the program's arguments (for some reason these are put in a file, too), outputs to the file `.bmp`. There are literally built-ins for everything! * built-in for reading arbitrary image format * built-in for downsampling * built-in for adjusting the contrast by \$9!\$ * built-in for writing all that into a file At least it's not `PixelArtify[Input[]]`. # Mathematica, ~~61~~ 31 bytes ``` ImageAdjust[#~Downsample~2,9!]& ``` Adjusts the contrast of the downsampled image by the factorial of nine. [Answer] # [MATL](https://github.com/lmendo/MATL), 18 bytes ``` Yi2Lt3:K$)127>o2YG ``` The input is a string with the file name. The output is an image displayed in a window. Input image: [![enter image description here](https://i.stack.imgur.com/uiS9x.jpg)](https://i.stack.imgur.com/uiS9x.jpg) Output image: [![enter image description here](https://i.stack.imgur.com/JQ5zp.png)](https://i.stack.imgur.com/JQ5zp.png) ### Explanation ``` Yi % Implicit input: filename. Read image. Gives an N×M×3 uint8 array 2L % Push [2 2 j] (predefined literal). When interpreted as an index, % this means 2:2:end t % Duplicate 3: % Push [1 2 3] K$) % 4-input indexing. Downsamples the image by a factor of 2 in each % dimension of the first two dimensions (vertical and horizontal), % while keeping the three colour components 127> % Greater than 127? Gives true (1) or false (0) o % Convert to double 2YG % Display image. For double data type this assumes range from 0 to 1 ``` [Answer] # [Python 3](https://docs.python.org/3/) + [imageio](http://imageio.github.io), ~~68~~ 67 bytes Takes the filename as input, overwrites the original file. ``` from imageio import* lambda f:imwrite(f,(~imread(f)[::2,::2]>>7)-1) ``` `imageio.imread` returns a numpy 3d array of unsigned 8-bit integers corresponding to the RGB value of each pixel. `array[::2, ::2]` takes every other row and every other column of the array. Because of the 8-bit data type `(~array>>7)-1` is equivalent to `((255-array)//128-1)%256`. [image source](https://commons.wikimedia.org/wiki/File:Supernumerary_rainbow_03_contrast.jpg) [![enter image description here](https://i.stack.imgur.com/z2bps.jpg)](https://i.stack.imgur.com/z2bps.jpg) [![enter image description here](https://i.stack.imgur.com/5Hdmd.png)](https://i.stack.imgur.com/5Hdmd.png) [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 69 bytes ``` Image[#&@@Nearest[{0,1}~Tuples~3,#]&/@#&/@ImageData@Downsample[#,2]]& ``` [![enter image description here](https://i.stack.imgur.com/FD53l.jpg)](https://i.stack.imgur.com/FD53l.jpg) [![enter image description here](https://i.stack.imgur.com/cqz9a.png)](https://i.stack.imgur.com/cqz9a.png) [Answer] # Java 10, ~~255~~ ~~254~~ ~~252~~ ~~251~~ 248 bytes ``` import java.awt.image.*;I->{int w=I.getWidth()/2,h=I.getHeight()/2,c[]={0,255,65535,65280,255<<16,16711935,16776960,-1>>>8};var r=new BufferedImage(w,h,13,new IndexColorModel(3,8,c,0,0>1,1,0));r.createGraphics().drawImage(I,0,0,w,h,null);return r;} ``` -2 bytes thanks to *@mypronounismonicareinstate* -4 bytes thanks to *@OlivierGrégoire*. **Some example I/O:** [![enter image description here](https://i.stack.imgur.com/5jYZV.jpg)](https://i.stack.imgur.com/5jYZV.jpg) [![enter image description here](https://i.stack.imgur.com/53yUfm.jpg)](https://i.stack.imgur.com/53yUfm.jpg) [![enter image description here](https://i.stack.imgur.com/NoWYU.jpg)](https://i.stack.imgur.com/NoWYU.jpg) [![enter image description here](https://i.stack.imgur.com/dLm1em.jpg)](https://i.stack.imgur.com/dLm1em.jpg) I/O as a `java.awt.image.BufferedImage`. **Explanation:** ``` import java.awt.image.*; // Import for BufferedImage and IndexColorModel I->{ // Method with BufferedImage as both parameter & return int w=I.getWidth()/2, // Get the width/2 of the input-image h=I.getHeight()/2, // Get the height/2 of the input-image c[]={ // Integer-arry for the colors: 0, // 0x000000 (black) 255, // 0x0000ff (blue) 65535, // 0x00ff00 (green) 65280, // 0x00ffff (aqua) 255<<16, // 0xff0000 (red) 16711935, // 0xff00ff (magenta) 16776960, // 0xffff00 (yellow) -1>>>8}; // 0xffffff (white) var r=new BufferedImage(w,h,// Create the return-BufferdImage with this size, and: 13, // An indexed byte image (BufferedImage.TYPE_BYTE_INDEXED) new IndexColorModel( // Using the following ColorModel: 3, // 3-bits 8,c, // with the 8 colors of the earlier created array 0, // without an offset index 0>1, // without alpha layers (false) 1, // without transparent colors (Transparency.OPAQUE) 0)); // using unsigned bytes as data (DataBuffer.TYPE_BYTE) r.createGraphics() // Convert this image to a Graphics2D object .drawImage(I, // So we can use the input-image for it 0,0, // with 0,0 as starting x,y coordinates w,h, // the same halved width & height null); // and no ImageObserver return r;} // Return this created BufferedImage as result ``` [Answer] # [Red](http://www.red-lang.org), ~~150~~ 148 bytes ``` func[s][r: func[a][round/to a 255]i: load s forall i[i/1: as-rgba r i/1/1 r i/1/2 r i/1/3 0]view compose[base(i/size / 2)draw[scale .5 .5 image i]]] ``` The output is an image displayed in a window. [![Figure](https://i.stack.imgur.com/cZimB.jpg)](https://i.stack.imgur.com/cZimB.jpg) Original [![Figure x.5](https://i.stack.imgur.com/SHt0w.png)](https://i.stack.imgur.com/SHt0w.png) Scale 0.5 [![Samoyed](https://i.stack.imgur.com/ORB61.jpg)](https://i.stack.imgur.com/ORB61.jpg) Original [![Samoyed x 0.5](https://i.stack.imgur.com/607WD.png)](https://i.stack.imgur.com/607WD.png) Scale x 0.5 [Answer] ## bash + ImageMagick, ~~123~~ 50 bytes ``` convert "$1" -sample 50% +dither -posterize 2 "$2" ``` Untested, as I haven't actually installed it; I've just cribbed stuff from Stack Overflow. Edit: Saved 73 bytes thanks to @someone. [Answer] # bash + [netpbm](https://en.wikipedia.org/wiki/Netpbm), 30 bytes ``` pnmdepth 1|pnmscale -nomix 0.5 ``` Takes input on stdin as a PNM file, and outputs on stdout as a PNM file. `pnmdepth 1` reduces the depth of the image on its stdin to 1, and `pnmscale 0.5` reduces the size by a half in each direction. The `-nomix` option is required for `pnmscale` to choose a pixel from the starting image for each output pixel, instead of mixing adjacent input pixels into one output pixel. [Answer] # Python 3 + PIL, ~~211~~ 208 bytes ``` from PIL import Image as I i=I.open(input(),'r') p=i.load() q,g=i.size;a=q//4;c=g//4 u=I.new('RGB',(a,c)) o=u.load() for w in range(a): for h in range(c):o[w,h]=tuple(e//128*255 for e in p[w*4,h*4]) u.show() ``` Golfed the testing script I used to create the test cases for this challenge [Answer] # MATLAB, 32 bytes ``` @(x)(x(1:2:end,1:2:end,:)>127)*1 ``` Both input and output are images. Output is an array storing image data, it's not specified in challenge that output image must be displayed. (to display result add 8 bytes for `imshow(`...`)` command) The actual result and original: [![input image](https://i.stack.imgur.com/2xFaL.png)](https://i.stack.imgur.com/2xFaL.png) [![output image](https://i.stack.imgur.com/8tktF.png)](https://i.stack.imgur.com/8tktF.png) Art credit to [Janna Sophia](https://www.artstation.com/jannasophia). [Answer] # Processing, 463 bytes ``` size(500,500);String u="";PImage p=loadImage(u);p.resize(p.width/2,p.height/2);noStroke();color[]c={#ff0000,#00ff00,#0000ff,#00ffff,#ff00ff,#ffff00,#ffffff,0};p.loadPixels();for(int i=0;i<p.width;i++){for(int j=0;j<p.height;j++){float[]d=new float[8];color x=p.get(i,j);for(int k=0;k<8;k++)d[k]=sqrt(sq(red(x)-red(c[k]))+sq(blue(x)-blue(c[k]))+sq(green(x)-green(c[k])));int b=0;for(int l=0;l<8;l++){if(d[l]<=d[b]){b=l;}}fill(c[b]);rect(i,j,1,1);}}save(u+"1.png"); ``` Takes image location, saves pixel art as image1.png. [![enter image description here](https://i.stack.imgur.com/4564D.png)](https://i.stack.imgur.com/4564D.png)[![enter image description here](https://i.stack.imgur.com/J1KAP.jpg)](https://i.stack.imgur.com/J1KAP.jpg) Image from [beeple.](https://www.beeple-crap.com/) ]
[Question] [ Write a program that outputs a list of the number of occurrences of each unique character in its source code. For example, this hypothetical program `{Source_Print_1};` should produce this output: ``` ; 1 P 1 S 1 _ 2 c 1 e 1 i 1 n 1 o 1 p 1 r 2 t 1 u 1 { 1 } 1 ``` The formatting should match this example. No extraneous whitespace is allowed, except an optional final newline. Your program may not read its own source code from the source file. The characters listed must be in one of two orders. Either the order of character values in the character encoding used by your language (probably ASCII), or the order the characters appear in your source. This question inspired by [this comment](https://codegolf.stackexchange.com/questions/12042/xkcd-challenge-percentage-of-the-screen-that-is-x-color#comment23272_12042) by [Jan Dvorak](https://codegolf.stackexchange.com/users/7209/jan-dvorak). [Answer] # [///](http://esolangs.org/wiki////), 12 bytes ``` 4 4 4 4 ``` *A big thank you goes to @user23013, who suggested this improvement over my CJam code, outgolfing his own, highest-scoring answer in the process.* The characters are sorted by appearance. This code works in any language that just prints its own source code under the given circumstances (PHP, ASP, etc.). --- # CJam, 20 bytes ``` ''S5N'5S5N'NS5N'SS5N ``` This approach doesn't use any built-in character counting. Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=''S5N'5S5N'NS5N'SS5N). ### How it works ``` ''S5N e# Push a single quote, a space, the integer 5 and a linefeed. '5S5N e# Push the character 5, a space, the integer 5 and a linefeed. 'NS5N e# Push the character N, a space, the integer 5 and a linefeed. 'SS5N e# Push the character S, a space, the integer 5 and a linefeed. ``` [Answer] # CJam, 20 bytes ``` {`"_~"+$e`{)S@N}%}_~ ``` **How it works** We first start off with one of the standard quine in CJam ``` {`"_~"}_~ ``` which pushes the first block on stack, copies it, and runs the copy, which makes it print the source code itself finally. Then we add the logic to compute the character count from the source code: ``` {`"_~"+ e# At this point, we have the full source code with us $e` e# Sort to get similar characters together and run RLE to e# get count of each character as [count char] array { }% e# Run each array element through this loop )S@N e# Pop the character, put a space, rotate the count after e# space and then finally put a newline after the trio }_~ e# Second half of the standard quine explained above ``` [Try it online here](http://cjam.aditsu.net/#code=%7B%60%22_~%22%2B%24e%60%7B)S%40N%7D%25%7D_~) [Answer] # CJam, 14 bytes ``` {S2N`/}`{S2N}/ ``` [Try it here](http://cjam.aditsu.net/#code=%7BS2N%60%2F%7D%60%7BS2N%7D%2F). Output is in the order they firstly appears: ``` { 2 S 2 2 2 N 2 ` 2 / 2 } 2 ``` It simply appends `<SP>2<NL>` to each character in `{S2N`/}`. [Answer] # [Python 3.5.0b1](https://www.python.org/downloads/release/python-350b1/), ~~107~~ 73 bytes ``` s="t='s=%r;exec(s)'%s;[print(c,t.count(c))for c in sorted({*t})]";exec(s) ``` Rather than the usual string replacement quine, which requires writing everything twice, here's an `exec` quine. [Answer] # Mathematica, 101 bytes ``` Apply[Print[#1, " ", #2] &, Tally[Characters[StringJoin[ToString[#0, InputForm], "[];"]]], {1}] & []; ``` Unfortunately, I can't use any of the normal golfing tricks like removing whitespace, `<>` for `StringJoin`, `#` instead of `#1`, `@` for prefix function calls or `@@@` instead of `Apply[...,{1}]`, because `ToString[...,InputForm]` thinks it has to pretty print everything... This prints the characters in the order they first appear in the code. If I can assume that this *isn't* run in a REPL environment (which is rather unusual for Mathematica) I can save two bytes by omitting the two `;`. [Answer] # Haskell, 178 bytes ``` main=putStr(unlines[s:' ':show t|(s,t)<-zip" \"'(),-0123456789:<=S[\\]aehilmnoprstuwz|"[3,3,3,3,3,41,4,1,6,19,12,5,5,2,2,2,2,3,2,2,2,3,3,3,2,2,2,4,2,2,4,2,3,2,5,5,3,2,2,2]])--178 ``` Nothing fancy. All characters of the program are in a literal list (String). So are the frequencies. Zip both lists and print. Output: ``` 3 " 3 ' 3 ( 3 ) 3 , 41 - 4 0 1 1 6 2 19 3 12 4 5 5 5 6 2 7 2 8 2 9 2 : 3 < 2 = 2 S 2 [ 3 \ 3 ] 3 a 2 e 2 h 2 i 4 l 2 m 2 n 4 o 2 p 3 r 2 s 5 t 5 u 3 w 2 z 2 | 2 ``` [Answer] # Dart - 214 127 A direct version: ``` main(){print(" 22\n\" 3\n( 3\n) 3\n1 3\n2 15\n3 8\n4 1\n5 2\n8 2\n; 2\n\\ 23\na 2\ni 3\nm 2\nn 23\np 2\nr 2\nt 2\n{ 2\n} 2");} ``` The "4" is just a fiddling factor to make the numbers add up. See/run on [DartPad](https://dartpad.dartlang.org/40c00f711f61447dfd83). Original: Standard quine tactic, and Dart's function names are a little too long for good golfing. ``` main({m,v,q:r'''main({m,v,q:r''}'')''{m={};for(v in q.split(''))m[v]=m[v]==null?2:m[v]+2;m.forEach((k,v)=>print("$k $v"));}'''}){m={};for(v in q.split(''))m[v]=m[v]==null?2:m[v]+2;m.forEach((k,v)=>print("$k $v"));} ``` See/run it on [DartPad](https://dartpad.dartlang.org/1f80c0106973bed9734f). [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `D`, 12 bytes ``` `:qpĊ⁋`:qpĊ⁋ ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=D&code=%60%3Aqp%C4%8A%E2%81%8B%60%3Aqp%C4%8A%E2%81%8B&inputs=&header=&footer=) [Answer] # [Haskell](https://www.haskell.org/), 146 bytes ``` main=mapM putStrLn[a:" "++show s|a<-[' '..],s<-[sum[2|b<-show"main=mapM putStrLn[a: ++show s|a<-[' '..],s<-[sum[2|b<-show,a==b]],s>0]",a==b]],s>0] ``` [Try it online!](https://tio.run/nexus/haskell#@5@bmJlnm5tY4KtQUFoSXFLkkxedaKWkoKStXZyRX65QXJNooxutrqCupxerUwxkFpfmRhvVJNnogqSVsOpWIEqvTqKtbVIsUMLOIFYJmfP/PwA "Haskell – TIO Nexus") **Output:** ``` 8 " 4 ' 4 + 4 , 6 - 6 . 4 0 2 2 2 : 2 < 6 = 6 > 2 L 2 M 2 S 2 [ 8 ] 8 a 10 b 4 h 4 i 2 m 6 n 4 o 4 p 4 r 2 s 12 t 4 u 4 w 4 | 4 ``` (Plus an additional newline) **Explanation:** The code is ``` main=mapM putStrLn[a:" "++show s|a<-[' '..],s<-[sum[2|b<-show"<code>",a==b]],s>0] ``` where `"<code>"` is a string of the program code without the `"`. `a` goes through the ascii characters starting with a space. `sum[2|b<-show"<code>",a==b]` counts how often the character appears in the string, with each occurrence counted twice. `a:" "++show s` builds a string of the current character, a space and the character count. Finally `mapM putStrLn` prints each string in the list with a trailing newline. The hardest part was getting the count of `"` right. Using just `b<-"<code>"` would count zero quotation marks because there are none in the string. Using `show"<code>"` adds a `"` to the front and end to the string, resulting in a count of four. So I had to put two additional quotation marks in the code, so instead of the (shorter) `a:' ':show s` I used `a:" "++show s`. ]
[Question] [ ### Instructions Barry is a *not so good* backend developer in charge of a small API that should give you information about purchases made in a client's shop. However, he hasn't done a great job and your boss tells you to fix it client-side instead. Ideally you should receive comma-separated values such as `927,2,45,90` which correspond to something like `item_id`,`item_amount`,`unit_price`,`total` In this first puzzle we only care about `item_id` and `item_amount` but we need the other fields in place to present the problem. Barry sometimes gets things mixed up and returns noise as part of the output, he also gets the order wrong, returning `noise`, `noise`, `unit_price`, `total`, `item_id`, `item_amount`. ### Your Task You need to store in a map (or similar structure) the pairs of `item_id` and `item_amount` regardless of whether Barry returns them correctly or not and print each element in a new line in the least number of characters possible. (Storing is not mandatory, we just care about the output) ### Sample input (mixed correct and messy formats) ``` 103,2,50,100 106,1,900,900 459,40,150,300,67,2 4,20,30,6000 ``` In other words input will be either `a,b,x,x` or `x,x,x,x,a,b` where what we care about is `a` & `b`. You need to provide code assuming we have a variable called `G` (or any other name) with all the lines of csv. ### Sample output ``` 103,2 106,1 67,2 //This one was messy 4,20 ``` ### Tolerance There is a certain margin for tolerance when it comes to the answer. Answers in similar formats but adhering to the correct values, will also be accepted. Formats like `[a,b]`,`(a,b)` or `{a,b}` are valid, but `a,b` is preferred. > > Although the first puzzle had mixed acceptance due to the fact that it > was easy and fast to solve, I also felt that some people liked that > too. So I'm going to continue making quickgolfs for now > > > [Answer] # Pyth, 10 bytes ``` FNG<.<N4 2 ``` Try it online: [Pyth Compiler/Executor](https://pyth.herokuapp.com/?code=%3DG.QFNG%3C.%3CN4+2&input=103%2C2%2C50%2C100%0A106%2C1%2C900%2C900%0A459%2C40%2C150%2C300%2C67%2C2%0A4%2C20%2C30%2C6000&debug=0) (The first 4 chars `=G.Q` reads all the data and stores it in `G`) ### Explanation ``` FNG for row N in G: .<N4 cyclic leftshift by 4 < 2 print the first two elements ``` [Answer] # Perl, 24 ``` perl -pe's/(\d+,){4}|,\d+,\d+$//' ``` Example: ``` perl -pe's/(\d+,){4}|,\d+,\d+$//' <in 103,2 106,1 67,2 4,20 ``` [Answer] # Python 3, ~~123~~ ~~76~~ ~~72~~ 62 bytes I'm a newcomer, gotta start somewhere... ``` for l in G: d=l.rstrip().split(',');x=[0,4][len(d)>5];print(d[x:x+2]) ``` With xnor's and DLosc's suggestions (62 bytes): ``` for l in G:d=l.rstrip().split(',');print(d[4*(len(d)>5):][:2]) ``` [Answer] # Sed, 32 bytes ``` s/,/=/4 s/.*=// s/,/:/2 s/:.*// ``` This deletes everything up to the 4th comma if there is one. Then it deletes everything from the 2nd comma (which may have previously been 6th). And I even managed to right-justify! [Answer] # Javascript, 44 bytes Assuming input in variable `G`. *Edit: I just realized, this looks a lot like nutki's perl solution.* ``` alert(G.replace(/(\d+,){4}|,\d+,\d+$/gm,'')) ``` **Snippet Demo:** ``` function run(){ G = input.value; /* start solution */ alert(G.replace(/(\d+,){4}|,\d+,\d+$/gm,'')) /* end solution */ } ``` ``` <textarea id="input" cols="25" rows="6">103,2,50,100 106,1,900,900 459,40,150,300,67,2 4,20,30,6000</textarea><br /> <button id="run" onclick="run();">Run</button> ``` [Answer] # Scala, 68 bytes ``` G.map(_.split(",")).map(x=>println((x++x).slice(4,6).mkString(","))) ``` -- [MrBones](/questions/50381/quickgolf-ignore-the-noise-1/50403?noredirect=1#comment119138_50403) # Scala, ~~46~~ 70 bytes *Edit: Print out the result* ``` for{l<-G;r=l.split(",");x=(r++r).slice(4,6).mkString(",")}{println(x)} ``` [Demo](http://goo.gl/eZDFs3) [Answer] # CJam, ~~18~~ ~~15~~ 14 bytes ``` r{',/4m<2<pr}h ``` Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=r%7B'%2C%2F4m%3C2%3Cpr%7Dh&input=103%2C2%2C50%2C100%0A106%2C1%2C900%2C900%0A459%2C40%2C150%2C300%2C67%2C2%0A4%2C20%2C30%2C6000). ### How it works ``` r e# Read a whitespace separated token from STDIN. { e# Do-while loop: ',/ e# Split at commas. 4m< e# Rotate the resulting array 4 units to the left. 2< e# Discard everything but the first 2 elements. p e# Print the array. r e# Read a whitespace separated token from STDIN. }h e# If the token is a nonempty string, repeat the loop. ``` [Answer] # POSIX shell, 30 bytes Assuming POSIX `sed` and `cut` are present: ``` sed 's/.*/&,&/'|cut -d, -f5,6 ``` Duplicates the line, leaving the data of interest ready to be extracted from fields 5 and 6. [Answer] # Javascript, ~~117~~ ~~112~~ ~~99~~ ~~95~~ ~~84~~ ~~76~~ 71 bytes ``` for(r of G.split('\n'))s=r.split(','),console.log(s[t=s[4]?4:0],s[t+1]) ``` [JS Fiddle](http://jsfiddle.net/fcnob9ne/12/) [Answer] # [Pip](http://github.com/dloscutoff/pip), 12 + 1 = 13 bytes Uses the `-l` flag, which gives the output as space-separated lists of numbers on each line.\* ``` _@[4 5]Mg^', ``` Explanation: * The list of numbers is expected in `g`. Since `g` is normally initialized from the command-line arguments, you can also put the input there for the same results. * `^',` splits (each string in) the list on commas. * `M` maps a function to each element in the result. * `_@[4 5]` defines a lambda function. The argument to the function is represented by `_`; `@[4 5]` returns a list of its 4th and 5th elements. If the list has six elements, these will be the last two. If it has four, the indices wrap around, and so the result is the first two. (E.g. `"abcd"@4 == "abcd"@0 == "a"`.) * We now have a list of lists, like `[[103 2] [106 1] [67 2]]`, which is auto-printed at the end of the program. The `-l` flag joins each sub-list on space and then the whole thing on newline, so the result is as follows: ``` C:\>pip.py -le "_@[4 5]Mg^'," 103,2,50,100 106,1,900,900 459,40,150,300,67,2 103 2 106 1 67 2 ``` \* Currently. I may change this behavior, but I'm still planning to have some flag that does the same thing. [Answer] # Perl, 37 ``` @c=/(\d+,\d+)/g;$_=@c>2?$c[2]:$c[0] ``` `35` characters `+2` for `-p` and `-l`. I'm not sure if there is an approach in Perl that would beat [@nutki's](https://codegolf.stackexchange.com/a/50390/29438) solution, but I figured I'd post this idea I had anyway. Run with: ``` cat input.txt | perl -ple'@c=/(\d+,\d+)/g;$_=@c>2?$c[2]:$c[0]' ``` [Answer] # bash, 54 ``` while IFS=, read {a..f};do echo ${e:-$a},${f:-$b};done ``` [Answer] # C, 95 bytes ``` f(a,b,c,d){scanf("%d,%d,%*d,%*d,%d,%d",&a,&b,&c,&d)>2?printf("%d,%d",c,d):printf("%d,%d",a,b);} ``` The code is simple. Here is the ungolfed version: ``` f(a,b,c,d){ //Four int variables scanf("%d,%d,%*d,%*d,%d,%d",&a,&b,&c,&d)>2 //Scan input ? //If scanf returned a value > 2 printf("%d,%d",c,d) //Print last two values : //else printf("%d,%d",a,b); //Print first two values } ``` # Test it [here](http://rextester.com/AIEQ43871) [Answer] # Ruby, 53 ``` G.each_line{|x|g=x.split',';p[g[4]||g[0],g[5]||g[1]]} ``` or is good. ]
[Question] [ The new weather predicting supercomputer has arrived, and it doesn't work. In the meantime your boss wants you to buy the technicians some time by faking the daily wind maps. **Your task is to draw a grid of arrows representing wind direction.** The grid is: * made up of 15px square tiles * 8 tiles by 8 tiles * 120px square total * # 000 background Each grid tile has 8 potential orientations, representing wind direction: 1. North 2. Northeast 3. East 4. Southeast 5. South 6. Southwest 7. West 8. Northwest Which must be depicted as follows: N ![N](https://i.stack.imgur.com/iH0rD.png) NE ![NE](https://i.stack.imgur.com/uaT3E.png) E ![E](https://i.stack.imgur.com/k2bDf.png) **The maps must vary gradually**, in order to be believable. This means each tile may only differ from its neighbour by one step. Specifically: * A tile can only differ by one increment or decrement from each of the 4 adjoining tiles. (or 3 for side tiles, 2 for corner tiles). * e.g. a tile with neighbour E could be NE, E or SE (assuming it accords with its other neighbours). * Orientations can loop back around, i.e. N -> NW and NW -> N. To illustrate, the following map is valid : ``` NW N NE NE NE NE NE NE N NE NE NE NE NE NE E NE NE NE NE NE NE E SE E NE NE NE NE E SE S SE E E E E SE S SE S SE SE SE SE S SE E SW S S S S SE E NE SW SW S S SE E NE N ``` **Maps must be unique**, don't generate the same map for different inputs. * Input is an integer corresponding to the days between now and your forecast (e.g. 1 is tomorrow's forecast, 365 is a year's time). * Output is the map as an image. * Output should be reproducible, the same input will always give the same output * You must give unique maps for at least 8 years - i.e. no identical output for any input between 1 and 2920 (I'm ignoring leap years). * There is no defined output for any input greater than 2920. The winning submission will produce valid maps (up to day 2920) with the fewest bytes of source code. [Answer] # Matlab (182\*) It is assumed that the input is stored in `n`. hen looking at the algorithm, it is not sure that the results will be unique, but I checked for `n=1 upto 3000` that they are unique and satisfy the rules. I basically just use complex numbers of the unit circle and 'smoothen' them by conv2 with a gaussian filter. After that they get 'rounded' to the 8 possible directions. \*I know no way how to scale the output to a certain number of pixels, so that has to be done manually=/ *EDIT: I just discovered that there are cases where my checking program didn't recognise wrong solutions (changes by more than 1 step), but I am trying to find another solution.* Input: ``` n = 1 ``` Code: ``` rand('seed',0); for x=1:n b = exp(1i*rand(8)*2*pi); end for k=1:12 b = conv2(b,[1,2,1]'*[1,2,1],'same');b=b./abs(b); end c = exp(1i*round(angle(b)*4/pi)*pi/4)/3; quiver(real(c),imag(c)); ``` ![vector field](https://i.stack.imgur.com/xqrLC.png) [Answer] ## Mathematica, ~~116~~ 115 bytes ``` f@n_:=Graphics[Array[(d=n~BitGet~#;Arrow@{1+{w=15#~Mod~8+6.5d,h=15Floor[#/8]},14+{w-13d,h}})&,64,0],ImageSize->120] ``` I suppose a good horse never jumps higher than it has to. 2920 different grids are very easily achieved with using only two directions (I'm using `N` and `NE`), which makes satisfying the continuity rule trivial. I'm simply choosing between N and NE based on the bits of `n`, so this will actually produce 264 different wind maps. Here are the first ten maps: ![enter image description here](https://i.stack.imgur.com/KsN3I.png) PS: My original idea was to enumerate all 84 combinations for the 4 corners and "linearly" interpolation the rest of the grid. That probably would have resulted in nicer maps, but this is code golf after all, so I went with the what fulfils the minimum requirements. [Answer] # PHP 5.4, 549 bytes Somewhat hindered by the need to define arrows as graphics, here is my PHP code: ``` <? $i=$argv[1];$p="R0lGODdhBQAFAIAAAP///wAAACwAAAAABQAFAAAC";$a=[$p."BwRiicGsDwoAOw",$p."CEQeoLfmlhQoADs",$p."CARiF8hnmGABADs",$p."CIwDBouYvGIoADs",$p."BwRil8Gs+QoAOw",$p."CIQRYcqrnkABADs",$p."CARihscYn1YBADs",$p."CAx+Bmq6HWIBADs"];$c=[$i&7,$i>>3&7,$i>>6&7,$i>>9];$m=imagecreate(120,120);imagecolorallocate($m,255,255,255);foreach($a as$_)$z[]=imagecreatefromstring(base64_decode($_));for($y=0;$y<8;$y++)for($x=0;$x<8;$x++)imagecopy($m,$z[($c[0]*(7-$x)*(7-$y)+$c[1]*$x*(7-$y)+$c[2]*(7-$x)*$y+$c[3]*$x*$y)/49%8],$x*15+5,$y*15+5,0,0,5,5);imagepng($m); ``` Takes its argument from the command line, such as: > > `php windmap.php 123` > > > This solution will use the input as the definition of the four corners. The rest of the map will be smoothly interpolated between values. It has defined results for all values from 0 to 4095, a grand total of ~11.25 years of fake forecast, which should be more than enough time to fix the weather software! Here's a GIF of all the results: ![Hot air!](https://i.stack.imgur.com/FT5zd.gif) And a ZIP containing each map can be downloaded [here](http://adamhaskell.net/misc/hotair.zip) (Small note: My domain recently expired because I wasn't paying attention. I've renewed it, but the above image and link may not work until the DNS updates) Unsquishified: ``` <?php $input = $argv[1]; $prefix = "R0lGODdhBQAFAIAAAP///wAAACwAAAAABQAFAAAC"; $arrows = [ $prefix."BwRiicGsDwoAOw", // E $prefix."CEQeoLfmlhQoADs", // NE $prefix."CARiF8hnmGABADs", // N $prefix."CIwDBouYvGIoADs", // NW $prefix."BwRil8Gs+QoAOw", // W $prefix."CIQRYcqrnkABADs", // SW $prefix."CARihscYn1YBADs", // S $prefix."CAx+Bmq6HWIBADs", // SE ]; $points = [ $input & 7, $input >> 3 & 7, $input >> 6 & 7, $input >> 9 // input beyond 0o7777 (4095) will be undefined due to lack of & 7 here ]; $img = imagecreate(120,120); imagecolorallocate($img,255,255,255); $arrowimgs = []; foreach($arrows as $src) { $arrowimgs[] = imagecreatefromstring(base64_decode($src)); } for($y=0; $y<8; $y++) { for($x=0; $x<8; $x++) { $point = ( $points[0] * (7-$x)/7 * (7-$y)/7 + $points[1] * $x /7 * (7-$y)/7 + $points[2] * (7-$x)/7 * $y /7 + $points[3] * $x /7 * $y /7 ) % 8; imagecopy($img,$arrowimgs[$point],$x*15+5,$y*15+5,0,0,5,5); } } imagepng($img,"out.png"); ``` [Answer] # BBC Basic, 83 ASCII characters, tokenised filesize 72 Download emulator at <http://www.bbcbasic.co.uk/bbcwin/bbcwin.html> ``` INPUTn:VDU23,48,516;543;4;0;23,49,783;5,9;0;0:WIDTH8FORi=1TO64PRINT;1ANDn;:n/=2NEXT ``` This is basically a port of Martin's concept, but the implementation in BBC basic is very different. I reprogram the font for the numbers `0` and `1` then output the binary digits of `n` in reverse order. Ungolfed code is below. In BBC basic you can print individual ASCII characters using the `VDU` command, but the language has a series of machine-specific codes similar to escape sequences but starting with unprintable characters. For reprogramming the font, we start with ASCII 23. Normally 8-bit values are taken, but if you use a semicolon as a separator instead of a comma, it takes 16-bit little endian values (as used in the golfed version.) ``` INPUTn VDU23,48,4,2,31,2,4,0,0,0 :REM redefine font for "0" as an east facing arrow, with an 8x8 bitmap VDU23,49,15,3,5,9,0,0,0,0 :REM redefine font for "1" as a northeast facing arrow, with an 8x8 bitmap WIDTH8 :REM set print width to 8 characters FORi=1TO64PRINT;1ANDn;:n/=2:NEXT :REM print the binary digits of n in reverse order from least significant to most significant. ``` **Output** For the numbers 0 to 7. Note that the font is not reset at the end of the program, hence the numbers 0 and 1 appear as arrows in the first two examples. ![enter image description here](https://i.stack.imgur.com/Pqh4I.png) ]
[Question] [ Consider a square n by n grid graph that looks like this. ![grid graph](https://i.stack.imgur.com/N23X2.png) **It is important to notice that this graph is 11 by 11**. At any given point a man stands at an intersection and he only ever moves vertically or horizontally by one step at a time to the next intersection. Sadly he has drunk a little too much so he chooses the direction he moves randomly from the up to 4 possible directions (up, down, left, right). This is up to 4 as if he is standing at a wall he has only 3 options of course and in a corner he only has 2. He starts in the bottom left hand corner and his goal is to get home which is the top right hand corner. The time is simply the number of steps it takes him. However, you are a malicious adversary who wants him to get home as slowly as possible. You can delete any number of edges from the graph **at any time during** during his walk. The only restriction is that you must always leave some way for him to get home and you can't delete an edge he has already used. > > The challenge is to devise as malicious an adversary as possible and > then test it on a 100 by 100 20 by 20 graph with a random drunken walker. Your > score is simply the average time it takes the random walker to get > home over 10 1000 runs. > > > You can use any language and libraries you like as long as they are freely available and easily installable in Linux. **What do I need to implement?** You should implement code for the random walker and also for the adversary and the code should be combined so that the output when run is simply the average of 1000 runs using your adversary code. The random walker code should be very simple to write as he just chooses from (x-1, y), (x+1, y), (x, y-1), and (x, y+1) making sure that none of those have been deleted or are out of range. The adversary code is of course more difficult and also needs to remember which edges the drunkard has already traversed so he doesn't try to delete any of them and to make sure there is still a route home for the drunkard, which is a little trickier to do quickly. --- **Addendum** 10 runs isn't really enough but I didn't want to punish people who managed to get really long walks. I have now increased it to 1000 due to popular request. However, if your walk is so long you can't do 1000 runs in a realistic amount of time, please just report for the maximum number of runs you can. --- **High score table for 100 by 100.** * 976124.754 by Optimizer. * 103000363.218 by Peter Taylor. --- **Edit 1.** Changed the graph size to 20 by 20 to help the running time of people's tests. I will make a new high table score for that size as people submit the scores. **High score table for 20 by 20.** ``` 230,794.38 (100k runs) by justhalf 227,934 by Sparr 213,000 (approx) by Peter Taylor 199,094.3 by stokastic 188,000 (approx) by James_pic 64,281 by Geobits ``` [Answer] # 230,794.38 on 20x20, 100k runs Latest Update: I finally built perfect dynamic 2-path solution. I said perfect since the previous version is actually not symmetric, it was easier to get longer path if the drunkard took one path over the other. The current one is symmetric, so it can get higher expected number of steps. After few trials, it seems to be around 230k, an improvement over the previous one which is about 228k. But statistically speaking those numbers are still within their huge deviation, so I don't claim that this is significantly better, but I believe this should be better than the previous version. The code is at the bottom of this post. It is updated so that it's much faster than the previous version, completing 1000 runs in 23s. Below is sample run and sample maze: ``` Perfect Walker Average: 230794.384 Max: 1514506 Min:25860 Completed in 2317.374s _ _ _ _ _ _ _ _ _ _ _ _. | | | | | | | | | | | | | | | _ _ _ _ | | | | | | | | | | | | | | | |_ _ _ _ | | | | | | | | | | | | | | | _ _ _ _| | | | | | | | | | | | | | | | |_ _ _ _ | | | | | | | | | | | | | | | _ _ _ _| | | | | | | | | | | | | | | | |_ _ _ _ | | | | | | | | | | | | | | | _ _ _ _| | | | | | | | | | | | | | |_| |_ _ _ _ | | | | | | | | | | | | | _ _ _ _ _ _| | | | | | | | | | | | | | |_ _ _ _ _ _ | | | | | | | | | | | | | _ _ _ _ _ _| | | | | | | | | | | | | | |_ _ _ _ _ _ | | | | | | | | | | | | | _ _ _ _ _ _| | | | | | |_| |_| |_| |_| |_ _ _ _ _ _ | | | | | _ _ _ _ _ _ _ _ _ _ _ _ _ _| | | | | | |_ _ _ _ _ _ _ _ _ _ _ _ _ _ | | | | | _ _ _ _ _ _ _ _ _ _ _ _ _ _| | |_| |_| |_ _ _ _ _ _ _ _ _ _ _ _ _ _ |_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _| ``` --- ### *Previous submissions* Finally I can match Sparr's result! =D Based on my previous experiments (see bottom of this post), the best strategy is to have double path and close one as the drunkard reaches any of them, and the variable comes from how good we can dynamically predict where the drunkard will go as to increase the chance of him getting into longer path. So based on my `DOUBLE_PATH` strategy, I built another one, which changes the maze (my `DOUBLE_PATH` maze was easily modifiable) depending on the drunkard movement. As he takes a path with more than one available options, I will close the paths so as to leave only two possible options (one from which he came, another the untravelled). This sounds similar to what Sparr has achieved, as the result shows. The difference with his is too small for it to be considered better, but I would say that my approach is more dynamic than him, since my maze is more modifiable than Sparr's =) The result with a sample final maze: ``` EXTREME_DOUBLE_PATH Average: 228034.89 Max: 1050816 Min:34170 Completed in 396.728s _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ | _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ | |_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ | _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _| | |_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ | _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _| | |_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ | _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _| | |_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ | _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _| | |_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ | _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _| | |_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ |_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _| _ _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ |_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ | _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _| | |_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _| _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _ _ |_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _| ``` --- ## Experiments Section The best turns out to be the same strategy as stokastic, I take pride in experimenting using various strategies and printing nice outputs :) Each of the printed maze below is the last maze *after* the drunkard has reached home, so they might be slightly different from run to run due to the randomness in the drunkard movement and dinamicity of the adversary. I'll describe each strategy: ### Single Path This is the simplest approach, which will create a single path from entry to exit. ``` SINGLE_PATH Average: 162621.612 Max: 956694 Min:14838 Completed in 149.430s _ _ _ _ _ _ _ _ _ _ | |_| |_| |_| |_| |_| |_| |_| |_| |_| | |_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _| ``` ### Island (level 0) This is an approach that tries to trap the drunkard in an almost isolated island. Doesn't work as good as I expected, but this is one of my first ideas, so I include it. There are two paths leading to the exit, and when the drunkard gets near to one of them, the adversary closes it, forcing him to find the other exit (and possibly gets trapped again in the island) ``` ISLAND Average: 74626.070 Max: 428560 Min:1528 Completed in 122.512s _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ | _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ | |_|_|_|_|_|_|_|_|_|_|_|_|_|_|_|_|_| | | |_|_|_|_|_|_|_|_|_|_|_|_|_|_|_|_|_| | | |_|_|_|_|_|_|_|_|_|_|_|_|_|_|_|_|_| | | |_|_|_|_|_|_|_|_|_|_|_|_|_|_|_|_|_| | | |_|_|_|_|_|_|_|_|_|_|_|_|_|_|_|_|_| | | |_|_|_|_|_|_|_|_|_|_|_|_|_|_|_|_|_| | | |_|_|_|_|_|_|_|_|_|_|_|_|_|_|_|_|_| | | |_|_|_|_|_|_|_|_|_|_|_|_|_|_|_|_|_| | | |_|_|_|_|_|_|_|_|_|_|_|_|_|_|_|_|_| | | |_|_|_|_|_|_|_|_|_|_|_|_|_|_|_|_|_| | | |_|_|_|_|_|_|_|_|_|_|_|_|_|_|_|_|_| | | |_|_|_|_|_|_|_|_|_|_|_|_|_|_|_|_|_| | | |_|_|_|_|_|_|_|_|_|_|_|_|_|_|_|_|_| | | |_|_|_|_|_|_|_|_|_|_|_|_|_|_|_|_|_| | | |_|_|_|_|_|_|_|_|_|_|_|_|_|_|_|_|_| | | |_|_|_|_|_|_|_|_|_|_|_|_|_|_|_|_|_| | |_|_|_|_|_|_|_|_|_|_|_|_|_|_|_|_|_|_| | |_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _| ``` ### Double Path This is the most discussed strategy, which is to have two equal length paths to the exit, and close one of them as the drunkard gets near to one of them. ``` DOUBLE_PATH Average: 197743.472 Max: 1443406 Min:21516 Completed in 308.177s _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ |_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ |_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _| _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ |_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _| _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ |_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _| _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ |_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _| _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ |_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _| _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ |_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _| _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ |_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _| _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ |_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _| _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ |_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _| ``` ### Island (level 1) Inspired by the multiple paths of island and the high walk count in single path, we connect the island to the exit and make single path maze in the island, creating in total three paths to exit, and similar to previous case, close any of the exit as the drunkard gets near. This works slightly better than pure single path, but still doesn't defeat the double path. ``` ISLAND Average: 166265.132 Max: 1162966 Min:19544 Completed in 471.982s _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ | _ _ _ _ _ _ _ _ _|_ | | |_| |_| |_| |_| |_| |_| |_| |_| | | |_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ | | _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _| | | |_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ | | _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _| | | |_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ | | _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _| | | |_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ | | _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _| | | |_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ | | _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _| | | |_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ | | _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _| | | |_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ | | _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _| | | |_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ | | _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _| | |_|_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _| ``` ### Island (level 2) Trying to expand the previous idea, I created nested island, creating in total five paths, but it doesn't seem to work that well. ``` ISLAND Average: 164222.712 Max: 927608 Min:22024 Completed in 793.591s _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ | _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ |_ | | _ _ _ _ _ _ _ _|_| | | | |_| |_| |_| |_| |_| |_| |_| | | | | |_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ | | | | _ _ _ _ _ _ _ _ _ _ _ _ _ _ _| | | | | |_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ | | | | _ _ _ _ _ _ _ _ _ _ _ _ _ _ _| | | | | |_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ | | | | _ _ _ _ _ _ _ _ _ _ _ _ _ _ _| | | | | |_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ | | | | _ _ _ _ _ _ _ _ _ _ _ _ _ _ _| | | | | |_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ | | | | _ _ _ _ _ _ _ _ _ _ _ _ _ _ _| | | | | |_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ | | | | _ _ _ _ _ _ _ _ _ _ _ _ _ _ _| | | | | |_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ | | | | _ _ _ _ _ _ _ _ _ _ _ _ _ _ _| | | |_|_|_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _| | |_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _| ``` ### Island (level 3) Noticing that double path actually works better than single path, let's make the island in double path! The result is an improvement over Island (level 1), but it still doesn't beat pure double path. For comparison, the result for double path of the size of the island is 131,134.42 moves on average. So this does add quite significant number of moves (around 40k), but not enough to beat double path. ``` ISLAND Average: 171730.090 Max: 769080 Min:29760 Completed in 587.646s _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ | _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ |_ | |_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _| | _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ | | |_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _| | | _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ | | |_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _| | | _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ | | |_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _| | | _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ | | |_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _| | | _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ | | |_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _| | | _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ | | |_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _| | | _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ | | |_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _| | | _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ | | |_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _| | |_|_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _| ``` ### Island (level 4) Again, experimenting with nested island, and again it doesn't work so well. ``` ISLAND Average: 149723.068 Max: 622106 Min:25752 Completed in 830.889s _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ | _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ |_| | | _ _ _ _ _ _ _ _ _ _ _ _ _ _ _|_| | | |_ _ _ _ _ _ _ _ _ _ _ _ _ _ | | | _ _ _ _ _ _ _| |_ _ _ _ _ _ _ | | | | |_ _ _ _ _ _ _ _ _ _ _ _ _ _| | | | | _ _ _ _ _ _ _| |_ _ _ _ _ _ _ | | | | |_ _ _ _ _ _ _ _ _ _ _ _ _ _| | | | | _ _ _ _ _ _ _| |_ _ _ _ _ _ _ | | | | |_ _ _ _ _ _ _ _ _ _ _ _ _ _| | | | | _ _ _ _ _ _ _| |_ _ _ _ _ _ _ | | | | |_ _ _ _ _ _ _ _ _ _ _ _ _ _| | | | | _ _ _ _ _ _ _| |_ _ _ _ _ _ _ | | | | |_ _ _ _ _ _ _ _ _ _ _ _ _ _| | | | | _ _ _ _ _ _ _| |_ _ _ _ _ _ _ | | | | |_ _ _ _ _ _ _ _ _ _ _ _ _ _| | | | | _ _ _ _ _ _ _| |_ _ _ _ _ _ _ | | | |_|_ _ _ _ _ _ _ _ _ _ _ _ _ _ _| | | |_|_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _| | |_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _| ``` ## Conclusion All in all, this proves that having a single long path from drunkard current position to the exit works best, which is achieved by the double path strategy, since after closing an exit, the drunkard will have to travel the maximum distance possible to get to the exit. This further hints that the basic strategy should still be double path, and we can only modify how dynamic the paths are created, which has been done by Sparr. So I believe his strategy is the way to go! ## Code ``` import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import java.util.Queue; import java.util.TreeSet; public class Walker { enum Strategy{ SINGLE_PATH, ISLAND, DOUBLE_PATH, EXTREME_DOUBLE_PATH, PERFECT_DOUBLE_PATH, } int width,height; int x,y; //walker's position int dX,dY; //destination Point[][] points; int stepCount = 0; public static void main(String[]args){ int side = 20; // runOnce(side, Strategy.EXTREME_DOUBLE_PATH, 0); runOnce(side, Strategy.PERFECT_DOUBLE_PATH, 0); // for(Strategy strategy: Strategy.values()){ // runOnce(side, strategy, 0); // } // runOnce(side, Strategy.ISLAND, 1); // runOnce(side, Strategy.ISLAND, 2); // Scanner scanner = new Scanner(System.in); // System.out.println("Enter side, strategy (SINGLE_PATH, ISLAND, DOUBLE_PATH, EXTREME_DOUBLE_PATH), and level:"); // while(scanner.hasNext()){ // side = scanner.nextInt(); // Strategy strategy = Strategy.valueOf(scanner.next()); // int level = scanner.nextInt(); // scanner.nextLine(); // runOnce(side, strategy, level); // System.out.println("Enter side, strategy (SINGLE_PATH, ISLAND, DOUBLE_PATH, EXTREME_DOUBLE_PATH), and level:"); // } // scanner.close(); } private static Walker runOnce(int side, Strategy strategy, int level) { Walker walker = null; long total = 0; int max = 0; int min = Integer.MAX_VALUE; double count = 1000; long start = System.currentTimeMillis(); for(int i=0; i<count; i++){ walker = new Walker(0,0,side,side,side-1,side-1, strategy, level, false); total += walker.stepCount; max = Math.max(walker.stepCount, max); min = Math.min(walker.stepCount, min); // System.out.println("Iteration "+i+": "+walker.stepCount); } System.out.printf("%s\nAverage: %.3f\nMax: %d\nMin:%d\n",strategy, total/count, max, min); System.out.printf("Completed in %.3fs\n", (System.currentTimeMillis()-start)/1000.0); walker.printPath(); return walker; } private void createIsland(int botLeftX, int botLeftY, int topRightX, int topRightY){ for(int i=botLeftY+1; i<topRightY; i++){ if(i>botLeftY+1) deletePath(points[botLeftX][i].right()); if(i<topRightY-1) deletePath(points[topRightX][i].left()); } for(int i=botLeftX+1; i<topRightX; i++){ if(i>botLeftX+1) deletePath(points[i][botLeftY].up()); if(i<topRightX-1) deletePath(points[i][topRightY].down()); } } private void createSinglePath(int botLeftX, int botLeftY, int topRightX, int topRightY){ for(int i=botLeftY; i<topRightY; i++){ if(i==topRightY-1 && (topRightY+1-botLeftY)%2==0){ for(int j=botLeftX; j<topRightX; j++){ if(j==topRightX-1 && (j-botLeftX)%2==0){ deletePath(points[topRightX][topRightY].down()); } else { deletePath(points[j][topRightY-1+((j-botLeftX)%2)].right()); } } } else { for(int j=botLeftX+(i-botLeftY)%2; j<topRightX+((i-botLeftY)%2); j++){ deletePath(points[j][i].up()); } } } } private void createDoublePath(int botLeftX, int botLeftY, int topRightX, int topRightY){ for(int i=botLeftY; i<topRightY; i++){ if(i>botLeftY && (width%4!=1 || i<topRightY-1)) deletePath(points[width/2-1][i].right()); if(i==topRightY-1 && (topRightY+1-botLeftY)%2==1){ for(int j=botLeftX; j<topRightX; j++){ if((j-botLeftX)%2==0 || j<topRightX-1){ deletePath(points[j][topRightY-1+((j-botLeftX)%2)].right()); } else { deletePath(points[topRightX-1][topRightY-1].right()); } } } else { if((i-botLeftY)%2==0){ for(int j=botLeftX+1; j<topRightX; j++){ deletePath(points[j][i].up()); } } else { for(int j=botLeftX; j<topRightX+1; j++){ if(j!=width/2 && j!=width/2-1){ deletePath(points[j][i].up()); } } } } } } public Walker(int startingX,int startingY, int Width, int Height, int destinationX, int destinationY, Strategy strategy, int level, boolean animate){ width = Width; height = Height; dX = destinationX; dY = destinationY; x=startingX; y=startingY; points = new Point[width][height]; for(int y=0; y<height; y++){ for(int x=0; x<width; x++){ points[x][y] = new Point(x,y); } } for(int y=0; y<height; y++){ for(int x=0; x<width; x++){ if(x<width-1) new Edge(points[x][y], points[x+1][y]); if(y<height-1) new Edge(points[x][y], points[x][y+1]); } } if(strategy == Strategy.SINGLE_PATH) createSinglePath(0,0,width-1,height-1); if(strategy == Strategy.DOUBLE_PATH) createDoublePath(0,0,width-1,height-1); List<EdgeList> edgeLists = new ArrayList<EdgeList>(); if(strategy == Strategy.ISLAND){ List<Edge> edges = new ArrayList<Edge>(); if(level==0){ createIsland(0,0,width-1,height-1); deletePath(points[width-2][height-2].right()); deletePath(points[width-2][height-2].up()); } else { for(int i=0; i<level; i++){ createIsland(i,i,width-1-i, height-1-i); } createDoublePath(level,level,width-1-level,height-1-level); for(int i=height-1; i>=height-level; i--){ edges.add(points[i-2][i].right()); edges.add(points[i][i-2].up()); edgeLists.add(new EdgeList(points[i-1][i].right(), points[i][i-1].up())); } } edges.add(points[width-1-level][height-1-level].down()); edges.add(points[width-1-level][height-1-level].left()); edgeLists.add(new EdgeList(edges.toArray(new Edge[0]))); } int[] availableVerticals = new int[height]; if(strategy == Strategy.EXTREME_DOUBLE_PATH){ for(int i=1; i<width-1; i++){ deletePath(points[i][0].up()); } availableVerticals[0] = 2; for(int i=1; i<height; i++){ availableVerticals[i] = width; } } boolean[][] available = new boolean[width][height]; if(strategy == Strategy.PERFECT_DOUBLE_PATH){ for(int x=0; x<width; x++){ for(int y=0; y<height; y++){ if(x%2==1 && y%2==1){ available[x][y] = true; } else { available[x][y] = false; } } } } // printPath(); while(!walk()){ if(animate)try{Thread.sleep(500);}catch(InterruptedException e){} if(strategy == Strategy.ISLAND){ if(x==y && (x==1 || (x>=2 && x<=level))){ if(!hasBeenWalked(points[x][x].down())){ deletePath(points[x][x].down()); } else if(!hasBeenWalked(points[x][x].left())){ deletePath(points[x][x].left()); } } } if(strategy == Strategy.EXTREME_DOUBLE_PATH){ Point cur = points[x][y]; int untravelled = 0; for(Edge edge: cur.edges) if(edge!=null && !edge.walked) untravelled++; if(untravelled>1){ if(cur.up()!=null && availableVerticals[y]>2 && !cur.up().walked){ deletePath(cur.up()); availableVerticals[y]--; } if(cur.down()!=null && !cur.down().walked){ deletePath(cur.down()); availableVerticals[y-1]--; } if(cur.up()!=null && cur.left()!=null && !cur.left().walked){ deletePath(cur.left()); deletePath(points[x][y+1].left()); } if(cur.up()!=null && cur.right()!=null && !cur.right().walked){ deletePath(cur.right()); if(y<height-1) deletePath(points[x][y+1].right()); } } } if(strategy == Strategy.PERFECT_DOUBLE_PATH){ Point cur = points[x][y]; int untravelled = 0; for(Edge edge: cur.edges) if(edge!=null && !edge.walked) untravelled++; if(x%2!=1 || y%2!=1){ if(untravelled>1){ if(cur.down()==null && hasBeenWalked(cur.right())){ if(canBeDeleted(cur.up())) deletePath(cur.up()); } if(cur.down()==null && hasBeenWalked(cur.left())){ if(x%2==0 && y%2==1 && canBeDeleted(cur.right())) deletePath(cur.right()); else if(cur.right()!=null && canBeDeleted(cur.up())) deletePath(cur.up()); } if(cur.left()==null && hasBeenWalked(cur.up())){ if(canBeDeleted(cur.right())) deletePath(cur.right()); } if(cur.left()==null && hasBeenWalked(cur.down())){ if(x%2==1 && y%2==0 && canBeDeleted(cur.up())) deletePath(cur.up()); else if (cur.up()!=null && canBeDeleted(cur.right())) deletePath(cur.right()); } } } else { if(!hasBeenWalked(cur.left())){ if(x>1 && available[x-2][y]){ if(untravelled>1){ available[x-2][y] = false; deletePath(cur.up()); } } else if(cur.up()!=null){ if(canBeDeleted(cur.left())) deletePath(cur.left()); if(canBeDeleted(points[x][y+1].left())) deletePath(points[x][y+1].left()); } } if(!hasBeenWalked(cur.down())){ if(y>1 && available[x][y-2]){ if(untravelled>1){ available[x][y-2] = false; deletePath(cur.right()); } } else if(cur.right()!=null){ if(canBeDeleted(cur.down())) deletePath(cur.down()); if(canBeDeleted(points[x+1][y].down())) deletePath(points[x+1][y].down()); } } } } if(strategy == Strategy.DOUBLE_PATH || strategy == Strategy.EXTREME_DOUBLE_PATH || strategy == Strategy.PERFECT_DOUBLE_PATH){ if(x==width-2 && y==height-1 && points[width-1][height-1].down()!=null){ deletePath(points[width-1][height-1].left()); } if(x==width-1 && y==height-2 && points[width-1][height-1].left()!=null){ deletePath(points[width-1][height-1].down()); } } else if(strategy == Strategy.ISLAND){ for(EdgeList edgeList: edgeLists){ boolean deleted = false; for(Edge edge: edgeList.edges){ if(edge.start.x == x && edge.start.y == y){ if(!hasBeenWalked(edge)){ deletePath(edge); edgeList.edges.remove(edge); if(edgeList.edges.size() == 1){ edgeLists.remove(edgeList); } deleted = true; break; } } } if(deleted) break; } } if(animate)printPath(); } } public boolean hasBeenWalked(Edge edge){ if(edge == null) return false; return edge.walked; } public boolean canBeDeleted(Edge edge){ if(edge == null) return false; return !edge.walked; } public List<Edge> getAdjacentUntravelledEdges(){ List<Edge> result = new ArrayList<Edge>(); for(Edge edge: points[x][y].edges){ if(edge!=null && !hasBeenWalked(edge)) result.add(edge); } return result; } public void printPath(){ StringBuilder builder = new StringBuilder(); for(int y=height-1; y>=0; y--){ for(int x=0; x<width; x++){ Point point = points[x][y]; if(this.x==x && this.y==y){ if(point.up()!=null) builder.append('?'); else builder.append('.'); } else { if(point.up()!=null) builder.append('|'); else builder.append(' '); } if(point.right()!=null) builder.append('_'); else builder.append(' '); } builder.append('\n'); } System.out.print(builder.toString()); } public boolean walk(){ ArrayList<Edge> possibleMoves = new ArrayList<Edge>(); Point cur = points[x][y]; for(Edge edge: cur.edges){ if(edge!=null) possibleMoves.add(edge); } int random = (int)(Math.random()*possibleMoves.size()); Edge move = possibleMoves.get(random); move.walked = true; if(move.start == cur){ x = move.end.x; y = move.end.y; } else { x = move.start.x; y = move.start.y; } stepCount++; if(x==dX && y == dY){ return true; } else { return false; } } public boolean isSolvable(){ TreeSet<Point> reachable = new TreeSet<Point>(); Queue<Point> next = new LinkedList<Point>(); next.offer(points[x][y]); reachable.add(points[x][y]); while(next.size()>0){ Point cur = next.poll(); ArrayList<Point> neighbors = new ArrayList<Point>(); if(cur.up()!=null) neighbors.add(cur.up().end); if(cur.right()!=null) neighbors.add(cur.right().end); if(cur.down()!=null) neighbors.add(cur.down().start); if(cur.left()!=null) neighbors.add(cur.left().start); for(Point neighbor: neighbors){ if(!reachable.contains(neighbor)){ if(neighbor == points[dX][dY]) return true; reachable.add(neighbor); next.offer(neighbor); } } } return false; } public boolean deletePath(Edge toDelete){ if(toDelete == null) return true; // if(toDelete.walked){ // System.err.println("Edge already travelled!"); // return false; // } int startIdx = toDelete.getStartIdx(); int endIdx = toDelete.getEndIdx(); toDelete.start.edges[startIdx] = null; toDelete.end.edges[endIdx] = null; // if(!isSolvable()){ // toDelete.start.edges[startIdx] = toDelete; // toDelete.end.edges[endIdx] = toDelete; // System.err.println("Invalid deletion!"); // return false; // } return true; } static class EdgeList{ List<Edge> edges; public EdgeList(Edge... edges){ this.edges = new ArrayList<Edge>(); this.edges.addAll(Arrays.asList(edges)); } } static class Edge implements Comparable<Edge>{ Point start, end; boolean walked; public Edge(Point start, Point end){ walked = false; this.start = start; this.end = end; this.start.edges[getStartIdx()] = this; this.end.edges[getEndIdx()] = this; if(start.compareTo(end)>0){ Point tmp = end; end = start; start = tmp; } } public Edge(int x1, int y1, int x2, int y2){ this(new Point(x1,y1), new Point(x2,y2)); } public boolean exists(){ return start.edges[getStartIdx()] != null || end.edges[getEndIdx()] != null; } public int getStartIdx(){ if(start.x == end.x){ if(start.y < end.y) return 0; else return 2; } else { if(start.x < end.x) return 1; else return 3; } } public int getEndIdx(){ if(start.x == end.x){ if(start.y < end.y) return 2; else return 0; } else { if(start.x < end.x) return 3; else return 1; } } public boolean isVertical(){ return start.x==end.x; } @Override public int compareTo(Edge o) { int result = start.compareTo(o.start); if(result!=0) return result; return end.compareTo(o.end); } } static class Point implements Comparable<Point>{ int x,y; Edge[] edges; public Point(int x, int y){ this.x = x; this.y = y; edges = new Edge[4]; } public Edge up(){ return edges[0]; } public Edge right(){ return edges[1]; } public Edge down(){ return edges[2]; } public Edge left(){ return edges[3]; } public int compareTo(Point o){ int result = Integer.compare(x, o.x); if(result!=0) return result; result = Integer.compare(y, o.y); if(result!=0) return result; return 0; } } } ``` [Answer] # 227934 (20x20) My third attempt. Uses the same general approach as @stokastic with two paths to the exit. When the walker reaches the end of one path, it closes, requiring him to return to get to the end of the other path to exit. My improvement is to generate the paths as the walker progresses, so that whichever path he is progressing further along in the first half of the process will end up being longer than the other path. ``` #include <stdio.h> #include <stdlib.h> #include <time.h> #include <math.h> #include <iostream> #define DEBUG 0 #define ROUNDS 10000 #define Y 20 #define X 20 #define H (Y*2+1) #define W (X*2+1) int maze[H][W]; int scores[ROUNDS]; int x, y; void print_maze(){ char line[W+2]; line[W+1]=0; for(int row=0;row<H;row++) { for(int col=0;col<W;col++) { switch(maze[row][col]) { case 0: line[col]=' '; break; case 1: line[col]=row%2?'-':'|'; break; case 8: line[col]=(row==y*2+1&&col==x*2+1)?'@':'?'; break; case 9: line[col]=(row==y*2+1&&col==x*2+1)?'@':'*'; break; } } line[W]='\n'; printf("%s",line); } printf("%d %d\n",y,x); } int main(){ srand (time(NULL)); long long total_turns = 0; for(int round=0;round<ROUNDS;round++) { for (int r=0;r<H;r++) { for (int c=0;c<W;c++) { maze[r][c]=0; } } maze[1][1]=9; maze[1][2]=1; maze[2][1]=1; maze[1][3]=8; maze[3][1]=8; int progress_l = 0; int progress_r = 0; int side = 0; int closed_exit = 0; x=0; y=0; if (DEBUG) print_maze(); long long turn = 0; int in = 0; while (x!=X-1||y!=Y-1) { turn++; int r = y*2+1; int c = x*2+1; int dx=0, dy=0; if (DEBUG) { std::cin>>in; switch(in) { case 0: dy=-1; dx=0; break; case 1: dy=0; dx=1; break; case 2: dy=1; dx=0; break; case 3: dy=0; dx=-1; break; default: dy=0; dx=0; break; } } else { int exits = maze[r-1][c] + maze[r][c+1] + maze[r+1][c] + maze[r][c-1]; int exit_choice = -1; do { if (rand()%exits == 0) { exit_choice = exits; break; } else { exits--; } }while(exits); --exits; if (maze[r-1][c]&&!dx&&!dy) { if (exits) { --exits; } else { dy = -1; dx = 0; } } if (maze[r][c+1]&&!dx&&!dy) { if (exits) { --exits; } else { dy = 0; dx = 1; } } if (maze[r+1][c]&&!dx&&!dy) { if (exits) { --exits; } else { dy = 1; dx = 0; } } if (maze[r][c-1]&&!dx&&!dy) { if (exits) { --exits; } else { dy = 0; dx = -1; } } } x+=dx; y+=dy; if(x==X-1 && y==Y-1) continue; if (x==0&&y==1) side=-1; if (x==1&&y==0) side=1; if (maze[y*2+1][x*2+1]==8) { // room needs another exit, maybe if (side==-1) { // left half of maze if (y==1) { // top of a column if (x%2) { // going up, turn right maze[y*2+1][x*2+2]=1; maze[y*2+1][x*2+3]=8; } else { // going right, turn down maze[y*2+2][x*2+1]=1; maze[y*2+3][x*2+1]=8; } } else if (y==Y-1) { // bottom of a column if (x%2 && x<(X-progress_r-3)) { // going right, turn up if there's room maze[y*2+0][x*2+1]=1; maze[y*2-1][x*2+1]=8; progress_l=x+1; } else { // going down or exiting, go right if (x!=X-2 or closed_exit==1) { maze[y*2+1][x*2+2]=1; maze[y*2+1][x*2+3]=8; } else { closed_exit = -1; } } } else { // in a column if (maze[y*2+0][x*2+1]) { // going down maze[y*2+2][x*2+1]=1; maze[y*2+3][x*2+1]=8; } else { // going up maze[y*2+0][x*2+1]=1; maze[y*2-1][x*2+1]=8; } } } else { // right half of maze if (y==0) { // top row if (x<X-1) { // go right maze[y*2+1][x*2+2]=1; maze[y*2+1][x*2+3]=8; } else { // go down maze[y*2+2][x*2+1]=1; maze[y*2+3][x*2+1]=8; } } else if (y==Y-2) { // heading right to the exit if (x<X-1) { // go right maze[y*2+1][x*2+2]=1; maze[y*2+1][x*2+3]=8; } else { // go down if (x!=X-1 or closed_exit==-1) { maze[y*2+2][x*2+1]=1; maze[y*2+3][x*2+1]=8; } else { closed_exit = 1; } } } else if (y==Y-3) { // bottom of a column if (x>progress_l+1) { // do we have room for another column? if (!(x%2)&&y>1) { // going left, turn up maze[y*2+0][x*2+1]=1; maze[y*2-1][x*2+1]=8; } else { // going down, turn left maze[y*2+1][x*2+0]=1; maze[y*2+1][x*2-1]=8; progress_r=X-x-1; } } else { // abort, move down to escape row maze[y*2+2][x*2+1]=1; maze[y*2+3][x*2+1]=8; } } else if (y==1) { // top of a column if (!(x%2)) { // going up, turn left maze[y*2+1][x*2+0]=1; maze[y*2+1][x*2-1]=8; } else { // going left, turn down maze[y*2+2][x*2+1]=1; maze[y*2+3][x*2+1]=8; } } else { // in a column if (maze[y*2+0][x*2+1]) { // going down maze[y*2+2][x*2+1]=1; maze[y*2+3][x*2+1]=8; } else { // going up maze[y*2+0][x*2+1]=1; maze[y*2-1][x*2+1]=8; } } } maze[y*2+1][x*2+1]=9; } if (DEBUG) print_maze(); } // print_maze(); printf("turns:%lld\n",turn); scores[round] = turn; total_turns += turn; } printf("%d rounds in a %d*%d maze\n",ROUNDS,X,Y); long long avg = total_turns/ROUNDS; printf("average: % 10lld\n",avg); long long var = 0; for(int r=0;r<ROUNDS;r++){ var += (scores[r]-avg)*(scores[r]-avg); } var/=ROUNDS; // printf("variance: %lld\n",var); int stddev=sqrt(var); printf("stddev: % 10d\n",stddev); } ``` output (with time): ``` ... turns:194750 turns:506468 turns:129684 turns:200712 turns:158664 turns:156550 turns:311440 turns:137900 turns:86948 turns:107134 turns:81806 turns:310274 100000 rounds in a 20*20 maze average: 227934 stddev: 138349 real 10m54.797s ... ``` example of my maze, with roughly equal length halves to the path, showing the left/lower path cut off from the exit (bottom right): ``` _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ | _ _ _ _ _ _ _ _ _ | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |_| |_| |_| |_| |_| | | | | | | | | | |_ _ _ _ _ _ _ _ _ _ |_| |_| |_| |_| |_ _ _ _ _ _ _ _ _ _ ! ``` PS: I am aware of a very minor improvement to this algorithm that requires more clever code to generate a different shape for the two paths, staircases instead of consistent height zig zags. [Answer] ## 135,488,307.9 for 98x98 ## 199094.3 for 20x20 I have implemented a solution that creates two paths to the finish, and closes exactly one of them once the drunkard reaches it. This simulates a path length which at the very least will be 1.5x the length of a single path from start to end. After 27 runs I hit an average of about 135 million. Unfortunately it takes several minutes per walk, so I will have to run it for the next few hours. One caveat - my double path generator only works if the size of the graph is in the form 4\*n + 2, meaning the closest I can get to 100 is 102 or 98. I am going to post results using 98, which I expect to still surpass the zigzag path method. I will work on a better pathing system later. Currently outputs results in the form of (numSteps, currentAverage) after each walk. EDIT: fixed so code now works on graph sizes that are any multiple of 2, rather than 4\*n + 2. Code: (add 'True' argument to walker constructor on line 187 for turtle drawing of the graph). ``` import random import turtle WIDTH = 20 HEIGHT = 20 L, U, R, D = 1, 2, 4, 8 def delEdge(grid, x1, y1, x2, y2): # check that coordinates are in-bounds if not (0 <= x1 < WIDTH): return False if not (0 <= y1 < HEIGHT): return False if not (0 <= x2 < WIDTH): return False if not (0 <= y2 < HEIGHT): return False # swap order such that x1 <= x2 and y1 <= y2 if x2 < x1: x2 ^= x1 x1 ^= x2 x2 ^= x1 if x2 < x1: print "Swap failure: {}, {}".format(x1, x2) if y2 < y1: y2 ^= y1 y1 ^= y2 y2 ^= y1 if y2 < y1: print "Swap failure: {}, {}".format(y1, y2) # check that only one of the deltas is = 1 dx = x2 - x1 dy = y2 - y1 if dx and dy: return False if not (dx or dy): return False if dx > 1: return False if dy > 1: return False #print "<{}, {}>, <{}, {}>".format(x1, y1, x2, y2) if dx > 0: try: grid[x1][y1].remove(R) except: pass try: grid[x2][y2].remove(L) except: pass if dy > 0: try: grid[x1][y1].remove(D) except: pass try: grid[x2][y2].remove(U) except: pass return True def newGrid(): grid = [[[] for y in xrange(HEIGHT)] for x in xrange(WIDTH)] for x in xrange(WIDTH): for y in xrange(HEIGHT): if x > 0: grid[x][y].append(L) if x < WIDTH-1: grid[x][y].append(R) if y > 0: grid[x][y].append(U) if y < HEIGHT-1: grid[x][y].append(D) return grid class walker: def __init__(self, grid, mode, draw=False): self.x = 0 self.y = 0 self.dx = WIDTH-1 self.dy = HEIGHT-1 self.grid = grid self.mode = mode self.draw = draw self.numSteps = 0 self.initGrid() def initGrid(self): if self.mode == 0: #pass if self.draw: drawGrid(grid) elif self.mode == 1: for y in xrange(HEIGHT-1): if y % 2 == 0: for x in xrange(WIDTH - 1): delEdge(grid, x, y, x, y+1) else: for x in xrange(1, WIDTH): delEdge(grid, x, y, x, y+1) if self.draw: drawGrid(grid) elif self.mode == 2: for y in xrange(HEIGHT/2): if y % 2 == 0: for x in xrange(1, WIDTH-1): delEdge(grid, x, y, x, y+1) else: for x in xrange(2, WIDTH): delEdge(grid, x, y, x, y+1) for y in xrange(HEIGHT/2, HEIGHT-1): if y%2 == 0: for x in xrange(1, WIDTH-1): delEdge(grid, x, y, x, y+1) else: for x in xrange(0, WIDTH-2): delEdge(grid, x, y, x, y+1) for y in xrange(1, HEIGHT-1): midpoint = HEIGHT/2 if HEIGHT % 4 == 0: midpoint = HEIGHT/2 + 1 if y < midpoint: delEdge(grid, 0, y, 1, y) else: delEdge(grid, WIDTH-1, y, WIDTH-2, y) if self.draw: drawGrid(grid) def walk(self): self.numSteps += 1 choices = grid[self.x][self.y] direction = random.choice(choices) #print (self.x, self.y), grid[self.x][self.y], direction if direction == L: self.x -= 1 elif direction == U: self.y -= 1 elif direction == R: self.x += 1 elif direction == D: self.y += 1 def main(self): hasBlocked = False while (self.x, self.y) != (self.dx, self.dy): #print (self.x, self.y), (self.dx, self.dy) self.walk() if self.mode == 2: if not hasBlocked: if (self.x, self.y) == (WIDTH-2, HEIGHT-1): delEdge(self.grid, WIDTH-2, HEIGHT-1, WIDTH-1, HEIGHT-1) hasBlocked = True elif (self.x, self.y) == (WIDTH-1, HEIGHT-2): delEdge(self.grid, WIDTH-1, HEIGHT-1, WIDTH-1, HEIGHT-2) hasBlocked = True return self.numSteps def drawGrid(grid): size = 3 turtle.speed(0) turtle.delay(0) turtle.ht() for x in xrange(WIDTH): for y in xrange(HEIGHT): dirs = grid[x][y] for dir in dirs: if dir == L: turtle.pu() turtle.setpos((x*4, y*4)) turtle.pd() turtle.setpos(((x-1)*4, y*4)) elif dir == R: turtle.pu() turtle.setpos((x*4, y*4)) turtle.pd() turtle.setpos(((x+1)*4, y*4)) elif dir == U: turtle.pu() turtle.setpos((x*4, y*4)) turtle.pd() turtle.setpos((x*4, (y-1)*4)) elif dir == D: turtle.pu() turtle.setpos((x*4, y*4)) turtle.pd() turtle.setpos((x*4, (y+1)*4)) turtle.mainloop() numTrials = 100 totalSteps = 0.0 i = 0 try: while i < numTrials: grid = newGrid() w = walker(grid, 2) steps = w.main() totalSteps += steps print steps, totalSteps/(i+1) i += 1 print totalSteps / numTrials except KeyboardInterrupt: print totalSteps / i ``` Raw data: (current numSteps, running average) ``` 358796490 358796490.0 49310430 204053460.0 106969130 171692016.667 71781702 146714438.0 49349086 127241367.6 40874636 112846912.333 487607888 166384194.571 56423642 152639125.5 71077302 143576700.667 101885368 139407567.4 74423642 133499937.818 265170542 144472488.167 59524778 137938048.923 86919630 134293876.143 122462528 133505119.6 69262650 129489965.25 85525556 126903823.529 161165512 128807250.667 263965384 135920836.632 128907594 135570174.5 89535930 133378067.619 97344576 131740181.636 98772132 130306788.174 140769524 130742735.5 198274280 133443997.28 95417374 131981434.846 226667006 135488307.852 ``` [Answer] ## 4-path approach, 213k The one-path approach is ![Straight line from S to E](https://i.stack.imgur.com/wSPif.png) and scores an average of `N^2`. The two-path approach is ![Loop with S and E opposite each other](https://i.stack.imgur.com/bAUcm.png) but then the first time the drunkard gets within reach of the end point, it's cut: ![Loop is cut to give a curved line from S to E](https://i.stack.imgur.com/Vtb8Q.png) It scores an average of `(N/2)^2 + N^2`. The four-path approach uses two cuts: ![Nested loops, joined in two forks, one either side of E](https://i.stack.imgur.com/d4k3F.png) ![Cut one of the forks on the E side](https://i.stack.imgur.com/tAcSW.png) ![On the other side, cut the fork on the non-E side. This leaves one convoluted path](https://i.stack.imgur.com/MQrUC.png) Assume that the outer loop is of length `xN` and the inner loop of length `(1-x)N`. For simplicity, I'll normalise to `N=1`. From start to the first cut scores an average of `(x/2)^2`. From first cut to second cut has two options, of lengths `x` and `1-x`; this gives an average of `(1-x)x^2 + x(1-x)^2 = x-x^2`. Finally the remaining path gives `1`. So the total score is `N^2 (1 + x - 3/4 x^2)`. I initially assumed that keeping the available paths of equal length at each step would be optimal, so my initial approach used `x = 1/2` giving a score of `1.3125 N^2`. But after doing the above analysis it turns out that the optimal split is given when `x = 2/3` with score `1.3333 N^2`. ``` 1000 walks with average 210505.738 in 202753ms ``` ``` 1000 walks with average 212704.626 in 205191ms ``` with code ``` import java.awt.Point; import java.util.*; // http://codegolf.stackexchange.com/q/37484/194 public class RandomWalker { private static final int SIZE = 19; private static final Point dest = new Point(SIZE, SIZE); private final Random rnd = new Random(); private Point p = new Point(0, 0); private int step = 0; private Set<Set<Point>> edges; private Map<Set<Point>, String> cuttableEdgeNames; private Set<String> cutSequences; private String cutSequence = ""; public static void main(String[] args) { long start = System.nanoTime(); long total = 0; int walks = 0; while (walks < 1000 && total < 1L << 40) { RandomWalker rw = new RandomWalker(); total += rw.walk(); walks++; } long timeTaken = System.nanoTime() - start; System.out.println(walks + " walks with average " + total / (double)walks + " in " + (timeTaken / 1000000) + "ms"); } RandomWalker() { loadMaze( "+-+ +-+ +-+ +-+ +-+ +-+ +-+-+-+-+-+-+-+", "| | | | | | | | | | | | | |", "+ + + + + + + + + + + + + +-+ +-+ +-+ +", "| | | | | | | | | | | | | | | | | | | |", "+ + + + + + + + + + + + + + + + + + + +", "| | | | | | | | | | | | | | | | | | | |", "+ + + + + + + + + + + +-+ + + + + + + +", "| | | | | | | | | | | | | | | | | |", "+ + + + + + + + + + + +-+-+ + + + + + +", "| | | | | | | | | | | | | | | | | |", "+ + + + + + + + + + + + +-+ + + + + + +", "| | | | | | | | | | | | | | | | | | | |", "+ + + + + + + + + + + + + + + + + + + +", "| | | | | | | | | | | | | | | | | | | |", "+ + + + + + + + + + + + + + + + + + + +", "| | | | | | | | | | | | | | | | | | | |", "+ + + + + + + + + + + + + + + + + + + +", "| | | | | | | | | | | | | | | | | | | |", "+ +-+ +-+ +-+ +-+ +-+ + + + + + + + + +", "| | | | | | | | | |", "+ +-+ +-+ +-+ +-+ +-+ + + + + + + + + +", "| | | | | | | | | | | | | | | | | | | |", "+ + + + + + + + + + + + + + + + + + + +", "| | | | | | | | | | | | | | | | | | | |", "+ + + + + + + + + + + + + + + + + + + +", "| | | | | | | | | | | | | | | | | | | |", "+ + + + + + + + + + + + + + + + + + + +", "| | | | | | | | | | | | | | | | | | | |", "+ + + + + + + + + + + + + + + + + + + +", "| | | | | | | | | | | | | | | | | | | |", "+ + + + + + + + + + + +-+ + + + + + + +", "| | | | | | | | | | | | | | | | | |", "+ + + + + + + + + + + +-+ + + + + + + +", "| | | | | | | | | | | | | | | | | | | d", "+ + + + + + + + + + + + + + +-+ +-+ +c+", "| | | | | | | | | | | | | | |", "+ + + + + + + + + + + + + +-+-+-+-+-+ +", "| | | | | | | | | | | | | f b", "+-+ +-+ +-+ +-+ +-+ +-+ +-+-+-+-+-+e+a+" ); cutSequences = new HashSet<String>(); cutSequences.add("ac"); cutSequences.add("ad"); cutSequences.add("be"); cutSequences.add("bf"); } private void loadMaze(String... row) { edges = new HashSet<Set<Point>>(); cuttableEdgeNames = new HashMap<Set<Point>, String>(); // Horizontal edges for (int y = 0; y <= SIZE; y++) { for (int x0 = 0; x0 < SIZE; x0++) { char ch = row[y * 2].charAt(x0 * 2 + 1); if (ch == ' ') continue; Set<Point> edge = new HashSet<Point>(); edge.add(new Point(x0, y)); edge.add(new Point(x0 + 1, y)); edges.add(edge); if (ch != '-') cuttableEdgeNames.put(edge, "" + ch); } } // Vertical edges for (int y0 = 0; y0 < SIZE; y0++) { for (int x = 0; x <= SIZE; x++) { char ch = row[y0 * 2 + 1].charAt(x * 2); if (ch == ' ') continue; Set<Point> edge = new HashSet<Point>(); edge.add(new Point(x, y0)); edge.add(new Point(x, y0 + 1)); edges.add(edge); if (ch != '|') cuttableEdgeNames.put(edge, "" + ch); } } } int walk() { while (!p.equals(dest)) { List<Point> neighbours = neighbours(p); int idx = rnd.nextInt(neighbours.size()); p = neighbours.get(idx); step++; } return step; } List<Point> neighbours(Point p) { List<Point> rv = new ArrayList<Point>(); if (p.x > 0) handlePossibleNeighbour(rv, p, new Point(p.x - 1, p.y)); if (p.x < SIZE) handlePossibleNeighbour(rv, p, new Point(p.x + 1, p.y)); if (p.y > 0) handlePossibleNeighbour(rv, p, new Point(p.x, p.y - 1)); if (p.y < SIZE) handlePossibleNeighbour(rv, p, new Point(p.x, p.y + 1)); return rv; } private void handlePossibleNeighbour(List<Point> neighbours, Point p1, Point p2) { if (edgeExists(p1, p2)) neighbours.add(p2); } private boolean edgeExists(Point p1, Point p2) { Set<Point> edge = new HashSet<Point>(); edge.add(p1); edge.add(p2); // Is it cuttable? String id = cuttableEdgeNames.get(edge); if (id != null) { String prefix = cutSequence + id; for (String seq : cutSequences) { if (seq.startsWith(prefix)) { // Cut it cutSequence = prefix; edges.remove(edge); return false; } } } return edges.contains(edge); } } ``` [Answer] I experimented with slicing the grid almost entirely across every `k` rows. This effectively converts it into something similar to a random walk on a `k` by `N * N/k` grid. The most effective option is to slice every row so that we force the drunkard to zigzag. For the 20x20 case (`SIZE=19`) I have ``` time java RandomWalker 1000 walks with average 148577.604 real 0m14.076s user 0m13.713s sys 0m0.360s ``` with code ``` import java.awt.Point; import java.util.*; // http://codegolf.stackexchange.com/q/37484/194 // This handles a simpler problem where the grid is mutilated before the drunkard starts to walk. public class RandomWalker { private static final int SIZE = 19; private final Random rnd = new Random(); public static void main(String[] args) { RandomWalker rw = new RandomWalker(); long total = 0; int walks = 0; while (walks < 1000 && total < 1L << 40) { total += rw.walk(); walks++; } System.out.println(walks + " walks with average " + total / (double)walks); } int walk() { Point dest = new Point(SIZE, SIZE); Point p = new Point(0, 0); int step = 0; while (!p.equals(dest)) { List<Point> neighbours = neighbours(p); int idx = rnd.nextInt(neighbours.size()); p = neighbours.get(idx); step++; } return step; } List<Point> neighbours(Point p) { List<Point> rv = new ArrayList<Point>(); if (p.x > 0) handlePossibleNeighbour(rv, p, new Point(p.x - 1, p.y)); if (p.x < SIZE) handlePossibleNeighbour(rv, p, new Point(p.x + 1, p.y)); if (p.y > 0) handlePossibleNeighbour(rv, p, new Point(p.x, p.y - 1)); if (p.y < SIZE) handlePossibleNeighbour(rv, p, new Point(p.x, p.y + 1)); return rv; } private void handlePossibleNeighbour(List<Point> neighbours, Point p1, Point p2) { if (edgeExists(p1, p2)) neighbours.add(p2); } private boolean edgeExists(Point p1, Point p2) { return p1.x != p2.x || p1.x == SIZE * (Math.max(p1.y, p2.y) & 1); } } ``` [Answer] # For those who don't want to reinvent the wheel Don't worry! I'll reinvent it for you :) This is in Java, by the way. I created a Walker class that deals with walking randomly. It also includes a helpful method for determining if a move is valid (if it has already been walked upon). I am assuming all of you smart people can figure out to put random numbers in for the constructor, I left it up to you so you could test certain cases. Also, just call walk() function to (you guessed it!) make the drunkard walk (randomly). I will implement canComeHome() function some other time. Preferably after I look up the best way to do that. ``` import java.util.ArrayList; import java.util.LinkedList; import java.util.Queue; import java.util.TreeSet; public class Walker { int width,height; int x,y; //walker's position (does anyone else keep thinking about zombies?!?) int dX,dY; //destination TreeSet<Edge> pathsNoLongerAvailable = new TreeSet<Edge>(); TreeSet<Edge> previouslyTraveled = new TreeSet<Edge>(); int stepCount = 0; public static void main(String[]args){ int side = 10; Walker walker = null; int total = 0; double count = 1000; for(int i=0; i<count; i++){ walker = new Walker(0,0,side,side,side-1,side-1); total += walker.stepCount; System.out.println("Iteration "+i+": "+walker.stepCount); } System.out.printf("Average: %.3f\n", total/count); walker.printPath(); } public Walker(int startingX,int startingY, int Width, int Height, int destinationX, int destinationY){ width = Width; height = Height; dX = destinationX; dY = destinationY; x=startingX; y=startingY; while(!walk()){ // Do something } } public void printPath(){ for(int i=0; i<width-1; i++){ if(!pathsNoLongerAvailable.contains(new Edge(i,height-1,i+1,height-1))){ System.out.print(" _"); } else { System.out.print(" "); } } System.out.println(); for(int i=height-2; i>=0; i--){ for(int j=0; j<2*width-1; j++){ if(j%2==0){ if(!pathsNoLongerAvailable.contains(new Edge(j/2,i,j/2,i+1))){ System.out.print("|"); } else { System.out.print(" "); } } else { if(!pathsNoLongerAvailable.contains(new Edge(j/2,i,j/2+1,i))){ System.out.print("_"); } else { System.out.print(" "); } } } System.out.println(); } } public boolean walk(){ ArrayList<int[]> possibleMoves = new ArrayList<int[]>(); if(x!=0 && !pathsNoLongerAvailable.contains(new Edge(x,y,x-1,y))){ possibleMoves.add(new int[]{-1,0}); } if(x!=width-1 && !pathsNoLongerAvailable.contains(new Edge(x,y,x+1,y))){ possibleMoves.add(new int[]{1,0}); } if(y!=0 && !pathsNoLongerAvailable.contains(new Edge(x,y,x,y-1))){ possibleMoves.add(new int[]{0,-1}); } if(y!=height-1 && !pathsNoLongerAvailable.contains(new Edge(x,y,x,y+1))){ possibleMoves.add(new int[]{0,1}); } int random = (int)(Math.random()*possibleMoves.size()); int[] move = possibleMoves.get(random); previouslyTraveled.add(new Edge(x,y,x+move[0],y+move[1])); x+=move[0]; y+=move[1]; stepCount++; if(x==dX && y == dY){ return true; } else { return false; } } public boolean isSolvable(){ TreeSet<Point> reachable = new TreeSet<Point>(); Queue<Point> next = new LinkedList<Point>(); next.offer(new Point(x,y)); reachable.add(new Point(x,y)); while(next.size()>0){ Point cur = next.poll(); int x = cur.x; int y = cur.y; ArrayList<Point> neighbors = new ArrayList<Point>(); if(x!=0 && !pathsNoLongerAvailable.contains(new Edge(x,y,x-1,y))){ neighbors.add(new Point(x-1, y)); } if(x!=width-1 && !pathsNoLongerAvailable.contains(new Edge(x,y,x+1,y))){ neighbors.add(new Point(x+1, y)); } if(y!=0 && !pathsNoLongerAvailable.contains(new Edge(x,y,x,y-1))){ neighbors.add(new Point(x, y-1)); } if(y!=height-1 && !pathsNoLongerAvailable.contains(new Edge(x,y,x,y+1))){ neighbors.add(new Point(x, y+1)); } for(Point neighbor: neighbors){ if(!reachable.contains(neighbor)){ if(neighbor.compareTo(new Point(dX, dY))==0){ return true; } reachable.add(neighbor); next.offer(neighbor); } } } return false; } public boolean hasBeenWalked(int x1, int y1, int x2, int y2){ return previouslyTraveled.contains(new Edge(x1, y1, x2, y2)); } public boolean hasBeenWalked(Edge edge){ return previouslyTraveled.contains(edge); } public void deletePath(int startX, int startY, int endX, int endY){ Edge toAdd = new Edge(startX,startY,endX,endY); if(hasBeenWalked(toAdd)){ System.out.println("Edge already travelled!"); return; } pathsNoLongerAvailable.add(toAdd); if(!isSolvable()){ pathsNoLongerAvailable.remove(toAdd); System.out.println("Invalid deletion!"); } } static class Edge implements Comparable<Edge>{ Point start, end; public Edge(int x1, int y1, int x2, int y2){ start = new Point(x1, y1); end = new Point(x2, y2); if(start.compareTo(end)>0){ Point tmp = end; end = start; start = tmp; } } @Override public int compareTo(Edge o) { int result = start.compareTo(o.start); if(result!=0) return result; return end.compareTo(o.end); } } static class Point implements Comparable<Point>{ int x,y; public Point(int x, int y){ this.x = x; this.y = y; } public int compareTo(Point o){ int result = Integer.compare(x, o.x); if(result!=0) return result; result = Integer.compare(y, o.y); if(result!=0) return result; return 0; } } } ``` [Answer] ### 64,281 **Update** since the grid was changed from 100x100 to 20x20 (1000 tests). Score on 100x100 (100 tests) was roughly 36M. While this isn't going to beat a 1D walk, I wanted to play with an idea I had. The basic idea is that the grid is split into square rooms, with only one path leading 'homeward' from each. The open path is whichever the drunk gets close to *last*, meaning he has to explore every possible exit, only to have all but one of them slammed in his face. After playing with room sizes, I came to the same conclusion as Peter, slicing it up smaller is better. The best scores come with a room size of 2. ``` Average score over 100 trials: 36051265 ``` The code is sloppy, don't mind the mess. You can flip on the `SHOW` switch and it will show an image of the paths every `SHOW_INT` steps so you can watch it in action. A completed run looks something like: ![enter image description here](https://i.stack.imgur.com/7lSFT.png) (This is the image from the previous 100x100 grid. 20x20 is just like this, but, well, smaller. Code below has been updated for new size/runs.) ``` import java.awt.Color; import java.awt.Graphics; import java.awt.Point; import java.awt.image.*; import java.util.*; import javax.swing.*; public class DrunkWalk { boolean SHOW = false; int SHOW_INT = 10; int SIZE = 20; Random rand = new Random(); Point pos; int[][] edges; int[][] wally; int[] wallx; int roomSize = 2; JFrame frame; final BufferedImage img; public static void main(String[] args){ long total=0,runs=1000; for(int i=0;i<runs;i++){ int steps = new DrunkWalk().run(); total += steps; System.out.println("("+i+") "+steps); } System.out.println("\n Average " + (total/runs) + " over " + runs + " trials."); } DrunkWalk(){ edges = new int[SIZE][SIZE]; for(int x=0;x<SIZE;x++){ for(int y=0;y<SIZE;y++){ if(x>0) edges[x][y] |= WEST; if(x+1<SIZE) edges[x][y] |= EAST; if(y>0) edges[x][y] |= NORTH; if(y+1<SIZE) edges[x][y] |= SOUTH; } } wallx = new int[SIZE/roomSize+1]; wally = new int[SIZE/roomSize+1][SIZE/roomSize+1]; pos = new Point(SIZE-1,SIZE-1); img = new BufferedImage(SIZE*6+1,SIZE*6+1, BufferedImage.TYPE_INT_RGB); frame = new JFrame(){ public void paint(Graphics g) { g.drawImage(img, 50, 50, null); } }; frame.setSize(700,700); if(SHOW) frame.show(); } void draw(){ try { Thread.sleep(200); } catch (InterruptedException e) { e.printStackTrace(); } Graphics g = img.getGraphics(); g.setColor(Color.WHITE); g.clearRect(0, 0, img.getWidth(), img.getHeight()); for(int x=0;x<SIZE;x++){ for(int y=0;y<SIZE;y++){ if((edges[x][y]&EAST)==EAST) g.drawLine(x*6, y*6, x*6+5, y*6); if((edges[x][y]&SOUTH)==SOUTH) g.drawLine(x*6, y*6, x*6, y*6+5); } } g.setColor(Color.RED); g.drawOval(pos.x*6-2, pos.y*6-2, 5, 5); g.drawOval(pos.x*6-1, pos.y*6-1, 3, 3); frame.repaint(); } int run(){ int steps = 0; Point home = new Point(0,0); while(!pos.equals(home)){ if(SHOW&&steps%SHOW_INT==0){ System.out.println(steps); draw(); } step(); adversary(); steps++; } if(SHOW) draw(); return steps; } void adversary(){ int rx = pos.x / roomSize; int ry = pos.y / roomSize; int maxWalls = roomSize - 1; if(wally[rx][ry] < maxWalls){ if(pos.y%roomSize==0) if(delete(pos.x,pos.y,NORTH)) wally[rx][ry]++; } maxWalls = SIZE-1; if(pos.x%roomSize==0){ if(wallx[rx] < maxWalls) if(delete(pos.x, pos.y,WEST)) wallx[rx]++; } } void step(){ List<Integer> choices = getNeighbors(pos); Collections.shuffle(choices); int dir = choices.get(0); pos.x += dir==WEST?-1:dir==EAST?1:0; pos.y += dir==NORTH?-1:dir==SOUTH?1:0; } boolean delete(int x, int y, int dir){ if((edges[x][y] & dir) != dir) return false; edges[x][y] -= dir; if(dir == NORTH) if(y>0) edges[x][y-1] -= SOUTH; if(dir == SOUTH) if(y+1<SIZE) edges[x][y+1] -= NORTH; if(dir == EAST) if(x+1<SIZE) edges[x+1][y] -= WEST; if(dir == WEST) if(x>0) edges[x-1][y] -= EAST; return true; } List<Integer> getNeighbors(Point p){ if(p.x==SIZE || p.y==SIZE){ System.out.println("wtf"); System.exit(0); } List<Integer> choices = new ArrayList<Integer>(); if((edges[p.x][p.y] & NORTH) == NORTH) choices.add(NORTH); if((edges[p.x][p.y] & SOUTH) == SOUTH) choices.add(SOUTH); if((edges[p.x][p.y] & EAST) == EAST) choices.add(EAST); if((edges[p.x][p.y] & WEST) == WEST) choices.add(WEST); return choices; } final static int NORTH=1,EAST=2,SOUTH=4,WEST=8; } ``` [Answer] # 188k, with 2 paths The best entries all seem to take the approach of generating 2 paths, and then cutting one off when the drunk nears the end of the path. I don't think I can beat justhalf's entry, but I couldn't help but wonder: Why 2 paths? Why not 3, or 5, or 20? **TL;DR**: 2 paths seems to be optimal So I did an experiment. Based on Stretch Maniac's framework, I wrote an entry to test various numbers of paths. You can tweak the `featureSize` parameter to vary the number of paths. A `featureSize` of 20 give 1 path, 10 gives 2 paths, 7 gives 3, 5 gives 4, and so on. ``` import java.util.ArrayList; import java.util.BitSet; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.Objects; import java.util.Queue; import java.util.Set; import java.util.concurrent.ThreadLocalRandom; public class Walker { final int width,height; int x,y; //walker's position (does anyone else keep thinking about zombies?!?) final int dX,dY; //destination final int featureSize; Set<Edge> pathsNoLongerAvailable = new HashSet<>(); Set<Edge> previouslyTraveled = new HashSet<>(); int stepCount = 0; private final BitSet remainingExits; public static void main(String[]args){ int side = 20; Walker walker = null; int total = 0; int featureSize = 10; double count = 1000; for(int i=0; i<count; i++){ walker = new Walker(0,0,side,side,side-1,side-1, featureSize); total += walker.stepCount; System.out.println("Iteration "+i+": "+walker.stepCount); } System.out.printf("Average: %.3f\n", total/count); walker.printPath(); } public Walker(int startingX,int startingY, int Width, int Height, int destinationX, int destinationY, int featureSize){ width = Width; height = Height; dX = destinationX; dY = destinationY; x=startingX; y=startingY; this.featureSize = featureSize; deleteBars(); remainingExits = new BitSet(); for (int yy = 0; yy < height; yy++) { if (!pathsNoLongerAvailable.contains(new Edge(width - 2, yy, width - 1, yy))) { remainingExits.set(yy); } } while(!walk()){ if (x == width - 2 && remainingExits.get(y) && remainingExits.cardinality() > 1) { deletePath(x, y, x + 1, y); remainingExits.set(y, false); } } } private void deleteBars() { for (int xx = 0; xx < width - 1; xx++) { for (int yy = 0; yy < height / featureSize + 1; yy++) { if (xx != 0) deletePath(xx, featureSize * yy + featureSize - 1, xx, featureSize * yy + featureSize); boolean parity = xx % 2 == 0; if (yy == 0) parity ^= true; // First path should be inverted for (int i = 0; i < featureSize && featureSize * yy + i < height; i++) { if (i == 0 && !parity) continue; if ((i == featureSize - 1 || featureSize * yy + i == height - 1) && parity) continue; deletePath(xx, featureSize * yy + i, xx + 1, featureSize * yy + i); } } } } public void printPath(){ for(int i=0; i<width-1; i++){ if(!pathsNoLongerAvailable.contains(new Edge(i,height-1,i+1,height-1))){ System.out.print(" _"); } else { System.out.print(" "); } } System.out.println(); for(int i=height-2; i>=0; i--){ for(int j=0; j<2*width-1; j++){ if(j%2==0){ if(!pathsNoLongerAvailable.contains(new Edge(j/2,i,j/2,i+1))){ System.out.print("|"); } else { System.out.print(" "); } } else { if(!pathsNoLongerAvailable.contains(new Edge(j/2,i,j/2+1,i))){ System.out.print("_"); } else { System.out.print(" "); } } } System.out.println(); } } public boolean walk(){ ArrayList<int[]> possibleMoves = new ArrayList<int[]>(); if(x!=0 && !pathsNoLongerAvailable.contains(new Edge(x,y,x-1,y))){ possibleMoves.add(new int[]{-1,0}); } if(x!=width-1 && !pathsNoLongerAvailable.contains(new Edge(x,y,x+1,y))){ possibleMoves.add(new int[]{1,0}); } if(y!=0 && !pathsNoLongerAvailable.contains(new Edge(x,y,x,y-1))){ possibleMoves.add(new int[]{0,-1}); } if(y!=height-1 && !pathsNoLongerAvailable.contains(new Edge(x,y,x,y+1))){ possibleMoves.add(new int[]{0,1}); } int random = ThreadLocalRandom.current().nextInt(possibleMoves.size()); int[] move = possibleMoves.get(random); previouslyTraveled.add(new Edge(x,y,x+move[0],y+move[1])); x+=move[0]; y+=move[1]; stepCount++; if(x==dX && y == dY){ return true; } else { return false; } } public boolean isSolvable(){ Set<Point> reachable = new HashSet<>(); Queue<Point> next = new LinkedList<>(); next.offer(new Point(x,y)); reachable.add(new Point(x,y)); while(next.size()>0){ Point cur = next.poll(); int x = cur.x; int y = cur.y; ArrayList<Point> neighbors = new ArrayList<>(); if(x!=0 && !pathsNoLongerAvailable.contains(new Edge(x,y,x-1,y))){ neighbors.add(new Point(x-1, y)); } if(x!=width-1 && !pathsNoLongerAvailable.contains(new Edge(x,y,x+1,y))){ neighbors.add(new Point(x+1, y)); } if(y!=0 && !pathsNoLongerAvailable.contains(new Edge(x,y,x,y-1))){ neighbors.add(new Point(x, y-1)); } if(y!=height-1 && !pathsNoLongerAvailable.contains(new Edge(x,y,x,y+1))){ neighbors.add(new Point(x, y+1)); } for(Point neighbor: neighbors){ if(!reachable.contains(neighbor)){ if(neighbor.compareTo(new Point(dX, dY))==0){ return true; } reachable.add(neighbor); next.offer(neighbor); } } } return false; } public boolean hasBeenWalked(int x1, int y1, int x2, int y2){ return previouslyTraveled.contains(new Edge(x1, y1, x2, y2)); } public boolean hasBeenWalked(Edge edge) { return previouslyTraveled.contains(edge); } public void deletePath(int startX, int startY, int endX, int endY){ Edge toAdd = new Edge(startX,startY,endX,endY); if(hasBeenWalked(toAdd)){ System.out.println("Edge already travelled!"); return; } pathsNoLongerAvailable.add(toAdd); if(!isSolvable()){ pathsNoLongerAvailable.remove(toAdd); System.out.println("Invalid deletion!"); } } public static class Edge implements Comparable<Edge>{ Point start, end; public Edge(int x1, int y1, int x2, int y2){ start = new Point(x1, y1); end = new Point(x2, y2); if(start.compareTo(end)>0){ Point tmp = end; end = start; start = tmp; } } @Override public int compareTo(Edge o) { int result = start.compareTo(o.start); if(result!=0) return result; return end.compareTo(o.end); } @Override public String toString() { return start.toString() + "-" + end.toString(); } @Override public int hashCode() { int hash = 7; hash = 83 * hash + Objects.hashCode(this.start); hash = 83 * hash + Objects.hashCode(this.end); return hash; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Edge other = (Edge) obj; if (!Objects.equals(this.start, other.start)) { return false; } if (!Objects.equals(this.end, other.end)) { return false; } return true; } } static class Point implements Comparable<Point>{ int x,y; public Point(int x, int y){ this.x = x; this.y = y; } public int compareTo(Point o){ int result = Integer.compare(x, o.x); if(result!=0) return result; result = Integer.compare(y, o.y); if(result!=0) return result; return 0; } @Override public String toString() { return "(" + x + "," + y + ")"; } @Override public int hashCode() { int hash = 7; hash = 23 * hash + this.x; hash = 23 * hash + this.y; return hash; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Point other = (Point) obj; if (this.x != other.x) { return false; } if (this.y != other.y) { return false; } return true; } } } ``` There are a few optimisations that I could do but haven't, and it doesn't support any of the adaptive trickery that justhalf uses. Anyway, here's the results for various `featureSize` values: ``` 20 (1 path): 156284 10 (2 paths): 188553 7 (3 paths): 162279 5 (4 paths): 152574 4 (5 paths): 134287 3 (7 paths): 118843 2 (10 paths): 94171 1 (20 paths): 64515 ``` And here's a map with 3 paths: ``` _ _ _ _ _ _ _ _ _ | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |_| |_| |_| |_| |_| |_| |_| |_| |_| | |_ _ _ _ _ _ _ _ _ _| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |_| |_| |_| |_| |_| |_| |_| |_| |_| | | _ _ _ _ _ _ _ _ _ | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |_| |_| |_| |_| |_| |_| |_| |_| |_| | | ``` [Answer] # 131k (20x20) My first attempt was to remove all of the horizontal edges except the top and bottom row, then each time the walker reached the bottom of a column I would remove the edge ahead of him, until he had visited the bottom of every column and would finally be able to reach the exit. This resulted in an average of 1/8 as many steps as @PeterTaylor's 1d walk approach. Next I decided to try something a bit more circuitous. I have split the maze into a series of nested hollow chevrons, and require him to traverse the perimeter of each chevron at least 1.5 times. This has an average time of about 131k steps. ``` #include <stdio.h> #include <stdlib.h> #include <time.h> #include <iostream> #include <math.h> #define DEBUG 0 #define ROUNDS 10000 #define Y 20 #define X 20 #define H (Y*2+1) #define W (X*2+1) int maze[H][W]; int scores[ROUNDS]; int x, y; void print_maze(){ char line[W+2]; line[W+1]=0; for(int row=0;row<H;row++) { for(int col=0;col<W;col++) { switch(maze[row][col]) { case 0: line[col]=' '; break; case 1: line[col]=row%2?'-':'|'; break; case 9: line[col]=(row==y*2+1&&col==x*2+1)?'@':' '; break; } } line[W]='\n'; printf("%s",line); } printf("%d %d\n",y,x); } int main(){ srand (time(NULL)); long long total_turns = 0; for(int round=0;round<ROUNDS;round++) { for (int r=0;r<H;r++) { for (int c=0;c<W;c++) { if (r==0 || r==H-1 || c==0 || c==W-1) maze[r][c]=0; // edges else if (r%2) { // rows with cells and E/W paths if (c%2) maze[r][c] = 9; // col with cells else if (r==1 || r==H-2) maze[r][c]=1; // E/W path on N/Smost row else if (c>r) maze[r][c]=1; // E/W path on chevron perimeter else maze[r][c]=0; // cut path between cols } else { // rows with N/S paths if (c%2==0) maze[r][c] = 0; // empty space else if (c==1 || c==W-2) maze[r][c]=1; // N/S path on E/Wmost row else if (r>c) maze[r][c]=1; // N/S path on chevron perimeter else maze[r][c]=0; } } } int progress = 0; int first_cut = 0; x=0; y=0; if(DEBUG) print_maze(); long long turn = 0; while (x!=X-1||y!=Y-1) { if(DEBUG) std::cin.ignore(); turn++; int r = y*2+1; int c = x*2+1; int exits = maze[r-1][c] + maze[r][c+1] + maze[r+1][c] + maze[r][c-1]; int exit_choice = -1; do { if (rand()%exits == 0) { exit_choice = exits; break; } else { exits--; } }while(exits); int dx=0, dy=0; --exits; if (maze[r-1][c]&&!dx&&!dy) { if (exits) { --exits; } else { dy = -1; dx = 0; } } if (maze[r][c+1]&&!dx&&!dy) { if (exits) { --exits; } else { dy = 0; dx = 1; } } if (maze[r+1][c]&&!dx&&!dy) { if (exits) { --exits; } else { dy = 1; dx = 0; } } if (maze[r][c-1]&&!dx&&!dy) { if (exits) { --exits; } else { dy = 0; dx = -1; } } x+=dx; y+=dy; if (first_cut==0) { if(x==X-1 && y==progress*2+1) { first_cut = 1; maze[y*2+2][x*2+1]=0; } if(y==Y-1 && x==progress*2+1) { first_cut = 2; maze[y*2+1][x*2+2]=0; } } else if (first_cut==1) { if (y==Y-1 && x==progress*2) { maze[y*2+1][x*2+2]=0; progress++; first_cut=0; } else if (y==Y-2 && x==progress*2+1) { maze[y*2+2][x*2+1]=0; progress++; first_cut=0; } } else if (first_cut==2) { if (x==X-1 && y==progress*2) { maze[y*2+2][x*2+1]=0; progress++; first_cut=0; } else if (x==X-2 && y==progress*2+1) { maze[y*2+1][x*2+2]=0; progress++; first_cut=0; } } if(DEBUG) print_maze(); } // printf("turns:%lld\n",turn); scores[round] = turn; total_turns += turn; } long long avg = total_turns/ROUNDS; printf("average: % 10lld\n",avg); long long var = 0; for(int r=0;r<ROUNDS;r++){ var += (scores[r]-avg)*(scores[r]-avg); } var/=ROUNDS; // printf("variance: %lld\n",var); int stddev=sqrt(var); printf("stddev: % 10d\n",stddev); } ``` [Answer] # Do Nothing Since the man moves randomly, one might think that removing any node will only increase his chances of getting home in the long term. First, lets have a look at the one-dimensional case, this can be achieved by removing nodes until you end up with a squiggly path, without deadends or cycles, that visits (almost) every gridpoint. On an `N x N` grid the maximal length of such a path is `L = N*N - 2 + N%2` (98 for a 10x10 grid). Walking along the path can be described by a transition matrix as generated by `T1d`. ![transition matrix](https://i.stack.imgur.com/yRckq.png) (The slight asymmetry makes it hard to find an analytical solution, except for very small or infinite matrices, but we obtain a numerical solution faster than it would take to diagonalize the matrix anyway). The state vector has a single `1` at the starting position and after `K` steps `(T1d**K) * state` gives us the probability distribution of being at a certain distance from the start (that is equivalent to averaging over all `2**K` possible walks along the path!) Running the simulation for `10*L**2` steps and saving the last element of the state vector after each step which gives us the probability of having made it to the goal after a certain total number of steps - the cumulative probability distribution `cd(t)`. Differentiating it gives us the probability `p` of reaching the goal exactly at a certain time. To find the average time we integrate `t*p(t) dt` The average time to reach the goal is proportional to `L**2` with a factor that goes very quickly to 1. The standard deviation is almost constant at around 79% of the average time. This graph shows the average time to reach the goal for different path lengths (corresponding to grid sizes of 5x5 to 15x15) ![enter image description here](https://i.stack.imgur.com/fXcJ9.jpg) Here is how the probability of reaching the goal looks like. The second curve looks filled out because at every odd timestep the position is odd and therefore cannot be at the goal. ![enter image description here](https://i.stack.imgur.com/VMtHe.png) From that we can see that the balanced dual-path strategy works best here. For larger grids, where the overhead of making more paths is negligible compared to their size, we might be better off increasing the number of paths, similar to how Peter Taylor described it, but keeping the lengths balanced # What if we dont remove any nodes at all? Then we would have twice as many walkable nodes, plus four possible directions instead of two. It would seem that it makes it very unlikely to ever get anywhere. However, simulations show otherwise, after just 100 steps on a 10x10 grid the man is pretty likely to reach his goal, so trappin him in islands is a futile attempt, since you are trading a potential `N**2` long winding path with an average completion time of `N**4` for an island which is passed in `N**2` steps ![probability of a walk on 2d grid](https://i.stack.imgur.com/fy7Cc.gif) ``` from numpy import * import matplotlib.pyplot as plt def L(N): # maximal length of a path on an NxN grid return N*N - 2 + N%2 def T1d(N): # transition along 1d path m = ( diag(ones(N-1),1) + diag(ones(N-1),-1) )/2. m[1,0] = 1 m[-2,-1] = 0 m[-1,-1] = 1 return m def walk(stepmatrix, state, N): data = zeros(N) for i in xrange(N): data[i] = state[-1] state = dot(stepmatrix, state) return data def evaluate(data): rho = diff(data)/data[-1] t = arange(len(rho)) av = sum(rho*t) stdev = sum((t-av)**2 * rho)**.5 print 'average: %f\nstd: %f'%(av, stdev) return rho, av, stdev gridsize = 10 M = T1d(L(gridsize)) initpos = zeros(L(gridsize)) initpos[0] = 1 cd = walk(M, initpos, L(gridsize)**2*5) plt.subplot(2,1,1) plt.plot(cd) plt.title('p of reaching the goal after N steps') plt.subplot(2,1,2) plt.plot(evaluate(cd)[0]) plt.title('p of reaching the goal at step N') plt.show() ''' # uncomment to run the 2D simulation # /!\ WARNING /!\ generates a bunch of images, dont run on your desktop def links(k,n): x = [k-n, k+n] if k%n != 0: x.append(k-1) if k%n != n-1: x.append(k+1) x = [i for i in x if 0<= i <n*n] return x N = 10 # gridsize MM = zeros((N*N, N*N)) # build transition matrix for i in range(N*N): temp = links(i,N) for j in temp: MM[i,j] = 1./len(temp) MM[:,-1] = zeros(N*N) MM[-1,-1] = 1 pos = zeros(N*N) pos[0] = 1 for i in range(N*N): plt.imsave('grid_%.2d'%i, kron(pos.reshape((N,N)), ones((10,10))), cmap='gray') pos = dot(MM, pos) ''' ``` ]
[Question] [ Write the shortest program that generates a [histogram](https://en.wikipedia.org/wiki/Histogram) (a graphical representation of the distribution of data). **Rules:** * Must generate a histogram based on the character length of the words (punctuation included) input into the program. (If a word is 4 letters long, the bar representing the number 4 increases by 1) * Must display bar labels that correlate with the character length the bars represent. * All characters must be accepted. * If the bars must be scaled, there needs to be some way that is shown in the histogram. **Examples:** ``` $ ./histogram This is a hole in one! 1 |# 2 |## 3 | 4 |### $./histogram Extensive word length should not be very problematic. 1 | 2 |# 3 |# 4 |## 5 | 6 |## 7 | 8 | 9 |# 10| 11| 12|# ./histogram Very long strings of words should be just as easy to generate a histogram just as short strings of words are easy to generate a histogram for. 1 |## 2 |####### 3 |# 4 |####### 5 |### 6 |# 7 |## 8 |## 9 |## ``` [Answer] # R, ~~55~~ 47 characters ``` hist(a<-sapply(scan(,""),nchar),br=.5+0:max(a)) ``` Luckily R comes with a plot function `hist` for histograms, here supplied with a `breaks` argument where the breaks are 0.5, 1.5, ... until max(input)+0.5. `sapply(scan(,""),nchar)` takes an input (as stdin), separates it following the spaces and count the number of characters of each element. Examples: ``` hist(a<-sapply(scan(,""),nchar),br=.5+0:max(a)) 1: Extensive word length should not be very problematic. 9: Read 8 items ``` ![enter image description here](https://i.stack.imgur.com/zo6Sb.png) ``` hist(a<-sapply(scan(,""),nchar),br=.5+0:max(a)) 1: Very long strings of words should be just as easy to generate a histogram just as short strings of words are easy to generate a histogram for. 28: Read 27 items ``` ![enter image description here](https://i.stack.imgur.com/RjdNi.png) ### Edit: A variation at **71 characters** with an axis label at each possible value: ``` hist(a<-sapply(scan(,""),nchar),br=.5+0:max(a),ax=F);axis(1,at=1:max(a)) ``` ![enter image description here](https://i.stack.imgur.com/jL6xm.png) [Answer] ## Python - 83 characters Seems that we can take input from anywhere, so this takes input during execution, rather than from the command line, and uses Ejrb's suggestion to shorten it by 8. ``` s=map(len,raw_input().split()) c=0;exec'c+=1;print"%3d|"%c+"#"*s.count(c);'*max(s) ``` ### Python - 91 characters This will fall over with quotes. ``` import sys;s=map(len,sys.argv[1:]) for i in range(1,max(s)+1):print"%3d|"%i+'#'*s.count(i) ``` Input: ``` > python hist.py Please write a specification rather than giving a single example which, solely by virtue of being a single example, cannot express the range of acceptable output styles, and which doesnt guarantee to cover all corner cases. Its good to have a few test cases, but its even more important to have a good spec. ``` Output: ``` 1|##### 2|###### 3|##### 4|########## 5|###### 6|############# 7|#### 8|# 9|## 10|# 11| 12| 13|# ``` [Answer] ## Haskell - 126 characters ``` p[d]=[' ',d];p n=n h l=[1..maximum l]>>= \i->p(show i)++'|':(l>>=($"#").drop.abs.(i-))++"\n" main=interact$h.map length.words ``` This takes the input from `stdin`, not the command line: ``` & head -500 /usr/share/dict/words | runhaskell 15791-Histogram.hs 1|## 2|## 3|###### 4|############### 5|################################################ 6|############################################################### 7|################################################################### 8|########################################################################### 9|############################################################# 10|########################################################## 11|######################################################### 12|######################### 13|####### 14|### 15|##### 16|### 17|# 18| 19|# 20|# ``` [Answer] # K, 35 ``` {(1+!|/g)#`$(#:'=g:#:'" "\:x)#'"#"} ``` . ``` k){(1+!|/g)#`$(#:'=g:#:'" "\:x)#'"#"}"Very long strings of words should be just as easy to generate a histogram just as short strings of words are easy to generate a histogram for." 1| ## 2| ####### 3| # 4| ####### 5| ### 6| # 7| ## 8| ## 9| ## ``` . A longer example ``` k){(1+!|/g)#`$(#:'=g:#:'" "\:x)#'"#"}"Please write a specification rather than giving a single example which, solely by virtue of being a single example, cannot express the range of acceptable output styles, and which doesnt guarantee to cover all corner cases. Its good to have a few test cases, but its even more important to have a good spec." 1 | ##### 2 | ###### 3 | ####### 4 | ######## 5 | ###### 6 | ############## 7 | ### 8 | # 9 | ## 10| # 11| 12| 13| # ``` [Answer] ## APL (42) ``` ⎕ML←3⋄K,⊃⍴∘'▓'¨+⌿M∘.=K←⍳⌈/M←↑∘⍴¨I⊂⍨' '≠I←⍞ ``` Could be shorter if I could omit lines where the value is 0. Explanation: * `⎕ML←3`: set the migration level to 3 (this makes `⊂` (partition) more useful). * `I⊂⍨' '≠I←⍞`: read input, split on spaces * `M←↑∘⍴¨`: get the size of the first dimension of each item (word lengths), and store in `M` * `K←⍳⌈/M`: get the numbers from 1 to to the highest value in `M`, store in `K` * `+⌿K∘.=M`: for each value in `M`, see how many times it is contained in `K`. * `⊃⍴∘'▓'¨`: for each value in that, get a list of that many `▓`s, and format it as a matrix. * `K,`: prepend each value in `K` to each row in the matrix, giving the labels. Output: ``` ⎕ML←3⋄K,⊃⍴∘'▓'¨+⌿M∘.=K←⍳⌈/M←↑∘⍴¨I⊂⍨' '≠I←⍞ This is a hole in one! 1 ▓ 2 ▓▓ 3 4 ▓▓▓ ⎕ML←3⋄K,⊃⍴∘'▓'¨+⌿M∘.=K←⍳⌈/M←↑∘⍴¨I⊂⍨' '≠I←⍞ Very long strings of words should be just as easy to generate a histogram just as short strings of words are easy to generate a histogram for. 1 ▓▓ 2 ▓▓▓▓▓▓▓ 3 ▓ 4 ▓▓▓▓▓▓▓ 5 ▓▓▓ 6 ▓ 7 ▓▓ 8 ▓▓ 9 ▓▓ ``` [Answer] # Python 3.3 (93) ``` a=[len(i) for i in input().split()] for i in range(1,max(a)+1): print(i,'|',"#"*a.count(i)) ``` Output: (the first line is the input string) ``` Very long strings of words should be just as easy to generate a histogram just as short strings of words are easy to generate a histogram for. 1 | ## 2 | ####### 3 | # 4 | ####### 5 | ### 6 | # 7 | ## 8 | ## 9 | ## ``` It doesn't justify numbers as Lego Stormtroopr's Python solution (which is also shorter than mine), but it's my first entry ever in a golfing contest, so I might as well leave it here I guess :) [Answer] ## Perl, 56 ``` $d[y///c].='#'for@ARGV;printf"%2d|$d[$_] ",$_ for+1..$#d ``` Added @manatwork's rewrite and literal newline suggestion, thank you very much! Added @chinese\_perl\_goth's updates. Usage: save as hist.pl and run `perl hist.pl This is a test` Example output: ``` $perl ~/hist.pl This is a test of the histogram function and how it will count the number of words of specific lengths. This sentence contains a long word 'complexity'. 1|## 2|##### 3|#### 4|###### 5|## 6|# 7| 8|##### 9|# 10| 11|# ``` [Answer] ## J, 48 47 46 45 43 characters ``` (;#&'#')/"1|:((],[:+/=/)1+[:i.>./)$;._1' ', ``` Usage: ``` (;#&'#')/"1|:((],[:+/=/)1+[:i.>./)$;._1' ','Very long strings of words should be just as easy to generate a histogram just as short strings of words are easy to generate a histogram for.' ┌─┬───────┐ │1│## │ ├─┼───────┤ │2│#######│ ├─┼───────┤ │3│# │ ├─┼───────┤ │4│#######│ ├─┼───────┤ │5│### │ ├─┼───────┤ │6│# │ ├─┼───────┤ │7│## │ ├─┼───────┤ │8│## │ ├─┼───────┤ │9│## │ └─┴───────┘ ``` [Answer] # Ruby, ~~98~~ 85 ``` a=$*.group_by &:size 1.upto(a.max[0]){|i|b=a.assoc i puts"%-2i|#{b&&?#*b[1].size}"%i} ``` Not golfed much. Will golf more later. ``` c:\a\ruby>hist This is a test for the histogram thingy. yaaaaaaaaaaaay 1 |# 2 |# 3 |## 4 |## 5 | 6 | 7 |# 8 | 9 |# 10| 11| 12| 13| 14|# ``` [Answer] ## Powershell, ~~97~~ 93 ``` $a=@{};$args-split ' '|%{$a[$_.length]++};1..($a.Keys|sort)[-1]|%{"{0,-2} |"-f $_+"#"*$a[$_]} ``` Example: ``` PS Z:\> .\hist.ps1 This is an example of this program running 1 | 2 |### 3 | 4 |## 5 | 6 | 7 |### ``` [Answer] # Mathematica 97 ``` Histogram["" <> # & /@ StringCases[StringSplit[InputString[]], WordCharacter] /. a_String :> StringLength@a] ``` When I input text of the Declaration of Independence as a single string (through cut and paste, of course), the output generated was: ![declaration of independence](https://i.stack.imgur.com/hz3FM.png) [Answer] ## Forth, 201 This was fun but my Ruby submission is more competitive. ;-) ``` variable w 99 cells allot w 99 cells erase : h begin 1 w next-arg ?dup while swap drop dup w @ > if dup w ! then cells + +! repeat w @ 1+ 1 ?do i . 124 emit i cells w + @ 0 ?do 35 emit loop cr loop ; h ``` Sample run: ``` $ gforth histo.fth Forth words make for tough golfing! 1 | 2 | 3 |# 4 |# 5 |### 6 | 7 | 8 |# ``` Max word length is 99. [Answer] ## Ruby, 79 ``` (1..(w=$*.group_by &:size).max[0]).map{|i|puts"%2i|#{?#*w.fetch(i,[]).size}"%i} ``` Example run: ``` $ ruby hist.rb Histograms, histograms, every where, nor any drop to drink. 1| 2|# 3|## 4|# 5|# 6|## 7| 8| 9| 10| 11|## ``` Please see my Forth submission for a laugh. [Answer] **Ruby 1.8.7, 74** A slightly different take than the other ruby solutions: ``` i=0;$*.map{|v|v.size}.sort.map{|v|$><<(i+1..v).map{|n|" %2i:"%i=n}+['#']} ``` output: ``` ruby hist.rb `head -400 /usr/share/dict/words` 1:# 2:### 3:###### 4:############################# 5:##################################################### 6:############################################################ 7:######################################################################## 8:###################################################### 9:############################################################ 10:######################## 11:########################### 12:###### 13:##### ``` [Answer] # JavaScript (159 133) Definitely not competitive, but so far the only JavaScript solution. Thanks to @manatwork for the tip on using `String.replace`. ``` prompt(o=[]).replace(/\S+/g,function(p){o[l=p.length]=(o[l]||'')+'#'});for(i=1;i<o.length;)console.log(i+(i>9?"|":" |")+(o[i++]||"")) ``` ### Input > > Code Golf is a question and answer site for programming puzzle enthusiasts and code golfers. It's built and run by you as part of the Stack Exchange network of Q&A sites. With your help, we're working together to build a library of programming puzzles and their solutions. > > > ### Output ``` 1 |## 2 |####### 3 |######### 4 |######## 5 |###### 6 |### 7 |#### 8 |#### 9 | 10|# 11|### ``` [Answer] ## PHP, 162 ``` <?php error_reporting(0);$b=0;while($argv[$b])$c[strlen($argv[++$b])]++;for($t=1;$t<=max(array_keys($c));$t++)echo $t.'|'.($c[$t]?str_repeat('#',$c[$t]):'')."\n"; ``` Usage: ``` php histogram.php Very long strings of words should be just as easy to generate a histogram just as short strings of words are easy to generate a histogram for. 1|## 2|####### 3|# 4|####### 5|### 6|# 7|## 8|## 9|## ``` [Answer] # [8th](https://8th-dev.com/), 162 bytes **Code** ``` a:new ( args s:len nip tuck a:@ ( 0 ) execnull rot swap n:1+ a:! ) 0 argc n:1- loop a:len n:1- ( dup . "|" . a:@ ( 0 ) execnull "#" swap s:* . cr ) 1 rot loop bye ``` **Usage** ``` $ 8th histogram.8th Nel mezzo del cammin di nostra vita mi ritrovai per una selva oscura ``` **Output** ``` 1| 2|## 3|#### 4|# 5|## 6|### 7| 8|# ``` **Ungolfed code** (**SED** is Stack Effect Diagram) ``` a:new \ create an empty array ( args s:len \ length of each argument \ SED: array argument lengthOfArgument nip \ SED: array lengthOfArgument tuck \ SED: lengthOfArgument array lengthOfArgument a:@ \ get item array at "lengthOfArgument" position ( 0 ) execnull \ if null put 0 on TOS \ SED: lengthOfArgument array itemOfArray rot \ SED: array itemOfArray lengthOfArgument swap \ SED: array lengthOfArgument itemOfArray n:1+ \ increment counter for the matching length a:! \ store updated counter into array ) 0 argc n:1- loop \ loop through each argument \ print histogram a:len n:1- ( dup . "|" . a:@ ( 0 ) execnull "#" swap s:* . cr ) 1 rot loop bye \ exit program ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 28 bytes ``` Ṡz+öTT' msŀSomȯ:'|R'##oḣ▲mLw ``` [Try it online!](https://tio.run/##AWMAnP9odXNr///huaB6K8O2VFQnIG1zxYBTb23IrzonfFInIyNv4bij4paybUx3////RXh0ZW5zaXZlIHdvcmQgbGVuZ3RoIHNob3VsZCBub3QgYmUgdmVyeSBwcm9ibGVtYXRpYy4 "Husk – Try It Online") Husk is an ASCII art language. [Answer] ### Pure bash, ~~120~~ 107 bytes ``` d=$*;d=${d//[ -z]/#};for a;do((b[${#a}]++));done;e=${!b[*]};for((i=0;i++<${e##* };)){ echo $i ${d:0:b[i]};} ``` or ``` d=$* d=${d//[ -z]/#} for a;do((b[${#a}]++));done e=${!b[*]} for((i=0;i++<${e##* };)){ echo $i ${d:0:b[i]} } ``` or ``` d=$*;d=${d//[ -z]/#};for a;do((b[${#a}]++));done;e=${!b[*]} for((i=0;i++<${e##* };)){ echo $i ${d:0:b[i]};} ``` Sample: ``` ./histogram.sh Very long strings of words should be just as easy to generate a histogram just as short strings of words are easy to generate a histogram for. 1 ## 2 ####### 3 # 4 ####### 5 ### 6 # 7 ## 8 ## 9 ## ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 31 bytes ([SBCS](https://github.com/abrudz/SBCS)) Anonymous tacit prefix function. ``` (I,'#'⍴⍤0⍨1⊥⊢∘.=I←⍳⌈/)'\S+'⎕S 1 ``` [Try it online!](https://tio.run/##fc6xSgQxEAbg3qcYsYiirh7WViK4rXtY2eTcSTaSyxxJ7nRr4TgWc2ghWIuChWChT@CjzIusuwfaCMIwxcx8PyMndrespSXdtpv5jtgQnD45Pe9zeh1w88LNEy8es8Oc53ecPvh2sbclzottwcuHAgatWs2X3Nxweuvo1/sBz@/75elR14cnedEqMaxMgK4kVGQRjANyuC7WlDi@juiCmSFckS/BotOxglDR1JbgKMIIYYa@homnkcWxjOYi6@FZP7TkNITojdMBSK0ywo/u5OU0RJABUIYaIoFGh15G7B8xIZL2cvx71DEf/6ZJj/97RT4T3w "APL (Dyalog Unicode) – Try It Online") `'\S+'⎕S 1` **S**earch for runs of non-**S**pace characters, returning the length of each `(`…`)` apply the following tacit function to that list of lengths:  `⌈/` the largest number (lit. maximum reduction)  `⍳` the indices 1…that  `I←` let `I` denote that function  `⊢∘.=` equality table of word lengths vertically and possible word lengths horizontally  `1⊥` sum the columns (lit. evaluate in base 1, with each row representing a digit)  `'#'⍴⍤0⍨` use each element to reshape the hash character, then stack the results and pad  `I,` prepend the result of `I` (i.e. all the possible lengths) as an additional column on the left ]
[Question] [ Write a program that accepts HTTP requests on any port of your choice above 1024, and responds to requests on any URL of your choice with its own source code. It must work with, at least, Firefox and Chrome. The code should be delivered ~~as `text/plain`~~ *(removed requirement because none of the answers but one met it)* with no formatting. There is no restriction on the URL, except that it must not be used to encode any portion of the code; serving on the root is encouraged and likely the shortest solution, but is not required. Standard quine restrictions apply. Web server frameworks are allowed, but are considered separate languages, so, for example, a Python + Flask answer does not compete with a stdlib-only Python answer. Bonus for HTTPS support: | HTTPS | HTTP | Bonus | | --- | --- | --- | | No | Yes | None | | Yes | No | 10% | | Yes | Yes | 15% | | Yes | Redirects to HTTPS | 20% | If you do include HTTPS support, you may access the certificate by any reasonable means. [Answer] # Javascript (Node.js), 77 bytes ``` (f=x=>require('http').createServer((_,x)=>x.end(`(f=${f})()`)).listen(1e4))() ``` [Answer] # Python 3, 176 bytes ``` _='_=%r;a=%r;exec(a)';a="from socket import*;s=socket();s.bind(('',9000));s.listen()\nwhile 1:q,c=s.accept();q.send(b'HTTP/1.0\\n\\n'+(_%(_,a)).encode());q=q.recv(999)";exec(a) ``` Listens to any requests to `localhost:9000`. Only listening for one request saves 11 bytes ### 165 bytes ``` _='_=%r;a=%r;exec(a)';a="from socket import*;s=socket();s.bind(('',9000));s.listen();q,c=s.accept();q.send(b'HTTP/1.0\\n\\n'+(_%(_,a)).encode());q.recv(999)";exec(a) ``` Both browsers (Firefox 120.0 & Chromium 119.0.6045.159) seem to be happy to accept responses with no status code. ### 147 bytes (only Firefox) ``` _='_=%r;a=%r;exec(a)';a="from socket import*;s=socket();s.bind(('',9000));s.listen();q,c=s.accept();q.send((_%(_,a)).encode());q.recv(999)";exec(a) ``` Firefox still supports HTTP/0.9 ### 146 bytes (only Chromium) ``` _='_=%r;a=%r;exec(a)';a="from socket import*;s=socket();s.bind(('',9000));s.listen();s.accept()[0].send(b'HTTP\\n\\n'+(_%(_,a)).encode())";exec(a) ``` Chromium doesn't seem to require the '/1.0' part, and also doesn't care if the server closes the connection early (?) [Answer] # Python 3 + http.server, ~~134~~ 95 bytes ``` exec(b:="import os;open('.txt','w').write('exec(b:=%r)'%b);os.system('python -m http.server')") ``` Uses a simple Exec quine and writes the contents of it to `.txt` and then launches a simple webserver in the current folder via the `python -m http.server` tool. Hosts on port `8000` at `/.txt` Very rarely use Python, so it might be golfable... [![enter image description here](https://i.stack.imgur.com/BlLX6.png)](https://i.stack.imgur.com/BlLX6.png) [Answer] # Python + Flask, 151 bytes ``` from flask import*;a=Flask('');s="from flask import*;a=Flask('');s=%s\[[email protected]](/cdn-cgi/l/email-protection)('/')\ndef i():return s%%repr(s)" @a.route('/') def i():return s%repr(s) ``` Doesn't show newlines as it's `text/plain`. Visible on `localhost:5000` and/or `127.0.0.1:5000`. The obvious python and flask solution. To be executed as a flask app. For example (on windows at least), assuming the file is called `flask_app.py`: ``` > set FLASK_APP=flask_app > flask run ``` [![enter image description here](https://i.stack.imgur.com/Hp12s.png)](https://i.stack.imgur.com/Hp12s.png) [Answer] # JavaScript ([Deno](https://deno.com/)), ~~60~~ 52 bytes ``` function f(){Deno.serve(_=>new Response(f+"f()")}f() ``` [Try it at the Deno Deploy Playground!](https://dash.deno.com/playground/web-server-quine) (Outdated). Saved 5 bytes by using a `function` declaration instead of an arrow function, because Deno runs in strict mode where you need `let` in variable declarations: ``` let f=_=>…`let f=${f};f()`…;f() function f(){…f+"f()"…}f() // allowed in Node, but not in Deno: f=_=>…`f=${f};f()`…;f() ``` Here's an alternate version that doesn't use function stringifying, ~~stolen~~ slightly modified from [Don Hastings's wonderful quine](https://codegolf.stackexchange.com/a/155125/108687), for **88 bytes**: ``` let Q="let q=Q.link()[8];Deno.serve(()=>new Response(`let Q=${q+Q+q};eval(Q)`))";eval(Q) ``` [Try it at the Deno Deploy Playground!](https://dash.deno.com/playground/non-stringifying-wsquine) [Answer] # [Lua](https://www.lua.org) + [LuaSockets](https://w3.impa.br/%7Ediego/software/luasocket/home.html), 138 bytes. ``` b="t=require('socket').tcp()t:bind('*',-1)t:listen()c=t:accept()c:receive()c:send(('HTTP/1.0 200\\n\\nb=%qload(b)()'):format(b))"load(b)() ``` Stores the main code in `b` and loads it, then wraps it in `('...b=%qload(b)()'):format(b)` to quine it. The webserver listens for any TCP connection on port `65535` (-1) and just immediately dumps the bare-minimum HTTP response to it. [![enter image description here](https://i.stack.imgur.com/m3vi2.png)](https://i.stack.imgur.com/m3vi2.png) [Answer] # Racket `#lang web-server/insta`, 199 bytes ``` #lang web-server/insta (define-syntax-rule(S n f)(define n(f'(S n f))))(S start (λ (s) (λ r (response/xexpr (~a "#lang web-server/insta (define-syntax-rule(S n f)(define n(f'(S n f))))" (~s s)))))) ``` Running the program (e.g. with `racket golf.rkt` or in DrRacket) prints something like: ``` Your Web application is running at http://localhost:34163/servlets/standalone.rkt. Stop this program at any time to terminate the Web Server. ``` and automatically launches your default browser with the page. Stopping the program (e.g. with Ctrl-C or DrRacket's Stop button) prints: ``` Web Server stopped. ``` Depending on your definition of "standard library", `web-server/insta` might be part of Racket's standard library. It is included in the "main distribution" you'd download from <https://download.racket-lang.org>. ## HTTPS Only, 241 bytes ``` #lang web-server (define-syntax-rule(S s)(s'(S s)))(S (λ (s) (local-require web-server/servlet-env) (serve/servlet (λ r (response/xexpr (~a "#lang web-server (define-syntax-rule(S s)(s'(S s)))" (~s s)))) #:ssl? #t #:server-root-path "."))) ``` This uses `server-cert.pem` and `private-key.pem` from the current directory. It serves on `https://localhost:8000/servlets/standalone.rkt`. ## HTTP→HTTPS, 356 bytes ``` #lang web-server (define-syntax-rule(S s)(s'(S s)))(S (λ (s) (local-require web-server/servlet-env) (thread (λ () (serve/servlet (λ r (redirect-to "https://localhost:8443/servlets/standalone.rkt"))))) (serve/servlet (λ r (response/xexpr (~a "#lang web-server (define-syntax-rule(S s)(s'(S s)))" (~s s)))) #:port 8443 #:ssl? #t #:server-root-path "."))) ``` Same certificate configuration as above, but listens on `http://localhost:8000/servlets/standalone.rkt` and `https://localhost:8443/servlets/standalone.rkt`. ## Original: With `text/plain`, 263 bytes ``` #lang web-server/insta (define-syntax-rule (S n f) (define n (f '(S n f)))) (S start (λ (s) (λ r (response/output #:mime-type #"text/plain;charset=utf-8" (λ (o) (fprintf o "#lang web-server/insta (define-syntax-rule (S n f) (define n (f '(S n f)))) ~s" s)))))) ``` [Answer] # [PowerShell Core](https://github.com/PowerShell/PowerShell), 149 bytes ``` $f={($h=[Net.HttpListener]::new()).Prefixes.Add("http://*:9090/") $h|% s*t (($r=$h|% G*t|% R*e)|% o*).Write([byte[]]("`$f={$f}"|% t*y)) $r.Close()} ``` Run it using `&$f` Listens on port `9090` Replies only once and does not free the port [![Example output](https://i.stack.imgur.com/sUcGt.png)](https://i.stack.imgur.com/sUcGt.png) [Answer] # Bash + ncat (from nmap), 106 bytes ``` h='HTTP/2\r\n\r\n';s='h=\47%s\47;s=\47%s\47;printf $h$s $h $s|ncat -lp2222';printf $h$s $h $s|ncat -lp2222 ``` ]
[Question] [ Given a number \$n\$, you are to compute the sequence of positive numbers where for each number \$a\$, the \$n\$-times multiple \$n\cdot a\$ is missing. ### Example We always start with the sequence of all positive numbers: $$1,2,3,4,5,6,7,8,9,10,11,12,13,14,15, \dots$$ For \$n=2\$, going left-to-right, we first encounter \$1\$ and remove its double, \$2\$: $$\require{cancel}\underline{1},\!\cancel{2}\!,3,4,5,6,7,8,9,10,11,12,13,14,15, \dots$$ Next is in line is thus number \$3\$, so we remove \$6\$: $$1,\!\cancel{2}\!,\underline{3},4,5,\!\cancel{6}\!,7,8,9,10,11,12,13,14,15, \dots$$ Continuing, we remove the \$8\$ because of the \$4\$, then the \$10\$ because of the \$5\$, but *not* the \$12\$ (because the \$6\$ has already been removed), then the \$14\$ and so on: $$1,\!\cancel{2}\!,3,4,5,\!\cancel{6}\!,\underline{7},\!\cancel{8}\!,9,\!\cancel{10}\!,11,12,13,\!\cancel{14}\!,15, \dots$$ Likewise, for \$n=3\$, we get the following sequence by removing the triple of each number we encounter: $$1,2,\!\cancel{3}\!,4,5,\!\cancel{6}\!,7,8,9,10,11,\!\cancel{12}\!,13,14,\!\cancel{15}\!, \dots$$ ### Task Given a number \$n>1\$ as input, compute the respective sequence as described above. The [default rules](https://codegolf.stackexchange.com/tags/sequence/info) for [sequence](/questions/tagged/sequence "show questions tagged 'sequence'") challenges apply, meaning you can either choose to * take no further input and output the sequence indefinitely, or * take an index \$i\$ as additional input and output (zero or one indexed) + the element at this index, or + all elements of the sequence up to this index. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes in each language wins. ### Testcases ``` n=2: [1,3,4,5,7,9,11,12,13,15,16,17,19,20,21,23,25,27,28,29,31,33,35,36,37,39,41,43,44,45,47,48,49,51,52,53,55,57,59,60,61,63,64,65,67,68,69,71,73,75,76,77,79,80,81,83,84,85,87,89,91,92,93,95,97,99,100,101,103,105,107,108,109,111,112,113,115,116,117,119,121,123,124,125,127,129,131,132,133,135,137,139,140,141,143,144,145,147,148,149] n=3: [1,2,4,5,7,8,9,10,11,13,14,16,17,18,19,20,22,23,25,26,28,29,31,32,34,35,36,37,38,40,41,43,44,45,46,47,49,50,52,53,55,56,58,59,61,62,63,64,65,67,68,70,71,72,73,74,76,77,79,80,81,82,83,85,86,88,89,90,91,92,94,95,97,98,99,100,101,103,104,106,107,109,110,112,113,115,116,117,118,119,121,122,124,125,126,127,128,130,131,133] n=4: [1,2,3,5,6,7,9,10,11,13,14,15,16,17,18,19,21,22,23,25,26,27,29,30,31,32,33,34,35,37,38,39,41,42,43,45,46,47,48,49,50,51,53,54,55,57,58,59,61,62,63,65,66,67,69,70,71,73,74,75,77,78,79,80,81,82,83,85,86,87,89,90,91,93,94,95,96,97,98,99,101,102,103,105,106,107,109,110,111,112,113,114,115,117,118,119,121,122,123,125] n=5: [1,2,3,4,6,7,8,9,11,12,13,14,16,17,18,19,21,22,23,24,25,26,27,28,29,31,32,33,34,36,37,38,39,41,42,43,44,46,47,48,49,50,51,52,53,54,56,57,58,59,61,62,63,64,66,67,68,69,71,72,73,74,75,76,77,78,79,81,82,83,84,86,87,88,89,91,92,93,94,96,97,98,99,100,101,102,103,104,106,107,108,109,111,112,113,114,116,117,118,119] n=6: [1,2,3,4,5,7,8,9,10,11,13,14,15,16,17,19,20,21,22,23,25,26,27,28,29,31,32,33,34,35,36,37,38,39,40,41,43,44,45,46,47,49,50,51,52,53,55,56,57,58,59,61,62,63,64,65,67,68,69,70,71,72,73,74,75,76,77,79,80,81,82,83,85,86,87,88,89,91,92,93,94,95,97,98,99,100,101,103,104,105,106,107,108,109,110,111,112,113,115,116] n=17: [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,103,104,105,106] ``` --- For n=2, the sequence is [A003159](https://oeis.org/A003159), for n=3 [A007417](https://oeis.org/A007417), and [A171948](https://oeis.org/A171948) for n=4 when dropping the zero. [Answer] # [Haskell](https://www.haskell.org/), ~~49~~ 48 bytes ``` n%a=not$mod a n<1&&n%div a n f n=filter(n%)[1..] ``` [Try it online!](https://tio.run/##Rcy9DoIwGIXh3as4aSRpQyXgT0yM9QrcHAlDIyU0lK8KRRfuvcLkdvLk5G312BnnYqREq97X0KBbPs/kA6ektp8VxKYBqca6YIZFRVlkWRV7bUmN5j0ZehqUryk8wnAnbMFIMaQpxtZ/QetiF/yFB90ZFHkOvnSFwLycrjuUe3mQR3mSxbmq4g8 "Haskell – Try It Online") `n%a` checks if there's an even amount of base-`n` zeros at the end of `a`. Laikoni saved a byte. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~7~~ 6 bytes ``` 1ọḂ¬ɗ# ``` [Try it online!](https://tio.run/##y0rNyan8/9/w4e7ehzuaDq05OV35////xv@NDAA "Jelly – Try It Online") A full program that takes two arguments: `n` is the first and the second is the number of terms to return, starting from the first. Thanks to @JonathanAllan for saving a byte! ## Explanation ``` 1ọḂ¬ɗ# 1 ɗ# | Starting with 1, find the number of valid sequence members indicated by the second argument by testing each positive integer in turn with the following: ọ | - Find out how many times the integer can be divided by the first argument Ḃ | - Mod 2 ¬ | - Not ``` [Answer] # [JavaScript (V8)](https://v8.dev/), 41 bytes Outputs the sequence indefinitely. ``` n=>{for(k=o=[];;)o[++k]||print(o[k*n]=k)} ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNEts/ifZvs/z9auOi2/SCPbNt82OtbaWjM/Wls7O7ampqAoM69EIz86Wysv1jZbs/Z/moax5n8A "JavaScript (V8) – Try It Online") ### Commented ``` n => { // n = input for( // infinite loop: k = // k = counter, initially zero'ish o = [];; // o[] = array to store excluded integers ) // o[++k] // increment k and test o[k] || // do nothing if o[k] is truthy, otherwise: print( // o[k * n] // set o[k * n] to something truthy = k // and print k ) // } // ``` [Answer] # [Haskell](https://www.haskell.org), ~~35~~ 34 bytes ``` f[1..] f(x:r)n=x:f[y|y<-r,y/=n*x]n ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m708I7E4OzUnZ0W0km5yQYFS7NJ0BVuFmKWlJWm6FjeV0qIN9fRiudI0KqyKNPNsK6zSoitrKm10i3Qq9W3ztCpi86Aqw3ITM_OAOnMTC3wVNGLyFHTtFApKS4JLinzyFFQUijPyyxXyFLS1FZSsFJRANFhEoyQxO1XB0MAAqCRdIU9TUyHaSMdYx0THVMdMx9A8VgFi-oIFEBoA) Call with, e.g., `f[1..] 17` for \$n=17\$. Contructs the sequence as infinite list by a recursive approach. We start with the infite list `[1..] = [1,2,3,4,5,...]`. In every recursive call, we take the first element `x` from the list, add it to our output list and remove the number `n*x` from the remaining list `r` with a list comprehension before the next recursive call. *Thanks to xnor for -1 byte* [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~10~~ 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ∞ʒIвγθ0¢È ``` -1 byte thanks to *@CommandMaster*. Outputs the infinite sequence. [Try it online](https://tio.run/##ARwA4/9vc2FiaWX//@KInsqSSdCyzrPOuDDCosOI//8z) or [verify the first 100 values of all test cases](https://tio.run/##AToAxf9vc2FiaWX/dnk/IiDihpIgIj95Vf/iiJ7KkljQss6zzrgwwqLDiP990YLCoyz/WzIsMyw0LDUsMTdd). **Explanation:**" The numbers that get removed are the ones with an odd amount of trailing `0`s in their base-\$n\$ representation. For \$n=2\$ this is [A036554](https://oeis.org/A036554) and for \$n=3\$ this is [A145204](https://oeis.org/A145204). ``` ∞ # Push an infinite positive list: [1,2,3,...] ʒ # Filter it by: Iв # Convert the current number to base-input as list γ # Group equal adjacent values together θ # Pop and keep the last group 0¢ # Pop and count the amount of 0s in this last group È # Check if this count is even (so the odd ones are removed after the filter) ``` [Answer] # [><> (Fish)](https://esolangs.org/wiki/Fish), ~~29~~ 24 bytes ``` ![i](https://$ "read a character")![}](https://$ "Shifts the entire stack left or right")![l](https://$ "Push the length of the stack to the stack")![2](https://$ "Push the number (0-9)")![g](https://$ "Pop the top 2 elements then push the code value at that position")![?](https://$ "Pop 1 value of the stack, if it's 0 skip the next instruction and move forward 2 spaces.")![!](https://$ "Skip the next instruction, moving 2 spaces instead of 1")![v](https://$ "Change Cursor Direction")![>](https://$ "Change Cursor Direction") ![l](https://$ "Push the length of the stack to the stack")![:](https://$ "Duplicate the top item on the stack")![:](https://$ "Duplicate the top item on the stack")![o](https://$ "output a character")![a](https://$ "Push the number in hexadecimal (10-15)")![n](https://$ "output a number in decimal")![l](https://$ "Push the length of the stack to the stack")![/](https://$ "Reflect the cursor direction")![\](https://$ "Reflect the cursor direction")![p](https://$ "Pop a postion and a value from the stack, then write the character to that position in the code.")![2](https://$ "Push the number (0-9)")![*](https://$ "Pop 2 values of the stack then perform the given operation.")![-](https://$ "Pop 2 values of the stack then perform the given operation.")![2](https://$ "Push the number (0-9)") ``` Hover over any symbol to see what it does [Try it](https://mousetail.github.io/Fish/#eyJ0ZXh0IjoiaX1sMmc/IXY+XG5sOjpvYW5sL1xccDIqLTIiLCJpbnB1dCI6IjIiLCJzdGFjayI6IiIsInN0YWNrX2Zvcm1hdCI6Im51bWJlcnMiLCJpbnB1dF9mb3JtYXQiOiJudW1iZXJzIn0=) If the above doesn't display correctly: ``` i}l2g?!v> l::oanl/\p2*-2 ``` [![enter image description here](https://i.stack.imgur.com/FxH3G.png)](https://i.stack.imgur.com/FxH3G.png) # [><> (Fish)](https://esolangs.org/wiki/Fish), 22 bytes Works on every integer except 7 so not technically valid ``` ![i](https://$ "read a character")![r](https://$ "Reverse the stack")![l](https://$ "Push the length of the stack to the stack")![3](https://$ "Push the number (0-9)")![g](https://$ "Pop the top 2 elements then push the code value at that position")![?](https://$ "Pop 1 value of the stack, if it's 0 skip the next instruction and move forward 2 spaces.")![!](https://$ "Skip the next instruction, moving 2 spaces instead of 1")![\](https://$ "Reflect the cursor direction") ![:](https://$ "Duplicate the top item on the stack")![l](https://$ "Push the length of the stack to the stack")![2](https://$ "Push the number (0-9)")![-](https://$ "Pop 2 values of the stack then perform the given operation.")![*](https://$ "Pop 2 values of the stack then perform the given operation.")![3](https://$ "Push the number (0-9)")![p](https://$ "Pop a postion and a value from the stack, then write the character to that position in the code.")![\](https://$ "Reflect the cursor direction")![l](https://$ "Push the length of the stack to the stack")![n](https://$ "output a number in decimal")![a](https://$ "Push the number in hexadecimal (10-15)")![o](https://$ "output a character")![:](https://$ "Duplicate the top item on the stack") ``` Hover over any symbol to see what it does [Try it](https://mousetail.github.io/Fish/#eyJ0ZXh0IjoiaXJsM2c/IVxcXG46bDItKjNwXFxsbmFvOiIsImlucHV0IjoiNyIsInN0YWNrIjoiIiwic3RhY2tfZm9ybWF0IjoibnVtYmVycyIsImlucHV0X2Zvcm1hdCI6Im51bWJlcnMifQ==) [Answer] # [Ruby](https://www.ruby-lang.org/), 39 bytes ``` ->n,*r{1.step{|x|r&[x]==[]&&r<<p(x)*n}} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y5PR6uo2lCvuCS1oLqmoqZILboi1tY2OlZNrcjGpkCjQlMrr7b2f1q0Uex/AA "Ruby – Try It Online") [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 5 bytes ``` ⁰Ǒ₂)ȯ ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyIiLCIiLCLigbDHkeKCginIryIsIiIsIjMwXG4zIl0=) Ports jelly. Tbh I don't know why this works. [Answer] # [R](https://www.r-project.org), 46 bytes ``` \(n)while(F<-F+1)if(all(T-F/n))T=c(T,print(F)) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGm3Mzi4sy89Pjc0pySzIKc1GLbpaUlaboWN_ViNPI0yzMyc1I13Gx03bQNNTPTNBJzcjRCdN308zQ1Q2yTNUJ0Cooy80o03DQ1Ibq2YBinYQKVWrAAQgMA) Prints the infinite sequence of missing-multiples-of-encountered-`n`. [Answer] # [Nibbles](http://golfscript.com/nibbles/index.html), 8.5 bytes ``` |,~%,/`=`@@*@$$@~ ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m708LzMpKSe1eMESGwVjg6WlJWm6FhtrdOpUdfQTbBMcHLQcVFQc6iDiCyDU4mjjWCgTAA) ``` |,~%,/`=`@@*@$$@~ | filter ,~ each k from 1 to ∞ *@$ k * n `@@ convert to base n `= $ group into chunks of equal digits / @ last group , length % ~ modulo 2 ``` Somehow still better than 05AB1E… [Answer] # [Haskell](https://www.haskell.org), 52 bytes ``` f m i n|i`elem`m=f m(i+1)n|1>0=i:f(n*i:m)(i+1)n f[]1 ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m708I7E4OzUnZ8GCpaUlaboWN83SFHIVMhXyajITUnNScxNybYECGpnahpp5NYZ2BraZVmkaeVqZVrmaEEGudNu06FhDqG7T3MTMPAVbhdzEAl-FgqLMvBIFFRBHQaMkMTtVwdDAQEFPIV1TIdpIx1jHRMdUx0zH0DwWohnmBAA) ### Explanation A somewhat "ugly" solution using the definition of the sequence rather than observations about multiplicity of factors. ``` f m i n ``` Helper function `f` takes: `m`, a list of multiples to be excluded; `i`, the current number under consideration; and `n`, the multiplier. ``` |i`elem`m= ``` If `i` is in the list `m`: ``` f m(i+1)n ``` Recursively call `f`, incrementing `i` and leaving `m` the same. (Don't add `i` to the returned list.) ``` |1>0= ``` Otherwise: ``` i:f(n*i:m)(i+1)n ``` Prepend `i` to a recursive call in which `n*i` is prepended to `m` (and `i` is incremented, as before). ``` f[]1 ``` Our submission function starts with `m` empty and `i` equal to 1, and takes `n` as an argument. [Answer] # [Fortran (GFortran)](https://gcc.gnu.org/fortran/), 115 bytes ``` program x real::r(999)=1 n=2 i=100 do j=1,999 if(r(j)/=0)then print*,j r(j*n)=0 i=i-1 if(i<1)stop end if end do end ``` [Try it online!](https://tio.run/##JYsxDsMgEAT7ewUlWLYC6bByj0ECnEPJgS4U/j3BSTWr0Wyu0iXwduT/GKNJPSS81QmSwmvfRXvvDTpgvAOhsxZiVQXdOj1Q1qKLuaE1/ZkYmhD3ZS0w7cIG7bzQ5q6OHs58em2QOCrKP8R6YYwv "Fortran (GFortran) – Try It Online") `n` is the input number, `i` is the number of result values to be created. How it works: create an array `r` of floating point numbers (because the word `real` is shorter than the word `integer`) of an adequate size (2 \* `i` is enough) and set all numbers to 1. Iterate the array with the loop variable `j`. Because of its name, `j` is implicitly an integer in Fortran, while an `a` as in the challenge description would be a floating point number, which would not be allowed as a loop variable. If the value at the index `j` of `r` is not 0, the value is printed, the value at `j*n` is set to 0, and the count of pending numbers is decreased by one. If the count of pending numbers is 0, the program ends. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 26 bytes ``` NθNηW‹Lυη⊞υ⁺⊕↨υ⁰№×υθ⊕↨υ⁰Iυ ``` [Try it online!](https://tio.run/##dY0xDsIwDEX3nCKjIxWpsHajUyWEMnCBECwSKUlpHMPxg7ux4OFL7/8n2QdX/epS70t5cbtyvmOFzUzql4PwJ8SEGi5IJFGeLQCbQQdjtGUSGLRNTLAUXzFjafiAsyPch9GIOa9cGtxiRtq7Tao/rtykbI2iz46a/DFT7yd1HPvhnb4 "Charcoal – Try It Online") Link is to verbose version of code. Outputs the first `i` values. Explanation: ``` NθNη ``` Input `n` and `i`. ``` W‹Lυη ``` Repeat until `i` values have been found. ``` ⊞υ⁺⊕↨υ⁰№×υθ⊕↨υ⁰ ``` Push the next integer, but add 2 if the next integer appears in `n` vectorised multiplied by the list. ``` Iυ ``` Output the found values. Would be 18 bytes to output the members of the sequence between `1` and `i` inclusive: ``` NθFNF¬№×υθ⊕ι⊞υ⊕ιIυ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/98zr6C0xK80Nym1SKNQ05orLb9IQQNZUFNTASzml1@i4ZxfmleiEZKZm1qsUaqjUKipo@CZl1yUmpuaV5KaopGpCQQKAaXFGSBZNBlrroCiTKBu58TiEo1SIP//fyMuQ4P/umU5AA "Charcoal – Try It Online") Alternative 18-byte version that outputs the members of the sequence between `1` and `i` inclusive in constant memory: ``` NθIΦ⊕N¬﹪⌕⮌X⁰↨ιθ⁰¦² ``` [Try it online!](https://tio.run/##TcqxCsMgEMbxPU/heAcWTNZuLRQyNIS@gdGDCkaby5k@vrFbh2/4f/zc27LLNtY6pk@RqawLMWx47WYOSeBud4FHiNLeMTmmlZKQh3@NqNWUBZ7Zl5ibTh5edBDvBHP@NmG0utlWQasNf9y0DYi1Dl1v6uWIJw "Charcoal – Try It Online") Link is to verbose version of code. Would be 17 bytes to output the members of the sequence less than `i` (remove the `⊕`). [Answer] # [Perl 5](https://www.perl.org/).10 -n, 31 bytes ``` 1while$d{++$k}||say$d{$k*$_}=$k ``` [Try it online!](https://tio.run/##K0gtyjH9/9@wPCMzJ1UlpVpbWyW7tqamOLESyFHJ1lKJr7VVyf7/3/hffkFJZn5e8X9d3zJTPUOD/7p5AA "Perl 5 – Try It Online") Translate of @Arnaulds Javascript method above. ]
[Question] [ Part of [**Code Golf Advent Calendar 2022**](https://codegolf.meta.stackexchange.com/questions/25251/announcing-code-golf-advent-calendar-2022-event-challenge-sandbox) event. See the linked meta post for details. --- As soon as the Elves get bored with the [last week's game](https://codegolf.stackexchange.com/q/255344/78410), Bin comes up with a new game. The rules are similar, except the Elves are supposed to say the numbers that have its "left side" equal to its "right side" when written in binary. The "left" and "right" sides are defined as the first and last `floor(k/2)` bits, where `k` is the total number of bits. Some examples: * The numbers that are just two copies joined together, such as 3 (`11`), 10 (`1010`), 15 (`1111`), ... are valid. This sequence is [A020330](http://oeis.org/A020330). * 1 (`1`) is valid because its left and right parts are both empty, and as are 18 (`10010`) and 22 (`10110`) because their left and right are both `10`. * 17 (`10001`) is not valid because `10` != `01`. You can use any of [sequence](/questions/tagged/sequence "show questions tagged 'sequence'") I/O methods: * Output the corresponding sequence infinitely * Given the index `k` (may be 1- or 0-indexed), output the `k`th number in the sequence * Given `k`, output the first `k` numbers of the sequence Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins. ## Test cases ``` 1, 3, 5, 7, 10, 15, 18, 22, 27, 31, 36, 45, 54, 63, 68, 76, 85, 93, 102, 110, 119, 127, 136, 153, 170, 187, 204, 221, 238, 255, 264, 280, 297, 313, 330, 346, 363, 379, 396, 412, 429, 445, 462, 478, 495, 511, 528, 561, 594, 627, 660, 693, 726, 759, 792, 825, 858, 891, 924, 957, 990, 1023, 1040, 1072, 1105, 1137, 1170, 1202, 1235, 1267, 1300, 1332, 1365, 1397, 1430, 1462, 1495, 1527, 1560, 1592, 1625, 1657, 1690, 1722, 1755, 1787, 1820, 1852, 1885, 1917, 1950, 1982, 2015, 2047, ... ``` This sequence is not yet on OEIS. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 8 bytes ``` bI∩v≈A)ȯ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJiSeKIqXbiiYhBKcivIiwiIiwiMTgiXQ==) ``` ȯ # First N integers ------) # Where... b # Binary I # Split into two halves ∩ # Transposed A # Are all... v # Pairs... ≈ # Each all the same element? ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes ``` 1BŒHṛ"Ƒ/Ɗ# ``` [Try it online!](https://tio.run/##y0rNyan8/9/Q6egkj4c7Zysdm6h/rEv5////liYA "Jelly – Try It Online") Full program outputting the first `k` numbers in the sequence given `k` as a command-line argument. (It's worth noting that the less-fun `1BŒHZE€P$Ʋ#` is shorter if 0 is included in the sequence.) ``` 1 Ɗ# Take the first k integers counting up from 1 which satisfy: B Get the binary digits of the candidate ŒH and split them in half, with the middle going to the left. Ƒ/ Is the left half unchanged by ṛ" replacing its elements with corresponding elements of the right? ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 22 bytes ``` ≔⍘⊕N²θI÷⍘ײΦθ⊖κ²⊕⁼§θ¹0 ``` [Try it online!](https://tio.run/##TY1BCsIwEEX3niJ0lUCEttuuqq3QjQh6gZgMNZhEk0yKt4/pQuzAh794/418iCBfwuTcx6hnRw8iwhWDdjOdnAxgwSGo0t8Jz8neIVDGOGlLPOt2l0IiPYqIBcFBL1rB1nHTFiJtOTlpg2XrORngr32yn2z7bPRJmEh7nJyCz7ppClHVFVuvy7mp834xXw "Charcoal – Try It Online") Link is to verbose version of code. Outputs the `n`th value. Explanation: ``` ≔⍘⊕N²θ ``` Convert `n+1` to base 2 as a string. ``` I÷⍘ײΦθ⊖κ²⊕⁼§θ¹0 ``` Delete the second character, duplicate the result, convert back from base 2, and halve the result if the second character was a `0`. [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 67 bytes ``` .+ $*11 +`(1+)\1 $+0 01 1 1(.)(.*) 1$+1$+$1 .0$|1$ 1 01 +`10 011 1 ``` [Try it online!](https://tio.run/##FYsxDoMwEAT7ecch2Zxk3QYCyQv4BAUUFGkoopT83THa6Wb2e/w@5167tGy1ONZL@JbkeRXmQYi2VHIqfUbmDRMl7JLRXNwH3WHrahUPBkaeTMy8eKP4Aw "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: Port of my Charcoal answer. ``` .+ $*11 ``` Convert `n` to unary and add `1`. ``` +`(1+)\1 $+0 01 1 ``` Convert `n+1` to binary. ``` 1(.)(.*) 1$+1$+$1 ``` Delete the second character of the binary string and duplicate the rest, then append the second character. ``` .0$|1$ ``` If the original second character was a `0` then integer divide the binary number by `2`. (Delete the original second character in any case.) ``` 1 01 +`10 011 1 ``` Convert from binary to decimal. [Answer] # [Python](https://www.python.org), 68 bytes ``` i=1 while[(k:=bin(i)[2:])[:(j:=len(k)//2)]==k[-j:]and print(i)]:i+=1 ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3XTJtDbnKMzJzUqM1sq1skzLzNDI1o42sYjWjrTSyrGxzUvM0sjX19Y00Y21ts6N1s6xiE_NSFAqKMvNKgCpjrTK1bQ0hZkGNhBkNAA) Outputs the sequence indefinitely [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` 1BŒHw/ḂƲ# ``` A full program that accepts an integer, \$k\$, and prints a Jelly representation of the list of the first \$k\$ entries. **[Try it online!](https://tio.run/##y0rNyan8/9/Q6egkj3L9hzuajm1S/v//v6UJAA "Jelly – Try It Online")** ### How? ``` 1BŒHw/ḂƲ# - Main Link: integer, k 1 # - starting with j=1, count up and yield the first k integers for which: Ʋ - last four links as a monad - f(j): B - binary digits (j) ŒH - split into halves - e.g. [1,0,0,1,1] -> [[1,0,0],[1,1]] / - reduce by: w - first index of sublist (right) in (left) 0 : does not exist 1 : at the start -> a "left equals right" number 2 : exists but is the second sublist of that length (other outputs not possible as only two sublists of that length exist) Ḃ - modulo two -> 1 if j is a "left equals right" number else 0 ``` [Answer] # [JavaScript (V8)](https://v8.dev/), ~~54~~ ~~51~~ 48 bytes ``` for(i=j=n=2;;i=i%~-n?i+2:n*=j^=3)print(i*n+i>>j) ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNEts/j/Py2/SCPTNss2z9bI2jrTNlO1TjfPPlPbyCpPyzYrztZYs6AoM69EI1MrTzvTzi5L8/9/AA "JavaScript (V8) – Try It Online") Fast and shorter than RegEx solution and scan all [Answer] # [JavaScript (V8)](https://v8.dev/), 63 bytes (fast) Prints the sequence infinitely. ``` for(i=k=n=1;k+=q=!(n&n+1);n+=2**(k-2*q>>1)+!(k*i++&!q))print(n) ``` [Try it online!](https://tio.run/##BcFLCoAgEADQs7iR@eBCV4GMd5EgMGFSC68/vXfXXd9ztfGFfZhdz4ImXVRi7ixTHKhXjpiVJRFBD4lmKRHZQafG7N1EHKvpB4pmPw "JavaScript (V8) – Try It Online") --- # [JavaScript (V8)](https://v8.dev/), 56 bytes (slow) Prints the sequence infinitely. ``` for(n=0;;)/^(.*).?\1$/.test((++n).toString(2))&&print(n) ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNEts/j/Py2/SCPP1sDaWlM/TkNPS1PPPsZQRV@vJLW4RENDWztPU68kP7ikKDMvXcNIU1NNrQDILNHI0/z/HwA "JavaScript (V8) – Try It Online") [Answer] # [Pyth](https://github.com/isaacg1/pyth), 22 bytes ``` .V1K.BbJ.:K/lK2IqhJeJb ``` [Try it online!](https://tio.run/##K6gsyfj/Xy/M0FvPKclLz8pbP8fbyLMwwyvVK@n/fwA "Pyth – Try It Online") Prints the sequence infinitely. ``` .V1 # Run an infinite loop from 1 with b K.Bb # Initialize K as binary representation of b J.:K/lK2 # Get all substrings of len(K)/2 and set as J hJ # First value of J eJ # Last value of J Iq # If equal b # Print b ``` [Answer] # [><>](https://esolangs.org/wiki/Fish), 72 bytes ``` 1:&:1(?v:2%$2,:1%-20. ]l2%?~1\~l:2%+2,[r =?v${=*>l1 ?v\ &/v&oan: 0.>&1+0 ``` [Try it online!](https://tio.run/##S8sszvj/39BKzcpQw77MykhVxUjHylBV18hAjys2x0jVvs4wpi4HKK5tpBNdxGVrX6ZSbatll2PIZV8Ww6WmX6aWn5hnxWWgZ6dmqG3w/z8A "><> – Try It Online") [Answer] # [Pip](https://github.com/dloscutoff/pip), 20 bytes ``` W UiI0=$@?R*RCHTBiPi ``` [Try It Online!](https://dso.surge.sh/#@WyJwaXAiLCIiLCJXIFVpPG1JMD0kQD9SKlJDSFRCaVBpIiwiIiwiYWJjYWIiLCItcCJd) (Since DSO doesn't handle infinite loops well, this link outputs elements of the sequence less than 1000.) ### Explanation The fact that the `CH` builtin makes the first half shorter than the second half when chopping odd-length strings is a bit of a problem here. ``` W UiI0=$@?R*RCHTBiPi i is 0 (implicit) W Loop while Ui i incremented is truthy: TBi Convert i to binary CH Chop into two halves (if uneven, the second half is longer) R Reverse (the potentially longer second element is now first) R* Reverse each element $@? Find index of first element in second element I0= If that index is zero: Pi Print i ``` Here are some worked examples to showcase the core logic. The `@?` operator gets the index of the first occurrence of its right argument as a substring of its left argument; if it is not a substring, the operator returns nil, here represented as `()`. ``` i 10 13 18 21 TB 1010 1101 10010 10101 CH [10;10] [11;01] [10;010] [10;101] R [10;10] [01;11] [010;10] [101;10] R* [01;01] [10;11] [010;01] [101;01] $@? 0 () 0 1 0= 1 0 1 0 ``` [Answer] # [JavaScript (V8)](https://v8.dev/), 50 bytes ``` for(n=p=0;;n%(1<<p/2)^n>>-~p/2||print(n))p+=++n>>p ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNEts/j/Py2/SCPPtsDWwNo6T1XD0MamQN9IMy7Pzk63DsiqqSkoyswr0cjT1CzQttXWBooX/P8PAA "JavaScript (V8) – Try It Online") And this is [64 bytes in C](https://tio.run/##S9ZNT07@/z/POjcxM0@jQLM6Lb9Iw9o6T1XD0MamQN9IMy7Pzk63DsiqqSkoyswrSdNQUk3RUdLJ09Qs0LbV1gZKF1jX/v8PAA). Thanks jdt for -2 bytes on JS. Thanks l4m2, jdt for -3 bytes on C. [Answer] # [Pip](https://github.com/dloscutoff/pip), 43 bytes ``` W1{k:(l:TBo)^@#l//2I#l%2k@1PK0Ik@0=k@1PoUo} ``` [Try It Online!](https://dso.surge.sh/#@WyJwaXAiLCIiLCJXMXtrOihsOlRCbyleQCNsLy8ySSNsJTJrQDFQSzBJa0AwPWtAMVBvVW99IiwiIiwiIiwiLXAiXQ==) Outputs the sequence indefinitely. Won't run on the above link very well as DSO doesn't handle infinite loops well, use [this](https://dso.surge.sh/#@WyJwaXAiLCIiLCJMMjA0N3trOihsOlRCbyleQCNsLy8ySSNsJTJrQDFQSzBJa0AwPWtAMVBvVW99IiwiIiwiIiwiLXAiXQ==) to verify. Explanation: ``` k:(l:TBo)^@#l//2 ``` Converts `o` to binary, splits into two. ``` I#l%2k@1PK0 ``` If the length of the binary string is odd, remove the first element from the second half. ``` Ik@0=k@1PoUo ``` If both halves are the same, print `o`, then increment `o` [Answer] # [Husk](https://github.com/barbuz/Husk), 9 bytes ``` föΠFz=½ḋN ``` [Try it online!](https://tio.run/##yygtzv7/P@3wtnML3KpsD@19uKPb7/9/AA "Husk – Try It Online") ``` f # filter N # 1..infinity ö # with composition of 4 functions: ḋ # get list of binary digits ½ # split into list of two halves F # fold across this list z # zip the two halves together = # by equality Π # and get the product ``` [Answer] # [Nibbles](http://golfscript.com/nibbles/index.html), 9.5 bytes (19 nibbles) ``` |,~~++!;``@$>>`\~@! ``` ``` | # filter ,~ # 1..infinity ~ # for falsy results of: ++ # sum of flattened list of ! # zip together ! # getting abs differences ``@$ # bits of input ; # (and save this) # with @ # saved bits of input `\~ # split into 2 chunks >> # discarding the first chunk ``` [![enter image description here](https://i.stack.imgur.com/MCP25.png)](https://i.stack.imgur.com/MCP25.png) [Answer] # [Excel](https://www.microsoft.com/en-us/microsoft-365/excel), 75 bytes ``` =LET(x,ROW(A:A),FILTER(x,LET(b,BASE(x,2),s,LEN(b)/2,LEFT(b,s)=RIGHT(b,s)))) ``` [![enter image description here](https://i.stack.imgur.com/XL7GX.png)](https://i.stack.imgur.com/XL7GX.png) [Answer] # [Factor](https://factorcode.org) + `lists.lazy`, 46 bytes ``` [ 1 lfrom [ >bin halves swap tail? ] lfilter ] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=JYwxDsIwDEV3TuELEAETAqlMCLGwIKaqg4lcNaqbBscFlauwdIErcJbehopMf3j_vdenRKutDOP-cj6eDhtgFzUaxmcPDWplAkokgUi3jrylCDWJJ4YgpNoHcV6TA9vZavHutJyvR5PDEriUtoEcsqvzUCHfJzk-MICi4x0U08GxTu0iWV-LzMCKNf2LGYpgDybRYUj7Aw) Returns an infinite lazy list of the sequence. * `1 lfrom` the natural numbers * `[ ... ] lfilter` take the ones that... * `>bin` convert integer to binary string * `halves` split in half with the second half larger, e.g. `"101"` -> `"1" "01"` * `swap tail?` does the second half end with the first half? [Answer] # PARI/GP, 59 bytes The basic idea is `is(n)=my(v=binary(n)); v[1..#v\2]==v[(#v+3)\2..#v]`. ``` for(n=1,oo,v=binary(n);v[1..#v\2]==v[(#v+3)\2..#v]&&print(n)) ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ∞ʒ2в2äøøË ``` [Try it online!](https://tio.run/##yy9OTMpM/f//Uce8U5OMLmwyOrzk8A4g7P7/HwA "05AB1E – Try It Online") Outputs the infinite sequence. * -6, -9 thanks to Steffan * -1 thanks to Kevin Cruijssen **Explanation:** ``` ∞ʒ2в2äøøË ∞ # Get all integers (>= 1) Example for n=19 ʒ # where the following evaluates to True: 2в # The binary representation of the number 10011 2ä # Sliced into two pieces [[1, 0, 0], [1, 1]] øø # Zipped together twice [[1, 0], [1, 1]] Ë # Are they equal? 0 ``` Previous 19-byte answer: ``` ∞ʒbVYg2÷UXYs£XYs.£Q ∞ʒ # Get all integers (>= 1) where the following evaluates to True: bV # Convert to binary and save in Y Yg # Get the length of Y 2÷ # Integer-divide by 2 UX # Save this in X for later Ys£ # And get that many elements from the front of Y XYs.£ # Do the same but from the back of Y Q # Check if they are equal # (Implicit output) ``` [Answer] # x86 32-bit machine code, 21 bytes ``` 40 0F BD C8 D3 D8 72 02 D1 C8 D3 C0 89 C2 D3 E0 09 D0 D1 E8 C3 ``` [Try it online!](https://tio.run/##XVHLbsMgEDybr9i6igKxU@Wh9pBHLz330lOlpooIxjaVjSOwU6wov153yauPCzAz7OywiGEmRNfdKi2KJpGwsHWiqrv8kfyhCrX5zxmlM8@R9ZrXiDZNLddrSo3MttyUdMwYA6VrSKlfOZsTbkug8BJSks4CtALJHQk21oAULj4hI4w/xCAKEnwIsEhVZ2pM7AxR8XOhrHYgk0utzX9JlyKUvXK1CIysCQsB8xAfrORKnxKaTGBpzg0MBgh2jOxJ4BUHSxjF0PptToLPXBUSaBQ5WCxhcv/ASBBscR51SsOegjDGNzuGDa7sSj9zkSstQVSJnIVec2e7pIL95R70RpNXrG@XlDbaqkzL5BhpwFL25qLonc0PcA7Qwg06uKfp705AMcGmraVlK41O7ig2tTeh/ZXue4wjaIz23Q@k675EWvDMdsNyOsEFf2mJXrL4Bg "C (gcc) – Try It Online") Following the `regparm(1)` calling convention, this takes the 1-indexed `k` in EAX and returns the `k`th number in EAX. --- If we look at the left halves *inclusive* of the middle bit (if it exists), they form a useful pattern: **1**, **1**1, **10**1, **11**1, **10**10, **11**11, **100**10, **101**10, **110**11, **111**11, **100**100, **101**101, **110**110, **111**111, ... They are the binary representations of the positive integers, grouped by length and then with each group repeated twice, first with the last bit omitted from the remainder of the number, then with the last bit kept. Add 1 to the 1-indexed `k`, to get numbers starting with 2=102, then take out the second bit of each number and use it to determine whether it goes in the first or second repetition of its group: ``` n k k+1 **1**₂ 1 **1**0₂ **1**1₂ 2 **1**1₂ **10**1₂ 3 **1**0**0**₂ **11**1₂ 4 **1**0**1**₂ **10**10₂ 5 **1**1**0**₂ **11**11₂ 6 **1**1**1**₂ **100**10₂ 7 **1**0**00**₂ **101**10₂ 8 **1**0**01**₂ **110**11₂ 9 **1**0**10**₂ **111**11₂ 10 **1**0**11**₂ **100**100₂ 11 **1**1**00**₂ **101**101₂ 12 **1**1**01**₂ **110**110₂ 13 **1**1**10**₂ **111**111₂ 14 **1**1**11**₂ ``` --- In assembly: ``` f: inc eax # Add 1 to EAX. bsr ecx, eax # Set ECX to the position of the first 1 bit in EAX. rcr eax, cl # Rotate EAX and the carry flag (CF) together right by that many bits. # (CL is the low byte of ECX; here it always equals the full value.) # The value of CF after BSR is officially undefined, but it is # consistently 0 (what this program needs) on at least some CPUs. # (To not rely on this, add CLC before this for +1 byte.) # The top 1 bit goes to the bottom, the second bit goes into CF, # and the rest of the bits go to the top of the value; # the bits we want to keep are now contiguous for plain rotates. jc s # Jump if CF=1, skipping an instruction. (It is shortest # to use CF immediately, before another instruction overwrites it.) ror eax, 1 # (If CF=0) Rotate EAX right by 1 bit. s: rol eax, cl # Rotate EAX left by CL, moving the value of the inclusive left half # to the bottom (0 removed) or one bit above the bottom (1 removed). mov edx, eax # Copy the value of EAX into EDX. shl eax, cl # Shift EAX left by CL, moving it to just above the copy in EDX. or eax, edx # Combine EAX and EDX by bitwise OR into EAX. shr eax, 1 # Shift EAX right by 1 bit. ret # Return. (EAX is the return value.) ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~99~~ 79 bytes * *-2 bytes thanks to [@ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)* * *-18 bytes thanks to [@jdt](https://codegolf.stackexchange.com/users/41374/jdt)* ``` b[11];n;main(l){for(;++n;)l=sprintf(b,"%b",n)/2,bcmp(b,b+l,l)||printf("%d",n);} ``` [Try it online!](https://tio.run/##S9ZNT07@/z8p2tAw1jrPOjcxM08jR7M6Lb9Iw1pbO89aM8e2uKAoM68kTSNJR0k1SUknT1PfSCcpObcAKJCknaOTo1lTA1WhpJoCkreu/f8fAA "C (gcc) – Try It Online") ]
[Question] [ A simplistic version of [English numeral calculator](https://codegolf.stackexchange.com/questions/12757/english-numeral-calculator) ### Task Write a program that takes a string as input and outputs the result of the expression. ### Rules The input string will be worded and not numeral. There will be no parentheses. Order of calculation will be divide,multiply,subtract then add. For same operations, the calculations must be done from left to right. All input numbers will be integers from -999 to 999 (both inclusive) Output will be an integer of any range. Division will always be perfectly divisible and zero will never be a denominator. Restriction of case for input is optional. You don't have to check for the validity of the input. ### Number Format ``` 0 to 20 -> zero,one,two...nineteen,twenty 21 to 99 -> twenty one,twenty two.....ninety eight,ninety nine 100 to 999 -> one hundred, one hundred one, one hundred two...one hundred ten....two hundred fifty....nine hundred ninety eight,nine hundred ninety nine ``` For negative numbers: Add `minus` to its positive equivalent ### Operation Format ``` Addition: one plus two Subtraction: one minus two Multiplication: one time two #Note that for one on the left of multiplication, it is one time and not times. two times one hundred Division: forty divided by two ``` ### Examples: ``` o/p <- input 20 four times five 35 twenty plus fifteen 70 fifty plus five times four -90 minus one time ninety 25 twenty one minus minus four 45 ninety divided by two 700 one time seven hundred 555 one hundred eleven times two plus three hundred thirty three 99 one hundred plus minus one 45 forty five plus two hundred times zero 4 four -3 three minus three minus three ``` **This is code-golf so shortest code wins** [Answer] # JavaScript (ES6), ~~257~~ ~~252~~ ~~249~~ 235 bytes *Saved 3 bytes thanks to @Shaggy* ``` s=>eval(s.split` `.map(w=>(i='zeonwohrr44fx3n5t54nn3leel8tou7fn7n98etetwthfofisiseeinihuplmitidiby'.match(/../g).findIndex(x=>~(w+w.length+w).search(x)))>28?n+' '+'+-*/ '[n='',i-29]:(n=+n+(i<28?i<20?i:i*10-180:n*99),''),n='').join``+n) ``` [Try it online!](https://tio.run/##hZDBbuIwEIbv@xRWL7YJGNpSFVBDz/sMq5VIyZhMZcaR7STQw74668S7VNoN6mVkeb75/5n/vWgLv3dYhxnZEi46v/h8C21hhFe@Nhh2bKeORS26fCsw5x9gqbOVc8ulPj3SU3haEj0aALMKtnnW9EzrFQQIXai01ejRAyBh1dTmiAFLfDvzKBj2lZgrNT9IpZHK71TCSZzy7S/RZZ0yQIdQZZ1UHgoX0ZOUcvuweqWMM57xbDaZM/6Dcs6nOHtY/9wIyjPKBL5EKJbFK25wcr@Y3a8WG5qs13LKuZz2A1K9W6TdLiN52Vvy1oAy9iC0uNO2cSzgETzT2MKdlN/@IUIHFM6sNk2P6ABAI1TfuUIt/JWM6iPwESlylhLGCAnC@bZ1D6aRVG@oJhlWYosllOztzEJnR7irr4cWiFUNlQ7KG@CfLgMzwOmsqJtODZWDTyZU6OICw@cXcsP0NYaxPG0vNUSZnKLl1WdY4gOcHR0cDSdtmhz/e0f@8hs "JavaScript (Node.js) – Try It Online") ## How? Once the input string has been split into words, each word \$W\$ of length \$L\$ is converted to an index \$i\$ by looking for the first 2-character key substring that can be found in \$W+L+W\$. ### Numbers ``` index | word | word + length + word | key substring -------+-------------------+------------------------------+--------------- 0 | "zero" | "zero4zero" | "ze" 1 | "one" | "one3one" | "on" 2 | "two" | "two3two" | "wo" 3 | "three" | "three5three" | "hr" 4 | "four" | "four4four" | "r4" 5 | "five" | "five4five" | "4f" 6 | "six" | "six3six" | "x3" 7 | "seven" | "seven5seven" | "n5" 8 | "eight" | "eight5eight" | "t5" 9 | "nine" | "nine4nine" | "4n" 10 | "ten" | "ten3ten" | "n3" 11 | "eleven" | "eleven6eleven" | "le" 12 | "twelve" | "twelve6twelve" | "el" 13 | "thirteen" | "thirteen8thirteen" | "8t" 14 | "fourteen" | "fourteen8fourteen" | "ou" 15 | "fifteen" | "fifteen7fifteen" | "7f" 16 | "sixteen" | "sixteen7sixteen" | "n7" 17 | "seventeen" | "seventeen9seventeen" | "n9" 18 | "eighteen" | "eighteen8eighteen" | "8e" 19 | "nineteen" | "nineteen8nineteen" | "te" 20 | "twenty" | "twenty6twenty" | "tw" 21 | "thirty" | "thirty6thirty" | "th" 22 | "forty" | "forty5forty" | "fo" 23 | "fifty" | "fifty5fifty" | "fi" 24 | "sixty" | "sixty5sixty" | "si" 25 | "seventy" | "seventy7seventy" | "se" 26 | "eighty" | "eighty6eighty" | "ei" 27 | "ninety" | "ninety6ninety" | "ni" 28 | "hundred" | "hundred7hundred" | "hu" ``` ### Operators ``` index | word | word + length + word | key substring -------+-------------------+------------------------------+--------------- 29 | "plus" | "plus4plus" | "pl" 30 | "minus" | "minus5minus" | "mi" 31 | "times" or "time" | "times5times" or "time4time" | "ti" 32 | "divided" | "divided7divided" | "di" 33 | "by" | "by2by" | "by" ``` ### Interpretation The current number is stored in \$n\$, which is initialized to an empty string. Given the index \$i\$ of the next word, the following logic applies: ``` i > 28 ? // if the word is an operator: n + // append n (which is either an empty string or a number) ' ' + // append a space '+-*/ '[n = '', i - 29] // reset n to an empty string and append the operator // the useless keyword 'by' is translated into a harmless space : ( // else: n = // update n: +n + ( // force the coercion of the current value of n to a number i < 28 ? // if the word is not 'hundred': i < 20 ? // if the value of the word is less than 'twenty': i // add i : // else: i * 10 - 180 // add i * 10 - 180 (e.g. 'fifty' -> 23 * 10 - 180 = 50) : // else: n * 99 // multiply n by 100 by adding 99 * n to itself ), // '' // remove this word from the original string ) // ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~170 139 129 128 124~~ 122 bytes *-13 bytes thanks to nwellnhof!* ``` {S:g/(<:N>+)+%\s/({'+'X$0})/.EVAL}o{S:g/" ҈"/00/}o{TR"⁢ʼn؊⟠"*/൰ "}o*.words>>.&{chr first *.uniname.comb(.uc),1..*} ``` [Try it online!](https://tio.run/##ZVHNTtwwED7jpxhFFJIsOGFh2y6UlXroreIAFUIqHJbNhFhK7JXtLNqucuit7UuA@gS98Ah9gZ56RLzIMrG7QdAcLHu@n/lmMkVdvl5Wc9jI4RCWi5P9qyR8t3806kW9V@cmCRebvc2z9bSJEv7h9P3HRjlKAH@@BUmaJvT@dBw8fP35@/vfHw83t0Gc3N/9gqBRMb9WOjOjEd9YTAoNudDGQsxrKeS4Qj5R1WXI60m0tcN53CwPWK40hKWQaCJYsDUKtT6mUNxMS2HD5NxAHEOfyEl0wNbMuMU/71zA4Qjy0F2jLQigvaYXUcAatuyn0H65qjVYUaGhGDNkuwNXttco7RymZd3Wc4so2Zt/Cnp2yAxXYvJh20NHqYQkUEmPAU2Fds76z5xb1PP86fR7nuIFkImZyDCDyzmJFLV35p2twRlKKGqZaSKxwWCwglc1LB3FByQLH9oWGp84thCaerkiGw7hpYeTdAOtEtL/IJEb33uSeefo2n1BrdgedDtm27t@fNfdG/53Z/23joTiqmhX/mxDFuUj "Perl 6 – Try It Online") `unival` to the rescue again! This is (currently) even beating golfing languages like [`05AB1E`](https://codegolf.stackexchange.com/a/175377/76162)! ### Explanation: ``` *.words # Split by word boundaries (in this case spaces) >>.{ } # Map each word to chr first ,1..* # The first character where: *.uniname # The unicode name of that character # e.g. DIGIT FIVE .comb(.uc) # Contains the uppercase of the word { }o # Pass this list to another function # That converts the list to a string TR"⁢ʼn؊⟠"*/൰ " #"# And parse out the garbage characters that were wrong # INVISIBLE TIMES => "*" # LOZENGE DIVIDED BY HORIZONTAL RULE => "/" # ARABIC-INDIC PER TEN THOUSAND SIGN => "൰" (value ten) # LATIN SMALL LETTER N PRECEDED BY APOSTROPHE => " " {S:g/" ҈"/00/}o # Replace the character for "hundred" with 00 { }o # And finally combine with S:g/(<:N>+)+%\s/ # Substitute each number-like character separated by spaces /({'+'X$0})/ # With the numbers prefixed by '+'s, in brackets # This works because Perl 6 supports numeric unicode literals, like # ፳ => 20, ፴ => 30, ፺ => 90, etc. .EVAL # And finally evaluate the whole expression ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~333~~ ~~...~~ ~~284~~ ~~277~~ 275 bytes ``` lambda s:eval(''.join((list('+-/*')+[`N(w,0)*100+N(w,2)`])['pmdt'.find(w)]for w in re.split(' *(?:(p|m)|(t|d)i|by).*? ',s)if w)) N=lambda x,y:sum(10*(w[-3:]in'lveen')+'zeontwthfofisiseeiniteel'.find(w[:2])/2*10**('y'in w)for w in x.rpartition('hundred')[y].split()) import re ``` [Try it online!](https://tio.run/##bVTRjtowEHznK1bqg@0QOA6KKpBO9wf8AEW60DjNVokdJQshJ/6dem3io6Iv7MYez4zHK5qBSmuWt@Lt563K6mOeQbfV56ySQsz/WDRSVtiRFNPZSyLUdP@xk326UMnrYjHldqk@DmovmjonMS/Q5LJXh8K20AMaaPW8ayp05yGR71vZXGt1lXTNFV6Pg5on7yDSTmEBvVKT3dvdwiUdtt2plq@LRPb72Wp7QCOqs9bGWRCf2hrqqSxsgR12WqNB0roa9ffb5UG9LJ3FJJFiEM5Hr6Kly7xtspaQ0BopypPJW50LtR8Od6vOCNaNbcm5vzUtGoJCisKeWiCsdQcFnrVQKSwXk7hNvTY0QFOdeL8gbzWF1foLwssRcdYjmeNl5I8HshqNA1kTMGDQaBoYNNs8SzIsHAi/I@HyQTowQI5nzHUOxwGotwz6/gCKep0@awMxGfa2gG87S26/zBzWRclga9y3hkoXBLaA@lQRugR/ZRxtCkiAD7fITA7GUrj2v6p3KdCVVw7BOIchLCpb/YWhElt3Fb/I3tbr9f/J/NmYJEM3m4fHsMzi3yGIOLUo4fU/dfsUUbASSJ96/0CrSUBPJpySOdU8clJ4shTYIBdOn4s/5hr/Zlx5slzt8OILx8GNxt8lccMP6ReqcctNQRUO@WR0WGXC2N/HMfDGlgnGD89/7/2s3HuKGm7SosYQFMaGx3okH76oh0g8RFo3xNsJhDh30qXj/j7SENjtLw "Python 2 – Try It Online") [Answer] # Wolfram Language ~~95 94~~ 82 bytes ``` Interpreter["SemanticExpression"][#~StringReplace~{"me "->"mes ","plus m"->"m"}]& ``` `#` represents the input for the pure function. If necessary,`StringReplace` replaces "time " with times ", "plus minus" with "minus" (through `"me "->"mes "`,`"plus m"->"m`", respectively). The shortened replacement forms, suggested by `lirtosiast`, saved 12 bytes. `Interpreter["SemanticExpression"]` does all the rest. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~166~~ ~~147~~ ~~141~~ ~~139~~ 135 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` „byK“¡×€µ‚•„í†ìˆÈŒšï¿Ÿ¯¥Š—¿áÓÁÏ“#vyN:}'tK'…§¦'+T«:'°¡„ *т«©:.•1×j›o!ĆÖ•3ôŽ9oS:'y®¨:©“‰´Øè„Æ€ººß“'tK#UX¡εð¡õK2ôJ.EO}®áX"+-**/"S:Sðì.ιJ.E ``` Way too long.. Will try to golf it down from here. -4 bytes thanks to *@Emigna*. -2 bytes thanks to *@JoKing*. [Try it online](https://tio.run/##PY7PSwJREMf/lZceFpQ2qlN775JQBwu8JvvMF7kb7lPZg/DyIN2CioyIcoNM0dSDC7UQwkx7CoT@hfePbCNCl4Hvj/nMuN5xUfAk0eqp6Oe0eoQAO7o1glCrB61eyMd3rbo4@mnjZXwdBziBefwBE3iNu1rdwhwDvMELvKLldN3ft5qGzBla9eANekb2EIaWAVMIiMQyvy0YwsAyibyJnVOtInftu413pLdxFn/tuHnL8GEMfQsGBNRqCjO8x/7yj/byrwgifKaEjqSPChAsQiQ4hrktnO2ZuwdNGGNQSGXXM5mNVN7K4xRH5uKToiSRDZeVa45d5TaTDe5Iny0tW9SFTVZxJaWocI9VhFPzWEmUqOTxOnfY@RkZslzl/B/CxUlZcspW7dWU3PkD) or [verify all test cases](https://tio.run/##bVFNSxtRFN3Pr3iNi4FEI21XzkJXbhpoF7HgtmFezJM4I5OXkRGFp4vQXaEtVaRUR/CLRM0iAQ0U4d7OqiD0L7w/kr6PGBnazZv3zj3n3HPvhK0PNUbHO3GyVCBzi6SwlIyl@FFLKlJ8hxQP5H4PhlIcSXGqcLyW4gR7vzv4MfucpXgLD9kd3MJZdiLFV3jAFL/gHn5S4pk4eevturziSnEOF3Dullag67nQh1Q5keKffejClVdWzi/xYF2KUfjiVwe/qfdrHGQ/F8Kq5yZwA5ceXClDKfowwEO81Dk6OtcIRnisKqrJzPtVSB@HqMxxWHmFgzfl5Xe7cIPpaqE0VyzOF6peFfvYKz/eq9J4dlwP2xHhbIO2SJ3F1OFbNOAJ2Wy2NVDnlAaO/k6hmD7RldLZYIFCw8CCJGAB5cmTiYYtwZ5GYSnEZzHzqU9qCeFboTN1aNGYBqTRDvyI@gae3AltmpJtrjQ2EG9E9JnDGyxS5gbMiQ13Gtaph5pmhrEuym7qYRps0yh0TGDbwWr/uTs5pR1bQ/nxJp6TLZht2jn/MwJlaw299dzmuPoL9pbbggmpj78). **Explanation:** ``` „byK # Remove "by" from the (implicit) input-string “¡×€µ‚•„í†ìˆÈŒšï¿Ÿ¯¥Š—¿áÓÁÏ“ # Push string "zero one two three four five six seven eight nine ten eleven twelve" # # Split by spaces v } # Loop over each of these items: yN: # Replace the item with its 0-indexed index 'tK '# Remove all "t" '…§¦ '# Push string "teen", and remove the first character: "een" '+ '# Push string "+" T« # Append 10: "+10" : # Replace all "een" with "+10" '°¡ '# Push string "hundred" „ * # Push string " *" т« # Append 100: " *100" © # Store it in the register (without popping) : # Replace all "hundred" with " *100" .•4º»Ÿć'Rþн• '# Push string "wenhirforfif" 3ô # Split the string into parts of size 3: ["wen","hir","for","fif"] Ž9o # Push integer 2345 S # Split to digits: [2,3,4,5] : # Replace each 'y '# Push string "y" ® # Push the " *100" from the register ¨ # Remove the last character: " *10" : # Replace all "y" with " *10" © # Save the current string in the register (without popping) “‰´Øè„Æ€ººß“ # Push string "plus minus times time divided" 'tK '# Remove all "t": "plus minus imes ime divided" # # Split by spaces: ["plus","minus","imes","ime","divided"] U # Pop and save it in variable `X` X # And push variable `X` back again ¡ # Split the string by those operator-strings ε } # Map each substring to: ð¡ # Split by spaces (NOTE: cannot be `#`; if the string contains no # spaces, `#` remains string, whereas `ð¡` wraps it in a list) õK # Remove empty strings from the list 2ô # Split the list into parts of two J # Join each pair together .E # Evaluate each as a Python `eval` expression O # Sum them ® # Put the string from the register to the stack again á # Remove everything except for letters X # Push variable `X`: ["plus","minus","imes","ime","divided"] "+-**/" # Push string "+-**/" S # Split to characters: ["+","-","*","*","/"] : # Replace each S # Split the string of operators to loose characters ðì # Prepend a space before each .ι # Interweave all sums with these operator-characters J # Join everything together to a single string .E # Evaluate each as a Python `eval` expression (and output implicitly) ``` [See this 05AB1E tip of mine (sections *How to use the dictionary?*, *How to compress strings not part of the dictionary?*, and *How to compress large integers?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand how `“¡×€µ‚•„í†ìˆÈŒšï¿Ÿ¯¥Š—¿áÓÁÏ“`, `'…§`, `'°¡`, `.•4º»Ÿć'Rþн•`, `Ž9o`, and `“‰´Øè„Æ€ººß“` work. **Step by step example:** * **Input:** `two hundred twenty two divided by two times minus fifty seven plus three hundred eighteen minus minus ten` * Step 1: Remove "by": `two hundred twenty two divided two times minus fifty seven plus three hundred eighteen minus minus ten` * Step 2: Convert "zero" through "twelve" with the correct number: `2 hundred twenty 2 divided 2 times minus fifty 7 plus 3 hundred 8een minus minus 10` * Step 3: Remove all "t": `2 hundred weny 2 divided 2 imes minus fify 7 plus 3 hundred 8een minus minus 10` * Step 4: Replace all "een" with "+10": `2 hundred weny 2 divided 2 imes minus fify 7 plus 3 hundred 8+10 minus minus 10` * Step 5: Replace all "hundred" with " \*100": `2 *100 weny 2 divided 2 imes minus fify 7 plus 3 *100 8+10 minus minus 10` * Step 6: Replace all ["wen","hir","for","fif"] with the correct digit: `2 *100 2y 2 divided 2 imes minus 5y 7 plus 3 *100 8+10 minus minus 10` * Step 7: Replace all "y" with " \*10": `2 *100 2 *10 2 divided 2 imes minus 5 *10 7 plus 3 *100 8+10 minus minus 10` * Step 8: Split by ["plus","minus","ime","imes","divided"]: `["2 *100 2 *10 2 "," 2 "," "," 5 *10 7 "," 3 *100 8+10 "," "," 10"]` * Step 9: Split each on spaces: `[["2","","*100","2","*10","2",""],["","","2",""],["",""],["","5","*10","7",""],["","3","","*100","8+10",""],["",""],["","10"]]` * Step 10: Remove empty items: `[["2","*100","2","*10","2"],["2"],[],["5","*10","7"],["3","*100","8+10"],[],["10"]]` * Step 11: Split into parts of size 2 and join: `[["2*100","2*10","2"],["2"],"",["5*10","7"],["3*100","8+10"],"",["10"]]` * Step 12: Python `eval` each: `[[200,20,2],[2],"",[50,7],[300,18],"",[10]]` * Step 13: Sum each: `[222,2,"",57,318,"",10]` * Step 14: Re-push the string from the register, and remove everything except letters: `dividedimesminusplusminusminus` * Step 15: Replace "plus","minus","imes","ime","divided" with the operator characters, and prepend them with a space: `[" /"," *"," -"," +"," -"," -"]` * Step 16: Interweave and join both together: `222 /2 * -57 +318 - -10` * **Output:** Python `eval` the string, and output implicitly: `-5999.0` [Answer] # [sfk](http://stahlworks.com/dev/swiss-file-knife.html), ~~572~~ ~~449~~ 423 bytes This could all be one line, but for the purposes of reading it I used newlines instead of spaces. ``` xed -i _plus_+_ _minus_-_ _times[ortext]time_*_ _divided?by_/_ +xed "_[white][2 chars of a-z][chars of a-z]ty_[parts 1,2]0_" "_[white][2 chars of a-z][chars of a-z]een_[part1]1[part2]_" _ten_10_ _lev_11_ _twe_12_ +xed _ze_0_ _on_1_ _tw_2_ _th_3_ _fo_4_ _fi_5_ _si_6_ _se_7_ _ei_8_ _ni_9_ +xed _0[white][keep][digit]__ "_[chars of e-z ]__" +xed "_?dd[keep][2 digits]_[part1]_" _?dd[keep][digit]_[part1]0_ _dd_00_ +calc #text ``` [Try it online!](https://tio.run/##jVLBbtswDL3rK4Tstixo7G3deuqHGAKRRnRN1JUCS3Hi/HxGUra7Ypdd/CjyPeqRcmrf7vcrersjA6f@nGALBt4pcLTjKNM7piYOGa/ZyQG@ctbTSB7988sED2C2rDcbaC4dZXRNbY/dYUg2tvawu7nm0ylP0JwOQ062@la7PWz@V4gYirJylWLtWAyZ09WeLfU4QlWJ4wtCVc@u4IYg1cgsrUEt0MF3hjbCDwGCnwyJ4FEA4RcDEvxmCARPS6v94vMN8eQaT6@UHYAMsDrF3c1ybrPs5Nn7mV5bFSS3TCHuP8pzt7kmlr2HPeP2eOiP9ovs/35v43mw@iS2pRENzxryZOXdONFmXpIRXFMjLnRWGn1WG0NJ2kAB87Q0kXQhlK8qCsXO721fJpsv0awdEo4YbHcOfuCq5pcD9lort7OoOMrdgB@c3NHA3TX5Sazc1a1po9B0mtKF26099IIbDtGo43JD0f4TG/5dTHEmY/eyQvGge2P1ukDBRNeCQtcI6bXTQNcigZj@e/t/AA "sfk – Try It Online") ]
[Question] [ Given a 2D array of integers, let's sort its rows and columns in blocks. This means that you only have to sort a given row or column, but applying the transformations needed for sorting it to every other row or column in the 2D array. ### Rules * Input will be a 2D array of integers and a 1-indexed integer. This integer will represent the row to be sorted if the number is positive, or the column to be sorted if the number is negative (or the other way round you want). Example: Given a `4x3` (rows x columns) array you can sort the second column with a `-2` argument or the third row with a `3` argument. This second argument will never be zero and its absolute value will never be greater than the corresponding dimension of the array. * Output will be also a 2D array of integers with the needed transformations applied to sort the given row or column. Alternatively you can just write the array to STDOUT. * The output array will have the specified row or column sorted in ascending order. Just note that when you need to swap two numbers in a row, the whole columns where the numbers lay will be swapped. And when you need to swap two numbers in a column, the whole rows where the numbers lay will be swapped. * In the case in which the same number appears several times in the row/column to be sorted, there will be several solutions possible according to the way you swap the values, just do accordingly with the rest of rows/columns to be swapped. ## Examples ``` Positive indices for rows and negative indices for columns [5 8 7 6 [1 3 2 4 1 3 2 4 order by -3 (3rd column) --> 9 6 3 0 9 6 3 0] 5 8 7 6] [5 8 7 6 [9 6 3 0 1 3 2 4 order by -4 (4th column) --> 1 3 2 4 9 6 3 0] 5 8 7 6] [5 8 7 6 [5 7 8 6 1 3 2 4 order by 2 (2nd row) --> 1 2 3 4 9 6 3 0] 9 3 6 0] [5 8 7 6 [6 7 8 5 1 3 2 4 order by 3 (3rd row) --> 4 2 3 1 9 6 3 0] 0 3 6 9] [1 2 [1 2 [3 2 3 2] order by -2 (2nd column) --> 3 2] or 1 2] (both are valid) [7 5 9 7 [5 7 7 9 [5 7 7 9 1 3 2 4 order by 1 (1st row) --> 3 1 4 2 or 3 4 1 2 9 6 3 0] 6 9 0 3] 6 0 9 3] ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so may the shortest code for each language win! [Answer] # [R](https://www.r-project.org/), 55 bytes ``` function(x,n)`if`(n>0,x[,+x[n,]],x[+x[,-n],]) `+`=order ``` [Try it online!](https://tio.run/##HYxBCsMgEADvvsLjLllLU3ts85EgGJoVhGZT1IK/t0tPMzAwZST7cCN95dXyKdBJMOYUQZYr9ZWmvgqFoKpGTgIFNHGKz7PsXEbldqnMO8xouo7ssbWSO9Tt@LwZ5huS9WTvWk3Succ/nMfxAw "R – Try It Online") Reassigns the `+` operator (actually a function in R) to the `order` function, which returns the indices of a vector from smallest to largest. Then it's just array manipulation. [Answer] # [R](https://www.r-project.org/), 55 bytes ``` f=function(m,i)"if"(i<0,t(f(t(m),-i)),m[,order(m[i,])]) ``` [Try it online!](https://tio.run/##Lc3LCsIwEIXhvU9RupqBU6hNvEHzFu5KFxoNDDgJhIj69LFSV99/VifXGlx4Rl8kRVIItxJakrFHoUCFlNEJM3RCyrd7Jp0EM89ctRm7Ri8ly5s87XDEAXtsYTDA4rS0Qc@IOb2cQfTp4Syun9888yYsZ535a1eHFcP1Cw "R – Try It Online") Alternative to [ngm's answer](https://codegolf.stackexchange.com/a/172063/67312); a recursive function which was inspired by [DimChtz's answer](https://codegolf.stackexchange.com/a/172066/67312) [Answer] ## Matlab, 73 62 47 bytes ``` @(m,i){sortrows(m,-i) sortrows(m',i)'}{(i>0)+1} ``` [Try it Online!](https://tio.run/##y08uSSxL/Z@mYKugp6f330EjVydTs7o4v6ikKL@8GMjTzdRUQHDVgbLqtdUamXYGmtqGtf/TNKJNFSwUzBXMrBUMFYwVjBRMrBUsFcyATINYHQVdY83/AA) -11 bytes thanks to @Giuseppe. -15 bytes thanks to @LuisMendo. [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~18~~ 17 bytes *negative for rows and positive for columns* ``` >0?VñgUÉ:ßUa Vy)y ``` [Try it online!](https://tio.run/##y0osKPn/387APuzwxvTQw51Wh@eHJiqEVWpW/v9vzBUdbapjoWOuYxarE22oY6xjpGMCZFnqmAHZBrGxCrpBAA "Japt – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~25~~ ~~24~~ 14 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` diø}Σ¹Ä<è}¹diø ``` Whopping -10 bytes thanks to *@Emigna*. Uses a positive integer-input to sort the rows, negative for columns. [Try it online](https://tio.run/##yy9OTMpM/f8/JfPwjtpziw/tPNxic3hF7aGdIIH//3WNuaKjTXUsdMx1zGJ1og11jHWMdEyALEsdMyDbIDYWAA) or [verify all test cases](https://tio.run/##yy9OTMpM/W/mpuSZV1BaYqWgZO/pYh@mpJCYlwJm6yj5l5ZAZSL/p2Qe3lF7bnHk4RabwytqI0Hc/7U6h7bZ/9c15oqONtWx0DHXMYvViTbUMdYx0jEBsix1zIBsg9hYLl0TgkqMCKogwhqQIYY6RkBBoCRQwBDIN9cx1bHUMceuBQA). **Explanation:** ``` di } # If the (implicit) integer input is positive: ø # Swap the rows and columns of the (implicit) matrix input # i.e. 3 and [[5,8,7,6],[1,3,2,4],[9,6,3,0]] # → [[5,1,9],[8,3,6],[7,2,3],[6,4,0]] Σ } # Sort the rows of this matrix by: ¹Ä # Take the absolute value of the input # i.e. -3 → 3 < # Decreased by 1 to make it 0-indexed # i.e. 3 → 2 è # And index it into the current row # i.e. [5,8,7,6] and 2 → 7 # i.e. [5,1,9] and 2 → 9 # i.e. [[5,1,9],[8,3,6],[7,2,3],[6,4,0]] sorted by [9,6,3,0] # → [[6,4,0],[7,2,3],[8,3,6],[5,1,9]] # i.e. [[5,8,7,6],[1,3,2,4],[9,6,3,0]] sorted by [7,2,3] # → [[1,3,2,4],[9,6,3,0],[5,8,7,6]] ¹di # And if the integer input was positive: ø # Swap the rows and columns back again now that we've sorted them # i.e. 3 and [[6,4,0],[7,2,3],[8,3,6],[5,1,9]] # → [[6,7,8,5],[4,2,3,1],[0,3,6,9]] # (And implicitly output the now sorted matrix) ``` [Answer] # JavaScript (ES6), 90 bytes ``` t=m=>m[0].map((_,x)=>m.map(r=>r[x])) f=(m,k)=>k<0?m.sort((a,b)=>a[~k]-b[~k]):t(f(t(m),-k)) ``` [Try it online!](https://tio.run/##rZHNCoMwEITvPsUeE1jFv9a2VPsgIZRotbQaIxqKp766XfUs9OBlYWaZ@RL2rT5qKPpXZ93WPMppsqlOMy186WnVMXbHkZNeRJ9mvRgl506VMo01Leqrf9PeYHrLmMKcHCW@tXTzefKLZRWzTHN0a86nwrSDaUqvMU/yhQMgDggnhAThKHHWAUKEECLEqz7TZrF86UgENyK4s0NPvE9PuE/N1q8oFq6BOb2@fAtJMKJScfIXMqB7/AA "JavaScript (Node.js) – Try It Online") ### How? JS has no native transposition method, so we need to define one: ``` t = m => // given a matrix m[] m[0].map((_, x) => // for each column at position x in m[]: m.map(r => // for each row r in m[]: r[x] // map this cell to r[x] ) // end of map() over rows ) // end of map() over columns ``` Main function: ``` f = (m, k) => // given a matrix m[] and an integer k k < 0 ? // if k is negative: m.sort((a, b) => // given a pair (a, b) of matrix rows, sort them: a[~k] - b[~k] // by comparing a[-k - 1] with b[-k - 1] ) // end of sort : // else: t(f(t(m), -k)) // transpose m, call f() with -k and transpose the result ``` *Example with \$k=2\$:* $$M=\pmatrix{5&8&7&6\\1&3&2&4\\9&6&3&0}\rightarrow t(M)=\pmatrix{5&1&9\\8&3&6\\7&2&3\\6&4&0}\rightarrow f(t(M),-2)=\pmatrix{5&\mathbf{\color{red}1}&9\\7&\mathbf{\color{red}2}&3\\8&\mathbf{\color{red}3}&6\\6&\mathbf{\color{red}4}&0}\\f(M,2)=t(f(t(M),-2))=\pmatrix{5&7&8&6\\\mathbf{\color{red}1}&\mathbf{\color{red}2}&\mathbf{\color{red}3}&\mathbf{\color{red}4}\\9&3&6&0}$$ [Answer] # [MATL](https://github.com/lmendo/MATL), 17 bytes ``` y0>XH?!]w|2$XSH?! ``` [Try it online!](https://tio.run/##y00syfn/v9LALsLDXjG2vMZIJSIYyPr/X9eYK9pUwULBXMHMWsFQwVjBSMHEWsFSwQzINIgFAA "MATL – Try It Online") Or [verify all test cases](https://tio.run/##y00syfmf8L/SwC7Cw14xtrzGSCUiGMj6H6uuq6se4RJVEfJf15gr2lTBQsFcwcxawVDBWMFIwcRawVLBDMg0iOXSNcErbYRXloDRQM2GCkbWIIlYLkOuaHMFU6CsORa1AA) ### Explanation ``` y % Implicit inputs: number n, matrix M. Duplicate from below: pushes n, M, n 0> % Greater than 0? XH % Copy into clipboard H ? % If true ! % Transpose matrix. This way, when we sort the rows it will correspond % to sorting the columns of the original M ] % End w % Swap: moves n to top | % Absolute value 2$XS % Two-input sortrows function: sorts rows by specified column H % Push contents from clipboard H ? % If true ! % Transpose again, to convert rows back to columns % Implicit end % Implicit display ``` [Answer] # [APL (Dyalog Classic)](https://www.dyalog.com/), 23 bytes ``` {⍺<0:⍉(-⍺)∇⍉⍵⋄⍵[;⍋⍺⌷⍵]} ``` [Try it online!](https://tio.run/##jY89TsNAEIV7n2I67xQWXv/GgWOkQxRWkJGFJaOkiqJUoEAIi6DgAJyAykKi5ChzEfO8RtsgITejt/PmfTtT3jTB5aZs2qtg2ZTrdb3s5fmtbmX/ovsKdSvm6yycizmoAJLl4R5aTCfHO9TzUzFH9OXpE6@LXd8vxlAnh/cVpDzeVicYmPvttY@MX5V14w8J06123vdHrGT/qlKaUU4ZK00xRZSwKiiDDJkXg/@n7RJAJJMQLul8h4gmAVK4s9GP0LZ@jImQvWlHZBaQskosQLMKLaAYjhh3AJoVwu7s36enrZ1TSgXl/66Yg4eMpmQIg074hX8A "APL (Dyalog Classic) – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), ~~71~~ 70 bytes ``` f=lambda m,n:n<0and sorted(m,key=lambda l:l[~n])or zip(*f(zip(*m),-n)) ``` [Try it online!](https://tio.run/##rZPRToMwFIbv9xQn8aYYSKAFJov6IqQXTFi2CO3SoWZe@Op4ehgTcBmY2aRAoRz@7/w/@2O91Yo3zeapzKp1nkHlqpV69DOVw0GbushZ5b4Wx@5xuSrTLyUdbeBzt2f3G0anynE95TjN3uxUDRuWppEL8IBziTOWeMBxBxMjDQAEAAcIF72b@LbAyXGG51La5IWB9RE8AUyYHF50@VYpB8DznnFHgt@lan6vVGLVnMr5UrqecKZVQYQoSGJBFotbES/qmkIMgYX1dox4sVu/EMP/RZyolUZUBovF1/l6eBwYx7wZ/XFGIzhOfNfg@DRbQkViu/9Gsrgji2aTnaI5JAs7suAK2Yxg@h1ZMiCzivjcONIvx9srm6WeIqKyAaIm/2Tx5NYoi5REidta5yQAW2uMbGYKeM/KXe70NdquWwcs9fIvuVqSocP1bDcCYMGhHrkhSHDriVUvaBEMezF2J5h2Jyal1iPZrf02jSO30CvsNarFTMbkfPMN "Python 2 – Try It Online") --- If `n` is negative, the rows are sorted based on column `n`. Otherwise the matrix is transposed, sorted the same way, and transposed back again. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes ``` ZṠ}¡ çị@ÞA}ç ``` [Try it online!](https://tio.run/##y0rNyan8/z/q4c4FtYcWch1e/nB3t8PheY61h5f///8/OtpUR8FCR8FcR8EsVodLIdpQR8FYR8FIR8EEzLUEioNFDGJj/xsDAA "Jelly – Try It Online") [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 186 bytes ``` (x,y)=>{Func<int[][],int[][]>shift=a=> a[0].Select((r,i)=>a.Select(c=>c[i]).ToArray()).ToArray();return y>0?shift(shift(x).OrderBy(e=>e[y-1]).ToArray()):x.OrderBy(e=>e[-y-1]).ToArray();} ``` [Try it online!](https://tio.run/##rZRNj9MwEIbv@RWjnmzhRP1YWKAkCFaCC4gVReIQ5WBct2uRxovtlkZVfnuZJGy3SbZRhJiD5Y9nxvY7YwvrC23kcWtVtoZFbp3czL3zUfBJZb/mnudlfCPtPRcSbvRSftTpyjt4gCZSbi3cGr02fFPN1POlWcedErDTagmfucqIdQZjxwlws7b0xD16lPZhm4k3KnNxEicMsFM15SiCH6kWPxfaOAiPZM9yGkaHBv9A2ju1ciEPI@DxOAkWMpXCEWKYQhf@MBZhJGKV0OCbfmcMzwk9686NdFuTQR6N31bhSN3uafDFLKV5nxMZRjLO/Ukjwut9c91vAfPiiIqe33jHDSqCixBCJn/HSWO1qU5pyACKeIDnDF4yuGbwAgp2GZswmDGYMrjqxV5hnIoct7GideBbTKMj1ZFpa@lGZ1anMvhulJNYPZKM/JON6JOBTlmtQzLwZxTJIeDVQHA6kKs2boCNxPQlA1We9uo7q4ABwnavOf33Y2F1YJlgbq//d410qGKQxBN6qWa@Sr6sSuYsV8Ujem/UjjvZ@FbqPf6@@lqUS//KCr86Lu6AlM/N4J/Sxp9@bA03UboZ2oG6bp23QAQ8gxGMWnVY37HXsy1J16UXL7yiOP4B "C# (.NET Core) – Try It Online") Ungolfed: ``` private static int[][] Blocksort0a(int[][] array, int sortingInstruction) { Func<int[][], int[][]> shift = a => a[0].Select((r, i) => a.Select(c => c[i]).ToArray()).ToArray(); sortingInstruction++; array = sortingInstruction < 0 ? shift(shift(array).OrderBy(e => e[-sortingInstruction]).ToArray()) : array.OrderBy(e => e[sortingInstruction]).ToArray(); return null; } ``` The shift function we'll use twice, so a function variable will save space. The function iterates through the horizontal dimension of the array on index, and adds every item on that index in of each horizontal array to a new output array (horizontally) - much the same as in Arnoud's JS solution. Now the ordering is simple, order horizontal array by number-at-index (argument -1), optionally shifting the array before and after sorting. Seen how the question talks about arrays specifically, we convert to array a few times (very, very wasteful). Feeling a bit silly to use such a verbose language in code golf hehe. [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), ~~142/139~~ 138/135 bytes (and yet another -1 by Kevin) ``` (a,s)=>s<0?a.OrderBy(e=>e[~s]).ToArray():a.Select(f=>a[s-1].Select((v,j)=>new{v,j}).OrderBy(e=>e.v).Select(e=>f[e.j]).ToArray()).ToArray() ``` [Try it online!](https://tio.run/##rZRLb9NAEIDv/hWjnHbFxmqSQoHWQVAJLlRUDRIHy4dlMwkujrfsbo2iyPz1MLbb1I/GshBzsPbxzXjnqexYaYP7exuna1hsrcPNuVff@Z/j9Ne553mp3KC9kwrhUi/xk05W3s4DEpVIa@Ha6LWRm/KkOi/EOuliBZmOl3Al45RZZ8h2GIE0a8sP3JNGIR/vU3URpy6MwkgALcpPsZvD90SrnwttHAR7JoXlwdxenLyT/hezRPNhyzCYY/jHRtz/qt8bI7eMv5X@AhNUjq2CuQzteBI9HrBM3JKJFH/vaJXzhhk/448cbVch@rd1s7XlniJU9yCThjykKwiAbIdR47bpbSHEAAVlBy8FvBZwJuAV5OI4NhEwEzAVcNqLvSE7JXnSxvLWg68pLY6VT@atq0udWp2g/83EDqkakI3GBxnxZw0dslSZFDCecSKHgKcDwelArvxxA2wkpi8ZFOVpb3xnJTAgsF03p//@LKoOKhPK7dn/rpEOlQ8K8YQfq5kblMuyZGq5yp/QOxNn0mFjTFT/eOj3KijH5sSKRpdUP4AV7WZoRrTx55utoaYKNcM7UFet0wtMwQsYwahVh5WPvZrtkHRVevHcy/P9Xw "C# (.NET Core) – Try It Online") Ungolfed: ``` private static int[][] Blocksort0b(int[][] array, int sortingInstruction) { if (sortingInstruction < 0) { return array.OrderBy(e => e[-sortingInstruction - 1]).ToArray(); } var rowIndices = array[sortingInstruction - 1].Select((value, index) => (value, index)).OrderBy(e => e.value); var newRow = new int[array[0].Length]; for (var i = 0; i < array.Length; i++) { int horizontalIndexer = 0; foreach (var e in rowIndices) { newRow[horizontalIndexer++] = array[i][e.index]; } array[i] = newRow.ToArray(); } return array; } ``` New all-inline approach; negative answer still orders arrays by element-at-index. Otherwise, a collection of value-index-pair is created of the array-at-index and sorted by value. This effectively creates a collection of indices in order of having-to-be-added. Then for each array, the elements in the predetermined positions are selected. Quite some trimming of code and ugly, ugly, ugly \*\*silently sobs\*\* reuse of input parameters is involved, and there you go ... 142 bytes. Again, the arrays argument is strictly enforced, adding quite some overhead for .ToArray() calls. 135 bytes claim, eh?! C# 7.2 inferred value-tuples would trim an additional three bytes, but tio.run doesn't allow. Therefor, this is the answer i decided to post for easy verification. [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), 326 bytes ``` (a,b)->{int l=a.length,w=a[0].length,k,m,t,i;if(b>0){for(i=0;i<w;i++){for(k=1;k<(w-i);k++){if(a[b-1][k-1]>a[b-1][k]){for(m=0;m<l;m++){t=a[m][k];a[m][k]=a[m][k-1];a[m][k-1]=t;}}}}}else{b*=-1;for(i=0;i<l;i++){for(k=1;k<(l-i);k++){if(a[k-1][b-1]>a[k][b-1]){for(m=0;m<w;m++){t=a[k][m];a[k][m]=a[k-1][m];a[k-1][m]=t;}}}}}return a;} ``` [Try it online!](https://tio.run/##dVJNc5swED03v2InJ6glwEmatJXxP2guOTIcBJZtgZBcSYRmGH67u3w4TtupDvD09q32ze5W/JVTcxK62tXnUnHn4AeXur8BkNoLu@elgOcecZZnOdjggjhBBEXIBpQ6z70s4Rl0CueAkyKk2zEHVMojJfTBH0mX8izJL7eaNMQTyeQ@KLZJ2O8NPp0mTG46JlermajTNas3QUdlyOqRRDXPCrrOsxo/2wvOZ3mD@c1GsWaUeizXjDG2/Jc7JrB3lHo2jEcoJ/ric0rX7GpE/WNE/WlkfGFygEbqGX000l2NYLQZy07/dMmcmRldjFjhW6uBs@HMsK@ntlDY16W9r0buoMHpBC/eSn3Ich72AHF89P7kvsdxaXbiYNQ@woSyFr/KI9cHEZWmiX@2wnlptIvXT3fJYxIXypQ1dcZ6fIla0znK9Y6WRrWNdlRqyundjnJr@Rs6mdYBrHCtmubPJm6@Qwo6soEWHSzb0U/R8fRfCHwl8ETgcSBXdk3gnsAdgYeP7DdUTYEE2U8DAfoQzoWmqaCBeTJz2WWVrlMaBRUKqkWQycu6sWrUvLw5L5rItD46Yf988C7Lqnx1C7e4zH9rlA7@x6Kx4WY4/wY "Java (OpenJDK 8) – Try It Online") Well guys, this question was very frustrating for me, and I posted my answer KNOWING I was forgetting something, luckily we have legends like [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen/%22Kevin%20Cruijssen%22) out here to help us out :) # [Java (OpenJDK 8)](http://openjdk.java.net/), 281 bytes ``` a->b->{int l=a.length,w=a[0].length,k,m,t,i;if(b>0)for(i=0;i<w;i++)for(k=0;++k<w-i;)for(m=0;a[b-1][k-1]>a[b-1][k]&m<l;a[m][k]=a[m][k-1],a[m++][k-1]=t)t=a[m][k];else for(b*=-1,i=0;i<l;i++)for(k=0;++k<l-i;)for(m=0;a[k-1][b-1]>a[k][b-1]&m<w;a[k][m]=a[k-1][m],a[k-1][m++]=t)t=a[k][m];} ``` [Try it online!](https://tio.run/##dVJNb5wwEL3nV1g5VFBsYJM0aeuFS6VKPfSUI@JgvGbXYGyKTcgK8du3w8f2uxzMmzfP80YzrtgLI6YVujrUF66Ytegrk3q8Qcg65iRHFSjC3kkVlr3mThodft7AXmqX5VmO/yX6ZLTtG9Htv2gnjqJLU1Si5MJIWpB0hJtIJSxUQh/dCQ8Jy@L8GtW4wQ5LKkuvSGO/NJ0nk5jK/UBlECxxDXEQ1PuBSLoQDRAsK8guz2o40ivO3zR7BZlmxsn6hwQGFAQrTpzvtkxOhbICzQWLtwnZ4dVX/eWrfvedyyyG4FuvCHwHukTN7Lsomtl3RWC@@S4KOl0ozLztCwUz30b/YuQBNbAO79l1Uh@znPkjQlF0cq61H6OIm4M4GlWGcIHX4pWfmD6KkJsm@tYLO@/BRrunu/gxjgpleE2s6RxUIp0ZLGH6QLhRfaMtkZowcncgrOvYGTpBaFsuNADmryhBWgxXclwU8ze@w@g9Rk8YPU74J7vD6B6jO4wefmU/gGpJxNNEF7oMWduqs7ea@CHjXLTOIw/@lp93D29l3cOq2p7JspPxKqhAUG2CTF6fEq1mzfPZOtGEpndhC3N03g9ZVuXBLbr16fSnRmnvfyw0Nt1Ml@8 "Java (OpenJDK 8) – Try It Online") [Answer] # [Clean](https://github.com/Ourous/curated-clean-linux), 95 bytes ``` import StdEnv,Data.List,Data.Func $n#f=if(n>0)transpose id =f o sortBy(on(<)\u=u!!(abs n-1))o f ``` [Try it online!](https://tio.run/##JczBCoJAFIXhvU9xoxYK16gsK8gWUUHgInBpLm7qxIBzR5wx8OWbBHffvzinbGpip3TVNzUokuykanVnIbPVjb94JUvLVBo76d5z6S14LhIpfD6vAtsRm1abGmTlJQI0mHF9GXzN/il49Uk/m/n0NsDhOgg0CJdZGu8TWEAYQZ7v8IB7jAvM1xjhBrejjhiPXhWF@5WioY9x4SN114FJyXKKZ0NW6E79AQ "Clean – Try It Online") [Answer] # [Kotlin](https://kotlinlang.org), 192 bytes ``` {m:Array<Array<Int>>,s:Int->if(s<0){m.sortBy{it[-s-1]}}else{val a=Array(m[0].size){c->Array(m.size){m[it][c]}} a.sortBy{it[s-1]} (0..m.size-1).map{r->(0..m[0].size-1).map{m[r][it]=a[it][r]}}}} ``` [Try it online!](https://tio.run/##vVjdUxs5En/3X9FQe9mZXdvYQGBhA1X52N3KVepIbXJPlB/EjGzrMjOalTQxhPhvz3a3pJkxMYTcVR0PwEj98etPtfRBu0JVX/b24HVVNw6UBVU5uZAG5tqA1cbB1Q0klVwIpz5KXs100ZRVOkAuXcFcGesApcgxvJOZrnL@IFG2FpkEK2thhJM5MRQKiUmIZzN6BYmtZabmN6paQNWUV6hbz4MSO2Y175fK5CBQ9JW8IQ0o3C0JTVHoFTGiIAtJqazFL2IJ/LCQDj5Jo6X9FeS1M6LdEQZBLiptZO61/Euj8eQF01Refi7noikcZMJKOx4Q0UsjyRa2wS0RR6ZzCQtdzE9pe@lcbU/39miVFsfWieyDvM6WolrIcabLvb8aaZ3Sld2bHu9PjibE9tbohRFlSaa8bT59KqSFJ/CSRP@BUojkRaGzDyOKSGsvOSRaoyoQsP8KrTLihpH@gfHqL5JXQ3DtEArpfrQ@wMrZrfKuSKMdk/ctlFKwU4SDG91g4IsbWArMCKe9FAELVkghbZNkCFfoT1HXBYeXfIohqCx6rxTsBKikzIM/o3HKkVT5URoEjTxmUyhhI0nRsDFZ@2eDPmO76cdn80oVBWbMPT5gcwVMR6rK5TVCCBvB4FgHLMTI2kgrK8eKCQ0CRMmEmDjnvB6yF5lrbRXVyxA4TWRE/jBXW2VJ4PLGrxC30Q2iJc@vROXSMfx2Lcq6kKdtmA@vDyDhMF7HIKbBaGLLROXjRHKtr9MAaqXcEgWM9pF80ZRkZdDvuO7I3EBz0JIELwVJLSN7q6LQkaFUeOxmSjFxZVGfk/BRFI28Q7ngsiKtogoOM@jxGoVTRuQKpVvMFwogbXeBp5@Lxm3Eu7D6vqCzIex2n3d305FyVdG67ty1JbHH8LxAvBXHq@hc/J8Gu9rKKCc7mCTr3ftXF/9@3wJ@T8H1oD0JQ/f1RPHhjkgwNhM/Jg7G22bSu0abnHL2n6S40qwXa3S1RMQEisxkY1aiBrfSId1Cw0DxQ9a4WupCtsWP3Eb2ktNCETFS@qKoGpsmPMfIPlJRbAedLk7VxynqqtqnBnZjkrpaqszH0oqyrSNiEYYyE1NLFOAwdWxsGah0b0spMi4jO8WBlxOW0wIL2qorhC0yzEx2PApga0KBebuXIb2xw3Iq5LrjKG667MPcdpSX5IW96PYAKVpNZocy953tbegqaE2uMrSKmmbbudvu0d8NopH9p8HlU4BfAI4BjuAbP5dTwFqHfYDDAXT/g882GglG2G0OTOwhKcBodA5wwrKRejLo/T/7lroO2GzwXTD7@rbDPITkEH2@CbNv3f8D5lOmQ@qjTZg9oPuQ7Fdc7xEkw9xn6u@DecJ0R0T6fTCPIsyn98IMUd@AeRhhTr8L5iTCPCGY3tbH5KUnuyR0A8Y468c7@HEz3oEM64F9OhtAcqXpQDNcripPEcExB/iEfdAJnHbxO@bdze@7jkqmfqpNwWudRveQ7gP@mDLwrxwVnAneJd49s/g98VGdDX7aG4SB2EIYPkc0Zw6xV0FJZw21wyV1NQTCsym1ASmwUxY4gjZiQW2u2gndpcbOQdNXU2Wud7wWorzKxXiA61Abjd3EJnhCGnV9Cs/pwHrmf7@u3Pn5kLvoKbZnl8LtYABA94l52/V5e8jHY2N9t79qVIGjHk6Vbqlzz9E/cbmp4bEbp8F2gsKZNRdOeA5hu4ZL7AHpGHdxtkpY2jOYECjyozdgTMsvbuBWuUsep0fT2TqAvqBjYKUszm2KxmM@ID0qdG87KpBWz@BFDjftosPGm0xtuakRcCDnmc6ohapEQSjXIAvk9PDQjDAMnHkfB49fTmZjqz5JNCMbnQ9iKfRJ4n5gUG52mc3Wa6b1k1LP6NZmztfJeNyTMZqm@FnDrRmdd1sRAe626j1Z2Dcz0om4WRnrN17/msxW8wH/DfHh1HulbF2EfA0AONtyv35/tnUp9jsedCFbzYLS3SdCOOqjUHKswa9rhIenBJcDzclE52m8UbzeSqASDrZSKvn1cxLTucDL5K0W0aIxPNnBEjWUDVadvwR/BdMzGPlXo3AWoOz182AEXMhqgR3qjJoqTTo4eiSkcOesS2hP8/PPg4hmD8kn0evMFIBt8/ZWVwTJ9zqjNjhJJ7v/@OHWK1/nu2M/PXvy1BMyWVElaQSDNIP@Mi@GWPvbqvRljpVksPJ8@6JBD5GEvOlfya3PllKoKkG32pgo79CKatFLkjfcyboGx0PRUhQEX3pnF1DDmaeenuxj00flX27L068bnT3Fv6NzNU/ss0l6W4ay8q2EampN9XzLlXwWCrQtX6resBYWyq5SRU8USxpw@fWLsq3JXjnyehnq70y0lbdef2F73uMNehE827l0bnTZOpt84JCMHcZMf0qR9zKlfQWiZEUZ2O6la2oQkb590@nx8EOKb4AmiIvkmN1KN/7JYdx2PlZyxsRvVCWTdGdn7DS6O0k7Gg6uRbKycQKn8Teo@WIegx4oceS@DdlKTPwY1RfcK2vew4qqGpz7nzzxr1ih8s6xztpSD5rHIs@Zye@sY2F@U060/fU83DTotq/b48MtqQrxfJTXmawpT71j@BQLqinicHbWofJMrzGTF6J4Hi7gv0UBye4Lkfsw7Ox2AGKZdc9vdJzS6baSfELPuYVF8raTieqmux1KvqnG2Jlw40EnB6ycoHiNxkYBu@FAaV2pXIzrugss2xbksKV3PHY3BzHI0lY/YtrhdKAbE6kf5VDONHQkfP7cDQkUNh4HMGD@NP38ucWchA2mikS9uKT/U0xe6gqvmz4u/gESuySdByb26ti/I0d/jmhtDm95vujyrxnmqlJ2icMettO8ydz4nqljwzCcBNCg3tjxVaxx/3HR/jWID6OMHw17kik2YfVZPxW6KozaLz3ZrN2grtujmoTRJx43uxfBV6e7oUWEIYMNDyeW//Bu3DzEdt/5ZxdMvx940t0uJYyQvZzDmVfj7V3QC0iVbxxjoQl6nvjM3HZo64fDTDgcIBJpjDanOPOjq6nrpb1e/bKvAE81jTySU2dTWM@aNgdpbOXHtXCk7ux2rZa7QpjnLubJ3b9Ph/DLEI6HcJQOW8fHzekQDoawP4TDdNguniAtr0/SLSw91v0eE4l5iBwBIBIUffzfwOisJV/ZLeZOhjA62CKa1vtSJ5uw8fNgO6BRnwyhTdOuDfwe72mOD9ms0JXcPIbpKhQaX2Siw73UOT8WjjfGvLv9IXJsaxMP9AeeBDmXaK4mP6W949W0vYMS5pL2sfnHwtzsK@Ei0u8qYadXuv4C0d14/Df1GJptQl0/UNlba7tX3YxwOkvvyumV@G2gWT8oszfV8r84QvmhlkbSL38D "Kotlin – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), 69 bytes ``` ->a,n{f=->x{[0,x.transpose,x][n<=>0]};f[f[a].sort_by{|x|x[n.abs-1]}]} ``` [Try it online!](https://tio.run/##TcpBCsMgEEDRfU/hAUYxMU1bWr3IMBQDNauaoBYMiWe3Wbp7H374TVuddeXGgt@d5ibvKCGLFKyP6xI/kAn9SxtJ5enQoSURl5De07Yf@cjohZ0i76hQqV@bmGaIV7jDDUYC7EBBD8OpB4ynJdFlZTOeJzCu2hia6Bsrqn8 "Ruby – Try It Online") [Answer] # [Red](http://www.red-lang.org), ~~190~~ 185 bytes ``` func[b n][t: func[a][c: length? a/1 a: to[]form a d: copy[]loop c[append/only d extract a c take a]d]d: does[if n > 0[b: t b]]d m: absolute n sort/compare b func[x y][x/(m) < y/(m)]d b] ``` [Try it online!](https://tio.run/##jY69bsMwDIR3P8WNzVA4dn7cCEXzDl0JDvpzW9QWBVkB7Kd3lXbJUsATj@B3d0zere/eEVe9WvtbsGQQmLLC76KZrMLgw0f@vELXDbRCFuJe0ghdOQUrcSEeRCIKH6MPrpYwLHDwc07aZmhYZP3todlxsTjxE331CHjDnkxJhGF21aigzSTDLftymyTl2soYdfIwf//MWJjm@mnc4RXLfbIr3jUmMR49iE54QYczgxoc0OJY1AXnovfMeD5Um9HjZrTdTD7WN2jLrTD3sseIDidc0P0T0aw/ "Red – Try It Online") ## Explanation: ``` f: func [ b n ] [ t: func [ a ] [ ; helper transpose function c: length? a/1 ; c is the length of the rows a: to-block form a ; flatten the list d: copy [] ; an empty block (list) loop c [ ; do as many times as the number of columns append/only d extract a c ; extract each c-th element (an entire column) ; and append it as a sublist to d take a ; drop the first element ] d ; return the transposed block (list of lists) ] d: does [ if n > 0 [ b: t b ] ] ; a helper function (parameterless) to transpose ; the array if positive n d ; call the function m: absolute n ; absolute n sort/compare b func[ x y ] [ x/(m) < y/(m) ]; sort the array according to the chosen column d ; transpose if positive n b ; return the array ] ``` My actual solution is 175 bytes long, but it doesn't work in TIO. Here it is, working normalyl in the Red console: ## [Red](http://www.red-lang.org), 175 bytes ``` func[b n][d: does[if n > 0[c: length? b/1 a: to-block form b t: copy[]loop c[append/only t extract a c take a]b: t]]d m: absolute n sort/compare b func[x y][x/(m) < y/(m)]d b] ``` [Answer] # VBA (Excel), 205 bytes Yay! 2nd longest byte count! I didn't completely lose :D Golfed: ``` Sub d(a) With ActiveSheet.Sort .SortFields.Clear .SortFields.Add Key:=IIf(a<0,ActiveSheet.Columns(Abs(a)),ActiveSheet.Rows(Abs(a))) .SetRange ActiveSheet.UsedRange .Orientation=IIf(a<0,1,2) .Apply End With End Sub ``` This sorts all the data on the open (active) worksheet using UsedRange... which can be buggy, but should only contain cells that have been edited. UnGolfed: ``` Sub d(a) 'Clear any Sort preferences that already exists ActiveSheet.Sort.SortFields.Clear 'Use the column if A is negative, the row if A is positive ActiveSheet.Sort.SortFields.Add Key:=IIf(a < 0, ActiveSheet.Columns(Abs(a)), ActiveSheet.Rows(Abs(a))) 'Set the area to sort ActiveSheet.Sort.SetRange ActiveSheet.UsedRange 'Orient sideways if sorting by row, vertical if by column ActiveSheet.Sort.Orientation = IIf(a < 0, xlTopToBottom, xlLeftToRight) 'Actually sort it now ActiveSheet.Sort.Apply End Sub ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 43 bytes ``` {($!=$_>0??&[Z]!!*[])o*.sort(*[.abs-1])o$!} ``` [Try it online!](https://tio.run/##HYvhCoIwFEZf5U6G3I27oWlWhPkeLRGDBkW52Poj0bOv6a@Pcw7f@@afTXzNkFto4xc5a/lwKrouN@eeMWl64aQOzn9QGj1egyqT4ewXwziDRT4IRNwS7Al2BI0gwJKgItgQ1Asdkl1FIYTQD3efMLtMWUrLgHUeVKqqXi/VMf4B "Perl 6 – Try It Online") Curried function. ### Explanation ``` { } # Block returning function composed of o$! # 1. Apply $! (transpose or not) o*.sort(*[.abs-1]) # 2. Sort rows by column abs(i)-1 $_>0??&[Z] # 3. If i > 0 transpose matrix !!*[] # Else identity function ($!= ) # Store in $! ``` [Answer] # [Physica](https://github.com/Mr-Xcoder/Physica), 45 bytes Very similar to [Arnauld's JS answer](https://codegolf.stackexchange.com/a/172067/594870). ``` F=>n;m:n<0&&Sort[->u:u{~n};m]||Zip@F#Zip@m#-n ``` [Try it online!](https://tio.run/##K8ioLM5MTvz/383WLs861yrPxkBNLTi/qCRa167UqrS6Lq/WOje2piYqs8DBTRlE5irr5v0PKMrMK4l2i9Y1tq6uNrW2sDa3Nqu1rja0NrY2sjYBsiytzYBsg9ra2Nj/AA "Physica – Try It Online") ### How it works? A more elaborate and visual explanation can be found in the linked answer. ``` F=>n;m: // Create a function F that takes two arguments, n and m. n<0&& // If n < 0 (i.e. is negative) Sort[->u{~n};m] // Sort the rows u of m by the result of the function u[~n]. // In short, sort by indexing from the end with n. || F#Zip@m#-n // Else, apply F to Zip[m] and -n. Uses a new feature, binding. Zip@ // And transpose the result. ``` [Answer] # [J](http://jsoftware.com/), 32 bytes ``` f=.[/:({"1~<:) g=.(f&.|:|)`f@.(0<]) ``` [Try it online!](https://tio.run/##y/r/P81WL1rfSqNaybDOxkqTK91WTyNNTa/GqkYzIc1BT8PAJlbzPxdXanJGvkKurZ6CsYKJgoqCqYKChYKCuYKCmYKCoQJQUMFIASihYAkWAXINIDrU1blgehXSFQzhgnCheMP/AA "J – Try It Online") Note: The `g=.` of the main verb doesn't count. ## An explicit version for the same bytes # [J](http://jsoftware.com/), 32 bytes ``` 4 :'y(]/:{"1)&.(|:^:(x<0))~<:|x' ``` [Try it online!](https://tio.run/##y/r/P91Wz0TBSr1SI1bfqlrJUFNNT6PGKs5Ko8LGQFOzzsaqpkL9PxdXanJGvkKurZ6CsYKJgoqCqYKChYKCuYKCmYKCoQJQUMFIASihYAkWAXINIDrU1bmgeo0U0hVy4YJgOh4s9h8A "J – Try It Online") [Answer] ## Clojure, 91 bytes ``` (fn f[A i](if(< i 0)(sort-by #(nth %(- -1 i))A)(apply map list(f(apply map list A)(- i))))) ``` Argh, `apply map list` \* 2. ]
[Question] [ # Background Skip to "Task" if you are familiar with Tic-Tac-Toe (I think most are!) [Tic-Tac-Toe](https://en.m.wikipedia.org/wiki/Tic-tac-toe) is a famous two-player game. It consists of a **3x3** board that is filled gradually by two players (clarifications below); The first player uses the character `X` and the other one uses `O`. The winner is the first to get 3 consecutive and identical characters (`X` or `O`), either horizontally, vertically or diagonally. In case the board is filled and none of the players managed to get three consecutive characters as decribed above, the game ends in a tie. Note that there might be empty spots at the end of the game, in case either of the players wins in less than 9 moves in total (this cannot happen in case of a tie). # Task Given a Tic-Tac-Toe board at the end of a game (in the form of a string, a matrix, a flat list of 9 ordered values, any other decent format), determine who wins the game. * The input will consist of distinct and *consistent* values, one for `X`, one for `O` and another one that represents an empty spot. * Your program should be able to output 3 distinct, consistent and non-empty values: one in case `X` wins, another one in case `O` wins or another if the players are tied. Please specify these values in your answer. You can assume that the input will be a valid Tic-Tac-Toe board. # Test Cases `X`, `O`, `_` are the input values here; `X wins`, `O wins` and `Tie` are for the output. ``` X O X O X _ O _ X ``` Output: `X wins`. ``` X _ O X O _ X O X ``` Output: `X wins`. ``` X O X _ O X _ O _ ``` Output: `O wins`. ``` X O X O O X X X O ``` Output: `Tie`. --- As usual, all our standard rules apply. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest code in bytes in every language wins! [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~16 15~~ 14 [bytes](https://github.com/DennisMitchell/jelly) ``` U,Z;ŒD$€ẎḄỊÐḟḢ ``` A monadic link accepting a list of lists (the rows - or columns) with the values: ``` X = 0.155; O = -0.155; _ = 0 ``` Returning results: ``` X wins = 1.085; O wins = -1.085; Tie = 0 ``` Note: using a value of zero for `_`, and equal but opposite values for `X` and `O`, this value (here `0.155`) may be in the range `(1/6, 1/7)` (exclusive at both ends) - I only chose a value in that range that gave a precisely representable floating point result for the win cases. **[Try it online!](https://tio.run/##y0rNyan8/z9UJ8r66CQXlUdNax7u6nu4o@Xh7q7DEx7umP9wx6L///9HRyvoGZqa6iggU7E6XArRCkBgoKOgS4x4LAA "Jelly – Try It Online")** ### How? ``` U,Z;ŒD$€ẎḄỊÐḟḢ - Link: list of lists (as described above) U - upend (reverse each row) Z - transpose (get the columns) , - pair the two $€ - last two links as a monad for each of them: ŒD - diagonals (leading diagonals - notes: 1. only one is of length 3; - 2. the upend means we get the anti-diagonals too) ; - concatenate (with the rows/columns) Ẏ - tighten (make a single list of all the rows, columns and diagonals) Ḅ - from binary (vectorises) (note that [0.155, 0.155, 0.155] - converts to 4*0.155+2*0.155+1*0.155 = 1.085 - and [-0.155, -0.155, -0.155] - converts to 4*-0.155+2*-0.155+1*-0.155 = -1.085 - while shorter lists or those of length three - with any other mixtures of 0.155, -0.155 and 0 - yield results between -1 and 1 - e.g. [.155,.155,0] -> 0.93) Ðḟ - filter discard if: Ị - insignificant (if abs(z) <= 1) (discards all non-winning results) Ḣ - head (yields the first value from the list or zero if it's empty) ``` [Answer] # Javascript (ES6), ~~103~~ 87 bytes ``` a=>"012+345+678+036+147+258+048+246T".replace(/\d/g,n=>a[n]||!1).match(/(\d)\1\1|T/)[0] ``` ## Input * X is represented as `1` * O is represented as `2` * \_ is represented as `0` ## Output * X wins is represented as `"111"` * O wins is represented as `"000"` * Tie is represented as `"T"` ## Explanation ``` a=> "012+345+678+036+147+258+048+246" // List of indexes for each row .replace(/\d/g,n=>a[n]||!1) // Replace all digits with the value of the cell .match(/(\d)\1\1|$/)[0] // Find the first row filled with the same value ``` ## Test cases ``` f= a=>"012+345+678+036+147+258+048+246T".replace(/\d/g,n=>a[n]||!1).match(/(\d)\1\1|T/)[0] console.log(f([1,2,1,2,1,0,2,0,1])) console.log(f([1,0,2,1,2,0,1,2,1])) console.log(f([1,2,1,0,2,1,0,2,0])) console.log(f([1,2,1,2,2,1,1,1,2])) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 18 bytes ``` UŒD;;Z;ŒDµSA⁼3µÐfḢ ``` [Try it online!](https://tio.run/##y0rNyan8/z/06CQXa@soayB1aGuw46PGPcaHth6ekPZwx6L///9HRysY6ijoArGCYawOl0K0LipXAcwECcXGAgA "Jelly – Try It Online") `X` = `1`, `O` = `-1`, `_` = `0` X wins = `[1, 1, 1]`, O wins = `[-1, -1, -1]`, Tie = `0` Input as list of 3 lists of 3 elements in `(1, -1, 0)` each. [Answer] # PHP, 70 bytes ``` for($c=95024101938;${${$i++&7}.=$argn[$c%9]}=1<$c/=3;);echo$XXX-$OOO; ``` Assumes `-n` (interpreter defaults). Additionally requires `-R` (execute `<code>` for every line of input), counted as one. Input is taken on a single line (exactly as in the problem description, except with all whitespace removed). Output is the following: `1` → X Wins, `-1` → O Wins, `0` → Tie . [Try it online!](https://tio.run/##S0oszvhfkFGgoJsXpP4/Lb9IQyXZ1tLUwMjE0MDQ0tjCWqUaCDO1tdXMa/VsVRKL0vOiVZJVLWNrbQ1tVJL1bY2tNa1TkzPyVSIiInRV/P39rf@r/4/wB8J4//gIAA "Bash – Try It Online") [Answer] ## [Perl 5](https://www.perl.org/), 58 bytes **56 bytes code + 2 fpr `-p0`.** ``` $_=eval sprintf'/(.)(.{%s}\1){2}/s||'x4 .'0?$1:T',0,2..4 ``` [Try it online!](https://tio.run/##JYzBCoMwEETv@xUSUqJgExW9tJR@wl562IOw9KAgSBKMlIL6602tPbyBeTDju2lsYu@mJA1@HGbT2taaXHK2RMm37vUck@Cnwc69MqnOUr2cwtaW2VJtJqyreteJVsVdlpeHyou80rqOVzgWQjKIDfYbISIhARIDMgEQIxAy/OQRfMD/gjtE@HF@HpwN8eyLLw "Perl 5 – Try It Online") Outputs `X` and `O` for wins, or `T` for a tie. Includes a bunch of header/footer code to test all at once. --- ## Alternative, 58 bytes ``` $}.="/(.)(.{$_}\\1){2}/s||"for 0,2..4;$_=eval$}.'0?$1:T' ``` [Try it online!](https://tio.run/##JYvBCoMwEETv@xUlBFSwiUq9VKSfsJce9hBYerAgSAwqvcT8etNoD29ghjduWKY2vuflkq9uGjdtrLG6lFz4KIPqhc5VkSsvORhTF74Jet13cRyqslHq1knuh89rSnJWPWR9f2axA7eMdhOSQQRIghCRkACJAZkAiBEIGY7xDD7hf8EEEX5nt42zXePVVT8 "Perl 5 – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 73 bytes ``` lambda b:{'XXX','OOO'}&{*b.split(),b[::4],b[1::4],b[2::4],b[::5],b[2::3]} ``` [Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSHJqlo9IiJCXUfd399fvVatWitJr7ggJ7NEQ1MnKdrKyiQWSBlCaSMobWVlCuUax9b@LyjKzCvRUEjTUI/wj4jJ84@IBxLxEeqaCppcSHLx/jF5Ef7xIAJDDqQvHkLEY5PzBxEREf4guf8A "Python 3 – Try It Online") --- # [Python 2](https://docs.python.org/2/), ~~100~~ ~~95~~ ~~92~~ ~~87~~ ~~82~~ 77 bytes ``` lambda b:{'XXX','OOO'}&set(b.split()+[b[::4],b[1::4],b[2::4],b[::5],b[2::3]]) ``` [Try it online!](https://tio.run/##ZYtBCsIwEEX3PUVXToKlYNVNwDPMdiAJQ4MWCzUNNhuRnj0aDAi6eY/P44dHvM6@S8PJpKm/uXNfO/UEIoIGEBHWzXKJwrVLmMYo5FY7rdTBNk7virtipY5l7q2VKdxHH@tBACEZj8RvMIGsqm9hNJ6QM35K/vAH/F8wgwhBphc "Python 2 – Try It Online") --- Takes input as a newline separated string of `XO_` Outputs: * `{'XXX'}` for `X`, * `{'OOO'}` for `O` * `{}` for a tie Works by slicing the string into rows columns and diagonals: ``` The board: 1 2 3 4 5 6 7 8 9 which is '123\n456\n789' is sliced into: ['123', '456', '789', '147', '258', '369', '159', '357'] rows: b.split() -> ['123', '456', '789'] cols: [b[::4],b[1::4],b[2::4]] -> ['147', '258', '369'] diag: [b[::5],b[2::3]] -> ['159', '357'] ``` then `'XXX'` and `'OOO'` are checked against the slices. Takes input as a newline separated string of `XO_` Outputs: * `{'XXX'}` for `X`, * `{'OOO'}` for `O` * `{}` for a tie Works by slicing the string into rows columns and diagonals: ``` The board: 1 2 3 4 5 6 7 8 9 which is '123\n456\n789' is sliced into: ['123', '456', '789', '147', '258', '369', '159', '357'] rows: b.split() -> ['123', '456', '789'] cols: [b[::4],b[1::4],b[2::4]] -> ['147', '258', '369'] diag: [b[::5],b[2::3]] -> ['159', '357'] ``` then `'XXX'` and `'OOO'` are checked against the slices. [Answer] # R, ~~118~~ ~~116~~ 115 bytes Thanks to [@user2390246](https://codegolf.stackexchange.com/users/66252) for two extra bytes. ``` function(M,b=table,u=unlist(c(apply(M,1,b),apply(M,2,b),b(diag(M)),b(M[2*1:3+1]))))`if`(any(u>2),names(u[u>2]),"T") ``` Slightly ungolfed: ``` function(M){ u=unlist(c(apply(M,1,table), #Contingency table of the rows apply(M,2,table), #of the columns table(diag(M)), #of the diagonal table(M[2*1:3+1]))) #of the opposite diagonal `if`(any(u>2),names(u[u>2]),"T") #Give name of element that occurs more than twice in any setting } ``` Returns `X` if X wins, `O` if O wins and `T` in case of a tie. [Try it online!](https://tio.run/##dY3BCoMwEETvfkZOu20u6q2Q/oHNpQdBRBNrSkCjqIH69Wm01IrQhYGZWd7u4BRzyppq0p2BhEo2CdnU1DJrGj1OUIHo@2b2q5BKpN8QLUHCQ4snJLjYJItO4SU@hzn6KbUqQZgZ7DVCakRbj2AzH3Kk5E7QpawV06Bf/gFJCd1UePGdirX3J6quYTEGClIM@AHmB3jvixX@oByD2x@U73y6dT/0hu4N "R – Try It Online") [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), ~~26~~ 21 bytes ``` ⌈/1 1(∨⌿⍉∘⌽,⍉,⍉⍤⊢,⊢)⊢ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn//1FPh76hgqHGo44Vj3r2P@rtfNQx41HPXh0gC4Qf9S551LVIB4g1gfh/2qO2CY96@x51NT/qXfOod8uh9caP2iY@6psaHOQMJEM8PIP/pykYAyFQUsEISEOwIZA0BNIA "APL (Dyalog Extended) – Try It Online") Algorithm taken from the J answer, and [verify a magic square.](https://codegolf.stackexchange.com/a/40084/80214) -5 bytes from Adám. Takes input as a 3x3 integer matrix where: 1 → blank, 2 → X, 3 → O. returns the appropriate integer for X and O, 1 if it's a tie. ## Explanation ``` {⌈/∨⌿(1 1∘⍉∘⌽,1 1∘⍉,⍉,⊢)⍵} ⍵ → input ( )⍵ pass ⍵ to inner fn: ⊢ return matrix containing argument, ⍉, argument transposed, 1 1∘⍉, it's main diagonal, 1 1∘⍉∘⌽, and the main diagonal of it's reverse. ∨⌿( ) take GCD of each column of the resultant matrix ⌈/ take the maximum of that ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~124~~ ~~118~~ ~~117~~ 115 bytes * Saved six bytes thanks to [Erik the Outgolfer](https://codegolf.stackexchange.com/users/41024/erik-the-outgolfer); using a string to avoid commata. * Saved one byte thanks to [Mr. Xcoder](https://codegolf.stackexchange.com/users/59487/mr-xcoder); golfing `[j*3:j*3+3]` to `[j*3:][:3]`. * Saved two bytes by using a magic number to compress the string. ``` def T(B): for j in range(8): a,b,c=map(int,`0x197bf3c88b2586f4bef6`[j*3:][:3]) if B[a]==B[b]==B[c]>0:return B[a] ``` [Try it online!](https://tio.run/##dY7RCoIwFIav3VMc8EZjF6ZlZqwLHyBvuhDGWM62MmjKMKint7WKCOrm8HHOd37@/jYcOx2P414q2AZFmCNQnYETtBpMrQ8yyOzOq7HADTnXfdDqAe@i63S5ECppskzE8yxVMyFVuqOnSZIzmicsRF6roKA1I6Sgws2GraPcyOFitLuMFZmuoCTxCjjZdFoi1Bsbb3tQVGEoMVQYuQncAbeMbPa3xx/q64G/4Yf3zOPfwP955RsqV6B0nv8RfRaOdw "Python 2 – Try It Online") ### Input / Output values * `X` is represented as `1` * `O` is represented as `2` * `_` is represented as `None` [Answer] # [Python 3](https://docs.python.org/3/), 173 bytes ``` lambda x:h(x,1)*2or+h(x,0) h=lambda x,y:g(x,y)or g(zip(*x),y)or x[0][0]==x[1][1]==x[2][2]==y or x[0][2]==x[1][1]==x[2][0]==y g=lambda x,y:any(all(e==y for e in r)for r in x) ``` [Try it online!](https://tio.run/##ZY3BCsMgEETv@QqPu6kHtbeAX2L3YGkSBWuC5KD9eau0gUJhYN/OMMxeDrfFa130rQb7vD8sy5ODzCWOakuXjgIHp8@Ql2ltXsEtsRVefocx4@fNRlCT1tlIauqgqEnrws5c/eW9UYb1d8HGAjYEmHtzadWZ@cgSdkwdM9Y9@XjAAsZILrgkbsT3St4cIsT6Bg "Python 3 – Try It Online") * Input as a matrix of `1 == X, 0 == O, -1 == _` * Output as a single value: `2 == X, 1 == O, 0 == TIE` -8 bytes thanks to Erik the Outgolfer [Answer] # Java 8, ~~112~~ ~~108~~ ~~106~~ ~~104~~ ~~90~~ ~~102~~ 93 bytes ``` b->b.replaceAll(".*(X|O)(\\1|...\\1...|.{4}\\1.{4}|..\\1..)\\1.*","$1").replaceAll("..+","T") ``` +12 bytes (90 → 102) due to bug-fix of only checking one diagonal instead of both.. -9 bytes (102 → 93) by using `replaceAll` instead of `matches`. Input in the format `XOX OX_ O_X`, output `X`, `O` or `T`. **Explanation:** [Try it here.](https://tio.run/##jU/BagIxEL37FUPoIbF1QOhNWugHaA56CGgJ2RhLNGaX3SiIu9@@nd3m0ksr5M1M3rzMvBzN1czKysXj/tTbYJoGlsbH@wTAx@Tqg7EOVsMVYJ1qH7/A8lwUYkF8R6DTJJO8hRVEeIO@mL0XWLsq0POPEDjDKVetFHy3m7eISIlii/fXbigptZkUQ5yyF/Y0Z@L3CHwmesNEv/hZWV2KQCvz5mvp93Am79ne9hOMyMZvTXJnLC8JK2qlEHlEy5mSCqTSILViYvzMH1otQUlNeEBLc/UI/ZBWEpSS/2rJJ2g1@sjabtL13w) ``` b->{ // Method with String as both parameter and return-type b.replaceAll(".*(X|O)(\\1|...\\1...|.{4}\\1.{4}|..\\1..)\\1.*", // If we found a line of X or O: "$1") // Replace it with either X or O .replaceAll("..+", // If there are now more than 2 characters left: "T") // Replace it with T // End of method (implicit / single-line return-statement) ``` Explanation regex: ``` .*(X|O)(\1|...\1...|.{4}\1.{4}|..\1..)\1.* .* .*# 0 or more trailing & leading chars (X|O) \1 # X or O next to those leading/trailing chars (\1 # A single X or O in between (row found) |...\1... # 3 chars, X or O, 3 chars (column found) |.{4}\1.{4} # 4 chars, X or O, 4 chars (diagonal TL→BR found) |..\1..) # 2 chars, X or O, 2 chars (diagonal TR→BL found) ``` [Answer] # [Retina](https://github.com/m-ender/retina), 51 bytes ``` .*(X|O)(\1|...\1...|.{4}\1.{4}|..\1..)\1.* $1 ..+ T ``` Port of [my Java 8 answer](https://codegolf.stackexchange.com/a/144273/52210). Input in the format `XOX OX_ O_X`, output `X`, `O` or `T`. **Explanation:** [Try it here.](https://tio.run/##K0otycxL/P9fT0sjosZfUyPGsEZPTy/GEEjU6FWb1AJZQLIGIqQJJLS4VAy59PS0uUL@/4/wj1Dwj4hX8I@PAAA) ``` .*(X|O)(\1|...\1...|.{4}\1.{4}|..\1..)\1.* .* .*# 0 or more trailing & leading chars (X|O) \1 # X or O next to those leading/trailing chars (\1 # A single X or O in between (row found) |...\1... # 3 chars, X or O, 3 chars (column found) |.{4}\1.{4} # 4 chars, X or O, 4 chars (diagonal TL→BR found) |..\1..) # 2 chars, X or O, 2 chars (diagonal TR→BL found) $1 # Replace match of above with either X or O ..+ # If there are now 2 or more characters left: T # Replace everything with T ``` [Answer] # [Retina](https://github.com/m-ender/retina), 49 bytes ``` ; ;; .*(\w)(.)*\1(?<-2>.)*(?(2)(?!))\1.* $1 ..+ T ``` [Try it online!](https://tio.run/##K0otycxL/B/Ppct1aBuXNZe1NYhW1QhJUEiI/w/m62lpxJRrauhpasUYatjb6BrZAZka9hpGmhr2ipqaMYZ6Wlwqhlx6etpcIf//Ryj4K0RwAbFCPJCMB7K5gEwFfy6QRDwXRBpKxcPJeJiQP5iMAGr3BwA "Retina – Try It Online") Takes input as an 11-character string of 9 `X`s, `O`s or `-`s in three groups of three separated by `;`s, although the link includes a header which translates the given test cases to this format. Works by matching a winning line directly using a balancing group to ensure that the three matching characters are equidistant. (Suitable distances are 0 (horizontal line), 4 (reverse diagonal), 5 (vertical line), or 6 (diagonal); other distances would hit a `;` or extend outside the string.) [Answer] # [Retina](https://github.com/m-ender/retina), 127 bytes ``` .*(X|O)\1\1.* $1 (X|O).. \1.. \1.. $1 .(X|O). .\1. .\1. $1 ..(X|O) ..\1 ..\1 $1 (X|O).. .\1. ..\1 $1 ..(X|O) .\1. \1.. $1 ..+ _ ``` [Try it online!](https://tio.run/##K0otycxL/P9fT0sjosZfM8YwxlBPi0vFkAvM1dNTAPIhBEhQDyKqoAcUABNgQYiogh5QAEwga4eohArCVYIE4WbqaXPF//8f4R@h4O/vrxAR4Q8A "Retina – Try It Online") ...I guess you could call this brute force... Thought there might be some merit to it... [Answer] # J, 34 bytes ``` [:>./[:+./"1(2 1 0},:0 1 2}),(,|:) ``` Ungolfed: ``` [: >./ [: +./"1 (2 1 0} ,: 0 1 2}) , (, |:) ``` ## Explanation Encoding: ``` X = 2 O = 3 _ = 1 ``` Our high-level strategy is first to create a matrix each of whose rows is a possible win. Row one is diagonal /, row 2 is diagonal \, the next three rows are the rows, and the final three rows are the columns. This part is accomplished by the phrase (using Item Amend `}`): ``` (2 1 0},:0 1 2}),(,|:) ``` Finally we take the GCD of each row: ``` +./"1 ``` Thanks to our encoding, any row with a blank will have a GCD of 1, as will any row that contains any mix of Xs and Os, because 2 and 3 are coprime. So all we need to do next is find the maximum element: `>./` If the game is a tie, it will be 1. If a player wins, it will be that player's number. [Try it online!](https://tio.run/##LU7LCgIxDLz3K0IRu8XSbZJblhX/YxHBRxERhK3e3G@vqUoSZjIzkNxqLjAKJNCpk2xjP8km9hY7AoS0BEmKtPjQhbf46o2N4PIoDgIsArkYc5zPY4RJGHi9stEmM1/K6/4sqnZD9jsNWDSX0/UBfwf2QzwgOCAmZiLixrC1XlNk1F3ZV0X9BbGlmsa/Qlc/ "J – Try It Online") [Answer] # JavaScript, 66 bytes ``` ([a,b,c,d,e,f,g,h,i])=>e&(a&i|c&g|b&h|d&f)|a&(b&c|d&g)|i&(c&f|g&h) ``` Keeping it simple. * Input: A string, or array of numbers or strings, with `0` corresponding to a blank space, `1` an X, and `2` an O. * Output: `0` for a tie, `1` for X victory, `2` for O victory. Expanded, lightly commented: ``` ( [a,b,c,d,e,f,g,h,i] ) => // Break apart the input into nine variables w/ destructuring // Run through all possible win conditions. 1&1&1 -> 1, 2&2&2 -> 2 e & ( // All victories involving the middle square a & i | c & g | // Diagonal lines b & h | d & f // Vertical/horizontal through the middle ) | a & ( b & c | d & g ) | // Victories with the top-left square i & ( c & f | g & h ) // Victories with the bottom-right square ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 14 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ø«IÅ\ªIÅ/ª€êéн ``` Input as a 3x3 matrix of integers: `X=1`, `O=-1`, `empty=0`. Output as: X wins: `[1]`; O wins: `[-1]`; tie: `[-1,1]`. [Try it online](https://tio.run/##yy9OTMpM/f//8I5Dqz0Pt8YcWgUk9Q@tetS05vCqwysv7P3/PzraUEfXUMcwVicaROkYQBgGQJFYAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaXL/8M7Dq2uPNwac2gVkNQ/tOpR05rDqw6vvLD3v87/6OhoQx1dQx3DWJ1oEKVjAGEYAEVidRRAsgZAeaAgWJkBjAGXheo1QGEYoMnqwlkgK4DGxcYCAA). **Explanation:** ``` ø # Zip/transpose the (implicit) input-matrix, swapping rows/columns « # Merge the list to the (implicit) input-matrix, so the list of rows in the # input now also contains the columns I # Push the input-matrix again Å\ # Pop and push its main diagonal ª # And append this triplet to the list as well IÅ/ª # Do the same for the main anti-diagonal € # Now map over each triplet in the list: ê # Sort and uniquify this triplet é # After the map, sort all inner lists by length н # And pop and push the first (thus shortest) one # (after which it is output implicitly as result) ``` [Try it online with a step-by-step output.](https://tio.run/##TZC/TsMwEMZ3nuLU2VWaFQlVSCwdmGAidLiSS3LCtY3tUHVF4mH4MyMWluQFeAZeJDh2o3Y6677v@53vtMMN0zDMVsq0/hxm4qL7Wp7N7thk3qJyRjsqwTcEPDn67@S5JltTlPxOg2TnHXhdU@jY0dd9JN8tPibbFllByVhrhRJ0dcQKQFUCGkOhsAd0sCMpR8qqf73v3hPpSseIwy1Bpe0RisrzfCIfUtmUutHWR36r@Knlag@ED00YrCggLBtJca@/l8/@NBLobuSHX5WH9TZ7kKRq38Q7vCXzpYoHUqCVHHV8TutWbJ3PXBNY5HxQaUz9/iyHoShyMc9FvhbFWMQiPRahs/4H) ]
[Question] [ The Banach–Tarski paradox states that, given a ball in 3‑dimensional space, you can decompose the ball into a finite number of point subsets. These disjoint sets of points can then be reassembled to produce two copies of the initial ball. You would then, theoretically, have two identical balls. The process of reassembly consists of only moving the aforementioned point subsets and rotating them, while not changing their spacial shape. This can be done with as few as five disjoint subsets. Disjoint sets have no common elements by definition. Where `A` and `B` are any two point subsets of the initial ball, the common elements between `A` and `B` is an empty set. This is shown in the following equation. ![LaTeX representation](https://i.stack.imgur.com/koP9Y.gif) For the disjoint sets below, the common members form an empty set. ![LaTeX representation](https://i.stack.imgur.com/zPB0N.gif) --- # The Challenge Write a program that can take an input ASCII "ball", and output a duplicate "ball". --- # Input Here is an example input ball: ``` ########## ###@%$*.&.%%!### ##!$,%&?,?*?.*@!## ##&**!,$%$@@?@*@&&## #@&$?@!%$*%,.?@?.@&@,# #,..,.$&*?!$$@%%,**&&# ##.!?@*.%?!*&$!%&?## ##!&?$?&.!,?!&!%## ###,@$*&@*,%*### ########## ``` Each sphere is outlined by pound signs (`#`) and filled with any of theses characters: `.,?*&$@!%`. Every input will be a 22x10 characters (width by height). --- # Creating a Duplicate First, each point inside the ball is given a numbered point based on its index in `.,?*&$@!%`. Here is the above example, once numbered: ``` ########## ###7964151998### ##86295323431478## ##5448269677374755## #75637896492137317572# #21121654386679924455# ##1837419384568953## ##85363518238589## ###2764574294### ########## ``` Then, each point is shifted up one (nine goes to one): ``` ########## ###8175262119### ##97316434542589## ##6559371788485866## #86748917513248428683# #32232765497781135566# ##2948521495679164## ##96474629349691## ###3875685315### ########## ``` Finally, each new point value is converted back to its corresponding character: ``` ########## ###!.@&,$,..%### ##%@?.$*?*&*,&!%## ##$&&%?@.@!!*!&!$$## #!$@*!%.@&.?,*!*,!$!?# #?,,?,@$&*%@@!..?&&$$# ##,%*!&,.*%&$@%.$*## ##%$*@*$,%?*%$%.## ###?!@&$!&?.&### ########## ``` --- # Output These two balls are then output side-by-side, in this form (separated by four spaces at the equators): ``` ########## ########## ###@%$*.&.%%!### ###!.@&,$,..%### ##!$,%&?,?*?.*@!## ##%@?.$*?*&*,&!%## ##&**!,$%$@@?@*@&&## ##$&&%?@.@!!*!&!$$## #@&$?@!%$*%,.?@?.@&@,# #!$@*!%.@&.?,*!*,!$!?# #,..,.$&*?!$$@%%,**&&# #?,,?,@$&*%@@!..?&&$$# ##.!?@*.%?!*&$!%&?## ##,%*!&,.*%&$@%.$*## ##!&?$?&.!,?!&!%## ##%$*@*$,%?*%$%.## ###,@$*&@*,%*### ###?!@&$!&?.&### ########## ########## ``` --- Note: Shifting the point values, and later characters, is symbolic of the rotations performed to reassemble the point subsets (character groupings). [Answer] # Pyth, 21 bytes ``` #++Jw*4d.rJ".,?*&$@!% ``` Try it online: [Demonstration](http://pyth.herokuapp.com/?code=%23%2B%2BJw*4d.rJ%22.%2C%3F*%26%24%40!%25&input=++++++%23%23%23%23%23%23%23%23%23%23++++++%0A+++%23%23%23%40%25%24*.%26.%25%25!%23%23%23+++%0A++%23%23!%24%2C%25%26%3F%2C%3F*%3F.*%40!%23%23++%0A+%23%23%26**!%2C%24%25%24%40%40%3F%40*%40%26%26%23%23+%0A%23%40%26%24%3F%40!%25%24*%25%2C.%3F%40%3F.%40%26%40%2C%23%0A%23%2C..%2C.%24%26*%3F!%24%24%40%25%25%2C**%26%26%23%0A+%23%23.!%3F%40*.%25%3F!*%26%24!%25%26%3F%23%23+%0A++%23%23!%26%3F%24%3F%26.!%2C%3F!%26!%25%23%23++%0A+++%23%23%23%2C%40%24*%26%40*%2C%25*%23%23%23+++%0A++++++%23%23%23%23%23%23%23%23%23%23++++++&debug=0) Finally a use-case for `.r`. ### Explanation ``` #++Jw*4d.rJ".,?*&$@!% # infinite loop Jw read a string from input and store it in J *4d 4 spaces .rJ".,?*&$@!% rotate the chars of J using this char order ++ combine the 3 strings (J, spaces, rotated) and print ``` The infinite loop breaks, when there is no more input available. [Answer] # Matlab, 120 Matlab is not the greatest language for handling strings. `\n` is always considered as two characters, which is quite annoying, and you cannot just make a matrix out of a line-breaked (line-broken?) string, you have to do it manually. At least I did not have to care about the size/padding as every line has the exact same length. ``` a='.,?*&$@!%.';b=input('');b(b>90)=[];b=reshape(b',22,10)';c=b;for k=1:9;c(b==a(k))=a(k+1);end;disp([b,ones(10,4)*32,c]) ``` Example Input: ``` ' ########## \n ###@%$*.&.%%!### \n ##!$,%&?,?*?.*@!## \n ##&**!,$%$@@?@*@&&## \n#@&$?@!%$*%,.?@?.@&@,#\n#,..,.$&*?!$$@%%,**&&#\n ##.!?@*.%?!*&$!%&?## \n ##!&?$?&.!,?!&!%## \n ###,@$*&@*,%*### \n ########## ' ``` Example output: ``` ########## ########## ###@%$*.&.%%!### ###!.@&,$,..%### ##!$,%&?,?*?.*@!## ##%@?.$*?*&*,&!%## ##&**!,$%$@@?@*@&&## ##$&&%?@.@!!*!&!$$## #@&$?@!%$*%,.?@?.@&@,# #!$@*!%.@&.?,*!*,!$!?# #,..,.$&*?!$$@%%,**&&# #?,,?,@$&*%@@!..?&&$$# ##.!?@*.%?!*&$!%&?## ##,%*!&,.*%&$@%.$*## ##!&?$?&.!,?!&!%## ##%$*@*$,%?*%$%.## ###,@$*&@*,%*### ###?!@&$!&?.&### ########## ########## ``` PS: If I can assume the input this way: ``` [' ########## ',' ###@%$*.&.%%!### ',' ##!$,%&?,?*?.*@!## ',' ##&**!,$%$@@?@*@&&## \n#@&$?@!%$*%,.?@?.@&@,#','#,..,.$&*?!$$@%%,**&&#',' ##.!?@*.%?!*&$!%&?## ',' ##!&?$?&.!,?!&!%## ',' ###,@$*&@*,%*### ',' ########## '] ``` I only need 88 characters: ``` a='.,?*&$@!%.';b=input('');c=b;for k=1:9;c(b==a(k))=a(k+1);end;disp([b,ones(10,4)*32,c]) ``` [Answer] # Ruby, 65 ``` 10.times{b=gets;puts b.chop.tr(',?*&$@!%.','.,?*&$@!%')+' '+b} ``` Works great when input is taken from a file instead of stdin: ``` ruby banach.rb < ball.txt ``` On the other hand, if you like typing in balls to stdin manually, and want the output at the end, try this 67-byte version: ``` puts (0..9).map{b=gets;b.chop.tr(',?*&$@!%.','.,?*&$@!%')+' '+b} ``` [Answer] ## Ruby, 102 ``` IO.readlines(?a).map(&:chomp).each{|x|puts"#{x+' '*x.count(' ')+?\s*4+x.tr('.,?*&$@!%',',?*&$@!%.')}"} ``` Basically, its just calling `tr` on the input [Answer] # sed (39 bytes) ``` h;y/.,?*&$@!%/,?*&$@!%./;H;x;s/\n/ / ``` [Answer] # CJam, 28 bytes ``` qN/{_".,?*&$@!%"_(+erS4*\N}% ``` [Try it online](http://cjam.aditsu.net/#code=qN%2F%7B_%22.%2C%3F*%26%24%40!%25%22_(%2BerS4*%5CN%7D%25&input=%20%20%20%20%20%20%23%23%23%23%23%23%23%23%23%23%20%20%20%20%20%20%0A%20%20%20%23%23%23%40%25%24*.%26.%25%25!%23%23%23%20%20%20%0A%20%20%23%23!%24%2C%25%26%3F%2C%3F*%3F.*%40!%23%23%20%20%0A%20%23%23%26**!%2C%24%25%24%40%40%3F%40*%40%26%26%23%23%20%0A%23%40%26%24%3F%40!%25%24*%25%2C.%3F%40%3F.%40%26%40%2C%23%0A%23%2C..%2C.%24%26*%3F!%24%24%40%25%25%2C**%26%26%23%0A%20%23%23.!%3F%40*.%25%3F!*%26%24!%25%26%3F%23%23%20%0A%20%20%23%23!%26%3F%24%3F%26.!%2C%3F!%26!%25%23%23%20%20%0A%20%20%20%23%23%23%2C%40%24*%26%40*%2C%25*%23%23%23%20%20%20%0A%20%20%20%20%20%20%23%23%23%23%23%23%23%23%23%23%20%20%20%20%20%20) Explanation: ``` qN/ Get input and split into lines. { Start loop over lines. _ Copy, since we need to output original. ".,?*&$@!%" List of characters, in order. _ Copy list of characters. (+ Rotate the list by popping first character and appending it. er Transliterate. S4* Create 4 spaces. \ Swap spaces between original and transliteration. N Add newline. }% End of loop over lines. ``` [Answer] # Python 3.5, ~~96~~ ~~89~~ 88 bytes ``` s='.,?*&$@!%. ##';i=1 while i:i=input();print(i,' ',''.join(s[s.find(y)+1]for y in i)) ``` # Python 3.3, ~~103~~ ~~96~~ 95 bytes ``` s='.,?*&$@!%. ##' for i in input().split('\n'):print(i,' ',''.join(s[s.find(y)+1]for y in i)) ``` ## Explanation Python 3.3 and 3.5 are listed separately because the way `input()` handles newlines ***in IDLE*** changed. This happened to save 8 bytes, which is cool. **Note on execution: use IDLE.** If you use a terminal, then the solution for 3.3 is the same as 3.5, but both interleave the input with the output. I reversed the symbol string `s` to take advantage of Python's negative indexing. Then for each line in the input, I output it, two spaces, and the line with each symbol replaced with its preceding symbol. The reason I only put two spaces is that I used `,` instead of `+`, which adds a space to the printed output. This (`,' ',`) saved me a byte over `+' '*4+`. **Thanks to xsot** for saving me ~~7~~ 8 bytes. I changed `s.find` to `s.rfind` to allow me to put the spaces and hashes into `s`, thereby removing the need to do a check for `y in s`. Plus, a space was saved. EDIT: changed back to `s.find` because the presence of `##` now allows me to `+1` without worrying about an index-out-of-bounds error. [Answer] # [Retina](https://github.com/mbuettner/retina), ~~45~~ 39 bytes ``` .+ $0 ; $0 T`.,?*&$@!%;`,?*&$@!%. `;.* ``` To run the code from a single file, use the `-s` flag. The first stage duplicates each line, separated by `" ; "`, to get ``` ########## ; ########## ###@%$*.&.%%!### ; ###@%$*.&.%%!### ##!$,%&?,?*?.*@!## ; ##!$,%&?,?*?.*@!## ##&**!,$%$@@?@*@&&## ; ##&**!,$%$@@?@*@&&## #@&$?@!%$*%,.?@?.@&@,# ; #@&$?@!%$*%,.?@?.@&@,# #,..,.$&*?!$$@%%,**&&# ; #,..,.$&*?!$$@%%,**&&# ##.!?@*.%?!*&$!%&?## ; ##.!?@*.%?!*&$!%&?## ##!&?$?&.!,?!&!%## ; ##!&?$?&.!,?!&!%## ###,@$*&@*,%*### ; ###,@$*&@*,%*### ########## ; ########## ``` Then the second stage only affects characters which are found in matches of `;.*`, i.e. only the second half of each line. Those characters are then transliterated via the following correspondence ``` .,?*&$@!%; ,?*&$@!%. ``` Where the first 9 pairs "increment" the characters in the ball and the last pair turns the semicolon into another space. [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal) `ja`, 22 bytes ``` ƛ:`.,?*&$@!%`:ǓĿð4*$++ ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=ja&code=%C6%9B%3A%60.%2C%3F*%26%24%40!%25%60%3A%C7%93%C4%BF%C3%B04*%24%2B%2B&inputs=%20%20%20%20%20%20%23%23%23%23%23%23%23%23%23%23%20%20%20%20%20%20%0A%20%20%20%23%23%23%40%25%24*.%26.%25%25!%23%23%23%20%20%20%0A%20%20%23%23!%24%2C%25%26%3F%2C%3F*%3F.*%40!%23%23%20%20%0A%20%23%23%26**!%2C%24%25%24%40%40%3F%40*%40%26%26%23%23%20%0A%23%40%26%24%3F%40!%25%24*%25%2C.%3F%40%3F.%40%26%40%2C%23%0A%23%2C..%2C.%24%26*%3F!%24%24%40%25%25%2C**%26%26%23%0A%20%23%23.!%3F%40*.%25%3F!*%26%24!%25%26%3F%23%23%20%0A%20%20%23%23!%26%3F%24%3F%26.!%2C%3F!%26!%25%23%23%20%20%0A%20%20%20%23%23%23%2C%40%24*%26%40*%2C%25*%23%23%23%20%20%20%0A%20%20%20%20%20%20%23%23%23%23%23%23%23%23%23%23%20%20%20%20%20%20&header=&footer=) `a` flag makes Vyxal take all newline-separated inputs as a list. ``` ƛ # Map... `.,?*&$@!%` # The characters :ǓĿ # Transliterate input by chars and chars shifted ?ð4*+ # Add four spaces to each line of the original $+ # Add the previous, with chars shifted ``` -1 thanks to Razetime [Answer] # Python 2, 77 bytes ``` while 1:r=raw_input();print r,' ',r.translate(' % #@.$ & ? , '*3+'!*'*104) ``` [Answer] # Perl, 59 bytes **56 bytes code plus 3 bytes for `-p` as this needs to be saved to a file.** ``` chop($s=$_);$l=',?*&$@!%';eval"y/.$l/$l./";$_="$s $_" ``` Example usage: ``` $perl -p ball.pl <<< ' ########## > ###@%$*.&.%%!### > ##!$,%&?,?*?.*@!## > ##&**!,$%$@@?@*@&&## > #@&$?@!%$*%,.?@?.@&@,# > #,..,.$&*?!$$@%%,**&&# > ##.!?@*.%?!*&$!%&?## > ##!&?$?&.!,?!&!%## > ###,@$*&@*,%*### > ########## > ' ########## ########## ###@%$*.&.%%!### ###!.@&,$,..%### ##!$,%&?,?*?.*@!## ##%@?.$*?*&*,&!%## ##&**!,$%$@@?@*@&&## ##$&&%?@.@!!*!&!$$## #@&$?@!%$*%,.?@?.@&@,# #!$@*!%.@&.?,*!*,!$!?# #,..,.$&*?!$$@%%,**&&# #?,,?,@$&*%@@!..?&&$$# ##.!?@*.%?!*&$!%&?## ##,%*!&,.*%&$@%.$*## ##!&?$?&.!,?!&!%## ##%$*@*$,%?*%$%.## ###,@$*&@*,%*### ###?!@&$!&?.&### ########## ########## ``` [Answer] # [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/wiki/Commands), 21 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` |ʒD4ú".,?*&$@!%"DÀ‡«, ``` Uses the legacy version of 05AB1E, because it was possible to use the filter `ʒ` with implicit `y` as a foreach to print, whereas with the new version the actual for-each loop `v` with explicit `y` should be used, which is 1 byte longer. [Try it online.](https://tio.run/##bY8xDgJBCEX7OYXsAAUhRBOtodiLaOItLPYM3sDaG1i6ncfwIiOzm2wlHQ/4/7M/nS@Ha2u3z308zq/B1IUxgIZxnr7T4/3U1nZL1a3WvqwsCMXYiGCdlE4BldhTy00COi9JWQQUCSM8JJiTlxqMnn4opObhFhxaS1UzNWRxQAwiFcn9LmKQx0YOmRPSpIssluzobKAODLRaLgE1UDhESbaA/975AQ) **Explanation:** ``` | # Get the input-lines as list ʒ # For-each over the lines to print using the filter-builtin: D # Duplicate the current line 4ú # Prepend 4 spaces to this copy ".,?*&$@!%" # Push this string DÀ # Duplicate it, and rotate its copy once towards the left ‡ # Transliterate the space-prepended string with these two strings « # Append it to the original duplicated line , # And print with trailing newlines ``` --- Here a version that also works in the new version of 05AB1E (credit to *@Grimy*): # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 21 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` TFD?4ú".,?*&$@!%"DÀ‡, ``` [Try it online.](https://tio.run/##bY@xDcNACEX7myL4gAIhVoDCygRZIJFSJE2KLGB5k8ySTbzIhfNJrkLHA/7/vN7X2@Pe2uU8@7auz8nUhTGApvm7bMtHWzvtVY8afRksCMXYiGBMSqeASuyp5CYBnZekLAKKhBEeEszJSw1GTzcUUvNwCw6tpaqZGrI4IAaRiuR@FzHIYyOHTAlp0kV2S3Z0NlAHBhqWe0ANFA5RkiPgv3d@) **Explanation:** ``` TF # Loop 10 times: D # Duplicate the (implicit) input-line ? # Pop and print the copy without trailing newline 4ú # Prepend 4 spaces to the input-line ".,?*&$@!%" # Push this string DÀ # Duplicate it, and rotate its copy once towards the left ‡ # Transliterate the space-prepended string with these two strings , # And print with trailing newlines ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), 16 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` âìè╩Jù╠╕╜☻u$1∞;ⁿ ``` [Run and debug it](https://staxlang.xyz/#p=838d8aca4a97ccb8bd02752431ec3bfc&i=++++++%23%23%23%23%23%23%23%23%23%23++++++%0A+++%23%23%23%40%25%24*.%26.%25%25%21%23%23%23+++%0A++%23%23%21%24,%25%26%3F,%3F*%3F.*%40%21%23%23++%0A+%23%23%26**%21,%24%25%24%40%40%3F%40*%40%26%26%23%23+%0A%23%40%26%24%3F%40%21%25%24*%25,.%3F%40%3F.%40%26%40,%23%0A%23,..,.%24%26*%3F%21%24%24%40%25%25,**%26%26%23%0A+%23%23.%21%3F%40*.%25%3F%21*%26%24%21%25%26%3F%23%23+%0A++%23%23%21%26%3F%24%3F%26.%21,%3F%21%26%21%25%23%23++%0A+++%23%23%23,%40%24*%26%40*,%25*%23%23%23+++%0A++++++%23%23%23%23%23%23%23%23%23%23++++++) just a simple ring translation. Takes the input directly through STDIN. ]
[Question] [ A binary eye is an odd set of digits, with all of its digits except the center one set to 1 or 0, and the center one set to the opposite of the others. Thus, there are two binary eyes for a given odd number of digits: | x | eyes | | --- | --- | | 1 | 1,0 | | 3 | 101,010 | | 5 | 11011,00100 | | 7 | 1110111,0001000 | | 9 | 111101111,000010000 | Make the smallest program possible, in any language, that prints out x number of binary eyes. For example, with an input of two, the program would output 1,0 and 101,010. With 3 it should output that and the next, and with 4 the next as well, and so on. with 5 it should output the complete table above. You can also have it just continue giving outputs, as long as it outputs only correct outputs, and at least the number of outputs asked for. [Answer] # [Python 3](https://docs.python.org/3/), 45 bytes ``` n=1 while[print(f'{0:1^{n}},{1:0^{n}}')]:n+=2 ``` [Try it online!](https://tio.run/##K6gsycjPM/7/P8/WkKs8IzMnNbqgKDOvRCNNvdrAyjCuOq@2Vqfa0MoAzFLXjLXK07Y1@v8fAA "Python 3 – Try It Online") [Answer] # [Python](https://www.python.org), 48 bytes ``` s,t="01" while[print(s,t)]:s,t=f"1{s}1",f"0{t}0" ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3DYp1SmyVDAyVuMozMnNSowuKMvNKNICCmrFWIKk0JcPq4lpDJZ00JYPqkloDJYg-qHaYMQA) -5 thanks to @loopy walt --- # [JavaScript (V8)](https://v8.dev/), 42 bytes ``` for([s,t]='01';!print(s,t);t=0+t+0)s=1+s+1 ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNEts/j/Py2/SCO6WKck1lbdwFDdWrGgKDOvRAMooGldYmugXaJtoFlsa6hdrG34/z8A "JavaScript (V8) – Try It Online") -9 bytes using the same trick loopy walt suggested for the Python answer. [Answer] # [Haskell](https://www.haskell.org/), 31 bytes ``` g[0] g x=x:map(0^)x:g(1:x++[1]) ``` [Try it online!](https://tio.run/##y0gszk7NyfmfZhvzPz3aIJYrXaHCtsIqN7FAwyBOs8IqXcPQqkJbO9owVvN/bmJmnq1CQVFmXolC2v9/yWk5ienF/3WTCwoA "Haskell – Try It Online") Infinite sequence [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes ``` ṬŒḄ¬Ƭ) ``` [Try it online!](https://tio.run/##AR8A4P9qZWxsef//4bmsxZLhuITCrMasKf/Dh0vigqxZ//81 "Jelly – Try It Online") Add another byte if the pairs can't be backwards. [Answer] # [Factor](https://factorcode.org/) + `combinators.extras`, 69 bytes ``` "0""1"[ 2dup ","glue print "1""1"rot "0""0"[ surround ] 3bi@ t ] loop ``` [Try it online!](https://tio.run/##JYqxCgIxEAV/5ZFa5NROGzuxsRErscjlVgnGbG43Ae/r44LwiuHNPH2oLP12PV9Oe3gRvyjeJJkSIkNpbpQDKQJ/xpi9xbqmbxWvKEK1LkVirjh0Nzi3cXdsp1bgVu6VGuEv7bcJG1k0WKRNhFue8MBujEdUg8Rcev8B "Factor – Try It Online") ## Explanation Outputs increasing binary eyes forever. In older versions of Factor (such as the build on TIO), whitespace is not required after strings. ##### The combinators * `[ ... t ] loop` Do `...` forever. * `3bi@` Apply a quotation to two sets of three things. ``` "0""1" ! "0" "1" 2dup ! "0" "1" "0" "1" "," glue ! "0" "1" "0,1" print ! "0" "1" (output w/ newline) "1""1" ! "0" "1" "1" "1" rot ! "0" "1" "1" "1" "0""0" ! "0" "1" "1" "1" "0" "0" [ surround ] 3bi@ ! "101" "010" (and so forth...) ``` [Answer] # x86-64 machine code, 32 bytes ``` 31 D2 B8 31 34 01 AA 34 01 89 D1 F3 AA F6 DC 78 F3 C6 07 0A AE 7B F0 FF C2 39 F2 75 EA 88 0F C3 ``` [Try it online!](https://tio.run/##VZLRT8IwEMafd3/FOUPSySQgYgyIDxofTQzxQQM8lK7barp2WYeOEP5155WhiS93ab/vfl8vmyjLy0yItuWuQIaLkMEg03bDNaaQToPGViiTJvYFgsFmV0scNg@3MdXxCHjn4DrGEQSutm4Dm393hf1EKX4BlSyxcwVGZshzCD4c8s728P76hC@vC1xWiVrT9JCQgnvzR2mRmjKi44iiPD3LKVKN9KpnnEaF9lk1RCFGM5BNLSuD4WOI@0@rEkyZyHl1gS5GZWo00ewAcE50vU0k3rk6UXaQ3wN4teDKsAj2lEpDWEm31fVyMrpazyBIaVN2ZOAcRzNqd3OcUO/3IwhoJkhZNxH7GDqXFdlTFvbUdGV6bmVCUuIT1jsO8OdZmWcuckXrCZvIaehlH9ZQ2DDGHR0Ti/tfO/aGV2@E280Z2xqnMiMTPG4apdGy6ffXtCh@5UpLZDs8I0jzOPbQPwLrKfQf2UXHhzUkHtr2W6SaZ669LG6uqdC/Mie/1D8 "C++ (gcc) – Try It Online") Following the standard calling convention for Unix-like systems (from the System V AMD64 ABI), this takes in RDI an address at which to place the result, as a null-terminated byte string, and takes the input number in ESI. In assembly: ``` f: xor edx, edx # Set EDX to 0. .byte 0xB8, 0x31# These bytes combine with the next two instructions to form # mov eax, 0xAA013431. In particular, the lowest byte (AL) is 0x31 ('1') # and the second-lowest byte (AH) is 0x34, which is positive. a: xor al, 1 # Change AL from '0' to '1' or vice versa. stosb # Write AL to the string, advancing the pointer. b: xor al, 1 # Change AL from '0' to '1' or vice versa. mov ecx, edx # Set ECX to EDX. rep stosb # Write AL to the string that many times, advancing the pointer. neg ah # Negate the value of AH. js a # Jump if it is negative (every other time). mov BYTE PTR [rdi], 10 # Put 10 (line feed) at the current output address. scasb # Set flags based on AL minus that value, advancing the pointer. jpo b # Jump if that has an odd number of 1 bits, # true if AL is '0' and not if AL is '1'. inc edx # Add 1 to EDX. cmp edx, esi # Compare that with the input number. jne b # Jump if they are not equal. mov [rdi], cl # Put the low byte of ECX, which is 0 # (REP STOSB counts it down to 0), at the current output address. ret # Return. ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `M`, 6 bytes ``` ƛÞǔ∞₍† ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJNIiwiIiwixpvDnseU4oie4oKN4oCgIiwiO3Z24bmF4oGLIiwiNSJd) ``` ƛÞǔḂḢJ:†" ƛ # Map implicit input (implicit range, flag M means inclusive zero range) Þǔ # Untruth ∞ # Palindromise ₍† # Parallel wrap apply with vectorised NOT ``` [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 32 bytes ``` .+ $* 1 $`0$`¶$`0$`¶ T`10`d`¶.+¶ ``` [Try it online!](https://tio.run/##K0otycxL/P9fT5tLRYvLkEslwUAl4dA2KMUVkmBokJACZOlpH9r2/78pAA "Retina 0.8.2 – Try It Online") Explanation: ``` .+ $* ``` Convert `n` to unary using the Retina 0.8.2 default character of `1`. ``` 1 $`0$`¶$`0$`¶ ``` Create all of the prefixes of `n` `1`s, and wrap `0` with them, duplicating each time. ``` T`10`d`¶.+¶ ``` Switch the `1`s and `0`s over in alternate duplicates. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 13 bytes ``` ENE²⪫E²⭆ι¬λIλ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM3sUDDM6@gtMSvNDcptUhDU0cBJGSko@CVn5mnAWUHlwAVp4M4mToKfvklGjmamkCVzonFEKampvX//6b/dctyAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` N First input as a number E Map over implicit range ² Literal integer `2` E Map over implicit range ² Literal integer `2` E Map over implicit range ι Outer index ⭆ Map over implicit range and join λ Inner index ¬ Logical Not ⪫ Joined by λ Inner index I Cast to string Implicitly print ``` [Answer] # [PARI/GP](https://pari.math.u-bordeaux.fr), 51 bytes ``` i=!o=0;while(!print(o","i),o=Str(1o,1);i=Str(0i,0)) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMGCpaUlaboWN40zbRXzbQ2syzMyc1I1FAuKMvNKNPKVdJQyNXXybYNLijQM83UMNa0zwWyDTB0DTU2IVqgJMJMA) --- # [PARI/GP](https://pari.math.u-bordeaux.fr), 57 bytes ``` for(i=0,oo,printf("%o,%0"j=2*i+1"o\n",(8^j-1)/7-k=8^i,k)) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMGCpaUlaboWNy3T8os0Mm0NdPLzdQqKMvNK0jSUVPN1VA2UsmyNtDK1DZXyY_KUdDQs4rJ0DTX1zXWzbS3iMnWyNTUhBkDNgZkHAA) I don't understand why `printf` doesn't support binary. [Answer] # [Perl 5](https://www.perl.org/) + `-M5.10.0`, 30 bytes Outputs infinitely ignoring input. ``` $,.=0while$}.=say"$}0$} $,1$," ``` [Try it online!](https://dom111.github.io/code-sandbox/#eyJsYW5nIjoid2VicGVybC01LjI4LjEiLCJjb2RlIjoiJCwuPTB3aGlsZSR9Lj1zYXlcIiR9MCR9ICQsMSQsXCIiLCJhcmdzIjoiLU01LjEwLjAifQ==) ## Explanation Uses a `while` loop where the condition appends the result of calling `say` (which is `1`) to `$}` which will always be truthy and the body appends `0` to `$,`. [Answer] ## Batch, 111 bytes ``` @set/ai=1,o=0 @for /l %%i in (1,1,%1)do @call:c @exit/b :c @echo %i% @echo %o% @set i=0%i%0 @set o=1%o%1 ``` Unfortunately string substitution fails for unset (i.e. empty) strings, otherwise the following would work for 108 bytes: ``` @set s= @for /l %%i in (1,1,%1)do @call:c @exit/b :c @echo %s%1%s% @echo %s:0=1%0%s:0=1% @set s=0%s% ``` [Answer] # [Bash](https://www.gnu.org/software/bash/), 50 bytes ``` s=0;t=1;while echo $s $t;do t=0${t}0;s=1${s}1;done ``` [Try it online!](https://tio.run/##S0oszvj/v9jWwLrE1tC6PCMzJ1UhNTkjX0GlWEGlxDolX6HE1kCluqTWwLrY1lClurjWECiYl/r/PwA "Bash – Try It Online") [Answer] # [R](https://www.r-project.org/), 56 bytes ``` a=0 b=1 `[`=paste0 repeat{cat(a,b,"") a=1[a,1] b=0[b,0]} ``` [Try it online!](https://tio.run/##K/r/P9HWgCvJ1pArITrBtiCxuCTVgKsotSA1saQ6ObFEI1EnSUdJSZMr0dYwOlHHMBao1CA6Sccgtvb/fwA "R – Try It Online") Takes no input and outputs binary eyes separated by spaces. [Answer] # [Haskell](https://www.haskell.org/), 64 bytes ``` flip take$[1]:[0]:(drop 2$[0]#[1]);x#y=x:y:(1:x++[1])#(0:y++[0]) ``` [Try it online!](https://tio.run/##FchBC8IgFADgv/LAHZSRaMcXnjoHOwYmITVL5pZsO@if72W3j@/tt2lMiYK5UUgxw@6nsbPaoVUO@XP9ZDh2zaydOBVWTcGKXGPp@38xrrA2Kido9nEBA7PPlzvwvMZlBwlBgNVSauXo@wjJvzY6XM/D8AM "Haskell – Try It Online") [Answer] # [V (vim)](https://github.com/DJMcMayhem/V), 20 bytes ``` i1,0ÀñÙé0wé0lá1Á1ñd ``` [Try it online!](https://tio.run/##K/v/P9NQx0D6cMPhjYdnHl5pUA7EOYcXGh5uNDy8MeX////GAA "V (vim) – Try It Online") Hexdump: ``` 00000000: 6931 2c30 1bc3 80fe 58c3 b1c3 99c3 a930 i1,0....X......0 00000010: 77c3 a930 6cc3 a131 c381 31c3 b164 c3bf w..0l..1..1..d.. 00000020: c3 . ``` Explanation: ``` i1,0 " Insert the text '1,0' <esc> " Return to normal mode Àñ " Arg times... Ù " Duplicate a line downwards é0 " Prepend a '0' w " Move forward one word é0 " Append a '0' l " Move one character right á1 " Append a '1' Á1 " Append a '1' to the end of this line " (implicitly end the loop) ``` This does one loop too many, but that seems to be allowed by the rules. To fix that, add `ñd` to the end (`ñ` is "explicitly end the loop" and `d` is "delete one line"). An infinite version saves one byte: ``` i1,0<esc>ÒÙé0wé0lá1Á1 ``` [Answer] # [Common Lisp](http://www.clisp.org/), 65 bytes ``` (do((i 1(+ 2 i)))(())(format t"~v,,,'1:@<0~> ~v,,,'0:@<1~> "i i)) ``` [Try it online!](https://tio.run/##S87JLC74/18jJV9DI1PBUENbwUghU1NTU0MDiNPyi3ITSxRKlOrKdHR01A2tHGwM6uwUIDwDIM8QyFPKBGn4/x8A "Common Lisp – Try It Online") **Explanation** Infinite loop, does not read input. It works by centering a 0 (resp. a 1) using the `~:@<...~>` directive in a field of size `2i + 1`, where the padding character is a 1 (resp. a 0). [Answer] # [C (GCC)](https://gcc.gnu.org), 90 bytes ``` n;main(b,i){for(;++n;)for(b=2;--b+1;putchar(b?44:10))for(i=n;i>1-n;)putchar(48|--i!=0^b);} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m700OT49OXnBgqWlJWm6Fjej8qxzEzPzNJJ0MjWr0_KLNKy1tfOsNUGsJFsja13dJG1D64LSkuSMRKCIvYmJlaGBJlg60zbPOtPOUBeoGiZvYlGjq5upaGsQl6RpXQuxAWoRzEIA) [Answer] # [Burlesque](https://github.com/FMNSSun/Burlesque), 23 bytes ``` q1j{0+]0[+}jC!ClJm{)n!} ``` [Try it online!](https://tio.run/##SyotykktLixN/V@U@b/QMKvaQDvWIFq7NstZ0TnHK7daM0@x9n9VdEHcf0NDAA "Burlesque – Try It Online") ``` q1 # Block containing 1 j # Reorder stack {0+]0[+} # Surround with 0s ({1} -> {0 1 0}) jC! # Put user input as argument for continue many Cl # Collect results Jm{)n!} # Duplicate and create `not`ed copy ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 42 bytes ``` a="0,1";loop{puts a;a[?,]="1,0";a=?1+a+?0} ``` [Try it online!](https://tio.run/##KypNqvz/P9FWyUDHUMk6Jz@/oLqgtKRYIdE6MdpeJ9ZWyVDHQMk60dbeUDtR296g9v9/AA "Ruby – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` 0L[=εN.ø ``` Outputs indefinitely. [Try it online.](https://tio.run/##yy9OTMpM/f/fwCfa9txWP73DO/7/BwA) **Explanation:** ``` 0L # Push list [1,0] [ # Start an infinite loop: = # Print the current pair with trailing newline (without popping) ε # Map over both values: N # Push the current (0-based) map-index .ø # Surround the value with this index as leading/trailing item ``` [Answer] # [MATLAB](https://www.gnu.org/software/octave/), 48 bytes ``` function b(n),1,o=0,for i=3:2:n,o=[1 o 1],~o,end ``` prints to command window. start off with a hard-coded 0 and 1, storing o as 0. Then in a for loop, loop through every 2 integers from 3 to input n (if n is 1, the loop is skipped) and add ones to either end of o, using a comma instead of a semicolon so the output is put to the command window. At the same time, this becomes the new value of o. Taking the logical not operator to o inverts the zeroes and ones. [Try it online!](https://tio.run/##y08uSSxL/f8/rTQvuSQzP08hSSNPU8dQJ9/WQCctv0gh09bYysgqD8iPNlTIVzCM1anL10nNS/n/3xgA "Octave – Try It Online") [Answer] # [sed](https://www.gnu.org/software/sed/), 40 ``` :x s/^$/1/p h y/10/01/ p x s/.*/0&0/p bx ``` [Try it online!](https://tio.run/##K05N0U3PK/3/36qCq1g/TkXfUL@AK4OrUt/QQN/AUJ@rgAskrqelb6BmAJRJqvj/HwA "sed – Try It Online") [Answer] # [Brainfuck](https://github.com/TryItOnline/brainfuck), 116 bytes ``` ++++++++++[->+>+++++<<]>>->,[->[->+<<<.>>]<<-.+>>>[-<+<<.>>>]<<<-----.++++>>[->+<<<.>>]<<+.->>>[-<+<<.>>>]<+<<+<.>>] ``` [Try it online!](https://tio.run/##XYuxDsIwDER/xcyu8wWWJcSUiYUNdUhDQBEoRGk69OtDnAEJTh7O7@6W4mK6b/7ZGn51JUEZjnkWIZk6UcjMRmRmJoMiHTEOoohJZXQlv2U09FfuBkfY2gGY4GLP4LwPua4QU94qvNNrB7fC8WTtBEsnsZ@mNZRcQg03jfV9hPIB "brainfuck – Try It Online") Explanation: ``` memory map: unused;nl;character;loop_count;digit_counter;digit_counter_copy ++++++++++[->+>+++++<<]>>- create newline and set character to "1" >, read loop_count [- loop loop_count times >+ increase digit counter @ [->+<<<.>>] print the "1"s and move digit_counter to digit_counter_copy @ <<-. set character to "0" and print @ + set character to "1" @ >>> go to digit counter_copy @ [-<+<<.>>>] print "1"s and move digit_counter_copy to digit_counter <<<-----. set character to "," and print ++++ set character to "0" >> go to digit counter now follows copy of previous block denoted by @ it is just slightly modified to ouput oposite eye @ [->+<<<.>>] print the "0"s and move digit_counter to digit_counter_copy @ <<+. set character to "1" and print @ - set character to "0" @ >>> go to digit counter_copy @ [-<+<<.>>>] print "0"s and move digit_counter_copy to digit_counter <<<+ set character back to "1" <. print newline >> got back to loop_count ] ``` ]
[Question] [ An **alternating permutation** is a permutation of the first \$ n \$ integers \$ \{ 1 ... n \} \$, such that adjacent pairs of values in the permutation alternate between increasing and decreasing (or vice versa). Equivalently, it is a permutation where there are no "runs" of continuously increasing or decreasing values with a length \$ > 2 \$. For example, `2 4 1 5 3 6` is an alternating permutation for \$ n = 6 \$, because \$ 2 < 4 \$, and \$ 4 > 1 \$, and \$ 1 < 5 \$, and \$ 5 > 3 \$, and \$ 3 < 6 \$: each pair alternates in their relative comparisons. However, `1 3 2 4 6 5` is not a valid alternating permutation, because it contains the continuously increasing sequence `2 4 6` (\$ 2 < 4 \$ and \$ 4 < 6 \$). In this challenge we will consider the number of alternating permutations for a given positive integer \$ n \$. For example, for \$ n = 4 \$, there are \$ 4! = 24 \$ permutations, of which \$ 10 \$ are alternating permutations: ``` 1 3 2 4 1 4 2 3 2 1 4 3 2 3 1 4 2 4 1 3 3 1 4 2 3 2 4 1 3 4 1 2 4 1 3 2 4 2 3 1 ``` You may notice that every permutation has a duplicate which is just its reverse. Thus, for this challenge, when there is a pair of permutations which are the reverses of each other, you should only count it once. Note that for \$ n = 1 \$, there is only one permutation, just `1`, which doesn't have a distinct reverse. So for \$ n = 1 \$, the output is still \$ 1 \$. For \$ n = 0 \$, there is also only one permutation, the empty one, but you do not need to handle it (we only care about \$ n \ge 1 \$). Your task, finally, is to output the sequence of the number of alternating permutations for positive integers \$ n \$, excluding reverse-duplicates. This sequence starts: ``` 1, 1, 2, 5, 16, 61, 272, 1385, 7936, 50521, 353792, 2702765 ``` This is [A000111](https://oeis.org/A000111) (after \$ n = 0 \$) in the OEIS, and it is half of [A001250](https://oeis.org/A001250) (after \$ n = 1 \$). ## Rules * As with standard [sequence](/questions/tagged/sequence "show questions tagged 'sequence'") challenges, you may choose to either: + Take an input \$ n \$ and output the \$ n \$th term in the sequence + Take an input \$ n \$ and output the first \$ n \$ terms + Output the sequence indefinitely, e.g. using a generator * You may use \$ 0 \$- or \$ 1 \$-indexing * You may use any [standard I/O method](https://codegolf.meta.stackexchange.com/q/2447) * [Standard loopholes](https://codegolf.meta.stackexchange.com/q/1061) are forbidden * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins [Answer] # [Python 3.8](https://docs.python.org/3.8/), 54 bytes *-4 bytes thanks to @ovs* *-2 bytes thanks to @Albert.Lang* Prints the sequence indefinitely. ``` s,*a=1, while[print(s)]:a=s,*[s:=s+x for x in a[::-1]] ``` [Try it online!](https://tio.run/##K6gsycjPM7YoKPr/v1hHK9HWUIerPCMzJzW6oCgzr0SjWDPWKtEWKBNdbGVbrF2hkJZfpFChkJmnkBhtZaVrGBv7/z8A "Python 3.8 (pre-release) – Try It Online") ### Explanation I originally found this method in one of the Python implementations on the OEIS page. Here is a simple explanation of how it works. The alternating permutation in this problem can be viewed as a chain of alternating less-than and greater-than signs such that it begins with `>`: `? > ? < ? > ? < ...`. Let \$ P(n,e) \$ be the number of alternating permutations of size \$ n \$ whose last element is \$ e \$. Given this, the number of alternating permutations of size \$ n \$ is simply \$ \sum\_{i=1}^n P(n,i) \$. Our goal now is to come up with a convenient algorithm to compute \$ P \$. Let's take the example \$ P(5,4) \$, for which the permutation would be in the form: ``` ? > ? < ? > ? < 4 ``` Now, the number to the left of the `4` must be either `1`, `2`, or `3`, while the rest of the numbers will be from the set `{1, 2, 3, 5}`. In other words, the four unknown numbers must form an alternating permutation whose last element is between `1` and `3`. This however, is exactly the same as asking the answer to \$ P(4,1) + P(4,2) + P(4,3) \$. One might argue that there is a difference in that the missing numbers do not necessarily form a permutation from `1` to `n`. However, as long as they are all distinct, this will not matter, since comparisons only care about the relative ordering of the numbers. More generally, we can say that \$ P(n,e) = \sum\_{i=1}^{e-1} P(n-1,i) \$. But, this formula only makes sense if the rightmost comparison is a `<` (odd \$ n \$). Instead if it were a `>` (even \$ n \$), we would have \$ P(n,e) = \sum\_{i=e+1}^{n} P(n-1,i) \$. [Answer] # [R](https://www.r-project.org/), ~~36~~ 35 bytes ``` while(T<-rev(diffinv(T)))show(T[1]) ``` [Try it online!](https://tio.run/##K/r/vzwjMydVI8RGtyi1TCMlMy0tM69MI0RTU7M4I79cIyTaMFbz/38A "R – Try It Online") Port of [@dingledooper's answer](https://codegolf.stackexchange.com/a/248146/55372). [Answer] # [PARI/GP](https://pari.math.u-bordeaux.fr), 23 bytes ``` n->2*abs(polylog(-n,I)) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMHiNAXbpaUlaboW2_N07Yy0EpOKNQrycypz8tM1dPN0PDU1IbI3VdLyizTyFGwVDHUUDI10FAqKMvNKgAJKCrp2QCJNI08TpnbBAggNAA) Based on the PARI/GP code on OEIS by M. F. Hasler. --- # [PARI/GP](https://pari.math.u-bordeaux.fr), 35 bytes ``` n->Vec(1/(1-sin(x+O(x^n))))[n]*n--! ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMHiNAXbpaUlaboWN5XzdO3CUpM1DPU1DHWLM_M0KrT9NSri8jSBIDovVitPV1cRqlQlLb9II0_BVsFQR8HQSEehoCgzrwQooKSgawck0jRAmiBqFyyA0AA) The exponential generating function of the sequence is \$1/(1-\sin(x))\$. [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 12 [bytes](https://github.com/abrudz/SBCS) Full program. Port of [dingledooper's answer](https://codegolf.stackexchange.com/a/248146/64121). ``` ⊃(⌽0,+\)⍣⎕,1 ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKM97f@jrmaNRz17DXS0YzQf9S5@1DdVxxAk819BIY3LkAtEGoFJYzBpAiZNwaQZmDQHkxZg0hJMGhpAKIhuQyMA "APL (Dyalog Unicode) – Try It Online") --- **31 bytes:** ``` {1<⍵:2÷⍨(k!⍵-1)+.××∘⌽⍨∇¨k←⍳⍵⋄1} ``` [Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=qza0edS71cro8PZHvSs0shWBHF1DTW29w9MPT3/UMeNRz16g@KOO9kMrsh@1TXjUuxmo4FF3i2EtAA&f=e9Q31dP/UdsEA65HbRN1HnXMSHvUu@LQCgVD7Ue9mw2NAA&i=AwA&r=tryapl&l=apl-dyalog&m=dfn&n=f) Implements a formula from OEIS: $$ 2\times a(n+1) = \sum\_{k=0..n} {n \choose k}\times a(k)\times a(n-k) $$ --- **31 bytes:** ``` {+/2((-\⍳⍵-1)≡⍥×-/)¨∪⍋⍤,¨,⍳⍴⍨⍵} ``` [Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=q9bWN9LQ0I151Lv5Ue9WXUPNR50LH/UuPTxdV1/z0IpHHase9XY/6l2ic2iFDljJlke9K4AKawE&f=e9Q2UedRx4y0R70rDq1QeNS72RwA&i=AwA&r=tryapl&l=apl-dyalog&m=dfn&n=f) Generates all permutations and counts the alternating ones that start with an increment. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 22 bytes ``` ⊞υ¹FN≔⊞O⮌EυΣ…υ⊕λ⁰υI§υ⁰ ``` [Try it online!](https://tio.run/##HY3LDsIgFET3fgXLS1ITuu6q6YqF2ugXIL1KE165QKNfj@Aks5mck9FGkQ7K1rqWZKAMbOTT6RWIgfSx5GtxTyTgnM0p7W8PHbtFJJUDwR0PpIRwUbGrj@Jg@WqLiwn/QXpN6NBn3MDynoGJ1tI@Vtp9hkWlDHOWfsNPN0RjplpHUc@H/QE "Charcoal – Try It Online") Link is to verbose version of code. Works for `n=0`. Explanation: Uses a formula from OEIS. ``` ⊞υ¹ ``` Start with the empty permutation. ``` FN ``` Repeat `n` times. ``` ≔⊞O⮌EυΣ…υ⊕λ⁰υ ``` Take the cumulative sums of the list, reverse the result, and append a zero. ``` I§υ⁰ ``` Output the first element of the final list. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~9~~ 8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` $F0).sO` ``` Port of [*@dingledooper*'s Python answer](https://codegolf.stackexchange.com/a/248146/52210), but outputs the \$n^{th}\$ value instead to save a byte. [Try it online](https://tio.run/##yy9OTMpM/f9fxc1AU6/YP@H/fxMA) or [verify the first 25 test cases](https://tio.run/##yy9OTMpM/W9k6upnr6TwqG2SgpK9n9J/FTcDTb1i/4T/SuoqjxrmGRZb6YXpaMb8BwA). Outputting the infinite sequence for a direct port would be: ``` 1[0ª.sO¤, ``` [Try it online.](https://tio.run/##yy9OTMpM/f/fMNrg0Cq9Yv9DS3T@/wcA) **Explanation:** ``` $ # Push 1 and the input F # Pop and loop the input amount of times: 0 # Push a 0 ) # Wrap the entire stack into a list .s # Get the suffixes of this list O # Sum each inner suffix-list ` # Pop and push all values to the stack # (after the loop, the top value is output implicitly as result) ``` ``` 1 # Start with 1 [ # Loop indefinitely: 0ª # Append 0 to the current list (convert an integer to a digit-list # before appending, which happens for the 1 in the first iteration) .s # Get the suffixes of this list O # Sum each inner suffix-list ¤ # Push the last integer (without popping the list) , # Pop and output it with trailing newline ``` [Answer] # Haskell + [hgl](https://gitlab.com/WheatWizard/haskell-golfing-library), 22 bytes ``` he<ix(rS(+)<he*^rv)[1] ``` This uses the by Chai Wah Wu that everyone else is using. It produces an infinite list of the results in order. ## Explanation First we have the iterative step `rS(+)<he*^rv` this gives the cumulative sums of the first element with the list reversed. With `ix` we iterate this infinitely starting with `[1]`. Then from there we just get the head of every element in the list with `he`. # New method, 25 bytes ``` cn(mF~<lt3<<fce)<tv e1<e1 ``` This method isn't new, but it hasn't been used here yet and it's pretty neat. And it's rather close to edging out the Chai Wah Wu method. ## Explanation From the comments on the OEIS: ``` Number of sequences (e(1), ..., e(n-1)), 0 <= e(i) < i, such that no three terms are equal. [Theorem 7 of Corteel, Martinez, Savage, and Weselcouch] - Eric M. Schmidt, Jul 17 2017 ``` First we use `e1` to get the range from \$1\$ to \$n\$. The next step is `tv e1` which is a little hard to explain, because `tv` is fundamentally a pretty weird operation. Instead we can talk about the equivalent but *slightly* longer `sQ<m e1`. `m e1` maps `e1` across the lists to creates ranges of increasing size. `sQ` creates a list of ways to pick one element in order from each list. So the result now is all the non-negative integer sequences whose values are smaller than their indexes. Now we count all the ones that don't have any value repeated 3 times. `cn` will take a predicate and count the number of elements satisfying that predicate so we use that. Now we just need a predicate that says "Contains no element 3 or more times". One way to do this is ``` pred x = mF(lt3<fce x)x ``` Here `fce` counts the number of times an element appears in a list, add it with `lt3` and `lt3<fce x` says "does this element appear less than three times in `x`". We use `mF` to collect the result of running this over every element of `x`, so it says "does all the elements of `x` appear less than 3 times in `x`". Now we use a bit of monad magic t make this point free and we have `mF~<lt3<<fce`. # Naive method, 31 bytes ``` dv2<P1<cn(fo<pa nq<pa cp)<pm<e0 ``` ## Explanation First we get all the permutations of size \$n+1\$. Now we count the satisfactory permutations with `cn`. To determine if a permutation is satisfactory we first compare consecutive elements `pa cp`. This gets us the direction of each change between elements, if there are two consecutive equal elements now that means that there is a run of 3 which is monotonic, and thus that permutation is invalid, so we use `pa nq` to compare the consecutive elements and `fo` to ensure they are all unequal. Once we've counted those we need to divide by two, rounding up. Do do this I do the old plus 1, divide by 2 trick. `dv2>P1` # Reflections The nice thing about this problem is there are many ways to approach it. Since I've tried this so many ways I have gotten quite a bit of useful reflection out of this. ### Reflections on the Chai Wah Wu method Overall this is the method with the least room for improvement. hgl doesn't seem to have any major gaps. * `rS(+)` which gives the cumulative sums might be worth having a short hand. Hard to say. * `[1]` is a little long, but I'm not sure if it's worth having a 2 bytes shorthand especially, when `[1]` never needs any whitespace padding while an alias would. ### Reflections on the new method * While I was working on this I found a bug with `mL` and related functions. It wouldn't have hurt this answer even if I went with the strategy that used those functions, but it was confusing and should be fixes. * There aren't really many functions having to do with sub-sequences. Originally I had tried to get all the subsequences longer than 3 and check that none of them contained only 1 type of element. However the only subsequence function was `ss` which just gets all the subsequences. If I had a function `ss3` which gets subsequences of size 3, then this could be ``` cn(no lq<ss3)<tv e1<e1 ``` which would have been 3 bytes shorter tying it with the shortest method. But moreover there should just be more than one function dealing with sub-sequences. ### Relfections on the naive method * There should be a shorthand for "all permutations of n elements". `pm<e1` is the shortest way to achieve that right now. Would save 2 bytes overall. * It might also be nice to have a "permutations such that" function, however it would need to be 2 bytes to save anything for this answer. * The naive method uses `pa cp`, and it's not even the first time I've used `pa cp`. The alternative answer [here](https://codegolf.stackexchange.com/a/243187/56656) uses `pa cp` and this change would have saved bytes there too. With a 3 byte name this would save 2 bytes here and 2 bytes on that answer. * `dv2<P1` is abysmal. There should be a built in for integer division rounding up. It would save another 3 bytes on the naive approach, which if combined with the above would put it much more on par with other methods. * Doesn't make a difference here, but for a short bit I was frustrated that while we have `ce`, which counts the number of elements equal to some element, we don't have something which counts elements *not* equal to some element. Wouldn't have saved bytes here, but it's worth having. [Answer] # [HOPS](https://akc.is/hops/), 7 bytes ``` bous(1) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70kI7-geG20kq5uQVFqsq2RgVLsgqWlJWm6FsuT8kuLNQw1ITyo4AIoDQA) This sequence is the [Boustrophedon transform](https://codegolf.stackexchange.com/questions/233507/boustrophedon-transform) of the sequence \$1,0,0,0,\dots\$. HOPS is an extremely powerful language for integer sequences. To print the first 20 terms (0-indexed) of the sequence, just run `hops --prec=20 "bous(1)"` [Answer] # [Factor](https://factorcode.org/), 50 bytes ``` [ { 1 } [ 0 suffix reverse cum-sum ] repeat last ] ``` [Try it online!](https://tio.run/##Dck7DsIwEAXAPqd4FyCCCgkOgGhoEFWUYmW9gIXjhN014iPObtLODBJ80no5H0@HHWal@3vWmB3GR2EONIzit9ZcPJrHYLhTMxOuzFRJ8bPElA37ptnWDl9s8EOHNawMQ3xB@aQaEcq4sjKiX2SmOJKYo69BUkJb/w "Factor – Try It Online") Returns the (1-indexed) \$n\$th term in the sequence. It uses dingledooper's method, but a comment by @Neil is what I based this answer on: "zero-prefixed cumulative sum of reverse of previous row." [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~106~~ 105 bytes ``` *a;*b;c;i;j;f(n){a=calloc(n,8);for(*a=i=1;n/i;++i,a=b)for(b=calloc(n,8),j=i,c=0;j--;)b[i-j]=c+=a[j];n=c;} ``` [Try it online!](https://tio.run/##VZBvb4IwEMbf@ykuJiYFSuRPEM2te7PsUygvSi2uzBUDJCMzfPWxQ9Fp0156v7t70qfKPyg1DK5EN0eFBkssmHXOUih5PFaKWb52sKhq5kphRIh2adDzDJcid0acPzbyUhiuRICl76OTb41fZkJ5Qm7LDK1Q2A/GtvAljWUOnGdAawS6O2nV6v02AwHnkAPtiENClxWH1ZillIfxmlC6iQkmQRIRj5M43URjPYjSVdLjRVNVtmlBfcjapajVp66v0vNd9x7tus0bnWTO4TGP59M02QI2PsvYve5oLMDp@gKN@dFVwW4PdpYTcO8Egb5n7HYuYleTN6MtqV2lPAjxqdRQqWCt80w10fvvXCaz/4ZTTS0Fmy/24L8CxUWzs@Sq5dDwu/FGCJ1Nsv2sH35VcZSHZvC//wA "C (gcc) – Try It Online") *Uses the same method [dingledooper](https://codegolf.stackexchange.com/users/88546/dingledooper) explains in his [Python answer](https://codegolf.stackexchange.com/a/248146/9481).* *Saved a byte thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!!* Inputs a positive integer \$n\$. Returns the \$1\$-based \$n^\text{th}\$ element of the sequence. [Answer] # [JavaScript (V8)](https://v8.dev/), 55 bytes A port of [dingledooper's algorithm](https://codegolf.stackexchange.com/a/248146/58563). A full program that prints the sequence forever. ``` for(a=[s=1];;)a=[s,...a.reverse(print(s)).map(x=>s+=x)] ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNEts/j/Py2/SCPRNrrY1jDW2loTxNLR09NL1CtKLUstKk7VKCjKzCvRKNbU1MtNLNCosLUr1rat0Iz9/x8A "JavaScript (V8) – Try It Online") [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 19 bytes ``` 2Abs@PolyLog[-#,I]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n27738gxqdghID@n0ic/PVpXWcczVu1/QFFmXolDenRQYl56arSRQWzs//8A "Wolfram Language (Mathematica) – Try It Online") Equivalent to the [PARI/GP answer by alephalpha](https://codegolf.stackexchange.com/a/248156/110698), but I first came across this representation in Peter Luschny's [An introduction to the Bernoulli function](https://arxiv.org/abs/2009.06743). [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 11 bytes ``` ɾṖƛ¯±¯A;∑½⌈ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLJvuG5lsabwq/CscKvQTviiJHCveKMiCIsIiIsIjEiXQ==) The `½⌈` is because of the requirement to handle reversed lists. ``` ɾṖ # Permutations of 1...n ƛ ;∑ # Count where... ¯ # Deltas of... ± # Signs of ... ¯ # Deltas A # Are all nonzero ½⌈ # Halve the final result and round up ``` The is-alternating code `¯±¯A` works because, for example with `[1, 6, 2, 4, 3]`: ``` ¯ # Deltas - [5, -4, 2, -1] - Signs should be alternating ± # Signs - [1, -1, 1, -1] - Should be list of alternating 1s and -1s ¯ # Deltas - [-2, 2, -2] - If there are two consecutive equal values in ^ there should be a 0 A # All - 1 - if and only if there's no zeroes in ^ the list is alternating. ``` ]
[Question] [ I'd like to roll up the ability scores for my Dungeons and Dragons character. But I'd also like them to be balanced (and slightly better than average). Typically, a character's stats are created by rolling four 6-sided dice, adding together the three highest results, and doing this 6 times. A 6 sided die has the numbers 1 to 6, with equal probability of landing on each. The 6 scores can be in any order, and are typically displayed out in an array. Unfortunately, this has a slight pitfall, namely that some players' stats can be much higher than other players' stats. So for this generator, the stats should be a little more balanced, namely that at least one stat should be less than or equal to a certain threshold, at least one stat should be greater than or equal to a certain threshold, and the total should be greater than or equal to a certain threshold. However, the randomness should still be preserved. If a generated stat array does not qualify, the entire array should be rerolled. Given 3 inputs, `l`, `h`, and `t`, respectively corresponding to the low threshold, the high threshold, and the total threshold, output 6 stats (in any order) that meet the criteria. All 6 stats must be included. The stats should be randomly generated, using the stat generation described above. For example: ``` l h t | low example | high example 10 15 75 | 6 14 18 12 10 15 | 10 18 18 18 18 18 8 18 80 | 10 18 16 13 8 15 | 18 18 18 8 18 18 18 18 108 | 18 18 18 18 18 18 | 18 18 18 18 18 18 ``` The code doesn't need to be fast, it just needs to get there eventually. Note that formatting doesn't much matter. Assume valid inputs. [Answer] # [Japt](https://github.com/ETHproductions/japt), 28 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Takes input as `t`, `l` & `h`. ``` @§Xx*Xd§V*Xd¨W}a@6Æ4ÆÒ6öÃÍÅx ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=QKdYeCpYZKdWKlhkqFd9YUA2xjTG0jb2w83FeA&footer=WyJPdXRwdXQ6ICIrVSAiTG93OiAiK1VybSAiSGlnaDogIitVctQiVG90YWw6ICIrVXhdtw&input=NzUgMTAgMTU) ``` @§Xx*Xd§V*Xd¨W}a@6Æ4ÆÒ6öÃÍÅx :Implicit input of integers U=t, V=l & W=h @ :Left function, taking an array X as input § : Is U less than or equal to ... Xx : X reduced by addition after * : Multiplying each element by ... Xd : Any in X § : Less than or equal to ... V* : V multiplied by ... Xd : Any in X ¨W : Greater than or equal to W } :End left function a :Repeatedly run the right function and return the first result that returns true when passed through the left function @ :Right function 6Æ : Map the range [0,6) 4Æ : Map the range [0,4) Ò : Negate the bitwise NOT of (i.e., increment) 6ö : Random integer in the range [0,6) Ã : End map Í : Sort Å : Slice off the first element x : Reduce by addition ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 40 bytes Full program. Prompts for total, then high, then low. ``` {(+/-⌊/)?6 4⍴6}⍣((∨/⎕≥⊣)∧(∨/⎕≤⊣)∧⎕≤1⊥⊣)⍬ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKO94H@1hra@7qOeLn1NezMFk0e9W8xqH/Uu1tB41LFC/1Hf1EedSx91LdZ81LEcIbIEKgLhGD7qgijpXQMy8b8CGBRwlVgpmJtyZVgpGJpy5QBJAwA "APL (Dyalog Unicode) – Try It Online") `{`…`}`…`⍬` apply the following lambda to the empty list dummy argument:  `6 4⍴6` cyclically reshape `6` into a 6-row, 4-column matrix  `?` roll those dice  `(`…`)` apply the following tacit function to that:   `+/-⌊/` the sum minus the minimum (lit. plus-reduction minus smallest-reduction …`⍣(`…`)` keep applying that function to its results until the following holds true:  `⊣` the results  `1⊥` evaluated as unary (i.e. summed)   `⎕≤` is the input (total) less than or equal to that?  `(`…`)∧` and:   `⊣` the results   `⎕≤` is the input (high) less than or equal to those?   `∨/` are any true? (lit. OR-reduction)  `(`…`)∧` and:   `⊣` the results   `⎕≥` is the input (low) greater than or equal to those?   `∨/` are any true? (lit. OR-reduction) [Answer] # [Troll](http://hjemmesider.diku.dk/%7Etorbenm/Troll/), 135 bytes Right tool for rolling dice, but not necessarily for golfing. ``` function s(x)=w:=x pick1;x:=x--w;'w<>x&call s(x) function f(l,h,t)=call s(repeat x:=6#sum largest3 4d6until h<=max x&l>=min x&t<=sum x) ``` [Try it online!](https://topps.diku.dk/torbenm/troll.msp?noOfDice=1&userExp=function%20s%28x%29%3Dw%3A%3Dx%20pick1%3Bx%3A%3Dx--w%3B%27w%3C%3Ex%26call%20s%28x%29%0Afunction%20f%28l%2Ch%2Ct%29%3Dcall%20s%28repeat%20x%3A%3D6%23sum%20largest3%204d6until%20h%3C%3Dmax%20x%26l%3E%3Dmin%20x%26t%3C%3Dsum%20x%29%0A%0Acall%20f%2810%2C15%2C75%29) (Click on `Make random rolls.` and the result will appear a bit further down.) The first function generates a shuffled string from a collection of numbers. This is necessary as collections in *Troll* are generally unordered and printed in ascending order. slightly ungolfed: ``` function shuffle(x) = w := x pick 1; x := x -- w; \ -- multiset difference 'w <> (x & call shuffle(x)) \ <> vertically concat strings function f(l, h, t) = call s( repeat x := 6 # sum largest 3 4d6 until h<=max x & l>=min x & t<=sum x ) call f(10, 15, 75) ``` [Answer] # JavaScript (ES6), 138 bytes ``` (l,h,t)=>eval(F="while(F||S-3<t)[F=3,S=3,...A=[3,3,3,3]].map(n=>(A.map(m=_=>n+=m<(v=Math.random()*6|0)?v:m=v),S+=n-=m,F&=n>l|2*(n<h),n))") ``` [Try it online!](https://tio.run/##PY9Pa4NAEMXv@RSDkDITN1uTQAmtY8mhHgppDx5DKIt/4hZ3FTU2pfazWyOkDI/5vccc3nyqTjVxrat2acskHTIesBC5aImDtFMFhux85bpIMez7aLnxWzqEvBHRKCnljg8bMc3xKI2q0HKAu4kMf3BgXTY@drxXbS5rZZPSIC0eeo@eu0fDHYnIZbtkI8I7tkHRrxdo/ZyEJXJoyMoaNTB4T6DBh9V1uy7BzwxAjXmGWwGrUVuPxigubVMWqSzKEzrzBnCv7Xg1T@Ae9upyw@hsJiRHwGv0/iabttb2pLNvVCQrlbzYBNceCZhqG21xfFX9e3W5eSXrNDnHKWIlICbgACpwIRbgEc1@hz8 "JavaScript (Node.js) – Try It Online") As pointed out by @Shaggy, a recursive version is shorter ([134 bytes](https://tio.run/##PY9Pa8JAEMXvfopBsMyYdRsNFLGZiId6KNgechQpS/65JbsJSQyW2s@ebgOW4TG/93iX96l61SaNrruFrdJsyHkoOTpzVHDHESo@7jkQsZOUcsfHQIx3OkmjarSushvJ8AdH1mMTYs8H1Z1lo2xaGaT5082nbb8x3JOIPbYLNmL/wDYqb6s52vBMwhKJ/S1eBGFH2wI72qghrxrUwOA/g4YQln/f8wi@JwDK5TmuCZdOa59clFS2rcpMllWB01kLeNDWtWYpPMJBXe8YX8yINBXwGr@/ybZrtC10/oWKZK3SF5viyicB4wijLbrh6t@r690r2WTpJckQawEJAUdQgweJAJ9o8jP8Ag)). But it will fail when the odds are low ... whereas the above version will just take forever to find a solution. :-) ### Commented The main function initializes `F` to a truthy value and invokes an `eval()` ... ``` (l, h, t) => eval(F = "...") ``` ... whose content is: ``` while(F || S - 3 < t) // while F is truthy or S - 3 is less than t: [ F = 3, // start with F = 3 (boundary flags) S = 3, // start with S = 3 (sum of all die + 3) ... A = [3, 3, 3, 3] // append 4 more 3's ] // .map(n => ( // for each entry, starting with n = 3: A.map(m = // repeat 4 times, starting with m non-numeric: _ => // n += m < ( // update n: v = Math.random() // pick a dice value v in [0 .. 5] * 6 | 0 // ) ? v // and add it to n : m = v // update m to min(m, v) ), // end of inner map() S += n -= m, // subtract m from n and add the result to S F &= n > l | // clear the bit #0 of F if n <= l 2 * (n < h), // clear the bit #1 of F if n >= h n // yield n )) // end of outer map() // implicit end of while() ``` [Answer] # [R 4.1](https://www.r-project.org/), 112 bytes Using the new shorthand notation of defining functions (`\(x) expr`): ``` r=\(l,h,t){x=l;while(sum(x)<t|min(x)>l|max(x)<h){x=matrix(sample(6,24,r=T),nr=6);x=rowSums(x)-apply(x,1,min)};x} ``` **Explanation** Generate 6x4 matrix (nrow=6) with random number 1-6: ``` x=matrix(sample(6,24,r=T),nr=6) ``` Calculate the sum over the rows and subtract the row-minimum to get the sum of the largest three values: ``` x=rowSums(x)-apply(x,1,min) ``` And repeat as long criteria not met: ``` while(sum(x)<t|min(x)>l|max(x)<h) ``` Initialise `x` to a value that violates criteria (could also have chosen `0`) ``` x = l ``` Edit: added explanation [Answer] # [Factor](https://factorcode.org/) + `dice math.unicode combinators.short-circuit.smart`, 153 bytes ``` [ [ 6 [ 4 [ ROLL: 1d6 ] replicate natural-sort rest Σ ] replicate 3dup { [ Σ <= nip ] [ nip minmax '[ _ _ between? ] ∀ ] } && ] [ drop ] until 2nip ] ``` [Try it online!](https://tio.run/##VVDLSgNBELznK@oUT1lcHzHE11GEoKB4WkQmsx3TZHdm7elFQwh49D/8Hz/CH1k7KwhO091MVXUxPQvnNUr3cH99czWFSyn6hJI9IdFLS8FTQoqiHJ5RO132JWsD@1gSViSBKvhYzzk4M0pZWpp65Fl8y5ql2on@ziR1yknZ/Pt7lJIEC1mjEVJdN8JBcToYbAaws7HI95EfY4sTK3/gBPnEsMm@YduuQIGx5ZHl3e1sNkVejvEIoaZi75Rg72rFVaPdFgYnxdfnP8Fh2TbmW@zws3MEbowu@l5zqN0b9go8WcxJX4nCpdHfH@9WtxgOe20pcTfUBuUKB71DtzG6/8@L2jWw7f0q634A "Factor – Try It Online") It's a quotation (anonymous function) that takes a low-high pair (like `{ 10 15 }`) and a sum target from the data stack as input and leaves a sequence of 6 stat values on the data stack as output. ## Explanation: * `[ ... 3dup ... ] [ drop ] until 2nip` Keep making stats (and discarding them) until one of them is valid. * `6 [ ... ] replicate` Create a sequence with 6 values given by a quotation. * `4 [ ROLL: 1d6 ] replicate` Roll 1d6 4 times and collect the results in a sequence. * `natural-sort rest Σ` Sort, remove the first (lowest) value, and sum. * `{ [ Σ <= nip ] [ nip minmax '[ _ _ between? ] ∀ ] } &&` Check if the sum is >= the target sum, and check whether both elements in the low-high pair are between the minimum and maximum value (inclusive) in the stats. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 36 bytes ``` W∨›Iζ↨υ¹∨›Iη⌈υ‹Iθ⌊υ≔EE⁶E⁴⊕‽⁶⁻Σκ⌊κυIυ ``` [Try it online!](https://tio.run/##XY3NCsIwDMfvPkWPGUxw4ObBk3oQwaHoE4QtuLK1m02r4svXdkMQAzkkv/9H1aCpeuy8fzayIwEnA3tDaMnADtnCO0nFFpnApSJLwvEvaMKvxJdUToGLgiMxT@gekdRfFEZsmOVNQ4nDuEX0DrBMxUFXhhRpSzVcUNe9giI6xgTHcA0Z7U9eOzKXrGdnI7WdCkPJ2vtsIbJcrHI/f3Qf "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` W∨›Iζ↨υ¹∨›Iη⌈υ‹Iθ⌊υ ``` Repeat until the initially empty predefined list fails to satisfy any of the conditions that its total is less than the third input, its highest member is less than the second input or its lowest member is greater than the third input. The total is checked first because using base 1 instead of Sum allows the check to run on the empty list. ``` ≔EE⁶E⁴⊕‽⁶⁻Σκ⌊κυ ``` Generate 6 sets of four dice, subtract the minimum of each set from their sums, and replace the predefined list with them. ``` Iυ ``` Output the valid list. [Answer] # [Python 3](https://docs.python.org/3/), ~~139~~ 137 bytes Recursive function which returns a tuple of integers. ``` from random import* f=lambda l,h,t,*k:k*(t<=sum(k)>max(k)>=h>=l>=min(k))or f(l,h,t,*eval('sum(sorted(map(randint,[1]*4,[6]*4))[1:]),'*6)) ``` [Try it online!](https://tio.run/##TY/LisMwDEX3/QrtahktYvqYEOr8SOjCJQkxfiQ4nqH9@lQuGWYWsnSQuPd6eeVpjqdtG9McIJnYc7NhmVOWh1F7Ex69AU8TZZKucVLkm16/g3DYBvMsTU@t9q0ONjLhnGAU@/3wY7w4luuV9YZeBLOI4mFjpk7d5Zm6K7@InWruSEd5RdxGlvgIgI0gVEWgLgRfFyQQNQNXXRVQO6mqxuYA4ED/eiPjktiGI/Fo1nVIGfbcOgNn4HoJe9MeiqEtZg7/Fvyt/4vtDQ "Python 3 – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), 91 bytes ``` ->l,h,t{1while(w=(k=*1..6).map{(k*4).sample(4).sort[1,3].sum};w.min>l||w.max<h||w.sum<t);w} ``` [Try it online!](https://tio.run/##JcnRDoIgFIDh@56iS3EnxllZbIov4rigLYcTiimOmvrsBHX3f/un5f6JvYin1oAGv2LQg3kUQRSjKJHSK6FWubUYywuhs7IuzVyvyXcIZ0nnxe51oHZ4tmbbUqh3o3Ok0XhShz26Y98hA6zgVslDFgfkwNkf@BMyLuMX "Ruby – Try It Online") [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 198 bytes ``` from random import* def g(l,h,t,r=range): while sum(k:=list(sum(sorted(randint(1,6)for _ in r(4))[1:])for _ in r(6)))<t or(n:=list(map(sum,zip(*((i<=l,i>=h)for i in k)))))[0]*n[1]!=1:pass return k ``` Not fast but gets the job done. It is quite possible that the last test won't finish as it needs perfect rolls. On TIO the additional output is a check that the sum is greater or equal than the `t` and the count of numbers less than or equal to `l` and greater or equal to `h`. [Try it online!](https://tio.run/##tY9Bb4QgFITv/orX28NwkLS7JWbZP2JMYyKuZBXIg82m/fMWrGn03nKBzGTmG/xnHJ19lZ6WZSA3A3W2T5eZvaNYFr0e4IYTH3nkpJJ506wu4DmaSUN4zHiv1WRCxPwOKaJ7zBXGRhT8zAZH8AHGAuEbY42o2710ZoxdIjhCu9XMnc9V/Mt4LBHNRU3cXNW4pkxO3Vk@TdWWthHtixK170IogHR8ULKXdawSFRcn/n4qPOUteef2j5TexHU/u6q4FzIS9rS9l5YcvR@Y5EJyWR1Ym/YPNLFWi0oeeL/qXxKXbw "Python 3.8 (pre-release) – Try It Online") [Answer] # Python 3, 138 bytes ``` from random import* def f(l,h,t): while l<min(s:=[3+sum(d:=choices(range(6),k=4))-min(d)for _ in[0]*6])or h>max(s)or t>sum(s):0 return s ``` [Answer] # [Java (JDK)](http://jdk.java.net/), 175 bytes ``` (l,h,t)->{int r[]=new int[6],i,j,m,d,s,x=0,T=0;for(;x<3|T<t;)for(x=T=i=0;i<6;T+=r[i++]=s-=m,x|=s<h?s>l?0:1:2)for(m=7,s=j=0;j++<4;s+=d+=Math.random()*6,m=d<m?d:m)d=1;return r;} ``` [Try it online!](https://tio.run/##JVDBcoIwFLz3K94xKTGjtdWO4en00psnuTkcUgMSSsBJgsVRvp0GPO3svN19@14pr3JWqt/hVEnnYC91DfcXAF37zObylME33Ed2TCEnAaFiI4XiCZ4K6IP@0v5U@gTOSx/g2mgFJmSRg7e6PgeztGdHp2gIkTkgDKRiBfN0tr2PSfaYYp39TbtWKdOsZIYp5liHc5bgXOSNJaKLl48k9oKOrMMEdZjoeCWSCO1RR1GKboaGdQ90cbFz22o33yw2b5Pe4Jo5LIOjjKL4XbgIVYR76QtuZa0aQ@jrihlUsdmpjaEKF8JmvrU1WNEPYip/lRZsqJ/znCzZ4pOtP@hzcrg5nxnetJ5fwtW@qkkZ3stbryv@Za28Oe6b50eIpZOrf@mHfw "Java (JDK) – Try It Online") [Answer] # [Ly](https://github.com/LyricLy/Ly), 104 bytes ``` n`n,n,>1[p6[>&p<6[>16?<,]p>arppp&+s>l<p<,]p>>&s<&l<<&s>>>>&p&l<a0Isp>rlGfp<s>flLfp<&+sp>rlLfp**sp<<<l!]> ``` [Try it online!](https://tio.run/##HYuxCoRAEEN7/8JmCt3CbWSLMFeKcH8gwtlYDUtwqvv6dTRF8ngQ@7dWfzXVpHnjvKkQ0Xn@IO3U4yIpo6uBr1BxiAHiGhEGH9Pq1MuWk3A97Rsbl0cFDoMTgPW7tla6XLoy3Q "Ly – Try It Online") The specific steps in this code are pretty straightforward, the only trick is keeping the data organized on the stacks. Here's how the stacks are used: ``` s0: low-high-total values (adjusted) s1: loop control numbers (three nested loops share one stack) s2: dice rolls and temp storage of stats s3: stats accumulator and workspace s4: low-high-test work area ``` Also, the input parameter are incremented/decremented to make the comparisons to the generated stats easier. The operators available in `Ly` are less than `<` and greater then `>` and the criteria allow the stat to equal the threshold. Adjusting the threshold was shorter than adding logic to check "greater than or equal", etc... ``` # Step 0: Read in low, high, sum thresholds, setup for comps n`n,n,> n` # Read line one, low thresh, increment n, # Read line two, high thresh, decrement n, # Read line three, sum of stats, decrement # Step 1: Loop until a set of stats meets all criteria 1[p ... l!] # The iteration check is pulled from the backup cell # Step 2: Generate a set of 6 stats 6[>&p<6[>16?<,]p>arppp&+s>l<p<,]p 6[ ,]p # Loop once for each stat # Step 2.1: Generate 6 random dice rolle >&p<6[>16?<,]p >&p< # Clear the stack to hold the rolls 6[ ,]p # Loop 6 times >16?< # Push random 1-6 on the dice roll stack # Step 2.2: Compute the stat from the 6 dice rolls >arppp&+s>l<p< >a # Switch to dice stack, sort entries rppp # Reverse stack, pop 3 entries (lowest rolls) &+s # Sum the remaining 3 (highest) and stash >l # Switch stacks and load sum (stat) <p # Switch back to dice stack and clear it < # Switch back to the loop iterator stack # Step 3: Check to see if stats meet criteria >>&s<&l<<&s>>>>&p&l<a0Isp>rlGfp<s>flLfp<&+sp>rlLfp**sp<<< # Step 3.1: Save a "ready to print" copy of the stats >>&s<&1 >>&s # Switch to the stats stack, stash on the backup cell <&1 # Switch to an empty stack and restore from backup # Step 3.2: Init test stack, copy in low/high/sum thresholds <<&s>>>>&p&l <<&s # Switch to rules stack, copy to backup cell >>>>&p&l # Switch to test stack, clear, load from backup # Step 3.3: Check minimum stat against threshold <a0Isp>rlGfp <a # Switch to stats stack, sort entries 0Is # Pull smallest entry to top, save in backup p # Clean-up stack (pop duplicate) >r # Switch to test stack, reverse entries lG # Load min stat, do "min-stat>min-thresh" comp fp # Stack cleanup, delete min-thresh # Step 3.4: Check maximum stat against threshold <s>flLfp <s # Save largest stats to backup cell >f # Switch to test stack, flip max-thresh to top lL # Load max stat, do "max-stat<max-thresh" comp fp # Stack cleanup, delete max-thresh # Step 3.5: Check sum of stats against threshold <&+sp>rlLfp <&+s # Sum stats, stash in back cell p> # Cleanup stack, switch to test stack r # Reverse stack, puts sum-thresh on top lL # Load sum, do "sum-stat<sum-thresh" comp fp # Stack cleanup, delete sum-thresh # Step 3.6: Consolidate test results **sp<<< **sp # Multiple all three comps, stash the result <<< # Switch to the iterator stack #Step 4: Print the result > # Switch to stack with copy "ready to print" of stats ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~35~~ 34 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` [6Lε₄ε6LΩ}{¦O}©O¹@i®δ.SεN‹NQà}P#]® ``` Can probably be shorter, but this will do for now. First input is `t`, second input is a pair `[l,h]`. [Try it online](https://tio.run/##AU4Asf9vc2FiaWX//1s2TM614oKEzrU2TM6pfXvCpk99wqlPwrlAacKuzrQuU861TuKAuU5Rw6B9UCNdwq7//zc3Cls5LDE3Xf8tLW5vLWxhenk) or [try it online with added debug lines](https://tio.run/##yy9OTMpM/f8/2szn3NZHTS3ntgIZK2urDy3zrz20UsmxpCQ1t6DESkHJ3tZfKbg0F8w6tNNBySMzPUMhNS@/ND3DHiSWeWjduS16wYc2qesc3qvknJ9bkFiUqlCeWZKhEH14fyxY37mtfo8advoFHl5Qq@SYV6lQlpiTmQKWCVByyy/NS1FIhIgpFKUWl@aUgA1Wrj20zR6ED61TcsvMS8yBSoL06fz/b27OFW2pY2ge@19XNy9fNyexqhIA). **Explanation:** ``` [ # Start an infinite loop: 6L # Push list [1,2,3,4,5,6] ε # Map each value to: ₄ # Push 1000 ε # Map each digit to: 6L # Push list [1,2,3,4,5,6] Ω # Pop and leave a random item from this list }{ # After the inner map: sort the four values from lowest to highest ¦ # Remove the first/lowest O # And sum the remaining three together }© # After the outer map: save this list of six values in variable `®` (without popping) O # Sum the list ¹@i # If the sum is larger than or equal to the first input: ® # Push the list from variable `®` again δ # Apply double-vectorized with the (implicit) second input-pair: .S # Compare: -1 if a<b; 0 if a==b; 1 if a>b ε # Map this list of lists to: N‹ # Check for each value if it's smaller than the 0-based map-index NQ # Then check if the result (0 or 1) is equal to the 0-based map-index à # Check if any is truthy by leaving just the maximum }P # After the map: check if both are truthy by taking the product # # If this is truthy: stop the infinite loop ] # Close the if-statement and infinite loop ® # Push list `®` # (after which it is output implicitly as result) ``` [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal), 29 bytes ``` ÷ʀ℅$19r℅":∑⁰$-:£4ḭw3ẋf:∑¥$-Wf ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%C3%B7%CA%80%E2%84%85%2419r%E2%84%85%22%3A%E2%88%91%E2%81%B0%24-%3A%C2%A34%E1%B8%ADw3%E1%BA%8Bf%3A%E2%88%91%C2%A5%24-Wf&inputs=%5B10%2C15%5D%0A75&header=&footer=) ]
[Question] [ Check if two blocks of bits dovetail perfectly. # Specifications * A block of bits is a fixed sequence of 8 bits just like this for example : **11110101**. * For simplicity we refer to `truthy`/`falsey` values as `1`/`0` bits but they can be everything capable of representing those two states in a clear, well defined and consistent way, for example :`0/1` `x/y` `False/True` `"false"/"true"` `'a'/'b'` `[]/[...]` `odd/even` `>0 / <0` `0 / !0` **What does it mean dovetail perfectly?** * 1's bits of one block can fit only into 0's of the other block or outside it. * You can shift an entire block left or right but you cannot modify a block nor reverse it. * The resulting block must contain all 1's of both inputted blocks and only those. * There must not be any 0's between 1's while there can be any trailing and leading 0's. * The resulting block can be more than 8 bits long. * Example ``` Input : [ 10010111, 01011010 ] 10010111 ↓ ↓ ↓↓↓ 01011010 &lt- shif by 2 result 0111111111 => dovetails perfectly ``` **Input:** two blocks of bits. * You don't need to handle empty blocks (all 0's). **Output:** your solution have to clearly state if input blocks can dovetail perfectly as described above or not. * the resulting block won't be a valid answer. # Test cases. ``` 00000000, 00000000 | you don't 00000000, ... | need to ... , 00000000 | handle these 11111111, 11111111 -> True 11111111, 10000000 -> True 11110000, 00101000 -> False 00101000, 10100000 -> True 10000000, 00111000 -> True 00110011, 11001100 -> True 00010000, 11101010 -> False 10000100, 10111101 -> True 01111010, 01011111 -> True 10010101, 00001101 -> False 01010011, 10110000 -> True 00000111, 00010011 -> False 00000011, 00000101 -> False ``` # Rules * Input/output can be given by [any convenient method](http://meta.codegolf.stackexchange.com/q/2447/42963). * You can print it to STDOUT, return it as a function result or error message/s. * Either a full program or a function are acceptable. * [Standard loopholes](http://meta.codegolf.stackexchange.com/q/1061/42963) are forbidden. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so all usual golfing rules apply, and the shortest code (in bytes) wins. --- [Sandbox](https://codegolf.meta.stackexchange.com/a/19178/84844) [Answer] # JavaScript (ES6), ~~63 54 52~~ 50 bytes *Saved 2 bytes by applying an optimization similar to the one suggested by @AZTECCO on my C answer* Expects `(a)(b)`, where **a** and **b** are bytes. Returns **0** if the blocks can dovetail perfectly or **1** otherwise. ``` a=>g=b=>b?a<<8&b|(c=a<<8|b,c+=c&-c)&c-1&&g(b<<1):1 ``` [Try it online!](https://tio.run/##hZHBDsIgDIbvPsVOZETn6M2YMW8@gS8AyBbNMsymnvbuKHTDJS6shKQkX3/@tnfxFr3qbo9n1pqrthW3gpc1l7yUJ1EUByKHVHGXDXKntlyRTFGiMiCkTmVRAD2CVabtTaP3janTKmUSxqDznCZ5nly6l95EcYaxgnvkmzMGDAJ@Fk2vk7@CAHl9WNWfLGApQBx3iLvYLL6iOAvunbY7M/fLbiCY9yU/@YVmEUH3WBDlAacD2K23D/Fp@hFO2xpXET6wHw "JavaScript (Node.js) – Try It Online") ### How? The recursive function **g** attempts to shift **b** to the left, 1 position at a time, until the following conditions are both met: * `(a << 8) & b` is equal to **0**, i.e. **a << 8** and **b** have no set bits in common * `c = (a << 8) | b` is a sequence of consecutive **1**'s, possibly followed by trailing **0**'s For the second test, we add to **c** the rightmost set bit in **c** and see if this results in a single **1**, by carry propagation along the sequence of consecutive **1**'s. We use the following bitwise tricks: ``` c & -c // returns the rightmost set bit in c c & (c - 1) // returns c without the rightmost set bit in c // (0 if c is an exact power of 2) ``` Example: ``` 0111111000 + (0111111000 & -0111111000) = 0111111000 + 0000001000 = 1000000000 1000000000 & (1000000000 - 1) = 1000000000 & 0111111111 = 0 ``` We stop the recursion when `b = 0`, which means that all bits have been thrown away. (This is why we do `b << 1` instead of `b * 2`, so that **b** is forced to a 32-bit integer rather than an IEEE 754 floating-point number.) [Answer] # [Python 3](https://docs.python.org/3/), 68 bytes ``` lambda a,b:any(a<<8&b<<x==('01'in bin(a<<8^b<<x))for x in range(17)) ``` [Try it online!](https://tio.run/##VY9Bb4MwDIXv/AqfBpHYlGyHTQh6a6@77DhtStZQ0CigABr8eubYQGkk5PA@@/mlnfqiqV/mPPucK301Zw06Nomup0in6duDSdMxy6JQqrCswZQ1yV9eFiJvHIyAutP1xUbqVYj5rygrCx9usEkA0LvJF0BTMDF8x@Agw4l26CPx1LVViXVrAD6@oY90/Cxiuhm8UU/r/G@OyCAKu6IZqjMYG6Kt77Djj217OL6fjs41LgHjrP6d1XJguzweKGFwI5LPHSFBSiXVQk666iwEm8RlP7XaYItSe@IF/wGXO8IuPh0Zb5vYTvEiousQZmABNzHbIcX5FND0MrVGp8j04OV9uxgUGniluk0xkozIe0P/ "Python 3 – Try It Online") The function tries all overlap configurations of the two binary sequences. It performs a bitwise `xor` for each configuration and checks if all the resulting `1`s are consecutive. This gives a false positive for some cases where the `xor` operation results in a leading `0`, so additionally it checks if the bitwise `and` operation yields `0`. -4 bytes thanks to xnor [Answer] # [Python 2](https://docs.python.org/2/), ~~78~~ ~~59~~ 57 bytes Output is via exit code. The program fails (1) for truthy inputs and completes (0) for falsely ones. Input are two non-negative integers. This is now quite similar to [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)'s answers, but I found the `d&-d` trick on [this website](https://www.geeksforgeeks.org/position-of-rightmost-set-bit/). ``` a,b=input() b<<=8 exec"d=a|b;a&b<1>d&(d&-d)+d>q;a*=2;"*17 ``` [Try it online!](https://tio.run/##XY9NbsMgEIX3nGKUhZ2/Skw2rWKTXbLtphcAgxQrke0SoiZS7@52GIyrgixmHt@8h4dnOPfdbmx660BBWZaj3hrVdsM9LFfC1LV6E@7hmoVV@ttUujA1HmyxtMWLXW3s4bPSa7WrFmt8HX@nhfg6t1cHH/7u9gIg@CcdAOQBlBK7wbddgJO@3qh3j8YNAY7vp6P3vecB452@5Mv9nzHyHqXBtLYw1@KfLHklmUqSpUSJLE8l05jpNJhonGmkjyO5i7LM3sTSnkwwe8cborlib9aR6TjJkdGbaTlHSv4HjozvSnREJllmOVoKSvoB "Python 2 – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~61 58 57~~ 53 bytes *Saved 4 bytes thanks to @AZTECCO* A port of my [JS answer](https://codegolf.stackexchange.com/a/211145/58563). Returns **0** if the blocks can dovetail perfectly or a non-zero integer otherwise. ``` c;f(a,b){for(a<<=8;b&&a&b|(c=a|b,c+=c&-c)&c-1;b*=2);} ``` [Try it online!](https://tio.run/##lZLRboIwFIbvfYqTmSFVGa1xiRlytWQvsF0uMaUUbIatKXW6qK8@VkAJJsvSHQI5NOfr3/@csiBnrApDeFYph1KK7ZYbyLTawNqYbfkUhqWh7EN9cp0Vav/A1CakIXkkZE4Wi3CG8XwxJ4NhyjMhOSRC@gcEryujVjan@mvlDw9oYDcxgoGQRV21k6XIJU@hUDJvPzcEU7I0wNZUw7hEcPwNEBADjmC/FgUHvy0TsFzGQCKbTGKLTiYQwAiPIjiD5manJQibVyzKfDpN0DFT2qeWWUSJ51EvOfkspqdkyiYx8wKGPBaQKBnHMxSdKyENbKg1aKUGYGOr7VLm392n7/JuCplfuyeXQFO4@UUoAtvnN73j7jBuwx1uqlsYY4JJD36hRfkH3ZVfpcl/pK8H7aQJcYbr6vrtOtYuuMK4b7rWrR9H0w1K@qabDRyl2@LOdEsT5441J@061pgmrsNqxtO7J5fJ96XP1TfLCpqXVbD/AQ "C (gcc) – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~18~~ 17 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` T_8+Ɱ17;ṢIPʋ€T}1e ``` A dyadic Link accepting two lists of eight ones/zeros which yields `1` if they may dovetail, or `0` if not. **[Try it online!](https://tio.run/##y0rNyan8/z8k3kL70cZ1hubWD3cu8gw41f2oaU1IrWHq////ow10DKEQxDKIhYggRA1jAQ "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8/z8k3kL70cZ1hubWD3cu8gw41f2oaU1IrWHq/8PL9YHM//@jo6MNdVBgrI4ChlAslw4OdQbIEKIOxDSEYpAgVJ0hujp0zUB1EK2GcK1I5kGEkNyHJIxuniGqvTATDWHmIQnB7EVWiaTOAN1ehFMg9iIHDIZHDDA9YoCqDskdYLcgeQQuDDMP4WFDZPPgYYZQh3AzmjoDVHVwa2JjYwE "Jelly – Try It Online") (I reordered them to have the eight truthy cases followed by the five falsey cases). There is probably a terser way... ### How? ``` T_8+Ɱ17;ṢIPʋ€T}1e - Link: block A; block B T - truthy indices of A _8 - subtract eight from each 17 - seventeen +Ɱ - map with addition -> a list of the 17 shifted versions of T € - for each: T} - using the truthy indices of B as the right argument ʋ - last four links as a dyad: ; - concatenate Ṣ - sort I - incremental differences P - product (0 if two 1-bits collide; >1 if zero-gaps would result) 1e - does 1 exist in that result? ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 18 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ¬0*æδì`âε0ζO0ÚPΘ}à ``` Input as a pair of lists of bit-integers, outputs `1`/`0` for truthy/falsey respectively. [Try it online](https://tio.run/##yy9OTMpM/f//0BoDrcPLzm05vCbh8KJzWw3ObfM3ODwr4NyM2sML/v@PjjbUMQBCQzAGwlidaAQPzIqNBQA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/Q2sMtA4vOzzz3JbDaxIOLzq31eDcNn@Dw7MCzs2oPbzgv87/6OhoQx0DIDQEYyCM1YlG8MCsWKBQtKEOCgQKoYvgUmWADFFUwcRANsLsRKhCF4OYZYhhFqr5MLMMsZgF8ynM9UiicFUGKO4yRIQCUkjAbDNEcRdcLdQsJBGou5DVGSKZBbcB6nqEuxBmGaC53gAlBBGuN0CJRwMUfaiqDFBUwd0RGxsLAA). (The test suite contains an additional `Ù` after the `æ`, otherwise it'll time out. The single TIO takes roughly 35-40 seconds without this uniquify.) **Explanation:** ``` ¬ # Push the first list of the (implicit) input-pair (without popping) 0* # Multiply each value by 0 to create a list of 0s of that same length æ # Get the powerset of this list of 0s (including empty list) # (prefixes builtin would be preferably here, but unfortunately it lacks # an empty list; obviously this powerset contains a lot of duplicated # lists, which is why the uniquify `Ù` in the test suite is used to # make the program faster) δ # Apply double-vectorized (using the powerset of 0s and implicit input) ì # Prepend the list of 0s to the inner input-list ` # Pop and push both list of lists separated to the stack â # Use the cartesian product to get every possible pair of inner lists ε # Map each pair of lists to: ζ # Zip/transpose; swapping rows/columns, 0 # using a 0 as trailing filler-item if the lists are unequal in length O # Sum each inner pair 0Ú # Remove all leading and trailing 0s from this list P # Take the product of the remaining values Θ # And check that this is equal to 1 }à # After the map: check if any are truthy by taking the maximum # (after which this is output implicitly as result) ``` [Try it online for a step-by-step from input to output (with the uniquify to speed it up).](https://tio.run/##dVJNb9QwEL33V4z20l2UaLNXEEKoB8SJio/TaiWcZNKM1o6NPzbdSvwP4IQ4cOII/QHde//SMrajllZCUeIkfm/eezPWTtSEx@Ps9WCCfwqz4uT5zfWLk9kr9OB7hI6s8yCJH7pLf@akjKSG/ALojnTzK9PeWzG4TlsFxHwN4o5auQSsnkxAscVUzugRrcOpPLnHhMPPTJh/GOhToG7/EBVXF5WcQWzj3nDhIBgQQwsqizDceTRlvS/jCjp49s3eajaptEVotDKi4SiLqPg1K55bNDjEmuhwEkq@olytfc/5B7S5C2Xen7c61BLLHTZeW7rCdpFS3P4@TB06syg8Aoqm5@zOEcPBCLJTf1nKj/phvlTi4@HHPz1mKi6vyBTgRmEMpwarR7dstAxqcM9gJDZ4Wp2CcDxEKdGW5FFlN3@q2@vPudq7oLKZFKZUmnWjnQR8kzFvUekdtwBFy0JLbwXJqFilhtyzk9s8Zg787fGkrW5D4/9HOZ/602OzhbEnRuyEDOhA8ITwkucj97DKAb5k8EseT5MI1PHE9wnqbfD9Hmo@KWIbbUZxJS5JcdR5rsxHQgcLFl2QPmLymcjDOnwvjsf1elVUfK3SzdemWN9/pbfN5i8) [Answer] # [Husk](https://github.com/barbuz/Husk), 15 bytes ``` VΠ¤×ż≠ö→kΣQṠ+mṗ ``` [Try it online!](https://tio.run/##yygtzv7/P@zcgkNLDk8/uudR54LD2x61Tco@tzjw4c4F2rkPd07///9/tIEODBqCYCxMxBAmFgsA "Husk – Try It Online") or [verify test cases.](https://tio.run/##RY4xCgIxEEX7nGJKxWbmKDaeQVlSiVhrsWAnNtsGFLzBwoJVFtu9w@YicWd@ggNhPv@//GR/OjaZYu9X8Z2ul9TeU/vw/nBexz7vphBfY/f9pFsY@yVopud2HsLGz0OXc5YyVIX7O4wxRwUxC6tyVRCWMgVWRiojegjLHND6lhXglqDHTFf20gNLlDGajAXDpZnxMcfIjLEIDsOxgh8 "Husk – Try It Online") Output is a positive integer for truthy cases and 0 for falsy. ## Explanation Parentheses added for clarity. ``` VΠ¤(׿≠)(→kΣQ(Ṡ+mṗ)) Implicit inputs: two lists of integers. ¤( A )( B ) Apply B to both and combine with A. →kΣQ(Ṡ+mṗ) Argument is a list x. m Map ṗ primality test Ṡ+ and concatenate before x. Since 0 and 1 aren't primes, this effectively prepends 8 zeros. Q All contiguous slices. k Classify (into separate lists) Σ by sum. → Get the last class, i.e. the slices with maximal sum. They are those that contain all the 1s of x. ׿≠ Combining function: × Cartesian product by ż zip (preserving overflowing elements) by ≠ absolute difference. Now we have a list of all combinations of slices from both extended lists, with 1 and 1 producing 0. V Does any of them have Π nonzero product (all 1s)? ``` [Answer] # x86 32-bit machine code, 27 bytes An x86-64 version would be callable from C as `int dovetail(dummy, unsigned x, unsigned y);` Returns EAX=0 for dovetail, non-zero for not; all paths of execution for non-zero inputs that don't dovetail lead to `EAX=(x<<n)|y` as the last thing calculated in EAX before returning. Also more simply and obviously, returns ZF=1 for dovetail, ZF=0 for not. [Try it online!](https://tio.run/##ZVPLbtswELzrK/bYonYgAUVgxLeiCVCgp/pSNEgDUlpZjNekSlKWbPTf3V3Kqh8xoIf3MZydWakQcKtpP7cqbI/HJfTObwL0DVrQnaEItfMwLO7n959nHIkQG4StKhtjEUpXIfSGCBq1Q1BV5TGEeTAHhNZjbQYMWVa5HUZl6AHe/5agnSOYSuDD4@rbDB6//vyYSXoomzVA1cygopu@0BBgNcwW/N61LXrQ@4gBlEc4oHfZHTnXPiQYjkdI1YDBpNCbPfD9js/1pNpr5I1pQdk9aBN5RFuTKSPPIVlCxXdUjPTMeJ8Y7uXUhn86s1OEljVy8BdYt99JPevs/HROa@xaYEMC06EWsFJoqSGFQuMn/JJuBzZ1BMcWkOvTiCOKseXY8l7b2HkrE0Sz7lwXUqOczj1MsYCAUf5fjJbIPDPYvHg545Sc89ItOk5NklK2OrHlxuuzyWwQNAU/FZwmfEu6T4a/1q4TjJFug2xerwI4S/szvxlL2EOeTW6NpvK2gdh56WlgaLH9RocNYgsSF/k7loOA9wwakUL2Obo2y244jYcsl@AxycjWdsjCwa@nMTWBF8nk/xtcYcQyGsffzx6@fF/9uCrOUzEOJgqVRHVnVGLDw6bg6ukBzLYlw8ssq5OWWbqZSHZck9OK4DVE5WM2PkY@W7cbVzzXeVHkeZGfw6JSriXI12h3qej83Y2zTuWA@nIlMR7YyOycFTuL0@5FyIdFfvwH "Assembly (nasm, x64, Linux) – Try It Online"). NASM listing: offset, machine code, source ``` 1 dovetail: ; bool dovetail (ESI, EDX) 2 00000000 86F2 xchg dh, dl ; shl edx,8 ; upper bytes are zero 3 .loop: 4 00000002 85F2 test edx, esi 5 00000004 7510 jnz .overlap ; skip any bit conflicts 6 7 00000006 8D0432 lea eax, [edx+esi] ; equivalent to | or ^ for non-overlapping bits 8 00000009 0FBCC8 bsf ecx, eax ; count trailing zeros 9 0000000C D3E8 shr eax, cl ; shift out low zeros 10 0000000E 40 inc eax ; turn contiguous low bits into 1 set bit 11 12 0000000F 8D48FF lea ecx, [eax-1] ; clear lowest set bit 13 00000012 21C8 and eax, ecx ; like blsr eax, eax 14 00000014 7404 jz .dovetail_found ; there was only 1 set bit, now 0 15 .overlap: 16 00000016 01F6 add esi, esi 17 00000018 79E8 jns .loop ; keep looping until ESI hits the top 18 19 .dovetail_found: 20 ;; return value in ZF: 21 ; 1 for dovetail detection by BLSR 22 ; 0 for exiting loop via ESI setting SF: implies non-zero 23 0000001A C3 ret ``` See <https://catonmat.net/low-level-bit-hacks> for an overview of bithack tricks including isolating or clearing the lowest set bit. --- Alternate versions: BMI1 [`blsr eax, eax`](https://www.felixcloutier.com/x86/blsr) is 5 bytes, same as `lea edx, [rax-1]` / `and eax, edx`. That would require BMI1 (Haswell+, Piledriver+). I used `and` instead of `test` so an integer result in EAX would be available. BMI1 [`blsi ecx, eax`](https://www.felixcloutier.com/x86/blsi) (5B) / `add eax, ecx` (2B) (`eax += lowest_set_bit(eax)`) turned out *not* to be the shortest way to turn a contiguous bit-range into a single set bit. Instead, shifting to the bottom with `bsf` / `shr` / `inc` saved 1 byte in 32-bit code, for a total of 6 bytes to turn a contiguous bit-range into a single set bit. An x86-64 version (no single-byte `inc` encoding) could save instructions at equal code-size by doing that, though, if BMI1 was available. --- I was hoping to avoid doing the `x & y == 0` test separately from combining the bits. e.g. by **XORing** them together and checking that a contiguous bit-range started at the bottom of one of the inputs: ``` mov eax, edx xor eax, esi jz .all_cancelled ; exclude all-zeros from the 1-set-bit test blsi ecx, esi ; isolate lowest set of the shifting input add eax, ecx ; carry turns contiguous set bits into 1 ; BROKEN, need blsi(esi|edx) ``` But we can't just use the lowest set bit of the XOR result; some conflicting bits might have cancelled each other. e.g. x=0b110010 y=1 would give a false-positive when with `x ^ (y<<1) = 0b110000` having all its set bits contiguous. And it doesn't work to isolate the lowest set bit of the input you're shifting; once you shift it left past the lowest set bit of the other input, you need to be adding *that* isolated bit instead. e.g. the following input was mis-handled by my first version using `xor` and `blsi ecx, esi`, because it only dovetails with ESI's lowest bit shifted left past EDX's lowest set bit. ``` mov edx, 0b0110010 mov esi, 0b1001100 ``` This way could still work with some kind of `min(blsi(x), blsi(y))`, or `blsi(x|y)`, but doing that separately is not a win. [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~105~~ \$\cdots\$ ~~63~~ 62 bytes Saved a whopping 13 bytes thanks to the man himself [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)!!! Saved a byte thanks to [AZTECCO](https://codegolf.stackexchange.com/users/84844/aztecco)!!! ``` t;f(a,b){for(a<<=t=8;b&&t;b*=2)t=a|b,t/=t&-t,t=a&b|t&-~t;t=b;} ``` [Try it online!](https://tio.run/##bVLbboJAEH33K6YkEtAxchHFrNuXpl9RTbMLS8tD0cA@kCL9dToLaLWRZE5m58ycnT0hWXwkSddpljkCpdtkx9IRux3XPGbStjWTMx64mouzRL3k2l5opJMtz5T@aKa5ZG2XFxq@RF447qSZAH2moFWl38XbATg0QRQhDLDyEEz4QYwQ@ZSsKcLAVAystghxiLBBCFt2ryZv1Pr5XmhNEJFI4K0IQgI/JpGtaSIhf2MuoEJ0I6fqk6q1SntBaMwaCF6P/3Lvgt44nnyKcgblsIq1r1@Dfb19oYgshNtzaNFEP0KugmOuzYtU1TTnsTHdQZV/q2PmXBZyl2Nhdq0wmM/7bhcGdy@PEKQ0utzzB3ZHywstH9KK6KsNjxoqanh6Gn6MeyY5lqVKtBEAzqs/8lQSnTnWNEwRCGDxDNMUptW@IHMEgkSokMwbFQ6jcDtpu18 "C (gcc) – Try It Online") Returns \$!0\$ for true and \$0\$ otherwise. ### Explanation Shifts the first parameter, \$a\$, over \$8\$-bits so we can try all different shift positions by just shifting the second parameter, \$b\$. Loops over all shifts of \$b\$ checking to see if all bits are ever different from \$a\$ and \$b\$ forms one continuous block of \$1\$s when combined with \$a\$. [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~82~~ 81 bytes ``` $'¶$`; (.+),(.*;.*) $2,$1 +`;(.)(.*),(.) -$1$3;$2, -(0|(1))+ $#2 ;|, m`^0*1+0*$ ``` [Try it online!](https://tio.run/##RY47DgIxDER7XwMj8vFG9lLmANwChYKCAgpEuefiAFwsu7azwlLk0czLJO/75/G69WO4tA54@n2xVQglRwol1ZIi4EwokFsNJW6eBhEmFDzXLYIp8BIkxgx4mKEuBPBsV06SOWHvMoZ2AX@HfcxRQczCqmAX5EuZASsjOyN6yJc5TutbVuC3xHvMhLG3HrdEGaPJWGd4NLN/DNgzYyxyh92xghU "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: ``` $'¶$`; ``` Create duplicates of the input with `;`s inserted at every position. ``` (.+),(.*;.*) $2,$1 ``` Swap the two inputs if the `;` lies within the second. ``` +`;(.)(.*),(.) -$1$3;$2, ``` Try to dovetail the part between the `;` and the `,` with the other input. ``` -(0|(1))+ $#2 ``` Count the number of bits in each overlap. ``` ;|, ``` Delete the separators. ``` m`^0*1+0*$ ``` Check whether a dovetail produced a valid result. Edit: Saved 1 byte by returning any non-zero value for a valid result (value is number of possible dovetailings plus one if concatenating the inputs is a valid dovetailing). [Answer] # [Perl 5](https://www.perl.org/) `-p`, 68 bytes ``` s/\b0+|0+\b//g;s/(1*)(.*?)(1*) //;y/01/10/;$_=/^(0*$1)?$2(${3}0*)?$/ ``` [Try it online!](https://tio.run/##RY7BCsIwEETv@YocckgjurOKpyL9kaJQEBGKLdaLqL9u7O6muBBmmH2ZZDzf@33OE7UdVm@s2o7oUk8UOVVxk5pKjCeqnwQmBtXhdKBjRApcNWEbw2v3QZot5cxl/GLcP4GNJmI8wBDnFuNNhCmwMLwwLMebaGK0vKUFdoutR0NXdO6xiIVR2itrDEoz7GMOtlNGV5bAEi34DuPjOtymvO7HHw "Perl 5 – Try It Online") * `s/\b0+|0+\b//g` trims 0 from two blocks * `s/(1*)(.*?)(1*) //` substitution to remove the first argument, and capture 3 groups : + $1: the left ones + $2: shortest sequence between + $3: the right ones (eventually) * `y/01/10/` transliteration of second argument remaining (bitwise not) * `/^(0*$1)?$2(${3}0*)?$/` the pattern second argument (inverted) must match [Answer] # [Factor](https://factorcode.org/), ~~149~~ 139 bytes ``` : d ( a b -- ? ) [ 8 [ 0 suffix ] times 15 rotate ] bi@ all-rotations [ dupd [ + ] 2map [ 0 = ] trim all-equal? ] map f [ or ] reduce nip ; ``` [Try it online!](https://tio.run/##dVBBTsMwELznFXMEIVc2EhJqheCAhHrpBXGqODiJU6w6dnAcKFS8PbiBYMelslZrz87OzrrihTO2f3pcrh7m2AgtLFfykztpdIuNNV0j9QZbYbVQqLl7QSteO6EL0YbbTOyc5S0aK5z7aKzUDotsuZrj3rwJx6Ui7t2QXJli2xJTkVy6tp@jxBk4chCCW5xjjWsfFG1XVXKHZzhZ@zHsCtY47oRHcnmXcaXIAAwe1yi7pvTpwpcva94MEjeHbitrHMjeJle3HvHVrPJ1Y/3DirIrBLRssOj3YMn5wn9YiVl2iksnJ@UGfD9k9hsx9xjfT95T3XTe2M9O6LK/PO4W4zGXJn5HzTGOPbDEb@gIumyi8@M3ZrNEN0wcdwt@p7r0aDea/Hm8W/iloBv3p1yacGnky3P7bw "Factor – Try It Online") Gets the input as arrays of integers. A naive solution - pads both arrays with 8 additional 0s, then adds each of the rotations of the second array to the first one, trims the leading/trailing zeros and check if the resulting arrays consist only of one number (1). [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~94~~ ~~82~~ ~~71~~ 70 bytes *Edit: -12 bytes by poring over Noodle9's similar C answer and rather shamelessly stealing all of the golfing tricks that I could use here... so please upvote that one, too!* *More edits: ...thanks to various stolen tips & tricks from Arnauld, also -12 more bytes...* ``` c;i;f(a,b){for(b<<=9,i=18;i-->1;i*=a&b||c&c++)a*=2,c/=(c=b|a)&-c;i=i;} ``` [Try it online!](https://tio.run/##nZFbboMwEEW/yyoQUpGdDGpsHgE57kryY1yoLKW0AvIVsnY6g1lAawmbI6R7uB7b7NPadbXKqZ4ZaPmj/x5Ze7noBpwWtXJZ9i6UO2iTtstiU3s8cnPQEuybZla3i@FphnHt1HN1wxx/GTcwHj2iOI5ffkb81LNk7qZZ6NePmEASjN10v81EbB7vHb8OCciy3FbPduJcRQEOIevdgfR3R29u0y4pToAPOjYIqIE5UZHBw/8M14En2yHKCg0eAjqUAuSpQIOHkEGICmROCg8BJUQuQdQNKTyFOKSEptxGQRB0kKLBKqTYIKBEnYM40314CClxBkGDoFdIPAeaAe4h4Qbo17hT@BlF6y8 "C (gcc) – Try It Online") My first ever answer in 'C' (which embarassingly didn't work the first time: thanks to Arnauld for spotting the bug...). Input is two 8-bit integers, outputs '-1' (truthy) if bits of input dovetail together perfectly, '0' (falsy) otherwise. Works by first bit-shifting b by 9 bits, and then testing for successful dovetailing with a shifted by 1..18 bits (so, all-the-way to the right up to all-the-way to the left). Tests dovetailing at each position by checking that a AND b is zero (so there are no 'clashing' bits), then taking A XOR B, chopping-off any trailing zeros, and testing whether x AND (x+1) is equal to zero (which is only true for 2^n-1 = strings of 1-bits). [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 29 bytes ``` ¬⬤α№⭆↨⁺×X³χ⍘η³×X³κ⍘賦³⮌⍘λ²01 ``` [Try it online!](https://tio.run/##XYwxDsIwDEV3TmF1cqQgxXRkAmZQBFwgqiJaYQgkaTl@cMMCLP9b7z@5613sguNSbBzuGQ8h44YZnYZdGAWcsvDL3j1w65JHy2PC83DzCW14@YitBjJKw7x@XOw1tErQn3b9tZ7VUnNqOPrJR3n/tbOGVd0bQ40cal0KGUOGiBa1JMpy4jc "Charcoal – Try It Online") Works by dovetailing in base 3, which avoids issues other answers have when trying to XOR or add the values together. Explanation: ``` α (Uppercase alphabet) ¬⬤ No indices match № (Non-zero) Count of 01 Literal string `01` in θ First input ⍘ ³ Converted as if base 3 × Multiplied by ³ Literal 3 X Raised to power κ Current index ⁺ Plus η Second input ⍘ ³ Converted as if base 3 × Multiplied by ³ Literal `3` X Raised to power χ Predefined constant 10 ↨ ³ Converted to base 3 as a list ⭆ Map over digits λ Current digit ⍘ ² Converted to base 2 as a string ⮌ Reversed Implicitly print ``` [Answer] # Java 8, ~~86~~ ~~83~~ 82 bytes ``` (a,b)->{int i=18,t;for(a<<=8;--i>0;i=(a&b)>-(t&(t&-t)+t)?i:0,b*=2)t=a|b;return i;} ``` Inspired by halve the other answers. -3 bytes thanks to *@AZTECCO*. -1 byte thanks to *@ceilingcat*. Inputs as (32-bit) integers. Output as `-1` for truthy and `0` for falsey. [Try it online.](https://tio.run/##dVI9T@QwEO35FSMXyL58yOYatCZLQUVxUFACxSR4F0PwRvFkpRPsb1/8kexdgxXNTJ7fzHuy/YZ7rN5e3o9dj97DH7Tu8wzAOjLjBjsDd/E3AdDxGLGMsRU64IezEDwh2Q7uwEFz5Fi2olp/Ro5t1GVJerMbOV5dNZe6quxaattwPG/FuuJ0Hr6KREHi2q5k2f5qLgQ1@NXq0dA0OrD6cNRRZJjaPojMWvudfYGP4JU/0Gjd9vEZcNx6kb1GwYwDGU836A2sgCkplVRKQUohaDUvWIr/EJlXQmIBqTsiSwE5Rc5Mjhy1cKJcnJzLgGR21JJZXWYMkqsQ9Jxldpj8ZLHgWaY5kSPnyTIb0zLvJU7ayojMSBrAaj/0ljjTTMyHBHA6OuuGiTw0p9Na2MDSLS/3j81teBZbM9Z77Cdzv@G581E@lxeinJlxtT8xVWQuMx/@ejIf9W6ieghWqHf/BhYMOCuwYAJYqFk9msEg8d8VDyATdW/cll65EMVpdO5pQ8/qiVjh6i69xlnvkN7r4fgN) **Explanation:** ``` (a,b)->{ // Method with two integer parameters and boolean return-type int i=18, // Index-integer, starting at 18 t; // Temp-integer, uninitialized for(a<<=8; // Bit-shift the first input-integer `a` 8 bits to the left --i>0 // Loop `i` in the range (18, 0): ; // After every iteration: i=(a&b) // Get `a` bitwise-AND `b` < // And check that it's smaller than: -( // The negative of: t // `t` & // Bitwise-AND with: (t&-t) // `t` bitwise-AND `-t` +t)// and add `t` ? // If this is truthy: 0 // Change `i` to 0 (which will also stop the loop) : // Else: i, // Keep `i` the same b*=2) // And multiply `b` by 2 t=a|b; // Set `t` to `a` bitwise-OR `b` return i;} // Return `i` as result (where -1 means we've changed `i` to 0 // manually as truthy output and 0 means the loop has fully // looped as falsey output) ``` ]
[Question] [ Given an integer array of at least two elements, output the **Matrix-Vector** (defined below) of the array. To compute the **Matrix-Vector**, first rotate through the size-`n` input array to create a matrix of size `n x n`, with the first element of the array following the main diagonal. This forms the matrix portion. For the vector, flip the input array vertically. Then perform normal matrix multiplication. The output vector is the result. For example, ``` a = [1, 2, 3] ``` First, rotate the array two times to the right, to obtain `[3, 1, 2]` and `[2, 3, 1]`, then stack them to form a `3x3` matrix ``` [[1, 2, 3] [3, 1, 2] [2, 3, 1]] ``` Next, flip the array vertically to form the vector ``` [[1, 2, 3] [[1] [3, 1, 2] x [2] [2, 3, 1]] [3]] ``` Perform usual matrix multiplication ``` [[1, 2, 3] [[1] [[1+4+9] [[14] [3, 1, 2] x [2] = [3+2+6] = [11] [2, 3, 1]] [3]] [2+6+3]] [11]] ``` And the output is `[14, 11, 11]` or `[[14], [11], [11]]` (your choice of whether it's flattened or not). ### Example #2 ``` a = [2, 5, 8, 3] [[2, 5, 8, 3] [[2] [[4+25+64+9] [[102] [3, 2, 5, 8] x [5] = [6+10+40+24] = [80] [8, 3, 2, 5] [8] [16+15+16+15] [62] [5, 8, 3, 2]] [3]] [10+40+24+6]] [80]] [102, 80, 62, 80] ``` ## Rules * The input and output can be assumed to fit in your language's native integer type. * The input and output can be given [in any convenient format](http://meta.codegolf.stackexchange.com/q/2447/42963). * Either a full program or a function are acceptable. If a function, you can return the output rather than printing it. * If possible, please include a link to an online testing environment so other people can try out your code! * [Standard loopholes](http://meta.codegolf.stackexchange.com/q/1061/42963) are forbidden. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so all usual golfing rules apply, and the shortest code (in bytes) wins. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes ``` ṙJṚæ. ``` [Try it online!](https://tio.run/##AScA2P9qZWxsef//4bmZSuG5msOmLv/Dh8WS4bmY//9bMiwgNSwgOCwgM10 "Jelly – Try It Online") ## Explanation Firstly: $$\left[\begin{matrix} \vec{v}\_1 \\ \vec{v}\_2 \\ \vec{v}\_3 \\ \vec{v}\_4 \\ \end{matrix}\right] \vec{x} = \left[\begin{matrix} \vec{v}\_1 \cdot \vec{x} \\ \vec{v}\_2 \cdot \vec{x} \\ \vec{v}\_3 \cdot \vec{x} \\ \vec{v}\_4 \cdot \vec{x} \\ \end{matrix}\right]$$ where \$\vec{v}\_k\$ are **row** vectors and \$x\$ is a **column** vector. This demonstrates that matrix multiplication is just dot product between rows and columns. Then, \$\vec{v}\_1\$ is actually \$\vec{v}\$ rotated \$0\$ to the right, and \$\vec{v}\_k\$ is \$\vec{v}\$ rotated \$k-1\$ to the right, etc. From another angle, \$\vec{v}\_1\$ is \$\vec{v}\$ rotated \$n\$ to the left, and \$\vec{v}\_n\$ is \$\vec{v}\$ rotated \$1\$ to the left, etc. ## How it works ``` ṙJṚæ. input: z (a list of length n) ṙJ [rot(z,1), rot(z,2), ..., rot(z,n)] (to the left) Ṛ [rot(z,n), ..., rot(z,2), rot(z,1)] æ. [rot(z,n).z , ..., rot(z,2).z , rot(z,1).z] (dot product) ``` [Answer] # [Python 2](https://docs.python.org/2/), 68 bytes ``` lambda x:[sum(map(int.__mul__,x,x[i:]+x[:i]))for i in range(len(x))] ``` [Try it online!](https://tio.run/##FYxBCsIwEAC/sscsLoIVQQK@JIYQsdGFzTakLcTXx@Y0zBym/LbvolNPj2eXmF/vCM26dc8mx2JYt3MIeZcQqFFzbP2pOcseMS0VGFihRv3MRmY1DdH30WV0dyGYCK6e3IEbwX2ILfWYglAygv0P "Python 2 – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 73 bytes ``` def f(v):r=range(len(v));return[sum(v[i]*(v*2)[i+j]for i in r)for j in r] ``` [Try it online!](https://tio.run/##NY1BCsIwEEX3nmJ2Teq4MCKIRS8SshBMdIpOy3Qa8PTRBNy9x4f3548@J3al3GOCZLI9y0Vu/IjmFfmndpCoq7Bf1rfJnkJvcu@sp@0Y0iRAQAxiK44NQytpXLTGYBZihYzQ7a4dtodNG/0eHR7C3xwe8VS9fAE "Python 2 – Try It Online") [Answer] # [Pyth](https://github.com/isaacg1/pyth), 10 bytes ``` ms*VQ.>QdU ``` [Test suite](http://pyth.herokuapp.com/?code=ms%2aVQ.%3EQdU&test_suite=1&test_suite_input=%5B1%2C+2%2C+3%5D%0A%5B2%2C+5%2C+8%2C+3%5D&debug=0). [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes ``` LḶN⁸ṙæ×W€ ``` [Try it online!](https://tio.run/##ATAAz/9qZWxsef//TOG4tk7igbjhuZnDpsOXV@KCrP/Dh8WS4bmY//9bMiwgNSwgOCwgM10 "Jelly – Try It Online") A function that returns a vertical array. As a full program it appears as if it returns a horizontal array. To return a horizontal array you'd do `LḶN⁸ṙ×⁸S€` instead. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 11 bytes ``` DgGDÁ})ε*}O ``` [Try it online!](https://tio.run/##MzBNTDJM/f/fJd3d5XBjrea5rVq1/v//RxvpKJjqKFjoKBjHAgA "05AB1E – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), 49 bytes ``` f v=sum.zipWith(*)v.fst<$>zip(iterate tail$v++v)v ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P02hzLa4NFevKrMgPLMkQ0NLs0wvrbjERsUOKKKRWZJalFiSqlCSmJmjUqatXaZZ9j83MTNPwVYhJZ9LQUGhoCgzr0RBRSFNIdpQx0jHOBZN0EjHVMcCKPwfAA "Haskell – Try It Online") For an input `v=[1,2]` * `iterate tail$v++v` yields the list `[[1,2,1,2],[2,1,2],[1,2],[2],[],...]` * `fst<$>zip l v` is the same as `take(length v)l` and yields `[[1,2,1,2],[2,1,2]]` * `sum.zipWith(*)v` is mapped on each element and to yield the vector-matrix row product. [Answer] # [R](https://www.r-project.org/), ~~66~~ 62 bytes ``` sapply(length(n<-scan()):1,function(i)c(n[-(1:i)],n[1:i])%*%n) ``` [Try it online!](https://tio.run/##K/r/vzixoCCnUiMnNS@9JEMjz0a3ODkxT0NT08pQJ600L7kkMz9PI1MzWSMvWlfD0CpTM1YnLxpIx2qqaqnmaf43UjBVsFAw/g8A "R – Try It Online") [Answer] # Mathematica, 35 bytes ``` Most@FoldList[RotateRight,#,1^#].#& ``` [Try it online!](https://tio.run/##y00sychMLv6fZvvfN7@4xMEtPyfFJ7O4JDoovySxJDUoMz2jREdZxzBOOVZPWe1/QFFmXomCQ1p0tZGOqY6FjnFt7H8A "Mathics – Try It Online") *-9 bytes from @Not a tree* [Answer] # [CJam](https://sourceforge.net/p/cjam), 17 bytes ``` {__,,\fm>\f.*::+} ``` [Try it online!](https://tio.run/##S85KzP1fWPe/Oj5eRycmLdcuJk1Py8pKu/Z/XcL/aCMFUwULBeNYAA "CJam – Try It Online") [Answer] # [GolfScript](http://www.golfscript.com/golfscript/), 37 bytes ``` {..,({.)\+}[*]{[1$\]zip{~*}%{+}*}%\;} ``` [Try it online!](https://tio.run/##S8/PSStOLsosKPlf979aT09Ho1pPM0a7NlortjraUCUmtiqzoLpOq1a1WrsWSMZY1/6vS/gfbaRgqmChYBwLAA "GolfScript – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/) + [numpy](http://www.numpy.org/), 68 bytes ``` lambda v:dot([roll(v,i)for i in range(len(v))],v) from numpy import* ``` [Try it online!](https://tio.run/##BcHBCoMwDADQ@74ix2TkNBmIsC9RDx1aDbRJCbXg19f3yl1P06HH39JTyP8tQJs2qzi7pYSNhaI5CIiCBz12TLtiI1q50Su6ZdArlxskF/P67sVFK0acPwxfhpFhWIn6Aw "Python 3 – Try It Online") [Answer] # [J](http://jsoftware.com/), 14 bytes ``` +/ .*~#\.1&|.] ``` [Try it online!](https://tio.run/##y/r/P03B1kpBW19BT6tOOUbPUK1GL5aLKzU5I19BwzpNU81OwVDBSMFYwRpImipYKBj//w8A "J – Try It Online") ## Explanation ``` +/ .*~#\.1&|.] Input: array M #\. Length of each suffix, forms the range [len(M), ..., 2, 1] ] Identity, get M 1&|. For each 'x' in the suffix lengths, rotate left M by 'x' +/ .*~ Dot product with M ``` [Answer] # APL, 17 bytes ``` (↑¯1⌽(⍳≢)⌽¨⊂)+.×⍪ ``` Explanation: ``` (↑¯1⌽(⍳≢)⌽¨⊂)+.×⍪ ↑ matrix format of ¯1⌽ right rotate by 1 of (⍳≢) the 1..[length N] ⌽¨ rotations of ⊂ the enclosed input +.× inner product with ⍪ 1-column matrix of input ``` [Answer] # [Octave](https://www.gnu.org/software/octave/), 34 bytes ``` @(a)a*toeplitz(a,shift(flip(a),1)) ``` [Try it online!](https://tio.run/##y08uSSxL/Z@mYKugp6f330EjUTNRqyQ/tSAns6RKI1GnOCMzrUQjLSezACijY6ip@T9NI9pQR8FIR8E4VpMLyAGyTHUULMD8/wA "Octave – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), ~~56~~ ~~55~~ 52 bytes ``` f l=[sum$zipWith(*)l$drop i$l++l|i<-[0..length l-1]] ``` [Try it online!](https://tio.run/##NYuxCsIwEED3fsUNGVqbBqsIDvYTnB2ODAFTc3iJRxNBxH@PdXB6PHgvuHz3zLXOwBPmZ1RvkguV0G46VtflIUCK@54/dBpwawz7dCsBeBitrf7lorDPMAHiqGGnYW81rjhoOP7ENk10lNYgOjlDKwulYuYO/mv9Ag "Haskell – Try It Online") *Saved one byte thanks to @Laikoni* *Saved three bytes: `l++l` instead of `cycle l`* [Answer] ## [Husk](https://github.com/barbuz/Husk), 11 bytes ``` mΣ§‡*´ṀKoṫ¢ ``` [Try it online!](https://tio.run/##AScA2P9odXNr//9tzqPCp@KAoSrCtOG5gEtv4bmrwqL///9bMiw1LDgsM10 "Husk – Try It Online") ## Explanation ``` mΣ§‡*´ṀKoṫ¢ Implicit input, e.g. [1,2,3] ¢ Cycle: [1,2,3,1,2,3,... oṫ Tails: [[1,2,3,1,2,3...],[2,3,1,2,3...],[3,1,2,3...]... ´ṀK Replace each element of input with input: [[1,2,3],[1,2,3],[1,2,3]] ‡* Vectorized multiplication (truncated with respect to shortest list) § applied to the last two results: [[1,4,9],[2,6,3],[3,2,6]] mΣ Sum of each row: [14,11,11] ``` [Answer] # Octave - ~~67~~ 48 bytes *Thanks to Luis Mendo for shaving this code down by 19 bytes!* *Note: This code can only run in Octave. MATLAB does not support expressions inside functions that can create variables while simultaneously evaluating the expressions that create them.* ``` n=numel(a=input(''));a(mod((x=0:n-1)-x',n)+1)*a' ``` The original code in MATLAB can be found here, but can be run in any version of MATLAB. This code is 67 bytes: ``` a=input('');n=numel(a)-1;a(mod(bsxfun(@minus,0:n,(0:n)'),n+1)+1)*a' ``` # Explanation 1. `a=input('');` - Receives a (row) vector from the user through standard input. You must enter the vector in Octave form (i.e. `[1,2,3]`). 2. `n=numel(...);` - Obtains the total number of elements in the input vector. 3. `x=0:n-1`- Creates a row vector that increases from `0` up to `n-1` in steps of 1. 4. `(x=0:n-1)-x'` - Performs broadcasting so that we have a `n x n` matrix so that each row `i` are elements from 0 up to `n-1` with each element in row `i` subtracted by `i`. 5. `mod(..., n)+1` - Ensures that any values that are negative wrap around to `n` so that each row `i` contains the vector from 0 up to `n-1` **circularly** shifted to the left by `i` elements. We add 1 as MATLAB / Octave starts indexing vectors or matrices with 1. 6. `a(...)` - Creates a `n x n` matrix where using (4), we access the correct indices of the input vector dictated by each value from (4) thus achieving the matrix we need. 7. `(...)*a'` - Performs matrix vector multiplication by transposing / flipping `a` to become a column vector prior to doing the multiplication. # Example Runs ``` >> n=numel(a=input(''));a(mod((x=0:n-1)-x',n)+1)*a' [1,2,3] ans = 14.00 11.00 11.00 >> n=numel(a=input(''));a(mod((x=0:n-1)-x',n)+1)*a' [2,5,8,3] ans = 102.00 80.00 62.00 80.00 ``` --- # [Try it online!](https://tio.run/##y08uSSxL/f8/zzavNDc1RyPRNjOvoLREQ11dU9M6USM3P0VDo8LWwCpP11BTt0JdJ09T21BTK1H9//9oQx0jHeNYAA) [Answer] # Javascript 79 bytes Takes in an input array and outputs an array of the matrix vector ``` a=>(b=[...a],a.map(x=>([...b].reduce((m,n,i)=>m+=n*a[i],0,b.push(b.shift()))))) ``` ## Explanation ``` a=>( b=[...a], // copy the input into b a.map(x=>( // transform a into a new array [...b].reduce( // copy b into a new array and reduce (m,n,i)=>m+=n*a[i], // memo += the element in the array * the ith // element in a 0, // start memo at 0 b.push(b.shift()) // shift the first element in b to the end // not used by reduce, but performing this op // here saves a few bytes ) )) ) ``` [Answer] ## Clojure, 80 bytes ``` #(map(fn[_ c](apply +(map * c %)))%(iterate(fn[c](into[(last c)](butlast c)))%)) ``` `iterate` produces an infinite sequence, but instead of using `(take (count %) (iterate ...))` to stop it I use `%` as an extra argument to `map`. [Answer] # [Perl 5](https://www.perl.org/), 65 + 1 (-a) = 66 bytes ``` @o=@F;for(@o){$r=0;$r+=$_*$F[$i++%@F]for@o;say$r;unshift@F,pop@F} ``` [Try it online!](https://tio.run/##K0gtyjH9/98h39bBzTotv0jDIV@zWqXI1sBapUjbViVeS8UtWiVTW1vVwS0WKO2Qb12cWKlSZF2aV5yRmVbi4KZTkF/g4Fb7/7@RgqmChYLxv/yCksz8vOL/ur6megaGBv91EwE "Perl 5 – Try It Online") Takes the input vector as space separated numbers. Outputs linefeed separated numbers representing the result vector. [Answer] # [C (gcc)](https://gcc.gnu.org/), 126 bytes ``` i,j;int*f(int*a,int n){int*r=malloc(n*sizeof(int));for(i=0;i<n;i++){r[i]=0;for(j=0;j<n;j++)r[i]+=a[j]*a[(j-i+n)%n];}return r;} ``` [Try it online!](https://tio.run/##RU3RisIwEHy@@4rgISRtPDyrIMTej4Q8hDTVDXUrafpi6bf3Norew87OzgyzbnN2bvkCdN3YeHYaUgP99@V3ARkUYCpantFKQoZiykesr7bresexGODu@0dECNX2kUO9VXBCBWUppqjB0J31QDuQHkjPcllbHUxhNQ8bKFGs0ag5@jRGZFHNS353tYC5mlkxfX5kkvyQ9N6wmk07eZBHWc3q4RQs@mHsEjktzym5F@TcInktX@l1I9n/mJV8xvXWvNjPm@3erDJUMi/VHw "C (gcc) – Try It Online") [An array may be represented in input as a pointer and length.](https://codegolf.meta.stackexchange.com/a/13262/48934) [Answer] # Common Lisp, 78 bytes ``` (lambda(x)(loop as i on(append x x)as y in x collect(reduce'+(mapcar'* i x)))) ``` [Try it online!](https://tio.run/##JY3BCgMhEEN/JTdntqduKezvTNWC4DqDWrBfv1WaS0LgJT6nZhdlVcNbK3psHanAEd2x48GgHU8cMzGCgqym0kETkfMVhAb/YWlI0EJiFkvAwOBZfdfWgNeco@9UY/j46G50inmpbpvM4Klr/S7/AQ) Double the array (in this case a Lisp list) and iterate over the sublists with `i` (using `x`, through `y`, to stop the iteration). Then calculate the next element of the result by summing the result of multiplying each element of `x` with each element of `i` (again stopping when the shorter list is terminated). ]
[Question] [ You will be given a String consisting of printable ASCII (without newlines). Your task is to build a nice Stairway for my Castle. # How to build a nice Stairway? * First off, you should get all the rotations of the String. For example, the String `abcd` has the following rotations: `abcd, bcda, cdab, dabc` (each character is moved to the end until we reach the last character). * We now place each rotation on top of each other: ``` abcd bcda cdab dabc ``` * We can't really climb on a straight wall, so we must build stairs. That means you should add a number of spaces before each rotation corresponding to its index in the rotation list: ``` abcd bcda cdab dabc ``` * You also need a Stairway that links to the other side of my castle, so you should build one like below, reversing each rotation and adding some spacing: ``` abcd dcba bcda adcb cdab badc dabccbad ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), hence the shortest code in bytes wins and standard rules for the tag apply. --- # Test Cases * Input: `abcd`, Output: ``` abcd dcba bcda adcb cdab badc dabccbad ``` * Input: `aaaa`, Output: ``` aaaa aaaa aaaa aaaa aaaa aaaa aaaaaaaa ``` * Input: `Code golf`, Output (Notice the spaces): ``` Code golf flog edoC ode golfC Cflog edo de golfCo oCflog ed e golfCod doCflog e golfCode edoCflog golfCode edoCflog olfCode g g edoCflo lfCode go og edoCfl fCode gollog edoCf ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 12 bytes ### Code: ``` vDNúsÀ}\».B∞ ``` Uses the **05AB1E** encoding. [Try it online!](https://tio.run/##MzBNTDJM/f@/zMXv8K7iww21MYd26zk96pj3/79zfkqqQnp@ThoA "05AB1E – Try It Online") ### Explanation: ``` v } # Length input times, do.. (N = iteration count) DNú # Duplicate and prepend N spaces sÀ # Swap and rotate one to the left \ # Discard the top of the stack » # Join the stack by newlines .B # Pad with spaces into a rectangle ∞ # Mirror the string ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 16 bytes ``` J’ɓ⁹⁶ẋ;"ṙz⁶Zm€0Y ``` [Try it online!](https://tio.run/##y0rNyan8/9/rUcPMk5MfNe581Ljt4a5ua6WHO2dWAdlRuY@a1hhE/v//XykxKTlFCQA "Jelly – Try It Online") Of course, -1 using [Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan)'s `ɓ`! [Answer] # [Python 3](https://docs.python.org/3/), 85 bytes ``` x=input() l=len(x) for i in range(l):y=x[i:]+x[:i];print(' '*i+y+' '*(l+~i)+y[::-1]) ``` [Try it online!](https://tio.run/##DcYxDkIhDADQ/Z@iG62Ng3GrYXLwEITBRL42IYUQTGD5V0ff9Orsn2LXtYZXq9@OtGWfk@GgbS8NFNSgPe2dMJNMP4JK5BFE4602tY4O3El5soN/MPOhxDOInC@R1rqXV4JHyfsP "Python 3 – Try It Online") -1 byte thanks to ovs -1 byte thanks to Lynn -4 bytes thanks to p1131 [Answer] # [Retina](https://github.com/m-ender/retina), 47 bytes ``` . $.`$* $&$'$`$.'$* ¶ %(`^ $_¶ O$^`.(?=.*$) ¶ ``` [Try it online!](https://tio.run/##K0otycxL/P9fj0tFL0FFS0FFTUVdJUFFTx3IPrSNS1UjIY5LJR7I8leJS9DTsLfV01LR5OICCvz/75yfkqqQnp@TBgA "Retina – Try It Online") Explanation: The first stage creates the left stairway by considering each character and creating spaces equal to the current position, then the remainder of the string, then the start of the string, then spaces equal to the remainder of the string. The rest of the script runs over each line just generated in turn. First the line is duplicated, then the characters in the duplicate are reversed, then the line and its duplicate are concatenated. [Answer] # [J](http://jsoftware.com/), 27 bytes ``` [:(,.|.)i.@#(|.,~' '#~[)"{] ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/o600dPRq9DQz9RyUNWr0dOrUFdSV66I1lapj/2typSZn5CukKagnJiWnqP8HAA "J – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), 126 bytes ``` i,j,k,l;f(char*s){for(l=strlen(s),i=0;i<l;i++,puts(""))for(j=0;j<4*l-2;j++,putchar(i<=k&k<i+l?s[k%l]:32))k=j<2*l-1?j:4*l-3-j;} ``` [Try it online!](https://tio.run/##JYzBDoIwEAXP8hWkiaYLJVHwRNtw8DOMB1IBt13BUDwRvr3SeHvJzDxTDMaEgMIKJ0j23LzaOfOw9tPMSftlpm7kHgTqs0RFEvNcfL6L54wBRMnuwKprRkUp7R/GD45Ku5NTmFPj7@5Ij7oqAZy2qtzdS2Pr2FSFlVvAcUnfLY48jhbW5NBzdpueXTpM1DOQyRZ@ "C (gcc) – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 23 21 20 bytes ``` FLθ«FLθ§θ⁺κι↘MLθ←»‖C ``` [Try it online!](https://tio.run/##S85ILErOT8z5///9nmXv96w5t@PQajhr@bkdjxp3ndt1buejthnv96wFiz5qm3Bo96OGae/3LP7/3zk/JdU9PycNAA "Charcoal – Try It Online") Can probably be golfed more, but I'm posting from the mobile app. Link to [the verbose version](https://tio.run/##XcxBCsIwEIXhfU8xyxlIL9CuSgURKkhvUJJJEwwZG0NVxLPHulFw@/2Pp92UtEyhFCsJcOA4Z4cLETwrgD/bBOCUfMzY5UM0fMdFQWcMnpUnonYbHGVlbHZyi6OfXf7Z90ZBM7D9lFc1sg2scy@XB1JbSi@G9xJsqddSX8Mb). [Answer] ## Haskell, ~~80~~ 79 bytes ``` (s:u)#t|q<-(t>>" ")++s:u++t++(u>>" ")=q++reverse q++'\n':u#(t++[s]) u#_=u (#"") ``` [Try it online!](https://tio.run/##ZYoxDgIhEEV7TjEZTBYy8QIb2cZ2O0s1hmRBjQguMFbeHUksfdXP@@9my8OF0JoqI2tZP@tuq@o0IaAm6o6oEin@GbMSZfd2uTjoczjFYWSpenEsZy1YXgwLb5RE1O1p7xEMLEkAwIvroeY5wgY84D4t7pqCx//LdrB9AQ "Haskell – Try It Online") How it works ``` (#"") -- start with the input string and an empty accumulator (s:u)#t -- let s be the first char and u the rest of the input -- string, and t the accumulator |q<- -- let q be half of the current line, i.e. (t>>" ")++ -- length of t times spaces s:u++ -- s and u (aka the input string) t++ -- the accumulator (u>>" ") -- length of u times spaces = q ++ reverse q ++ -- the current line is q and q reversed '\n' : -- and a newline u#(t++[s]) -- and a recursive call with u as the new input -- string and s put at the end of t _#_=[] -- base case: stop if the input string is empty ``` Edit: Thanks to @Ørjan Johansen for a byte. [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal), ~~26 24 23~~ 20 bytes ``` L(DL‹n-ð$*+mðn*$+,1Ǔ ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=L%28DL%E2%80%B9n-%C3%B0%24*%2Bm%C3%B0n*%24%2B%2C1%C7%93&inputs=Code%20golf&header=&footer=) Thanks to lyxal for -3 bytes [Answer] # [Pyth](https://github.com/isaacg1/pyth), 19 bytes ``` jms_BdC.tm+*d;.<QdU ``` [Try it online!](http://pyth.herokuapp.com/?code=jms_BdC.tm%2B%2ad%3B.%3CQdU&input=%22Code+golf%22&debug=0) [Answer] # Mathematica, 119 bytes ``` b=StringRotateLeft;j=Table;Column@j[""<>{" "~j~i,b[s=#,i],j[" ",t-i],b[StringReverse@s,-i]},{i,0,t=StringLength@#-1}]& ``` [Answer] # PHP, 95 bytes ``` for($e=strlen($s=$argn);$i<$e;$s.=$s[$i],$s[$i++]=" ")echo$t=str_pad($s,2*$e-1),strrev($t)," "; ``` Run as pipe with `-nR` or [try it online](http://sandbox.onlinephpfunctions.com/code/84fe030042310b1b9f67e56ed3b98130fedb5723). **breakdown** ``` for($e=strlen($s=$argn); # import input $i<$e; # loop length times $s.=$s[$i], # 2. append current character $s[$i++]=" ") # 3. set current character to space echo$t=str_pad($s,2*$e-1), # 1. print string padded with length-1 spaces strrev($t), # print reverse "\n"; # print newline ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 22 bytes ``` l VÇç +UéZn)+´Vç)ê1÷ ``` Leading newline is part of the program. [Try it online!](http://ethproductions.github.io/japt/?code=CmwKVsfnICtV6VpuKSu0Vucp6jHDtw==&input=IkNvZGUgZ29sZiIK) [Run all test cases](https://codepen.io/justinm53/full/NvKjZr?code=CmwKVsfnICtV6VpuKSu0Vucp6jHDtw==&inputs=ImFiY2Qi,ImFhYWEi,IkNvZGUgZ29sZiI=) using my WIP CodePen. ## Explanation Implicit: `U` = input string. First line is blank to not overwrite `U`. Second line implicitly assigns the length (`l`) of `U` to `V`. Third line: ``` VÇç +UéZn)+´Vç)ê1÷ VoZ{Zç +UéZn)+--Vç)ê1} · Ungolfed VoZ{ } Create array [0, V) and map by... Zç The current value (Z) times " " +UéZn) Concatenated with U rotated Z times left +--Vç) Concatenated with --V times " ". This decrements V ê1 Palindromize with repeated last char · Join with newlines and implicitly output ``` [Answer] # Pyth, 20 bytes ``` jms_B.>+.<Qd*\ tlQdl ``` [Try it online!](http://pyth.herokuapp.com/?code=jms_B.%3E%2B.%3CQd%2a%5C+tlQdl&input=%22Code+golf%22&debug=0) [Answer] # Javascript (ES6), 118 bytes ``` s=>[...s].map((_,y)=>Array(l=(j=s.length)*4-2).fill().map((_,x)=>(x=x<l/2?x:l-x-1)>=y&y+j>x?s[x%j]:" ").join``).join` ` ``` Example code snippet: ``` f= s=>[...s].map((_,y)=>Array(l=(j=s.length)*4-2).fill().map((_,x)=>(x=x<l/2?x:l-x-1)>=y&y+j>x?s[x%j]:" ").join``).join` ` o.innerText=f("Code golf") ``` ``` <pre id=o> ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~85~~ 83 bytes * Thanks @ovs for 2 bytes: `l+~i` and helped me spot a unwanted space ``` x=input() l=len(x) for i in range(l):r=i*' '+x[i:]+x[:i]+(l+~i)*' ';print r+r[::-1] ``` [Try it online!](https://tio.run/##FcixCsMgEADQPV9xmxrJkI5XnPoZwaEQTQ@OUw4LZumv22R5w6tn@xR5jNEDSf026yYOnMR2N@WiQEAC@pYjWXaogWYDxveNMF4iRW/Z/8jd/axK0kC9bojLGscwr7InOApn8wc "Python 2 – Try It Online") [Answer] # [8th](http://8th-dev.com/), ~~173~~ 168 bytes **Code** ``` s:len n:1- ( >r dup s:len n:1- "" ( " " s:+ ) rot times dup 0 r@ s:slice -rot r> -1 s:slice s:+ s:+ dup s:rev swap . . cr null s:/ a:shift a:push "" a:join ) 0 rot loop ``` **Ungolfed version with comments** ``` : shifter \ s -- s null s:/ \ convert string into array a:shift \ remove the first item in the array and put it on TOS a:push \ append the former 1st item to array "" a:join \ convert array into string ; : stairway \ s -- s s:len n:1- ( >r \ save loop index dup \ duplicate input string s:len n:1- \ get string length "" ( " " s:+ ) rot times \ make filler dup \ duplicate filler 0 r@ s:slice \ make left filler -rot \ put left filler at proper position r> -1 s:slice \ make right filler s:+ s:+ \ build string ( 1st half of stairway ) dup s:rev \ build 2nd half swap . . cr \ print it shifter \ shift rotate 1st character ) 0 rot loop \ loop from 0 to len(string)-1 ; ``` **Usage and examples** ``` ok> "abcd" s:len n:1- ( >r dup s:len n:1- "" ( " " s:+ ) rot times dup 0 r@ s:slice -rot r> -1 s:slice s:+ s:+ dup s:rev swap . . cr null s:/ a:shift a:push "" a:join ) 0 rot loop abcd dcba bcda adcb cdab badc dabccbad ``` Or more clearly ``` ok> "Code golf" stairway Code golf flog edoC ode golfC Cflog edo de golfCo oCflog ed e golfCod doCflog e golfCode edoCflog golfCode edoCflog olfCode g g edoCflo lfCode go og edoCfl fCode gollog edoCf ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 29 bytes ``` {w←⍵⋄(⊢,⌽)↑{(-⍵+⍴w)↑⍵⌽w}¨⍳⍴⍵} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkG/6vLgdSj3q2Puls0HnUt0nnUs1fzUdvEag1doKD2o94t5SAuSEHP3vLaQyse9W4GCgL5tf/TwDr7HnU1P@pdAxQ8tN4YpLRvanCQM5AM8fAM/p@moJ6YlJyizgUUACpXV@cCiQABqohzfkqqQnp@Tpo6FxcA "APL (Dyalog Unicode) – Try It Online") ## Explanation ``` {w←⍵⋄(⊢,⌽)↑{(-⍵+⍴w)↑⍵⌽w}¨⍳⍴⍵} ⍵ → input w←⍵ assign original input to w ⍳⍴⍵ range from 0 to length of ⍵ { }¨ map range to function, loop var i ⍵⌽w input rotated i characters (-⍵+⍴w) i + length of input, negated ↑ take that much from the rotated string (prepends spaces) ↑ mix the array to create one side of the pattern (⊢,⌽) append the reverse of the matrix to itself ``` [Answer] # [Perl 5](https://www.perl.org/) + `-lF -M5.10.0`, 57 bytes ``` @F=@F[1..$#F,!say$"x$-,@F," "x($#F-$-++),reverse@F]for@F ``` [Try it online!](https://tio.run/##K0gtyjH9r6Jra2D938HN1sEt2lBPT0XZTUexOLFSRalCRVfHwU1HSUFBqUIDKKyroqutralTlFqWWlSc6uAWm5Zf5OD2/39iUnIKVyIQcDnnp6QqpOfnpP3LLyjJzM8r/q@b4/Zf19dUz9BAzwAA "Perl 5 – Try It Online") ## Explanation Using `-F` (specifying the `-F` switch without an argument, `-F` controls how a string is split into `@F`) the input is split into a list of singular chars. `for` each char in `@F`, `@F` is then set to the slice of index `1` to `$#F` (which is the last index in `@F`) followed by the item at index `!say...` which equates to `0`. The effectively shifts the list content backwards by one index each iteration. `say` is called within the indexing operation to produce the output before the list is re-indexed and is provided with `$"x$-` (`$-`, which is a special int only variable that is preinitialised to `0`, copies of `$"`, which is the special list separator variable, preinitialised to space) followed by `@F`, followed by `" "x($#F-$-++)` (two spaces repeated by the final index of `@F` with the current value of `$-` times - `$-` is post-incremented here so will increase on the next iteration), finally followed by the `reverse` of `@F`. [Answer] # [Python 2](https://docs.python.org/2/), 82 bytes ``` x=input() i=l=-len(x) while i:s=x[i:]+x[:i];i+=1;print' '*(~l+i)+s+' '*-i+s[::-1] ``` [Try it online!](https://tio.run/##DccxDgIhEAXQfk9BtgGcUKwlm6k8BqET3Z9MgAhmsfHq6Ote/fSj5Oucg5Hruxu7gIWdpGyGXc4DkhR84xHgI43gEXcQb3t9IXet9MV8hWCpkVb/OVAL3rstzrneyj2pZ5HH@gM "Python 2 – Try It Online") [Answer] # [Pip](https://github.com/dloscutoff/pip) `-l`, 21 bytes ``` aMERF:sX#aRA_a@Y_+,#a ``` [Try it online!](https://tio.run/##K8gs@P8/0dc1yM2qOEI5McgxPtEhMl5bRznx////ujn/E5OSUwA "Pip – Try It Online") ### Explanation ``` a is command-line argument; s is space (implicit) aME Map this function to each number in 0 .. len(a)-1: ,#a Range(len(a)) _+ Add the function's argument: Range(_, _+len(a)) Y Yank that range (just to get the precedence right) a@ Use the range as the (modular) indices to slice into the string sX#a Get a string of spaces of the same length as the input string RA_ Replace the space at index _ with the slice calculated above RF: Reflect the string, appending its reverse to it Output the result list one item per line (-l flag) ``` [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-R`](https://codegolf.meta.stackexchange.com/a/14339/), 15 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` ¬£éYn)iYçÃú mê1 ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVI&code=rKPpWW4paVnnw/ogbeox&input=IkNvZGUgZ29sZiI) ``` ¬£éYn)iYçÃú mê1 :Implicit input of string U ¬ :Split £ :Map each character at 0-based index Y é : Rotate U right Yn : -Y times ) : End rotate i : Prepend Yç : Space repeated Y times à :End map ú :Right pad with spaces to the length of the longest m :Map ê1 : Mirror :Implicit output joined with newlines ``` ]
[Question] [ Note: this is heavily inspired by *[this question](https://codegolf.stackexchange.com/questions/92944/hyperprogramming-nn-n%C3%97n-nn-all-in-one)*. # Task: Your task is to generate the `n`th prime, when each character of your program is repeated `n` times in place. Let's say your program is: ``` Derp ``` Every character in there is repeated once, so it should output `2`. When every character is duplicated in place, like so: ``` DDeerrpp ``` This should generate the 2nd prime, which is `3`. # Specs: * Your program must accept no input, and output the respective prime. * Your program must work for all primes, given enough time and memory. * Leading and trailing newlines are fine. * The output must be in the default base of the language - if there is no default, any base is fine. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 13 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` “Ŀo‘’FQỌµḟ;¹V ``` [Try it online!](http://jelly.tryitonline.net/#code=4oCcxL9v4oCY4oCZRlHhu4zCteG4nzvCuVY&input=) or [run the first ten programs](http://jelly.tryitonline.net/#code=eMOQ4oKsMTBW4oKsRw&input=&args=4oCcxL9v4oCY4oCZRlHhu4zCteG4nzvCuVY). ### Background Jelly has several different types of string literals; all of them start with a `“`. If the literal contains more than one `“`, a string array is returned, and `“` separates the strings from each other. For example, `“abc“def”` yields `['abc', 'def']`. Depending on the last character of the literal (any of `”«»‘’`, where `«` is currently unimplemented), one can choose between the different types of literals. For `‘`, we get the code points in [Jelly's code page](https://github.com/DennisMitchell/jelly/wiki/Code-page) instead of the corresponding Unicode characters. For example, `“abc“def‘` yields `[[97, 98, 99], [100, 101, 102]]`. The literals in the first three programs correspond to the following code point arrays. ``` “Ŀo‘ -> [199, 111] ““ĿĿoo‘ -> [[], [199, 199, 111, 111]] “““ĿĿĿooo‘ -> [[], [], [199, 199, 199, 111, 111, 111]] ``` ### How it works (**n = 3**) ``` “““ĿĿĿooo‘‘‘’’’FFFQQQỌỌỌµµµḟḟḟ;;;¹¹¹VVV Main link. Implicit argument: 0 “““ĿĿĿooo‘ Yield the 2D array [[], [], [199, 199, 199, 111, 111, 111]]. ‘‘ Increment twice, yielding [[], [], [201, 201, 201, 113, 113, 113]]. ’’’ Decrement thrice, yielding [[], [], [198, 198, 198, 110, 110, 110]]. F Flatten, yielding [198, 198, 198, 110, 110, 110]. FF Twice more. Does nothing. Q Unique; yield [198, 110]. QQ Twice more. Does nothing. Ọ Unordinal; convert the Unicode code points 198 and 110 to 'Æ' and 'n'. ỌỌ Twice more. Does nothing. µµµ Begin three monadic chains, all with argument s := "Æn". ḟ Filter-false; remove the characters of s from s, yielding "". ḟḟ Twice more. Does nothing. ;;;¹ Concatenate with s three times, yielding "ÆnÆnÆn". ¹¹ Identity function. Does nothing. V Eval the resulting Jelly code, i.e., call the next-prime atom thrice, with initial implicit argument 0. VV Eval two more times. This is a no-op on integers. ``` [Answer] # GS2 ([commit 67fea47](https://github.com/nooodl/gs2/tree/67fea4776db4af37c3df830ca4793c1ee1e9ddc8)), ~~6~~ 3 bytes ``` dnR ``` ### How it works Like most commands, GS2‘s `d` is overloaded. Initially, there's an empty list (the input or the lack thereof) on the stack, so `d` computes its sum. After the first iteration, there's a **0** on the stack, and `d` computes its parity (also **0**). Thus, no matter how many times we repeat `d`, the result will always be a single **0**. The next part is straightforward. The command `n` pops the top of the stack and pushes the next prime number. Thus, repeating `n` **k** times computes the **k** prime. Finally, the command simply applies *str* to the top of the stack, which converts a number to its string representation and does no affect strings. Thus, no matter how many times we repeat `R`, the result will be the string representation of the **k** prime. ]
[Question] [ ## Details Write a function or program that, given an array (or list), containing only integers, returns or output an array with all sub-elements reversed. That is, reverse all elements of the deepest array, then the second deepest, etc. The dimensions need not be specified, but the function or program must work for [jagged arrays](https://en.wikipedia.org/wiki/Jagged_array) in your programming language's native format. --- ## Examples **This:** ``` [[1,2], [3,4]] ``` **Would become this:** ``` [[4,3], [2,1]] ``` --- **This:** ``` [[[ 1, 2, 3], [ 4, 5, 6], [ 7, 8, 9]], [[10,11,12], [13,14,15], [16,17,18]], [[19,20,21], [22,23,24], [25,26,27]], [[28,29,30], [31,32,33], [34,35,36]], [[37,38,39], [40,41,42], [43,44,45]], [[46,47,48], [49,50,51], [52,53,54]]] ``` **Would become this:** ``` [[[54,53,52], [51,50,49], [48,47,46]], [[45,44,43], [42,41,40], [39,38,37]], [[36,35,34], [33,32,31], [30,29,28]], [[27,26,25], [24,23,22], [21,20,19]], [[18,17,16], [15,14,13], [12,11,10]], [[ 9, 8, 7], [ 6, 5, 4], [ 3, 2, 1]]] ``` --- **This:** ``` [[[1,2]], [[3,4], [5]], [[6,7,8], [9], [10,11]], [[[12,13], [14,15]], [16], [17,18,19,20]], [21]] ``` **Would become this:** ``` [[21], [[20,19,18,17], [16], [[15,14], [13,12]]], [[11,10], [9], [8,7,6]], [[5], [4,3]], [[2,1]]] ``` --- ## Bonus This will *hopefully* encourage answers in some [object-oriented programming languages](https://en.wikipedia.org/wiki/Category:Object-oriented_programming_languages)... **-50% Bytecount** If your program can take as input an array (or list) with its member's of various types (these can be in the form of objects) and successfully reverse all arrays. **This:** ``` [["Foo",["Bar",1]], 2, ["Baz"], [[["Qux"],3],3.14]] ``` **Would become this:** ``` [[3.14,[3,["Qux"]]], ["Baz"], 2, [[1,"Bar"],"Foo"]] ``` [Answer] # Pyth, 11 - 50% = 5.5 bytes ``` L?+IbY_yMbb ``` Try it online: [Demonstration](http://pyth.herokuapp.com/?code=L%3F%2BIbY_yMbb%0AyQ&input=[[1%2C2]%2C%20[3%2C4]]&test_suite_input=[[[%201%2C%202%2C%203]%2C%20[%204%2C%205%2C%206]%2C%20[%207%2C%208%2C%209]]%2C%20[[10%2C11%2C12]%2C%20[13%2C14%2C15]%2C%20[16%2C17%2C18]]%2C%20[[19%2C20%2C21]%2C%20[22%2C23%2C24]%2C%20[25%2C26%2C27]]%2C%20[[28%2C29%2C30]%2C%20[31%2C32%2C33]%2C%20[34%2C35%2C36]]%2C%20[[37%2C38%2C39]%2C%20[40%2C41%2C42]%2C%20[43%2C44%2C45]]%2C%20[[46%2C47%2C48]%2C%20[49%2C50%2C51]%2C%20[52%2C53%2C54]]]%0A[[%22Foo%22%2C[%22Bar%22%2C1]]%2C2%2C[%22Baz%22]%2C%20[[[%22Qux%22]%2C3]%2C3.14]]%0A[[[1%2C2]]%2C%20[[3%2C4]%2C%20[5]]%2C%20[[6%2C7%2C8]%2C%20[9]%2C%20[10%2C11]]%2C%20[[[12%2C13]%2C%20[14%2C15]]%2C%20[16]%2C%20[17%2C18%2C19%2C20]]%2C%20[21]]&debug=0) or [Test Suite](http://pyth.herokuapp.com/?code=L%3F%2BIbY_yMbb%0AyQ&input=[[1%2C2]%2C%20[3%2C4]]&test_suite=1&test_suite_input=[[[%201%2C%202%2C%203]%2C%20[%204%2C%205%2C%206]%2C%20[%207%2C%208%2C%209]]%2C%20[[10%2C11%2C12]%2C%20[13%2C14%2C15]%2C%20[16%2C17%2C18]]%2C%20[[19%2C20%2C21]%2C%20[22%2C23%2C24]%2C%20[25%2C26%2C27]]%2C%20[[28%2C29%2C30]%2C%20[31%2C32%2C33]%2C%20[34%2C35%2C36]]%2C%20[[37%2C38%2C39]%2C%20[40%2C41%2C42]%2C%20[43%2C44%2C45]]%2C%20[[46%2C47%2C48]%2C%20[49%2C50%2C51]%2C%20[52%2C53%2C54]]]%0A[[%22Foo%22%2C[%22Bar%22%2C1]]%2C2%2C[%22Baz%22]%2C%20[[[%22Qux%22]%2C3]%2C3.14]]%0A[[[1%2C2]]%2C%20[[3%2C4]%2C%20[5]]%2C%20[[6%2C7%2C8]%2C%20[9]%2C%20[10%2C11]]%2C%20[[[12%2C13]%2C%20[14%2C15]]%2C%20[16]%2C%20[17%2C18%2C19%2C20]]%2C%20[21]]&debug=0). This defines a function `y`. The additional 3 bytes `<newline>yQ` simply call the function with the input list and therefore doesn't need to be counted towards the bytes total. ### Explanation: ``` L?+IbY_yMbb L define a function y(b), that returns: ?+IbY if b + [] == b (test if b is a list): _yMb recursively call y on all elements in b, then reverse the list b else: b ``` [Answer] # [Dyalog APL](http://goo.gl/9KrKoM), 14 - 50% = 7 bytes ``` {∇¨⍣(×|≡⍵)⌽⍵} ``` `⌽⍵` reverse argument `⍣(×|≡⍵)` if the argument is not an atom (sign of the [absolute] depth)... `∇¨` ... apply the function to each element (of the reversed argument). If `⎕ML←3` (IBM style), which is the case on systems that migrated from APL2, one byte can be saved by removing `|`. [Try APL](http://tryapl.org/?a=%7B%u2207%A8%u2363%28%D7%7C%u2261%u2375%29%u233D%u2375%7D%281%202%29%283%204%29&run) online. For curiosity, the [proposed](https://codegolf.stackexchange.com/questions/75687/reverse-an-n-dimensional-array#comment183906_75687) int and float reversing: ``` {∇¨⍣(×≡⍵){0::⌽⍵⋄⍎⌽⍕⍵}⍵} ``` The inner function: `0::⌽⍵` if any error occurs, just return the revesed argument `⍎⌽⍕` make into string, reverse, make into number [Answer] # Prolog, 40 - 50% = 20 bytes ``` a(X,Y):-reverse(X,Z),maplist(a,Z,Y);X=Y. ``` This recursively calls predicate `a/2` with `maplist/3`, for each member of the list, until `reverse/2` fails (i.e. last element wasn't a list). [Answer] # Python 2, 40 - 50% = 20 ``` f=lambda x:map(f,x)[::-1]if"">x>[]else x ``` Only some minor modifications needed from the basic way to do it are needed to get the bonus. Uses the fact that all lists are less than the empty string, and all numbers are less than the empty list. [All test cases](https://ideone.com/kLmvdI) [Answer] ## Emacs Lisp, 46 bytes \* 0.5 = 23 ``` (defun g(x)(if(atom x)x(mapcar'g(reverse x)))) ``` Usage example: `(g '((1 2) 3 (four 5)))` -> `((5 four) 3 (2 1))` Classic recursive approach: if the argument isn't a list, take it unchanged, if it's a list, map the function over the reverse of the list. [Answer] # Mathematica, 34/2=17 bytes ``` Quiet[Reverse//@#]/.Reverse->(#&)& ``` Or just `Reverse//@#&` if you want a ton of errors and `Reverse`s everywhere. [Answer] # Clojure 43/2=21.5 bytes ``` (defn f[x](if(coll? x)(reverse(map f x))x)) ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 5 - 50% = 2.5 bytes ``` ċ↔↰ᵐ| ``` [Try it online!](https://tio.run/##PU@7TsNAEOzzFdHVI@R93NmukCjoqU8ukiiCAmQpCIlnkyISoqHgQ2hAiJofsX/E7J4RzXl2drwzs96tNhd3l/05Tw/D93NYrLeb/mp7vQg2HY@H93G/NzR8fdr7NHy8Tj8v4@HNFoYfpykvcyZwhyzQroONPkOMUUQk@9Zo0NrONhWIQC4nASkoOkygGtTMkhZcgckwM1jA6jCCE7guEm7ALaRyU4KYmbuJQiIkFYnUkAbSeooKSlD3VMuo0FgkmqA1tHG@RawQ3TMyoiBalf8u80F4jPnPBGtkwK@XRoXNxCAPMtcqvfzxZiitnGP6OxxO@z4gh5PVLsBJLsN9KLfC2c2tITsnR2Rhlt0v "Brachylog – Try It Online") ``` The input ċ which is a list ↔ reversed ᵐ with each element ↰ passed through this same predicate | is the output. If the input isn't a list, it is the output. ``` Since `↔` can also reverse strings and integers, we have to explicitly fail non-lists with `ċ`. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~23~~ ~~22~~ 21 bytes -50% bonus ``` #0/@Reverse@*List@@#& ``` [Try it online!](https://tio.run/##NVA9T8MwFNz7K6xE6oAOmvfhfAygiIGJAVgRQ1SlIkOp1AaEsPLbg/2SLtbZd@/enY/d@Nkfu3HYd/Phfs6LXfvW//TnS9/ePA@XsW3z7fxyHr7G9/z24dDmH9tdGzYhEHhCEOg0IV6DIziGkwkuOIXzcKXhCq6Ga5LMxbECRCBOFAlIQd5wCapA9VXWgAswJYoZLGA17MEluFplXIMbSJEoIQhDLIAoxEPKVSYVpIY0idICSlALoDG@Qv0q0xJaQWujGvgC3gJ4hhf42HSpmqqvxrBUV4MSFWzaNlnVlQnEIIu2NF4q25law/ouWqZlTfZ0OmUI2WN3zrD4xA@Ogvjyl6222ev3b8TRWe4oBtxM8z8 "Wolfram Language (Mathematica) – Try It Online") Only works on nested `List`s of atoms. Reverse a list, then reverse its elements. `@@` and `/@` are no-ops on atoms. [Answer] # JavaScript ES6, 42 - 50% = 21 bytes My score is perfect in so many ways. Implements a function `r` which recursively applies itself to the members of its input. ``` r=a=>Array.isArray(a)?a.reverse().map(r):a ``` If we assume no object has the property `pop`, then this becomes (31 - 50% = 15.5), thanks to dev-null: ``` r=a=>a.pop?a.reverse().map(r):a ``` Or, if we assume the object has a sane `reverse` property, we could do that as well (35 - 50% = 17.5): ``` r=a=>a[R="reverse"]?a[R]().map(r):a ``` [Answer] # Lua, ~~111~~ 99 \* .5 = ~~55.5~~ 49.5 bytes ``` function r(a)local t={}for i,v in next,a do t[#a+1-i]=type(v)=="table"and r(v)or v end return t end ``` Good bit of recursion [Answer] ## CJam, 20 bytes \* 50% = 10 ``` {_`0='[={W%{F}%}&}:F ``` Defines the named block `F` which can be applied to an array on top of the stack (or anything else, in which case it's a no-op). [Test it here.](http://cjam.aditsu.net/#code=%5B%5B%5B1%202%5D%5D%20%5B%5B3%204%5D%20%5B5%5D%5D%20%5B%5B6%207%208%5D%20%5B9%5D%20%5B10%2011%5D%5D%20%5B%5B%5B12%2013%5D%20%5B14%2015%5D%5D%20%5B16%5D%20%5B17%2018%2019%2020%5D%5D%20%5B21%5D%5D%0A%0A%7B_%600%3D'%5B%3D%7BW%25%7BF%7D%25%7D%26%7D%3AF%0A%0A~p) [Answer] ## Clojure, 38 bytes **(and a bonus I guess, but Clojure is a dynamic language so it comes for free)** ``` (fn f[x](if(seq? x)(map f(into()x))x)) ``` [This](https://codegolf.stackexchange.com/a/75733/59617) is a good start but didn't employ these optimizations: * Define an anonymous function with `fn` instead of a named one with `defn`. But we still need a "scoped" name `f` for recursion * Take input as a list instead of vector, then we can use `seq?` instead of `coll?` * Use `(into () ...)` instead of `reverse` * Reverse `x` before mapping, we don't need as many spaces then [Answer] # [Clojure](https://clojure.org/), ~~40~~ 38 -50% = 19 bytes ``` (fn r[s](if(coll? s)(map r(rseq s))s)) ``` [Try it online!](https://tio.run/##DYpBCoAgFAWv8nD1XVoHiM4hQmEahql9Dbq9CbOZYWzM18uu0@E8vk4@gXU1FDzZHOOCKuneC5i4umeYHHRJhUNqMYE@bFpBrKhtpFNAT1AGsxnbDw "Clojure – Try It Online") A translation of [the JavaScript answer](https://codegolf.stackexchange.com/a/75692/107299). Matched the score with the best Clojure answer ;) [Answer] # [Haskell](https://www.haskell.org/) + [free](https://hackage.haskell.org/package/free-5.1.7/docs/Control-Monad-Free.html), 8.5 bytes (17 bytes -50% bonus) In order to represent a ragged list in Haskell we use a free monad of lists. We use the [free](https://hackage.haskell.org/package/free-5.1.7/docs/Control-Monad-Free.html) library to get these free monads. ``` hoistFree reverse ``` [Try it online!](https://tio.run/##bZBRS8MwFIXf@ysOrLAWVkF9ctg@DgQVEd9kyF1728bVZCSpQ9TfXtPUthN8Sjjn5jv3pCaz56bpPpMFbklWLVWMR5L7@6ePAxssku@gIEvYaGaUoABI8dBq9tevQY9KRONAHAeBZqspt1ivcackFU5PswmBJPOkcSoacLEDO6nV8tTzj8j0JhlkmZ/prSColTDW@y5n08rcKo2qT4pKpalpQGdjXtXzk2mH3XSvsDsBvczLzDVnu/yzz1D91L0OfTMTd1U665rfWRvu3khIpO7XkgQ3KJRcWhxJWliFoxaWYWvGQQsnFVwKKaxQEq7LEGXcGOMoXLHxe4TFa2s8Ia853zthaeBiepIWVW2hdMHahQ7ccHoauurhAH72Rc9XQ@GL3/Ny9Z97td12Pw "Haskell – Try It Online") ## Explanation `hoistFree` takes a natural transformation from some functor \$F\$ to another functor \$G\$ and makes a natural transformation from \$\mathrm{Free}(F)\$ to \$\mathrm{Free}(G)\$. Here the natural transformation is reverse, from lists to lists. Because `hoistFree` must work with any natural transformation we know it must apply `reverse` exactly once to every sublist. For example imagine we had a natural transformation: ``` newtype Reversed f a = Reversed (f a) reverse' :: [a] -> Reversed [] a reverse' = Reversed . reverse ``` This is functionally identical to `reverse` but the types prove it must be applied exactly once to every list. [Answer] # [Ruby](https://www.ruby-lang.org/), 32 - 50% = 16 bytes Recursive function. Using `rescue` to catch the `NoMethodError` that triggers when trying to `reverse` a number or `map` a string turns out to be 2 bytes shorter than checking if the input is an array via `a==[*a]`. ``` f=->a{a.reverse.map(&f)rescue a} ``` [Try it online!](https://tio.run/##KypNqvz/P81W1y6xOlGvKLUstag4VS83sUBDLU2zKLU4uTRVIbH2f4FCml5yYk6ORmpZYo5CcIiLpx9QcWKK5v/oaCW3/HwlnWglp8QiJR3D2FgdLgUFIyABEqlSAnGjgYoCSyuAbGMg0jM0iY0FAA "Ruby – Try It Online") [Answer] # [Julia 1.0](http://julialang.org/), 27 -50% = 13.5 ``` !x=x !x::Array=reverse(.!x) ``` [Try it online!](https://tio.run/##yyrNyUw0rPj/X7HCtoJLscLKyrGoKLHStii1LLWoOFVDT7FC839KZnFBTmKlhoJidLSSW36@kk60klNikZKOYWysDpeCghGQAIlUKYG40UBFgaUVQLYxEOkZmsTGav4HAA "Julia 1.0 – Try It Online") ]
[Question] [ **Updated Results** # Introduction To celebrate Monster Hunter 4 Ultimate launch on new 3DS (February 13th), here's a King of the Hill themed on this game. You are a novice hunter, who'll take part in a tournament consisting of 5 consecutives hunts. At the end of these hunts, hunters will be ranked depending on the damage they dealt to monsters and of course wether they slayed it or have been vanquished by it. Also, as a novice, you'll have to stick to the weapon you choose until you are more experienced. # Lexicon `ATK` : Attack `DEF` : Defense `HP` : Health Points `NRG` : Energy `GRD` : Guard `SPD` : Speed `SHP` : Sharpness `AGR` : Aggressivity `POT` : Potion `RAT` : Ration `WHE` : Whetstone # Principle Hunters can choose among a variety of **4 weapons** : ``` | Id | ATK | GRD | SPD | ------------------------------------------------ Great Sword | GS | 7 | 2 | 2 | Dual Blade | DB | 3 | 0 | 7 | Lance | LA | 5 | 4 | 3 | Hammer | HA | 9 | 0 | 1 | ``` The **5 monsters** to hunt are : ``` | HP | ATK | DEF | ---------------------------------------- Yian Kut-ku | 1500 | 5 | 4 | Rathian | 1800 | 7 | 4 | Rathalos | 1800 | 4 | 7 | Tigrex | 2000 | 8 | 6 | Fatalis | 2500 | 11 | 7 | ``` When the game begins, you have to choose a weapon. Then, for each of the 5 hunts, you'll be split among teams of **4 players** and you'll start hunting. Each hunter basic stats are : ``` | HP | NRG | DEF | SHP | AGR | ------------------------------------------------------- Hunter | 100 | 100 | 5 | 4 | 0 | ``` Stats can't go beyond their initial values (i.e. taking a potion with 50HP only restores your health up to 100HP). Each hunter starts with : ``` | POT | RAT | WHE | --------------------------------------- Hunter Items | 5 | 5 | 5 | ``` The controller provides you with input via command arguments, your program has to output via stdout. # Syntax **Output (preparation)** Before the game starts, the controller invokes you submission without arguments. This means you have to choose one of the 4 weapon by outputing its Id. You'll keep this weapon till the end of the game. You need to output : `WeaponID` For example : `GS`. **Input** Each time your program is called, it will receive arguments in this format (newlines *not* part of the input an only used for formatting): ``` Round;YourPlayerId;Monster_ATK;Monster_DEF;Monster_HP;Monster_TargetId;Monster_NextMoveId; PlayerId_WeaponId_ATK_DEF_HP_NRG_GRD_SPD_SHP_AGR_POT_RAT_WHE_CurrentCombo; PlayerId_WeaponId_ATK_DEF_HP_NRG_GRD_SPD_SHP_AGR_POT_RAT_WHE_CurrentCombo; PlayerId_WeaponId_ATK_DEF_HP_NRG_GRD_SPD_SHP_AGR_POT_RAT_WHE_CurrentCombo; PlayerId_WeaponId_ATK_DEF_HP_NRG_GRD_SPD_SHP_AGR_POT_RAT_WHE_CurrentCombo ``` **Example input** ``` 3;3;5;5;1164;2;S; 0_LA_5_5_75_45_4_3_2_55_5_5_5_AA; 1_HA_9_5_75_100_0_1_3_321_5_5_5_N; 2_GS_7_5_75_35_2_2_2_59_5_5_5_BB; 3_DB_3_5_75_78_0_7_2_0_5_5_5_AB ``` Here, you see it is the 3rd minute (starts at 1) and you are player 3. You are carrying Dual Blades, you have 3 ATK, 5 DEF, 75 HP, 78 NRG, 0 GRD, 7 SPD, 2 SHP, 5 POT, 5 RAT, 5 WHE and your current combo is A->B. **Output** See gameplay. # Gameplay Teams of 4 hunters are made randomly at the start of each hunt. If there are not enough hunters to make teams, the game will automatically add 1 or more of the 4 "helper" (Felyne, Melynx, Palico or Koneko) choosen randomly to reach desired numbers. Each hunt lasts **50 minutes**, and you can take **1 action per minute** (i.e. 50 actions per hunt). For each of these 50 minutes, you'll need to output a letter corresponding to the action you'll take (see actions). Hunters go first (in a random order choosen at the beginning), then the monster executes its action (which was provided as `Monster_NextMoveId`). So each minute goes like this : Hunter 1 > Hunter 2 > Hunter 3 > Hunter 4 > Monster > Next minute... On the first minute, the monster will always use `O` (see actions). Each turn after its action, the monster will choose its next target by selecting the hunter with the highest `AGR` value. `AGR` decreases by 30 per minute. If the monster or all hunters are killed, the hunt stops. The hunters are revived after each hunts, and their stats, items, combos and actions are reset to their default values. # Hunters' actions > > * `A` : Attack A [Requires `NRG`] > * `B` : Attack B [Requires `NRG`] > * `C` : Attack C [Requires `NRG`] > * `G` : Guard [Requires 15 `NRG`. Can only be used if the weapon has GRD > 0. Activates `GRD` stat in damage formula for next turn.] > * `D` : Dodge [Requires 30 `NRG`. Completely dodge damage for next turn.] > * `W` : Wait [Restores 30 `NRG`. Does nothing else.] > * `T` : Taunt [Restores 80 `NRG`. Increases `AGR` by 300.] > * `P` : Potion [Requires 1 `POT`. Restores 90 `HP`. Reduces `DEF` by 2 for next turn.] > * `R` : Ration [Requires 1 `RAT`. Restores 30 `HP` AND 50 `NRG`. Reduces `DEF` by 2 for next turn.] > * `S` : Sharpen [Requires 1 `WHE`. Restores `SHP` to 4. Reduces `DEF` by 2 for next turn.] > > > # Monsters' actions Monsters choose their action randomly. > > * `O` : Observe (5% chance) [Does nothing.] > * `A` : Attack (40% chance) [Attacks target (defined in `Monster_TargetId`).] > * `R` : Roar (10% chance) [Stuns everyone. Hunters do nothing next turn.] > * `F` : Fly (10% chance) [Completely dodge every attack next turn.] > * `C` : Charge (15% chance) [Attacks target (defined in `Monster_TargetId`). Completely dodge every attack next turn.] > * `S` : Spin (20% chance) [Attacks every hunter.] > > > # Attacks & Combos Each weapon can be used to launch 3 differents attacks : `A`, `B` and `C`. Each attacks requires and consumes `NRG` according to this formula : `energy = floor(100 / (SPD + 2))` Damages are calculated with this formula : `damage = ATK * (10 + SHP - DEF [- GRD])`. `GRD` is only applied if the hunter is currently guarding (see actions). When a hunter is using an item (see actions), his `DEF` is reduced by 2. Each hit on a monster reduces `SHP` by 1 till the minimum of 1. Monsters have a `SHP` of 0. Each damage inflicted to a monster increases `AGR` by the same value. If you manage to chain attack to create a specific combo, your damage will be multiplicated by the corresponding bonus. Any action other than an attack reset your current combo, and combo with `reset = 1` will also reset it. ``` | Combo | Bonus | Reset | ------------------------------------------------------------ Great Sword | B -> B -> A | 3 | 1 | Great Sword | B -> B -> B -> C | 4 | 1 | ------------------------------------------------------------ Dual Blade | C -> C | 2 | 1 | Dual Blade | A -> B -> A -> B | 3 | 0 | Dual Blade | A -> B -> A -> B -> A | 4 | 0 | Dual Blade | A -> B -> A -> B -> A -> C | 5 | 1 | ------------------------------------------------------------ Lance | B -> B -> B | 3 | 1 | Lance | A -> A -> A | 2 | 0 | Lance | A -> A -> A -> C | 4 | 1 | ------------------------------------------------------------ Hammer | B -> B -> A | 2 | 1 | Hammer | C -> C -> A | 2 | 1 | ``` # Rules * Writing to files is allowed. Please write to "yoursubmissionname.txt", the folder will be emptied before a game starts. Other external resources are disallowed. * Your submission has 1 second to respond. * Provide commands to compile and run your submissions. # Scoring & Winning You get : * +1000 points for surviving a successful hunt (monster dead). * +0 points for surviving a unsuccessful hunt (monster alive). * -1000 points for passing away (hunter dead) no matter of the result of the hunt. * +1 point per damage dealt to the monster Winner is the one with the highest score after 5 hunts. # Controller [You can find the controller on github.](https://github.com/Thrax37/mon-master) It also contains 4 samplebots, written in Java. Open it in Eclipse, place the compiled bots in the root folder and add a class to the control program (just like the samplebots). # Results Average of 10 games : ``` 1. Lancer: 5495 2. Felyne: 4786 3. Melynx: 4190 4. RedViper: 3886 5. Koneko: 3639 6. TheKingsJester: 3100 7. RoranStronghammer: 3046 8. WeaselWill: 2849 ``` Complete logs of 1 game : <http://pastebin.com/bfR5ZiMJ> Results of 10 games : <http://pastebin.com/YWFf6qT7> [Answer] # Java, Roran Stronghammer He wields the hammer of death. ``` import java.util.ArrayList; import java.util.List; public class RoranStronghammer { int round; int playerID; Hunter thisHunter; List<Hunter> hunters = new ArrayList<>(); List<Hunter> otherHunters = new ArrayList<>(); Monster monster; boolean canTauntSafely; public static void main(String[] args){ if (args.length == 0) { System.out.println("HA");//ha! } else { System.out.println(new RoranStronghammer(args).hunt()); } } private String hunt() { int requiredEnergy = 100 / (thisHunter.getSpeed() + 2); if (requiredEnergy > thisHunter.getEnergy()){ if (canTauntSafely){ return "T"; } if (thisHunter.getRations() > 0){ return "R"; } return "T"; } int damage = thisHunter.getAtk() * (10 + thisHunter.getSharpness() - monster.getDef()); int monsterDamage = monster.getAtk() * (10 - thisHunter.getDef()); String currentCombo = thisHunter.getAttacks(); if (damage > monster.getHp()){//Kill monster if possible. return "B"; } if (currentCombo.length() >= 2 && damage * 2 > monster.getHp()){//Kill monster if possible. return "A"; } if (monsterDamage > thisHunter.getHp()){ if (thisHunter.getPotions() > 0 && thisHunter.getHp() <= 10){ return "P"; } if (thisHunter.getEnergy() <= 50 && thisHunter.getRations() > 0){ return "R"; } if (thisHunter.getPotions() > 0){ return "P"; } } if (currentCombo.length() >= 2){ return "A"; //Do critical hit } if (currentCombo.length() == 0){ if (thisHunter.getEnergy() < requiredEnergy * 3) { if (canTauntSafely){ return "T"; } if (thisHunter.getRations() > 0) { return "R"; } return "T"; } if (thisHunter.getSharpness() < 4){ return "S"; } } if (currentCombo.length() == 1){ if (thisHunter.getEnergy() < requiredEnergy * 2) { if (canTauntSafely){ return "T"; } if (thisHunter.getRations() > 0) { return "R"; } return "T"; } if (thisHunter.getSharpness() < 3){ return "S"; } } return "B"; //Attack constantly. } public RoranStronghammer(String[] args) { args = args[0].split(";"); round = Integer.parseInt(args[0]); playerID = Integer.parseInt(args[1]); monster = new Monster(args[2]+";"+args[3]+";"+args[4]+";"+args[5]+";"+args[6]); for (int i = 7; i < args.length; i++){ hunters.add(new Hunter(args[i])); } int mostAggressiveness = 0; int myAggressiveness = 0; for (Hunter hunter : hunters) { if (hunter.isMe()){ thisHunter = hunter; myAggressiveness = hunter.getAggro(); } else { otherHunters.add(hunter); mostAggressiveness = Math.max(mostAggressiveness, hunter.getAggro()); } } canTauntSafely = myAggressiveness + 300 < mostAggressiveness; } private class Monster { int atk; int def; int hp; int targetId; String nextMove; public Monster(String string) { String[] args = string.split(";"); atk = Integer.parseInt(args[0]); def = Integer.parseInt(args[1]); hp = Integer.parseInt(args[2]); targetId = Integer.parseInt(args[3]); nextMove = args[4]; } public int getAtk() { return atk; } public void setAtk(int atk) { this.atk = atk; } public int getDef() { return def; } public void setDef(int def) { this.def = def; } public int getHp() { return hp; } public void setHp(int hp) { this.hp = hp; } public int getTargetId() { return targetId; } public void setTargetId(int targetId) { this.targetId = targetId; } public String getNextMove() { return nextMove; } public void setNextMove(String nextMove) { this.nextMove = nextMove; } } private class Hunter { int hunterID; String weapon; int atk; int def; int hp; int energy; int guard; int speed; int sharpness; int aggro; int potions; int rations; int whetstones; String attacks; public Hunter(String string) { String[] args = string.split("_"); hunterID = Integer.parseInt(args[0]); weapon = args[1]; atk = Integer.parseInt(args[2]); def = Integer.parseInt(args[3]); hp = Integer.parseInt(args[4]); energy = Integer.parseInt(args[5]); guard = Integer.parseInt(args[6]); speed = Integer.parseInt(args[7]); sharpness = Integer.parseInt(args[8]); aggro = Integer.parseInt(args[9]); potions = Integer.parseInt(args[10]); rations = Integer.parseInt(args[11]); whetstones = Integer.parseInt(args[12]); attacks = args[13]; } public int getHunterID() { return hunterID; } public void setHunterID(int hunterID) { this.hunterID = hunterID; } public String getWeapon() { return weapon; } public void setWeapon(String weapon) { this.weapon = weapon; } public int getAtk() { return atk; } public void setAtk(int atk) { this.atk = atk; } public int getDef() { return def; } public void setDef(int def) { this.def = def; } public int getHp() { return hp; } public void setHp(int hp) { this.hp = hp; } public int getEnergy() { return energy; } public void setEnergy(int energy) { this.energy = energy; } public int getGuard() { return guard; } public void setGuard(int guard) { this.guard = guard; } public int getSpeed() { return speed; } public void setSpeed(int speed) { this.speed = speed; } public int getSharpness() { return sharpness; } public void setSharpness(int sharpness) { this.sharpness = sharpness; } public int getAggro() { return aggro; } public void setAggro(int aggro) { this.aggro = aggro; } public int getPotions() { return potions; } public void setPotions(int potions) { this.potions = potions; } public int getRations() { return rations; } public void setRations(int rations) { this.rations = rations; } public int getWhetstones() { return whetstones; } public void setWhetstones(int whetstones) { this.whetstones = whetstones; } public String getAttacks() { return attacks; } public void setAttacks(String attacks) { this.attacks = attacks; } public boolean isMe() { return getHunterID() == playerID; } } } ``` [Answer] # Weasel Will I'm not sure I entirely trust this guy, but his blades are nice to have around in case of trouble. ``` public class WeaselWill { int id, round, atk, def, hp, energy, guard, speed, sharp, aggro, potions, rations, whets; String combo; Monster monster; int[] aggros; void hunt(){ if(willKillMe(false)) dontDie(); if(energy < 11){ if(aggroDiff() > 300) output("T"); output("W"); } if(willHitMe()&&energy>29) output("D"); int potDamage = attack(false); if(potDamage>monster.hp/2) attack(true); if(aggroDiff()*2>potDamage || round==1) attack(true); if(sharp==1&&whets>0&&!willKillMe(true)) output("S"); output("W"); } int aggroDiff(){ int highest = 0; for(int agg : aggros) highest = agg>highest?agg:highest; return highest - aggro; } int attack(boolean output){ if(output) output("C"); return willHitFor(combo.length()+1); } void dontDie(){ if(energy>=30) output("D"); int dmg = hitsMeFor(true); if(hp-dmg>-30 && rations>0) output("R"); if(potions>0) output("P"); if(energy>10) attack(true); output("W"); } boolean willKillMe(boolean item){return willHitMe()&&(hitsMeFor(item)>=hp);} boolean willHitMe(){ if(monster.move.equals("S")) return true; else if((monster.move.equals("A")||monster.move.equals("C"))&&monster.target==id) return true; return false; } int hitsMeFor(boolean item){ return monster.atk*(10-def+(item?2:0)); } int willHitFor(int combo){ return atk*(10+sharp-monster.def)*combo; } static int atoi(String in){ return Integer.parseInt(in); } void output(String out){ System.out.println(out); System.exit(0); } public static void main(String[] args){ if(args.length==0){ System.out.println("DB"); } else { new WeaselWill(args[0]).hunt(); } } WeaselWill(String input){ String[] tokens = input.split(";"); round = atoi(tokens[0]); id = atoi(tokens[1]); monster = new Monster(new String[]{tokens[2],tokens[3],tokens[4],tokens[5],tokens[6]}); aggros = new int[3]; for(int i=7,j=0;i<tokens.length;i++){ String[] in = tokens[i].split("_"); if(atoi(in[0])==id){ atk = atoi(in[2]); def = atoi(in[3]); hp = atoi(in[4]); energy = atoi(in[5]); guard = atoi(in[6]); speed = atoi(in[7]); sharp = atoi(in[8]); aggro = atoi(in[9]); potions = atoi(in[10]); rations = atoi(in[11]); whets = atoi(in[12]); combo = in[13]; } else { aggros[j++] = atoi(in[9]); } } } class Monster{ int atk, def, hp, target; String move; Monster(String[] in){ atk = atoi(in[0]); def = atoi(in[1]); hp = atoi(in[2]); target = atoi(in[3]); move = in[4]; } } } ``` [Answer] # The King's Jester The monsters (especially Fatalis) have an extreme dislike for his rock throwing skills. ``` import java.util.ArrayList; import java.util.List; public class TheKingsJester { int round; int playerID; Hunter thisHunter; List<Hunter> hunters = new ArrayList<>(); List<Hunter> otherHunters = new ArrayList<>(); Monster monster; boolean canTauntSafely; public static void main(String[] args){ if (args.length == 0) { System.out.println("HA");//Ha ha ha ha } else { System.out.println(new TheKingsJester(args).hunt()); } } private String hunt() { String monstersNextMove = monster.getNextMove(); boolean rest = false; switch (monstersNextMove){ case "A": case "C": case "S": int mostAggresiveness = 0; for (Hunter hunter : otherHunters){ mostAggresiveness = Math.max(mostAggresiveness, hunter.getAggro()); } if (thisHunter.getAggro() >= mostAggresiveness || monstersNextMove.equals("S")) { if (thisHunter.getEnergy() >= 30){ return "D"; } } else if (thisHunter.getAggro() + 300 >= mostAggresiveness) { rest = true; } default: if (thisHunter.getHp() <= 10 && thisHunter.getPotions() > 0){ return "P"; } int monsterAttack = monster.getAtk() * 7; int difference = monsterAttack - thisHunter.getHp() + 1; if (difference > 0){ if (difference <= 30 && thisHunter.getRations() > 0){ return "R"; } if (thisHunter.getPotions() > 0) { return "P"; } if (thisHunter.getRations() > 0){ return "R"; } } if (rest){ return "W"; } return "T"; } } public TheKingsJester(String[] args) { args = args[0].split(";"); round = Integer.parseInt(args[0]); playerID = Integer.parseInt(args[1]); monster = new Monster(args[2]+";"+args[3]+";"+args[4]+";"+args[5]+";"+args[6]); for (int i = 7; i < args.length; i++){ hunters.add(new Hunter(args[i])); } int mostAggressiveness = 0; int myAggressiveness = 0; for (Hunter hunter : hunters) { if (hunter.isMe()){ thisHunter = hunter; myAggressiveness = hunter.getAggro(); } else { otherHunters.add(hunter); mostAggressiveness = Math.max(mostAggressiveness, hunter.getAggro()); } } canTauntSafely = myAggressiveness + 300 < mostAggressiveness; } private class Monster { int atk; int def; int hp; int targetId; String nextMove; public Monster(String string) { String[] args = string.split(";"); atk = Integer.parseInt(args[0]); def = Integer.parseInt(args[1]); hp = Integer.parseInt(args[2]); targetId = Integer.parseInt(args[3]); nextMove = args[4]; } public int getAtk() { return atk; } public void setAtk(int atk) { this.atk = atk; } public int getDef() { return def; } public void setDef(int def) { this.def = def; } public int getHp() { return hp; } public void setHp(int hp) { this.hp = hp; } public int getTargetId() { return targetId; } public void setTargetId(int targetId) { this.targetId = targetId; } public String getNextMove() { return nextMove; } public void setNextMove(String nextMove) { this.nextMove = nextMove; } } private class Hunter { int hunterID; String weapon; int atk; int def; int hp; int energy; int guard; int speed; int sharpness; int aggro; int potions; int rations; int whetstones; String attacks; public Hunter(String string) { String[] args = string.split("_"); hunterID = Integer.parseInt(args[0]); weapon = args[1]; atk = Integer.parseInt(args[2]); def = Integer.parseInt(args[3]); hp = Integer.parseInt(args[4]); energy = Integer.parseInt(args[5]); guard = Integer.parseInt(args[6]); speed = Integer.parseInt(args[7]); sharpness = Integer.parseInt(args[8]); aggro = Integer.parseInt(args[9]); potions = Integer.parseInt(args[10]); rations = Integer.parseInt(args[11]); whetstones = Integer.parseInt(args[12]); attacks = args[13]; } public int getHunterID() { return hunterID; } public void setHunterID(int hunterID) { this.hunterID = hunterID; } public String getWeapon() { return weapon; } public void setWeapon(String weapon) { this.weapon = weapon; } public int getAtk() { return atk; } public void setAtk(int atk) { this.atk = atk; } public int getDef() { return def; } public void setDef(int def) { this.def = def; } public int getHp() { return hp; } public void setHp(int hp) { this.hp = hp; } public int getEnergy() { return energy; } public void setEnergy(int energy) { this.energy = energy; } public int getGuard() { return guard; } public void setGuard(int guard) { this.guard = guard; } public int getSpeed() { return speed; } public void setSpeed(int speed) { this.speed = speed; } public int getSharpness() { return sharpness; } public void setSharpness(int sharpness) { this.sharpness = sharpness; } public int getAggro() { return aggro; } public void setAggro(int aggro) { this.aggro = aggro; } public int getPotions() { return potions; } public void setPotions(int potions) { this.potions = potions; } public int getRations() { return rations; } public void setRations(int rations) { this.rations = rations; } public int getWhetstones() { return whetstones; } public void setWhetstones(int whetstones) { this.whetstones = whetstones; } public String getAttacks() { return attacks; } public void setAttacks(String attacks) { this.attacks = attacks; } public boolean isMe() { return getHunterID() == playerID; } } } ``` [Answer] ## RedViper Waits for the right moment to strike. ``` import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class RedViper { private static final int ENERGY_PER_GUARD = 15; private static final int ENERGY_PER_HIT = 20; private static final String FILE_PATH = "RedViper.txt"; int round; int playerID; Hunter me; List<Hunter> otherHunters = new ArrayList<>();; Monster monster; public static void main(String[] args){ if (args.length == 0) { System.out.println("LA"); } else { RedViper redViper = new RedViper(args); String output = redViper.hunt(); redViper.updateDataFile(); System.out.println(output); } } private void updateDataFile() { File f = new File(FILE_PATH); if (f.exists()) f.delete(); if(monster.nextMove.equals("F") || monster.nextMove.equals("C")) { try { f.createNewFile(); } catch (IOException e) {} } } private String hunt() { //low hp if (me.hp <= monster.dmg(me, false, false)) { if (!monster.attacksMe()) { if (me.potions > 0) return "P"; else if (me.rations > 0) return "R"; } else { if (me.hp > monster.dmg(me, true, false) && me.energy > ENERGY_PER_GUARD) return "G"; else if (me.potions > 0) return "P"; else if (me.rations > 0 && me.hp + 30 > monster.dmg(me, false, true)) return "R"; else return "B"; } } if (monster.attacksMe() && me.energy >= ENERGY_PER_GUARD) return "G"; if (isSafeToTaunt() && me.energy < 80) return "T"; if (!monster.attacksMe() && !(me.attacks.equals("BB") && me.energy >= ENERGY_PER_HIT && !monster.dodges()) && !(me.attacks.equals("B") && me.energy >= ENERGY_PER_HIT*2) && round < 48) { if (me.sharpness < 2 && me.whetstones > 0) return "S"; if (me.energy <= 50 && me.hp <= 70 && me.rations > 0) return "R"; } if ((monster.dodges() && !(me.attacks.equals("B") && me.energy >= ENERGY_PER_HIT*2)) || me.energy < ENERGY_PER_HIT) return "W"; return "B"; } private boolean isSafeToTaunt() { int highestAggro = Integer.MIN_VALUE; for (Hunter hunter : otherHunters) { if (hunter.aggro > highestAggro) highestAggro = hunter.aggro; } return highestAggro > me.aggro + 300; } public RedViper(String[] args) { List<Hunter> allHunters = new ArrayList<>(); args = args[0].split(";"); round = Integer.parseInt(args[0]); playerID = Integer.parseInt(args[1]); monster = new Monster(args[2]+";"+args[3]+";"+args[4]+";"+args[5]+";"+args[6]); for (int i = 7; i < args.length; i++){ allHunters.add(new Hunter(args[i])); } for (Hunter hunter : allHunters) { if (hunter.isMe()){ me = hunter; } else { otherHunters.add(hunter); } } } private class Monster { int atk; int targetId; String nextMove; public Monster(String string) { String[] args = string.split(";"); atk = Integer.parseInt(args[0]); targetId = Integer.parseInt(args[3]); nextMove = args[4]; } public boolean attacksMe() { return nextMove.equals("S") || (nextMove.equals("C") && targetId == playerID) || (nextMove.equals("A") && targetId == playerID); } public int dmg(Hunter hunter, boolean guard, boolean using) { int damageMultiplicator = 10 - hunter.def; if (guard) { damageMultiplicator -= hunter.guard; } if (using) { damageMultiplicator += 2; } int damage = monster.atk * damageMultiplicator; return damage; } public boolean dodges() { File f = new File(FILE_PATH); return f.exists(); } } private class Hunter { int id; int def; int hp; int energy; int guard; int sharpness; int aggro; int potions; int rations; int whetstones; String attacks; public Hunter(String string) { String[] args = string.split("_"); id = Integer.parseInt(args[0]); def = Integer.parseInt(args[3]); hp = Integer.parseInt(args[4]); energy = Integer.parseInt(args[5]); guard = Integer.parseInt(args[6]); sharpness = Integer.parseInt(args[8]); aggro = Integer.parseInt(args[9]); potions = Integer.parseInt(args[10]); rations = Integer.parseInt(args[11]); whetstones = Integer.parseInt(args[12]); attacks = args[13]; } public boolean isMe() { return id == playerID; } } } ``` [Answer] # Java, Felyne (helper) One of the 4 example bots. This one wields a Lance. ``` import java.util.ArrayList; import java.util.List; public class Felyne { private static final int ENERGY_PER_DODGE = 30; private static final int ENERGY_PER_GUARD = 15; private static final int ENERGY_PER_WAIT = 30; private static final int ENERGY_PER_TAUNT = 80; private static final int AGGRO_PER_TAUNT = 300; int round; int playerID; Hunter thisHunter; List<Hunter> hunters = new ArrayList<>();; List<Hunter> otherHunters = new ArrayList<>();; Monster monster; public static void main(String[] args){ if (args.length == 0) { System.out.println("LA"); } else { System.out.println(new Felyne(args).hunt()); } } private String hunt() { if (thisHunter.getHp() <= (monster.getAtk() * 5)) { if (thisHunter.getPotions() > 0) return "P"; else if (thisHunter.getRations() > 0) return "R"; else if (thisHunter.getEnergy() > ENERGY_PER_GUARD) return "G"; else return attack(); } else if (monster.getTargetId() == playerID) { if (thisHunter.getEnergy() > ENERGY_PER_GUARD) return "G"; else return attack(); } else if (thisHunter.getSharpness() < 2) { if (thisHunter.getWhetstones() > 0) return "S"; else return attack(); } else { return attack(); } } private String attack() { int energyPerHit = Math.floorDiv(100, thisHunter.getSpeed() + 2); // Lance Combos : AAA, AAAC, BBB if (thisHunter.getEnergy() >= (energyPerHit * 4) && thisHunter.getAttacks().equals("N")) return "A"; else if (thisHunter.getEnergy() <= (energyPerHit * 4) && thisHunter.getAttacks().equals("N")) if (100 - thisHunter.getAggro() <= ENERGY_PER_TAUNT && thisHunter.getAggro() < (otherHunters.stream().max((x, y) -> x.getAggro() - y.getAggro()).get().getAggro() + AGGRO_PER_TAUNT + 1)) return "T"; else return "W"; else if (thisHunter.getEnergy() >= (energyPerHit * 3) && thisHunter.getAttacks().equals("A")) return "A"; else if (thisHunter.getEnergy() >= (energyPerHit * 2) && thisHunter.getAttacks().equals("AA")) return "A"; else if (thisHunter.getEnergy() >= (energyPerHit * 1) && thisHunter.getAttacks().equals("AAA")) return "C"; else return "W"; } public Felyne(String[] args) { args = args[0].split(";"); round = Integer.parseInt(args[0]); playerID = Integer.parseInt(args[1]); monster = new Monster(args[2]+";"+args[3]+";"+args[4]+";"+args[5]+";"+args[6]); for (int i = 7; i < args.length; i++){ hunters.add(new Hunter(args[i])); } for (Hunter hunter : hunters) { if (hunter.isMe()){ thisHunter = hunter; } else { otherHunters.add(hunter); } } } private class Monster { int atk; int def; int hp; int targetId; String nextMove; public Monster(String string) { String[] args = string.split(";"); atk = Integer.parseInt(args[0]); def = Integer.parseInt(args[1]); hp = Integer.parseInt(args[2]); targetId = Integer.parseInt(args[3]); nextMove = args[4]; } public int getAtk() { return atk; } public void setAtk(int atk) { this.atk = atk; } public int getDef() { return def; } public void setDef(int def) { this.def = def; } public int getHp() { return hp; } public void setHp(int hp) { this.hp = hp; } public int getTargetId() { return targetId; } public void setTargetId(int targetId) { this.targetId = targetId; } public String getNextMove() { return nextMove; } public void setNextMove(String nextMove) { this.nextMove = nextMove; } } private class Hunter { int hunterID; String weapon; int atk; int def; int hp; int energy; int guard; int speed; int sharpness; int aggro; int potions; int rations; int whetstones; String attacks; public Hunter(String string) { String[] args = string.split("_"); hunterID = Integer.parseInt(args[0]); weapon = args[1]; atk = Integer.parseInt(args[2]); def = Integer.parseInt(args[3]); hp = Integer.parseInt(args[4]); energy = Integer.parseInt(args[5]); guard = Integer.parseInt(args[6]); speed = Integer.parseInt(args[7]); sharpness = Integer.parseInt(args[8]); aggro = Integer.parseInt(args[9]); potions = Integer.parseInt(args[10]); rations = Integer.parseInt(args[11]); whetstones = Integer.parseInt(args[12]); attacks = args[13]; } public int getHunterID() { return hunterID; } public void setHunterID(int hunterID) { this.hunterID = hunterID; } public String getWeapon() { return weapon; } public void setWeapon(String weapon) { this.weapon = weapon; } public int getAtk() { return atk; } public void setAtk(int atk) { this.atk = atk; } public int getDef() { return def; } public void setDef(int def) { this.def = def; } public int getHp() { return hp; } public void setHp(int hp) { this.hp = hp; } public int getEnergy() { return energy; } public void setEnergy(int energy) { this.energy = energy; } public int getGuard() { return guard; } public void setGuard(int guard) { this.guard = guard; } public int getSpeed() { return speed; } public void setSpeed(int speed) { this.speed = speed; } public int getSharpness() { return sharpness; } public void setSharpness(int sharpness) { this.sharpness = sharpness; } public int getAggro() { return aggro; } public void setAggro(int aggro) { this.aggro = aggro; } public int getPotions() { return potions; } public void setPotions(int potions) { this.potions = potions; } public int getRations() { return rations; } public void setRations(int rations) { this.rations = rations; } public int getWhetstones() { return whetstones; } public void setWhetstones(int whetstones) { this.whetstones = whetstones; } public String getAttacks() { return attacks; } public void setAttacks(String attacks) { this.attacks = attacks; } public boolean isMe() { return getHunterID() == playerID; } } } ``` [Answer] # Lancer A disciplined warrior who employs a defensive fighting style ``` /*jshint node:true */ 'use strict'; var fs = require('fs'); var dataFile = 'lancer.txt'; function getData(callback) { fs.readFile(dataFile, 'utf8', function(err, contents) { var data = {}; if(!err) { data = JSON.parse(contents); } callback(data); }); } function saveData(data, callback) { fs.writeFile(dataFile, JSON.stringify(data), callback); } function parseArgs(args){ var gameState = { monster: {}, hunters: [], otherHunters: [] }; var argArray = args.split(';'); gameState.round = +argArray.shift(); var myId = +argArray.shift(); gameState.monster.attack = +argArray.shift(); gameState.monster.defense = +argArray.shift(); gameState.monster.hp = +argArray.shift(); var monsterTargetId = +argArray.shift(); gameState.monster.nextMove = argArray.shift(); gameState.monster.guard = 0; gameState.monster.sharpness = 0; for(var index = 0; index < argArray.length; index++) { var hunterArgs = argArray[index].split('_'); var hunterId = +hunterArgs.shift(); var hunter = {}; hunter.weapon = hunterArgs.shift(); hunter.attack = +hunterArgs.shift(); hunter.defense = +hunterArgs.shift(); hunter.hp = +hunterArgs.shift(); hunter.energy = +hunterArgs.shift(); hunter.guard = +hunterArgs.shift(); hunter.speed = +hunterArgs.shift(); hunter.sharpness = +hunterArgs.shift(); hunter.aggro = +hunterArgs.shift(); hunter.potions = +hunterArgs.shift(); hunter.rations = +hunterArgs.shift(); hunter.whetstones = +hunterArgs.shift(); hunter.combo = hunterArgs.shift().split(''); gameState.hunters.push(hunter); if(myId === hunterId) { gameState.me = hunter; } else { gameState.otherHunters.push(hunter); } if(monsterTargetId === hunterId) { gameState.monster.target = hunter; } } return gameState; } function getAttackEnergy(hunter) { return Math.floor(100 / (hunter.speed + 2)); } function getDamage(attacker, defender, useGuard) { var guard = useGuard ? defender.guard : 0; return attacker.attack * (10 + attacker.sharpness - defender.defense - guard); } function isAttackingMe(gameState) { var nextMove = gameState.monster.nextMove; return nextMove === 'S' || (gameState.monster.target === gameState.me && (nextMove === 'A' || nextMove === 'C')); } function isSafeToTaunt(gameState) { var maxAggro = Math.max.apply(null, gameState.otherHunters.map(function(hunter){return hunter.aggro;})); return gameState.me.aggro + 300 < maxAggro; } function getAction(gameState) { var damage = getDamage(gameState.me, gameState.monster); if(gameState.me.combo.length === 2) { damage *= 3; } if(damage >= gameState.monster.hp && !gameState.monster.isImmune && gameState.me.energy >= getAttackEnergy(gameState.me)) { return 'B'; } var monsterDamage = getDamage(gameState.monster, gameState.me); var attackingMe = isAttackingMe(gameState); if(monsterDamage > gameState.me.hp) { if(attackingMe) { if(gameState.me.energy >= 30) { return 'D'; } if(monsterDamage < getDamage(gameState.monster, gameState.me, true) && gameState.me.energy >= 15) { return 'G'; } } if(gameState.me.potions > 0) { return 'P'; } if(gameState.me.rations > 0) { return 'R'; } } if(attackingMe && gameState.me.energy >= 15) { return 'G'; } if(gameState.me.sharpness <= 1 && gameState.me.whetstones > 0 && !attackingMe) { return 'S'; } if(gameState.me.energy >= getAttackEnergy(gameState.me) * Math.min((3 - gameState.me.combo.length), 1) && (gameState.me.combo.length < 2 || !gameState.monster.isImmune)) { return 'B'; } if(gameState.me.energy <= 20 && isSafeToTaunt(gameState)) { return 'T'; } if(gameState.me.rations > 0 && gameState.me.hp <= 70 && gameState.me.energy <= 50 && !attackingMe) { return 'R'; } return 'W'; } function startGame() { console.log('LA'); } if(process.argv.length <= 2) { startGame(); } else { var gameState = parseArgs(process.argv[2]); getData(function(data) { if(data.monsterLastAttack === 'F' || data.monsterLastAttack === 'C') { gameState.monster.isImmune = true; } data.monsterLastAttack = gameState.monster.nextMove; saveData(data, function() { console.log(getAction(gameState)); }); }); } /*jshint node:true */ 'use strict'; var fs = require('fs'); var dataFile = 'lancer.txt'; function getData(callback) { fs.readFile(dataFile, 'utf8', function(err, contents) { var data = {}; if(!err) { data = JSON.parse(contents); } callback(data); }); } function saveData(data, callback) { fs.writeFile(dataFile, JSON.stringify(data), callback); } function parseArgs(args){ var gameState = { monster: {}, hunters: [], otherHunters: [] }; var argArray = args.split(';'); gameState.round = +argArray.shift(); var myId = +argArray.shift(); gameState.monster.attack = +argArray.shift(); gameState.monster.defense = +argArray.shift(); gameState.monster.hp = +argArray.shift(); var monsterTargetId = +argArray.shift(); gameState.monster.nextMove = argArray.shift(); gameState.monster.guard = 0; gameState.monster.sharpness = 0; for(var index = 0; index < argArray.length; index++) { var hunterArgs = argArray[index].split('_'); var hunterId = +hunterArgs.shift(); var hunter = {}; hunter.weapon = hunterArgs.shift(); hunter.attack = +hunterArgs.shift(); hunter.defense = +hunterArgs.shift(); hunter.hp = +hunterArgs.shift(); hunter.energy = +hunterArgs.shift(); hunter.guard = +hunterArgs.shift(); hunter.speed = +hunterArgs.shift(); hunter.sharpness = +hunterArgs.shift(); hunter.aggro = +hunterArgs.shift(); hunter.potions = +hunterArgs.shift(); hunter.rations = +hunterArgs.shift(); hunter.whetstones = +hunterArgs.shift(); hunter.combo = hunterArgs.shift().split(''); gameState.hunters.push(hunter); if(myId === hunterId) { gameState.me = hunter; } else { gameState.otherHunters.push(hunter); } if(monsterTargetId === hunterId) { gameState.monster.target = hunter; } } return gameState; } function getAttackEnergy(hunter) { return Math.floor(100 / (hunter.speed + 2)); } function getDamage(attacker, defender, useGuard) { var guard = useGuard ? defender.guard : 0; return attacker.attack * (10 + attacker.sharpness - defender.defense - guard); } function isAttackingMe(gameState) { var nextMove = gameState.monster.nextMove; return nextMove === 'S' || (gameState.monster.target === gameState.me && (nextMove === 'A' || nextMove === 'C')); } function isSafeToTaunt(gameState) { var maxAggro = Math.max.apply(null, gameState.otherHunters.map(function(hunter){return hunter.aggro;})); return gameState.me.aggro + 300 < maxAggro; } function getAction(gameState) { var damage = getDamage(gameState.me, gameState.monster); if(gameState.me.combo.length === 2) { damage *= 3; } if(damage >= gameState.monster.hp && !gameState.monster.isImmune && gameState.me.energy >= getAttackEnergy(gameState.me)) { return 'B'; } var monsterDamage = getDamage(gameState.monster, gameState.me); var attackingMe = isAttackingMe(gameState); if(monsterDamage > gameState.me.hp) { if(attackingMe) { if(gameState.me.energy >= 30) { return 'D'; } if(monsterDamage < getDamage(gameState.monster, gameState.me, true) && gameState.me.energy >= 15) { return 'G'; } } if(gameState.me.potions > 0) { return 'P'; } if(gameState.me.rations > 0) { return 'R'; } } if(attackingMe && gameState.me.energy >= 15) { return 'G'; } if(gameState.me.sharpness <= 1 && gameState.me.whetstones > 0 && !attackingMe) { return 'S'; } if(gameState.me.energy >= getAttackEnergy(gameState.me) * Math.min((3 - gameState.me.combo.length), 1) && (gameState.me.combo.length < 2 || !gameState.monster.isImmune)) { return 'B'; } if(gameState.me.energy <= 20 && isSafeToTaunt(gameState)) { return 'T'; } if(gameState.me.rations > 0 && gameState.me.hp <= 70 && gameState.me.energy <= 50 && !attackingMe) { return 'R'; } return 'W'; } function startGame() { console.log('LA'); } if(process.argv.length <= 2) { startGame(); } else { var gameState = parseArgs(process.argv[2]); getData(function(data) { if(data.monsterLastAttack === 'F' || data.monsterLastAttack === 'C') { gameState.monster.isImmune = true; } data.monsterLastAttack = gameState.monster.nextMove; saveData(data, function() { console.log(getAction(gameState)); }); }); } ``` Save as `lancer.js`, run with `node lancer` [Answer] # Java, Koneko (helper) One one of the 4 example bot. This one wields Dual Blades ``` import java.util.ArrayList; import java.util.List; public class Koneko { private static final int ENERGY_PER_DODGE = 30; private static final int ENERGY_PER_GUARD = 15; private static final int ENERGY_PER_WAIT = 30; private static final int ENERGY_PER_TAUNT = 80; private static final int AGGRO_PER_TAUNT = 300; int round; int playerID; Hunter thisHunter; List<Hunter> hunters = new ArrayList<>();; List<Hunter> otherHunters = new ArrayList<>();; Monster monster; public static void main(String[] args){ if (args.length == 0) { System.out.println("DB"); } else { System.out.println(new Koneko(args).hunt()); } } private String hunt() { if (thisHunter.getHp() <= (monster.getAtk() * 5)) { if (thisHunter.getPotions() > 0) return "P"; else if (thisHunter.getRations() > 0) return "R"; else if (thisHunter.getEnergy() > ENERGY_PER_GUARD) return "G"; else return attack(); } else if (monster.getTargetId() == playerID) { if (thisHunter.getEnergy() > ENERGY_PER_GUARD) return "G"; else return attack(); } else if (thisHunter.getSharpness() < 2) { if (thisHunter.getWhetstones() > 0) return "S"; else return attack(); } else { return attack(); } } private String attack() { int energyPerHit = Math.floorDiv(100, thisHunter.getSpeed() + 2); // Dual Blade Combos : CC, ABAB, ABABA, ABABAC if (thisHunter.getEnergy() >= (energyPerHit * 6) && thisHunter.getAttacks().equals("N")) return "A"; else if (thisHunter.getEnergy() <= (energyPerHit * 6) && thisHunter.getAttacks().equals("N")) if (100 - thisHunter.getAggro() <= ENERGY_PER_TAUNT && thisHunter.getAggro() < (otherHunters.stream().max((x, y) -> x.getAggro() - y.getAggro()).get().getAggro() + AGGRO_PER_TAUNT + 1)) return "T"; else return "W"; else if (thisHunter.getEnergy() >= (energyPerHit * 5) && thisHunter.getAttacks().equals("A")) return "B"; else if (thisHunter.getEnergy() >= (energyPerHit * 4) && thisHunter.getAttacks().equals("AB")) return "A"; else if (thisHunter.getEnergy() >= (energyPerHit * 3) && thisHunter.getAttacks().equals("ABA")) return "B"; else if (thisHunter.getEnergy() >= (energyPerHit * 2) && thisHunter.getAttacks().equals("ABAB")) return "A"; else if (thisHunter.getEnergy() >= (energyPerHit * 1) && thisHunter.getAttacks().equals("ABABA")) return "C"; else return "W"; } public Koneko(String[] args) { args = args[0].split(";"); round = Integer.parseInt(args[0]); playerID = Integer.parseInt(args[1]); monster = new Monster(args[2]+";"+args[3]+";"+args[4]+";"+args[5]+";"+args[6]); for (int i = 7; i < args.length; i++){ hunters.add(new Hunter(args[i])); } for (Hunter hunter : hunters) { if (hunter.isMe()){ thisHunter = hunter; } else { otherHunters.add(hunter); } } } private class Monster { int atk; int def; int hp; int targetId; String nextMove; public Monster(String string) { String[] args = string.split(";"); atk = Integer.parseInt(args[0]); def = Integer.parseInt(args[1]); hp = Integer.parseInt(args[2]); targetId = Integer.parseInt(args[3]); nextMove = args[4]; } public int getAtk() { return atk; } public void setAtk(int atk) { this.atk = atk; } public int getDef() { return def; } public void setDef(int def) { this.def = def; } public int getHp() { return hp; } public void setHp(int hp) { this.hp = hp; } public int getTargetId() { return targetId; } public void setTargetId(int targetId) { this.targetId = targetId; } public String getNextMove() { return nextMove; } public void setNextMove(String nextMove) { this.nextMove = nextMove; } } private class Hunter { int hunterID; String weapon; int atk; int def; int hp; int energy; int guard; int speed; int sharpness; int aggro; int potions; int rations; int whetstones; String attacks; public Hunter(String string) { String[] args = string.split("_"); hunterID = Integer.parseInt(args[0]); weapon = args[1]; atk = Integer.parseInt(args[2]); def = Integer.parseInt(args[3]); hp = Integer.parseInt(args[4]); energy = Integer.parseInt(args[5]); guard = Integer.parseInt(args[6]); speed = Integer.parseInt(args[7]); sharpness = Integer.parseInt(args[8]); aggro = Integer.parseInt(args[9]); potions = Integer.parseInt(args[10]); rations = Integer.parseInt(args[11]); whetstones = Integer.parseInt(args[12]); attacks = args[13]; } public int getHunterID() { return hunterID; } public void setHunterID(int hunterID) { this.hunterID = hunterID; } public String getWeapon() { return weapon; } public void setWeapon(String weapon) { this.weapon = weapon; } public int getAtk() { return atk; } public void setAtk(int atk) { this.atk = atk; } public int getDef() { return def; } public void setDef(int def) { this.def = def; } public int getHp() { return hp; } public void setHp(int hp) { this.hp = hp; } public int getEnergy() { return energy; } public void setEnergy(int energy) { this.energy = energy; } public int getGuard() { return guard; } public void setGuard(int guard) { this.guard = guard; } public int getSpeed() { return speed; } public void setSpeed(int speed) { this.speed = speed; } public int getSharpness() { return sharpness; } public void setSharpness(int sharpness) { this.sharpness = sharpness; } public int getAggro() { return aggro; } public void setAggro(int aggro) { this.aggro = aggro; } public int getPotions() { return potions; } public void setPotions(int potions) { this.potions = potions; } public int getRations() { return rations; } public void setRations(int rations) { this.rations = rations; } public int getWhetstones() { return whetstones; } public void setWhetstones(int whetstones) { this.whetstones = whetstones; } public String getAttacks() { return attacks; } public void setAttacks(String attacks) { this.attacks = attacks; } public boolean isMe() { return getHunterID() == playerID; } } } ``` [Answer] # Java, Palico (helper) One of the 4 example bots. This one wields a Hammer. ``` import java.util.ArrayList; import java.util.List; public class Palico { private static final int ENERGY_PER_DODGE = 30; private static final int ENERGY_PER_GUARD = 15; private static final int ENERGY_PER_WAIT = 30; private static final int ENERGY_PER_TAUNT = 80; private static final int AGGRO_PER_TAUNT = 300; int round; int playerID; Hunter thisHunter; List<Hunter> hunters = new ArrayList<>();; List<Hunter> otherHunters = new ArrayList<>();; Monster monster; public static void main(String[] args){ if (args.length == 0) { System.out.println("HA"); } else { System.out.println(new Palico(args).hunt()); } } private String hunt() { if (thisHunter.getHp() <= (monster.getAtk() * 5)) { if (thisHunter.getPotions() > 0) return "P"; else if (thisHunter.getRations() > 0) return "R"; else if (thisHunter.getEnergy() > ENERGY_PER_GUARD) return "G"; else return attack(); } else if (monster.getTargetId() == playerID) { if (thisHunter.getEnergy() > ENERGY_PER_GUARD) return "G"; else return attack(); } else if (thisHunter.getSharpness() < 2) { if (thisHunter.getWhetstones() > 0) return "S"; else return attack(); } else { return attack(); } } private String attack() { int energyPerHit = Math.floorDiv(100, thisHunter.getSpeed() + 2); // Hammer Combos : CCA, BBA if (thisHunter.getEnergy() >= (energyPerHit * 3) && thisHunter.getAttacks().equals("N")) return "C"; else if (thisHunter.getEnergy() <= (energyPerHit * 3) && thisHunter.getAttacks().equals("N")) if (100 - thisHunter.getAggro() <= ENERGY_PER_TAUNT && thisHunter.getAggro() < (otherHunters.stream().max((x, y) -> x.getAggro() - y.getAggro()).get().getAggro() + AGGRO_PER_TAUNT + 1)) return "T"; else return "W"; else if (thisHunter.getEnergy() >= (energyPerHit * 3) && thisHunter.getAttacks().equals("C")) return "C"; else if (thisHunter.getEnergy() >= (energyPerHit * 2) && thisHunter.getAttacks().equals("CC")) return "A"; else return "W"; } public Palico(String[] args) { args = args[0].split(";"); round = Integer.parseInt(args[0]); playerID = Integer.parseInt(args[1]); monster = new Monster(args[2]+";"+args[3]+";"+args[4]+";"+args[5]+";"+args[6]); for (int i = 7; i < args.length; i++){ hunters.add(new Hunter(args[i])); } for (Hunter hunter : hunters) { if (hunter.isMe()){ thisHunter = hunter; } else { otherHunters.add(hunter); } } } private class Monster { int atk; int def; int hp; int targetId; String nextMove; public Monster(String string) { String[] args = string.split(";"); atk = Integer.parseInt(args[0]); def = Integer.parseInt(args[1]); hp = Integer.parseInt(args[2]); targetId = Integer.parseInt(args[3]); nextMove = args[4]; } public int getAtk() { return atk; } public void setAtk(int atk) { this.atk = atk; } public int getDef() { return def; } public void setDef(int def) { this.def = def; } public int getHp() { return hp; } public void setHp(int hp) { this.hp = hp; } public int getTargetId() { return targetId; } public void setTargetId(int targetId) { this.targetId = targetId; } public String getNextMove() { return nextMove; } public void setNextMove(String nextMove) { this.nextMove = nextMove; } } private class Hunter { int hunterID; String weapon; int atk; int def; int hp; int energy; int guard; int speed; int sharpness; int aggro; int potions; int rations; int whetstones; String attacks; public Hunter(String string) { String[] args = string.split("_"); hunterID = Integer.parseInt(args[0]); weapon = args[1]; atk = Integer.parseInt(args[2]); def = Integer.parseInt(args[3]); hp = Integer.parseInt(args[4]); energy = Integer.parseInt(args[5]); guard = Integer.parseInt(args[6]); speed = Integer.parseInt(args[7]); sharpness = Integer.parseInt(args[8]); aggro = Integer.parseInt(args[9]); potions = Integer.parseInt(args[10]); rations = Integer.parseInt(args[11]); whetstones = Integer.parseInt(args[12]); attacks = args[13]; } public int getHunterID() { return hunterID; } public void setHunterID(int hunterID) { this.hunterID = hunterID; } public String getWeapon() { return weapon; } public void setWeapon(String weapon) { this.weapon = weapon; } public int getAtk() { return atk; } public void setAtk(int atk) { this.atk = atk; } public int getDef() { return def; } public void setDef(int def) { this.def = def; } public int getHp() { return hp; } public void setHp(int hp) { this.hp = hp; } public int getEnergy() { return energy; } public void setEnergy(int energy) { this.energy = energy; } public int getGuard() { return guard; } public void setGuard(int guard) { this.guard = guard; } public int getSpeed() { return speed; } public void setSpeed(int speed) { this.speed = speed; } public int getSharpness() { return sharpness; } public void setSharpness(int sharpness) { this.sharpness = sharpness; } public int getAggro() { return aggro; } public void setAggro(int aggro) { this.aggro = aggro; } public int getPotions() { return potions; } public void setPotions(int potions) { this.potions = potions; } public int getRations() { return rations; } public void setRations(int rations) { this.rations = rations; } public int getWhetstones() { return whetstones; } public void setWhetstones(int whetstones) { this.whetstones = whetstones; } public String getAttacks() { return attacks; } public void setAttacks(String attacks) { this.attacks = attacks; } public boolean isMe() { return getHunterID() == playerID; } } } ``` [Answer] # Java, Melynx (helper) One of the 4 example bots. This one wields a Great Sword. ``` import java.util.ArrayList; import java.util.List; public class Melynx { private static final int ENERGY_PER_DODGE = 30; private static final int ENERGY_PER_GUARD = 15; private static final int ENERGY_PER_WAIT = 30; private static final int ENERGY_PER_TAUNT = 80; private static final int AGGRO_PER_TAUNT = 300; int round; int playerID; Hunter thisHunter; List<Hunter> hunters = new ArrayList<>();; List<Hunter> otherHunters = new ArrayList<>();; Monster monster; public static void main(String[] args){ if (args.length == 0) { System.out.println("GS"); } else { System.out.println(new Melynx(args).hunt()); } } private String hunt() { if (thisHunter.getHp() <= (monster.getAtk() * 5)) { if (thisHunter.getPotions() > 0) return "P"; else if (thisHunter.getRations() > 0) return "R"; else if (thisHunter.getEnergy() > ENERGY_PER_GUARD) return "G"; else return attack(); } else if (monster.getTargetId() == playerID) { if (thisHunter.getEnergy() > ENERGY_PER_GUARD) return "G"; else return attack(); } else if (thisHunter.getSharpness() < 2) { if (thisHunter.getWhetstones() > 0) return "S"; else return attack(); } else { return attack(); } } private String attack() { int energyPerHit = Math.floorDiv(100, thisHunter.getSpeed() + 2); // Great Sword Combos : BBA, BBBC if (thisHunter.getEnergy() >= (energyPerHit * 4) && thisHunter.getAttacks().equals("N")) return "B"; else if (thisHunter.getEnergy() <= (energyPerHit * 4) && thisHunter.getAttacks().equals("N")) if (100 - thisHunter.getAggro() <= ENERGY_PER_TAUNT && thisHunter.getAggro() < (otherHunters.stream().max((x, y) -> x.getAggro() - y.getAggro()).get().getAggro() + AGGRO_PER_TAUNT + 1)) return "T"; else return "W"; else if (thisHunter.getEnergy() >= (energyPerHit * 3) && thisHunter.getAttacks().equals("B")) return "B"; else if (thisHunter.getEnergy() >= (energyPerHit * 2) && thisHunter.getAttacks().equals("BB")) return "B"; else if (thisHunter.getEnergy() >= (energyPerHit * 1) && thisHunter.getAttacks().equals("BBB")) return "C"; else return "W"; } public Melynx(String[] args) { args = args[0].split(";"); round = Integer.parseInt(args[0]); playerID = Integer.parseInt(args[1]); monster = new Monster(args[2]+";"+args[3]+";"+args[4]+";"+args[5]+";"+args[6]); for (int i = 7; i < args.length; i++){ hunters.add(new Hunter(args[i])); } for (Hunter hunter : hunters) { if (hunter.isMe()){ thisHunter = hunter; } else { otherHunters.add(hunter); } } } private class Monster { int atk; int def; int hp; int targetId; String nextMove; public Monster(String string) { String[] args = string.split(";"); atk = Integer.parseInt(args[0]); def = Integer.parseInt(args[1]); hp = Integer.parseInt(args[2]); targetId = Integer.parseInt(args[3]); nextMove = args[4]; } public int getAtk() { return atk; } public void setAtk(int atk) { this.atk = atk; } public int getDef() { return def; } public void setDef(int def) { this.def = def; } public int getHp() { return hp; } public void setHp(int hp) { this.hp = hp; } public int getTargetId() { return targetId; } public void setTargetId(int targetId) { this.targetId = targetId; } public String getNextMove() { return nextMove; } public void setNextMove(String nextMove) { this.nextMove = nextMove; } } private class Hunter { int hunterID; String weapon; int atk; int def; int hp; int energy; int guard; int speed; int sharpness; int aggro; int potions; int rations; int whetstones; String attacks; public Hunter(String string) { String[] args = string.split("_"); hunterID = Integer.parseInt(args[0]); weapon = args[1]; atk = Integer.parseInt(args[2]); def = Integer.parseInt(args[3]); hp = Integer.parseInt(args[4]); energy = Integer.parseInt(args[5]); guard = Integer.parseInt(args[6]); speed = Integer.parseInt(args[7]); sharpness = Integer.parseInt(args[8]); aggro = Integer.parseInt(args[9]); potions = Integer.parseInt(args[10]); rations = Integer.parseInt(args[11]); whetstones = Integer.parseInt(args[12]); attacks = args[13]; } public int getHunterID() { return hunterID; } public void setHunterID(int hunterID) { this.hunterID = hunterID; } public String getWeapon() { return weapon; } public void setWeapon(String weapon) { this.weapon = weapon; } public int getAtk() { return atk; } public void setAtk(int atk) { this.atk = atk; } public int getDef() { return def; } public void setDef(int def) { this.def = def; } public int getHp() { return hp; } public void setHp(int hp) { this.hp = hp; } public int getEnergy() { return energy; } public void setEnergy(int energy) { this.energy = energy; } public int getGuard() { return guard; } public void setGuard(int guard) { this.guard = guard; } public int getSpeed() { return speed; } public void setSpeed(int speed) { this.speed = speed; } public int getSharpness() { return sharpness; } public void setSharpness(int sharpness) { this.sharpness = sharpness; } public int getAggro() { return aggro; } public void setAggro(int aggro) { this.aggro = aggro; } public int getPotions() { return potions; } public void setPotions(int potions) { this.potions = potions; } public int getRations() { return rations; } public void setRations(int rations) { this.rations = rations; } public int getWhetstones() { return whetstones; } public void setWhetstones(int whetstones) { this.whetstones = whetstones; } public String getAttacks() { return attacks; } public void setAttacks(String attacks) { this.attacks = attacks; } public boolean isMe() { return getHunterID() == playerID; } } } ``` ]
[Question] [ Almost every function can be expressed as a polynomial with infinite terms. For example, `e^x = 1 + x + x^2/2! + x^3/3! + x^4/4! + ...` For example, `sin(x) = x - x^3/3! + x^5/5! - x^7/7! + ...` The coefficients of the `n`-th terms form a sequence, and the corresponding function is called the **Generating Function** of the sequence. The coefficients of the `n`-th terms form a sequence. Often, the `n`-th term would have a denominator of `n!`. Therefore, we multiply the coefficient by `n!` to obtain another sequence, whose **Exponential Generating Function** would be the original function. For example, the sequence whose **Exponential Generating Function** is `e^x` would be `1,1,1,1,...`. For example, the sequence whose **Exponential Generating Function** is `sin(x)` would be `0,1,0,-1,0,1,0,-1,...`. # Task Your task is to find the `n`-th term of the sequence whose **Exponential Generating Function** is `tan(x)`. # Testcases ``` n result 0 0 1 1 2 0 3 2 4 0 5 16 6 0 7 272 8 0 9 7936 10 0 11 353792 12 0 13 22368256 14 0 15 1903757312 16 0 17 209865342976 18 0 19 29088885112832 20 0 21 4951498053124096 22 0 23 1015423886506852352 24 0 25 246921480190207983616 26 0 ``` (Copied from [here](https://oeis.org/A009006/b009006.txt).) (Warning: the `0`-th term is different) # Example implementation ``` # copied from https://github.com/Mego/Seriously/blob/v2.0/SeriouslyCommands.py#L16 def memoized(f): memo = {} def m_fun(*args): if args in memo: return memo[args] else: res = f(*args) memo[args] = res return res return m_fun # copied from https://github.com/Mego/Seriously/blob/v2.0/SeriouslyCommands.py#L169 @memoized def binomial(n,r): if r > n: return 0 elif r==n: return 1 res = 1 i = 1 while i<=r: res *= (n+1-i) res /= i i+=1 return int(res) # 2*u(n+1) = Sum_{k=0..n} binomial(n, k)*u(k)*u(n-k) # from A000111 @memoized def u(n): if n<0: return 0 if n==0: return 1 if n==1: return 1 return sum([binomial(n-1,k)*u(k)*u(n-1-k) for k in range(n)])//2 def t(n): if n%2 == 0: return 0 return u(n) print('\n'.join([str(x) + ' ' + str(t(x)) for x in range(26)])) ``` [Ideone it!](http://ideone.com/mqeyal) # References * [Generating function on Wikipedia](https://en.wikipedia.org/wiki/Generating_function) * [Exponential generating function on Wikipedia](https://en.wikipedia.org/wiki/Generating_function#Exponential_generating_function) * [Exponential generating function example on Wikipedia](https://en.wikipedia.org/wiki/Generating_function#Exponential_generating_function_2) * [Generating function on MathWorld](http://mathworld.wolfram.com/GeneratingFunction.html) * [Exponential generating function on MathWorld](http://mathworld.wolfram.com/ExponentialGeneratingFunction.html) * [Taylor series on Wikipedia](https://en.wikipedia.org/wiki/Taylor_series) * [Derivation of first 9 terms of required sequence](http://www.petervis.com/mathematics/maclaurin_series/maclaurin_series_tanx.html) * [Obligatory OEIS A009006](https://oeis.org/A009006) (Note that the `0`-th term is different) * [Algorithm](http://www.wikiwand.com/en/Trigonometric_functions#/Tangent) * [OEIS A000111: up/down numbers](https://oeis.org/A000111) [Answer] ## CJam (33 32 27 26 23 20 bytes) ``` 2,{ee::*_(@+.+}ri*0= ``` [Online demo](http://cjam.aditsu.net/#code=2%2C%7Bee%3A%3A*_(%40%2B.%2B%7Dri*0%3D&input=25) ### Dissection This essentially implements the [recurrence described by xnor](https://codegolf.stackexchange.com/a/83019/194). ``` 2, e# [0 1] represents the base case f(0,j) = j==1 { e# Loop... ee::* e# Multiply each array element by its index _(@+.+ e# Sum the array shifted left and the array shifted right }ri* e# ... n times 0= e# Evaluate at j=0 ``` --- Or with a rather different approach, for 23 bytes: ``` ri_1&a{{1$+}*]W%0+}@*0= ``` [Online demo](http://cjam.aditsu.net/#code=ri_1%26a%7B%7B1%24%2B%7D*%5DW%250%2B%7D%40*0%3D&input=25). Thanks to Dennis for 3 bytes. ### Dissection ``` 1a e# Push [1] { e# Repeat... {1$+}*] e# Compute array of partial sums W%0+ e# Reverse and append 0 }qi:A* e# ... A times, where A is the input value 0=A1&* e# Result is first element if A odd, and 0 otherwise ``` --- Or with a very different approach, for 29 bytes: ``` qie!Ma-{W\+W+3ew{_$.=1=},!},, ``` [Online demo](http://cjam.aditsu.net/#code=qie!Ma-%7BW%5C%2BW%2B3ew%7B_%24.%3D1%3D%7D%2C!%7D%2C%2C&input=5) Unfortunately a special case is required for input `0`. ### Dissection ``` qi e# Take an integer n from stdin e! e# Compute all permutations of [0 ... n-1] Ma- e# Special-case n=0 { e# Filter... W\+W+ e# Prepend and postpend -1 3ew e# Take slices of 3 consecutive elements { e# Filter... _$.=1= e# Test whether the middle element is the second largest },! e# ... and require no matches },, e# ... and count ``` --- You may be thinking "WTF?! He's answering the wrong question." If so, that's understandable, but both approaches [do indeed give the correct results](http://arxiv.org/abs/math/0303267). [Answer] # Julia, ~~40~~ ~~38~~ 32 bytes ``` !n=2(2*4^n-2^n-0^n)abs(zeta(-n)) ``` Input and output is in form of `BigFloat`s. [Try it online!](http://julia.tryitonline.net/#code=IW49MigyKjRebi0yXm4tMF5uKWFicyh6ZXRhKC1uKSkKCmZvciBuIGluIGJpZygwLjA6MjYuMCkKICAgIEBwcmludGYoIiUyZDogJWRcbiIsbiwhbikKZW5k&input=) ### Background The Maclaurin series of the tangent function satisfies the identity ![](https://i.stack.imgur.com/SSucT.png) whenever **x** lies in its convergence radius, where **Bn** is a Bernoulli number. Since **B2(n+1)** and **(-1)n** have the same sign, **B2n+1 = 0** if **n > 0** and **B1 = 1/2**, we can rewrite the above as follows. ![](https://i.stack.imgur.com/KFYyI.png) Furthermore, whenever **n** is a non-negative integer, we have ![](https://i.stack.imgur.com/r0XVf.png) where **ζ** denotes the [Riemann zeta function](https://en.wikipedia.org/wiki/Riemann_zeta_function). From this, with the convention **00 = 1**, it follows that ![](https://i.stack.imgur.com/lVEXG.png) which is the formula the implementation uses. [Answer] ## Python, 57 bytes ``` f=lambda i,j=0:~-j*f(i-1,j-1)-~j*f(i-1,j+1)if i else j==1 ``` Less golfed: ``` f=lambda i,j=0:j==1 if i==0 else (j-1)*f(i-1,j-1)+(j+1)*f(i-1,j+1) ``` We can compute the `i`th coefficient of the exponential generating function by differentiating the tangent function `i` times and evaluating at `0`. Each derivative is a polynomial in `tan(x)`, and its value at 0 is its constant term. We recursively express the coefficient of `tan(x)**j` in the `i`th derivative of `tan` with the function `f(i,j)`. The recursive expression comes from the relation `tan(x)' = 1 + tan(x)**2`. So, the derivative of `tan(x)**j` is ``` j*tan(x)**(j-1)*(tan(x)**2+1), or equivalently j*tan(x)**(j+1) + j*tan(x)**(j-1) ``` So, the contributors to `tan(x)**j` in the `i`th derivative are `tan(x)**(j-1)` and `tan(x)**(j+1)` in the `(i-1)`st derivative, each with coefficient equal to its power. This gives the recursive expression ``` f(i,j) = (j-1)*f(i-1,j-1) + (j+1)*f(i-1,j+1) ``` Note that we don't need to exclude negative exponents `j` because they evaluate to zero anyway and don't contribute because crossing `j=0` gives a multiplier of `0`. The base case of `i==0` corresponds to `tan(x)` itself with `j==1`, and zero coefficients otherwise. The final evaluation happens at the constant term `j=0`, which is put in as a default value. [Answer] # Mathematica, 20 bytes ``` Tan@x~D~{x,#}/.x->0& ``` Straight-forward approach. Calculate the *n*th derivative of *tan(x)* and evaluate it at *x = 0*. ## Usage [![Example](https://i.stack.imgur.com/iWWRp.png)](https://i.stack.imgur.com/iWWRp.png) [Answer] ## Haskell, 48 bytes ``` 0%1=1 0%_=0 i%j=sum[k*(i-1)%k|k<-[j+1,j-1]] (%0) ``` We can compute the `i`th coefficient of the exponential generating function by differentiating the tangent function `i` times and evaluating at `0`. Each derivative is a polynomial in `tan(x)`, and the value at 0 is its constant term. We recursively express the coefficient of `tan(x)^j` in the `i`th derivative of `tan` with the function `i%j`. The recursive expression comes from the relation `tan(x)' = 1 + tan(x)^2`. So, the derivative of `tan(x)^j` is ``` j*tan(x)^(j-1)*(tan(x)^2+1), or equivalently j*tan(x)^(j+1) + j*tan(x)^(j-1) ``` So, the contributors to `tan(x)^j` in the `i`th derivative are `tan(x)^(j-1)` and `tan(x)^(j+1)` in the `(i-1)`st derivative, each with coefficient equal to its power. [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), ~~12~~ 11 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` Ṛ+\;S ḂÇ⁸¡Ḣ ``` Like [Peter Taylor's CJam answer](https://codegolf.stackexchange.com/a/83011), this computes the **n**th term of [Euler's up/down sequence](https://oeis.org/A000111) if **n** is odd and special-cases even **n** as **0**. [Try it online!](http://jelly.tryitonline.net/#code=4bmaK1w7Uwoxw4fCoeG4osOX4biC&input=&args=MTM) or [verify all test cases](http://jelly.tryitonline.net/#code=4bmaK1w7Uwoxw4figbjCoeG4osOX4biCCnIyNsK1xbzDh-KCrEc&input=). ### How it works ``` ḂÇ⁸¡Ḣ Main link. Argument: n Ḃ Bit; yield n's parity. Ç⁸¡ Apply the helper link (Ç) n (⁸) times. Ḣ Head; retrieve the first element of the resulting list. Ṛ+\;S Helper link. Argument: A (list or 1/0) Ṛ Cast A to list (if necessary) and reverse the result. +\ Take the cumulative sum. ;S Append the sum of A. ``` [Answer] ## Sage, 26 bytes ``` lambda n:tan(x).diff(n)(0) ``` Like the other solutions in math-oriented languages, this function computes the `n`th derivative of `tan(x)` and evaluates it at `x = 0`. [Try it online](https://sagecell.sagemath.org/?z=eJxLs81JzE1KSVTIsypJzNOo0NRLyUxL08jT1DDQ5OJKyy9SyFTIzFMoSsxLT9UwMte04lIAgoKizLwShTSNTE0AgfsS0w==&lang=sage) [Answer] # J, ~~15~~ 13 bytes There is also the builtin `t:` which calculates the *n*th coefficient of the exponential generating function of *tan(x)*. ``` (1&o.%2&o.)t: ``` Thanks to @[Leaky Nun](https://codegolf.stackexchange.com/users/48934/leaky-nun) for reminding me of Taylor series adverbs in J which saved 2 bytes. Alternative for **15 bytes**. ``` 3 :'(3&o.d.y)0' ``` Another approach is to calculate the *n*th derivative of *tan(x)* and evaluate it at *x = 0*. Note: In **J**, the amount of memory used by the derivative function `d.` grows quickly as *n* passes 10. ## Usage ``` f =: (1&o.%2&o.)t: f 7 272 (,.f"0) i. 11 NB. Additional commands are just for formatting the output 0 0 1 1 2 0 3 2 4 0 5 16 6 0 7 272 8 0 9 7936 10 0 ``` ## Explanation ``` (1&o.%2&o.)t: Input: n ( ) Define a monad (one argument function), call the input y 1&o. Get the trig function sin(x) and call it on y 2&o. Get the trig function cos(x) and call it on y % Divide sin(y) by cos(y) to get tan(y) t: Get the nth coefficient of the exponential generating series for that function and return 3 :'(3&o.d.y)0' Input: n 3 :' ' Define a monad (one argument function) with input y 3&o. Get the trig function tan(x) y The input n d. Get the nth derivative of tan(x) 0 Evaluate the nth derivative at x = 0 and return ``` [Answer] # Julia, ~~39~~ 37 bytes ``` !n=(spdiagm((0:n,1:n+1),(1,-1))^n)[2] ``` Saved 2 bytes thanks to Dennis. Not the shortest Julia solution (see Dennis's solution), but this one is done purely using derivative logic... in the form of matrices. Basically, it uses the fact that the derivative of tan(x) is 1+tan(x)^2. So since the derivative of any power of tan(x), say tan(x)^k, is k tan(x)^(k-1) tan(x)' = k tan(x)^(k-1) + k tan(x)^(k+1), we can use a simple matrix power on a matrix with the appropriate values to generate the expansion, with the second row or column (depending on construction) holding the derivatives of tan(x) itself. So we just need to find the constant in the resulting expression, and that's the first value in the corresponding row or column. [Answer] ## JavaScript (ES6), ~~127~~ 45 bytes ``` f=(n,m=0)=>n?++m*f(--n,m--)+--m*f(n,m):m-1?0:1 ``` Port of @xnor's solutions. [Answer] # Haskell, ~~95~~ 93 bytes ``` p=product f n=sum[(-1)^(n`div`2+j+1)*j^n*p[k-j+1..n+1]`div`p[1..n+1-k+j]|k<-[1..n],j<-[0..k]] ``` It is basically an implementation of the general formula with some minor optimizations. [Answer] # MATLAB with Symbolic Toolbox, 84 bytes ``` n=input('');syms x;c=coeffs(taylor(tan(x),'Order',n+1))*factorial(n);c(end)*mod(n,2) ``` Example runs: ``` >> n=input('');syms x;c=coeffs(taylor(tan(x),'Order',n+1))*factorial(n);c(end)*mod(n,2) 7 ans = 272 >> n=input('');syms x;c=coeffs(taylor(tan(x),'Order',n+1))*factorial(n);c(end)*mod(n,2) 8 ans = 0 >> n=input('');syms x;c=coeffs(taylor(tan(x),'Order',n+1))*factorial(n);c(end)*mod(n,2) 9 ans = 7936 ``` [Answer] **Haskell** (too many bytes) Using only operations on lists and Raymond Manzoni's [result](https://math.stackexchange.com/a/286628/339790): ``` c n = last $ map numerator $ zipWith (*) (scanl (*) (1) [2,3..]) (intersperse 0 $ foldr (.) id (replicate n (\xs->(xs ++ [(1%(1+2*length xs)) * (sum (zipWith (*) xs (reverse xs)))]))) [1]) ``` Unfortunately, this overflows for modest values of `n`, as it uses `Int` values. I will try to fix the problem using `Integer`values. Until then, suggestions are welcome. [Answer] # Axiom, 46 bytes ``` f(n:NNI):NNI==(n=0=>0;eval(D(tan(x),x,n),x=0)) ``` code for test and results ``` (32) -> [[i, f(i)] for i in 0..26] (32) [[0,0], [1,1], [2,0], [3,2], [4,0], [5,16], [6,0], [7,272], [8,0], [9,7936], [10,0], [11,353792], [12,0], [13,22368256], [14,0], [15,1903757312], [16,0], [17,209865342976], [18,0], [19,29088885112832], [20,0], [21,4951498053124096], [22,0], [23,1015423886506852352], [24,0], [25,246921480190207983616], [26,0]] Type: List List NonNegativeInteger ``` ]
[Question] [ Inspired by the [previous question](https://codegolf.stackexchange.com/questions/8369/generate-a-kolakoski-sequence). [Golomb's self-describing sequence](https://oeis.org/A001462) g(n) is a sequence where any natural number `n` is repeated within the sequence g(n) times. The first few numbers in the sequence are: ``` n 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 g(n) 1 2 2 3 3 4 4 4 5 5 5 6 6 6 6 7 7 7 7 8 ``` You can see that g(4)=3, and that "4" is repeated 3 times in the sequence. Given an input of `n`, output `g(n)`. Limitations: n < 100000. Smallest code wins. [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), 10 bytes ``` ’ßßạ¹ß‘µṖ¡ ``` This uses the recursive formula **a(1) = 1, a(n + 1) = 1 + a(n + 1 - a(a(n)))** from the OEIS page. [Try it online!](http://jelly.tryitonline.net/#code=4oCZw5_Dn-G6ocK5w5_igJjCteG5lsKh&input=&args=MTI) ### How it works ``` ’ßßạ¹ß‘µṖ¡ Main link. Input: n ’ Decrement; yield n - 1. ßß Recursively call the main link twice, with argument n - 1. ạ¹ Take the absolute difference of a(a(n - 1)) and n. ß Recursively call the main link, with argument n - a(a(n - 1)). ‘ Increment the result, yielding 1 + a(n - a(a(n - 1))). µ Combine the chain to the left into a single link. Ṗ Pop [1, ..., n]. This yields [] iff n == 1. ¡ Execute the chain iff Ṗ returned a non-empty array. ``` [Answer] ## GolfScript (31 chars) ``` ~([1 2.]2{.2$=[1$)]*@\+\)}3$*;= ``` [Demo](http://golfscript.apphb.com/?c=OyIyMCIKCn4oWzEgMi5dMnsuMiQ9WzEkKV0qQFwrXCl9MyQqOz0%3D) [Answer] # PHP - 63 Chars ``` function g($n){for(;++$i<=$n;){for(;++$j<=$i;){echo $i;}$j=0;}} ``` Fast AND short. I appear to have had the wrong sequence in mind. Derp. This is CORRECT, fast, and short. ``` function g($n){for(;++$i<$n;){echo round(1.201*pow($i,.618));}} ``` Accuracy may suffer past the required 100,000 mark, but I did in fact meet the mark. [Answer] # [Oasis](http://github.com/Adriandmen/Oasis), 7 bytes (non-competing) Code: ``` n<aae>T ``` [Try it online!](http://oasis.tryitonline.net/#code=bjxhYWU-VA&input=&args=MjA) Oasis is a language designed by [Adnan](https://codegolf.stackexchange.com/users/34388/adnan) which is specialized in sequences. Currently, this language can do recursion and closed form. The `T` at the end is shorthand for `10`, which indicates that `a(0) = 0` and `a(1) = 1`. To add more testcases, simply add to the list at the end. ``` n<aae>T n<aae>10 expanded 0 a(0) = 0 1 a(1) = 1 n push n (input) < -1 a a(above) [a is the sequence] a a(above) e a(n-above) > +1 ``` Now we essentially calculated `a(n-a(a(n-1))+1`. [Answer] # PHP This recursive version is shorter (60) but computationally inefficient: ``` function g($n){return$n==1?1:1+g($n-g(g($n-1)));}echo g($n); ``` This is much faster but longer (78): ``` $a=[1,2,2];for($i=3;$i<$n;$i++)for($j=0;$j<$a[$i-1];$j++)$a[]=$i;echo$a[$n-1]; ``` Much faster, but at 89 characters would be: ``` $a=[1,2,2];for($i=3;!isset($a[$n-1]);$i++)for($j=0;$j<$a[$i-1];$j++)$a[]=$i;echo$a[$n-1]; ``` Which is O(n) [Answer] # Haskell, ~~30~~ 27 Chars ``` g 1=1 g n=1+(g$n-g(g$n-1)) ``` [Answer] # [APL (Dyalog Classic)](https://www.dyalog.com/), ~~24~~ 19 bytes ``` {⍵=1:1⋄1+∇⍵-∇ ∇⍵-1} ``` -5 bytes from ngn's suggestion. [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@/@lHvVltDK8NH3S2G2o862oFcXSClAGUa1v5Pe9Q24VFv36Ou5ke9ax71bjm03vhR28RHfVODg5yBZIiHZ/D/NAVDrjQFIyA2BmITIDY0AAA "APL (Dyalog Classic) – Try It Online") Same as the recursive function used in the PHP answer. ``` {⍵=1:1⋄1+∇(⍵-∇(∇(⍵-1)))} ⍵(left arg) is n 1+∇(⍵-∇(∇(⍵-1))) recursive step: return 1 + f(n - f(f(n - 1))) if n is not 1. ⍵=1:1 if n is 1, then return 1. ``` [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), ~~11~~ 10 bytes ``` ⊢/⎕⍴∘⍸⍣≡,1 ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qKM97f@jrkX6j/qmPurd8qhjxqPeHY96Fz/qXKhjCJL9z1kNJB/19qmnPepuedS7Rr0WSHAZchlxGXOZcJlyGRoAAA "APL (Dyalog Extended) – Try It Online") -1 byte by converting to a full program, thanks to Adám. Also works in Dyalog APL 18.0. (TIO's version is 17.1, so Extended is used for the extended functionality of `⍸`.) A port of [randomra's J answer](https://codegolf.stackexchange.com/a/47220/78410) as a full program. ``` ⊢/⎕⍴∘⍸⍣≡,1 ⍣≡ ⍝ Repeat until convergence ,1 ⍝ with the starting value of [1]: ⍸ ⍝ Convert [a b c ...] into a copies of 1, b copies of 2, ... ⎕⍴∘ ⍝ and take first n values (recycling values if necessary) ⊢/ ⍝ Get the rightmost element ``` [Answer] ## Perl, 48 chars ``` (@a=(@a,($,)x($a[$,++]||$,)))<$_?redo:say$,for<> ``` Input on stdin, output to stdout. Needs Perl 5.10+ and the `-M5.010` to enable the `say`feature. Takes about O(*n*2) time due to inefficient array manipulation, but still fast enough to easily calculate up to the 100,000th term. [Answer] # Julia - 28 By a [recursive](http://en.wikipedia.org/wiki/Golomb_sequence) way: ``` a(n)=n==1?1:1+a(n-a(a(n-1))) ``` Output: ``` [a(i) for i=1:20]' 1x20 Array{Int64,2}: 1 2 2 3 3 4 4 4 5 5 5 6 6 6 6 7 7 7 7 8 ``` [Answer] # Python - 64 chars ``` n=input() g=[1,2,2] for i in range(3,n):g+=[i]*g[i-1] print g[n] ``` [Answer] ## Javascript, 93 chars ``` c=[,1],i=c.length;function g(n){for(i;i<n;i++) c[i]=g(i);return c[n]||(c[n]=1+g(n-g(g(n-1))))} ``` [Answer] ## J, 43 characters ``` f=:3 :'<.@:+&0.5(p^2-p)*y^p-1[p=:(+%)/20$1' ``` Defines a function using the asymptotic expression given on the wikipedia page. ``` f 5 3 f 20 8 f 100000 1479 ``` Annoyingly 9 characters are used just rounding to the nearest integer. [Answer] # [Prelude](http://esolangs.org/wiki/Prelude), ~~69~~ ~~55~~ 54 bytes ``` ?1-(v #1)- 1 0v ^(# 0 (1+0)#)! (#) ^#1-(0)# ``` If a standard compliant interpreter is used, this takes input and output as [byte values](https://codegolf.meta.stackexchange.com/a/4719/8478). To actually use decimal numbers on STDIN/STDOUT, you'd need [the Python interpreter](http://web.archive.org/web/20060504072747/http://z3.ca/~lament/prelude.py) with `NUMERIC_OUTPUT = True` and an additional option `NUMERIC_INPUT = True`. ## Explanation The skeleton of the program is ``` ?1-( 1 - 1 )! ``` We read the input `N` onto the first voice and decrement it to get `N-1`. We also initialise the second voice to `1`. Then we loop `N-1` one times, each iteration of which gets the next value of the sequence on the second stack. At the end we print the `N`th number. The idea of the program is to put each element of the sequence in a queue on the third voice, and to decrement the head of that queue in each iteration. When the head reaches `0`, we increment the value of the sequence and remove that `0`. Now the issue is that Prelude uses stacks and not queues. So we need to shift around that stack a bit to use it like a queue. ``` v # 0v ^ (#) ``` This copies the current value of the sequence to the first voice (as a temporary copy), pushes a `0` onto the second voice (to mark the end of the queue). And then performs a loop to shift (and thereby reverse) the third stack onto the second. After the loop, we put the copy of the current sequence value on top of the second stack (which is the tail of our queue). ``` ) (# ^#1- ``` This looks a bit ugly, but essentially it's a loop that shifts the stack back onto the third voice. Since the `)` is in the same column as the shifting instructions, the `0` we put on the second voice earlier will also end up on the third voice, so we need to remove it with another `#`. Then decrement the top of the 3rd voice, i.e. the head of the queue. Now it gets a bit annoying - we want run some code when that value is `0`, but Prelude's only control structure (the loop) only responds to non-zero values. ``` 0 (1+0)# (0)# ``` Note that the top of the second voice is truthy (since the Golomb sequence does not contain any `0`s). So the workload goes into that voice (the latter pair of parentheses). We just need to *prevent* that from happening if the head of the queue isn't `0` yet. So first we have a "loop" on the third voice which pushes a `0` onto the second voice if the head of the queue is still non-zero. We also put a `0` on the third voice to exit the loop right away. The `#` on the third voice then either removes that `0`, or removes the head of the queue if *that* was already zero. Now that second loop is only entered if the head of the queue was zero (and the `0` on the second voice was never pushed). In that case we increment the current value of the sequence and push a `0` to exit the loop. Lastly, there will always be a `0` on top of the stack, which we need to discard. I told you that logical negation is annoying in Prelude... [Answer] # Mathematica, 27 bytes ``` f@1=1;f@n_:=1+f[n-f@f[n-1]] ``` Another recursive solution. [Answer] # CJam, 14 bytes CJam is much younger than this challenge, so this answer is not eligible for the green checkmark. However, it's quite rare that you get to use `j` this nicely, so I wanted to post it anyway. ``` l~2,{_(jj-j)}j ``` [Test it here.](http://cjam.aditsu.net/#code=l~2%2C%7B_(jj-j)%7Dj&input=5) ## Explanation `j` is basically the "memoised recursion operator". It takes an integer `N`, an array and a block `F`. The array is used to initialise the memoisation: the element at index `i` will be returned for `F(i)`. `j` then computes `F(N)`, either by looking it up, or by running the block (with `n` on the stack) if the value hasn't been memoised yet. The really nifty feature is that *within* the block, `j` only takes an integer `i`, and calls `F(i)` recursively. So here is the code: ``` l~ "Read and eval input."; 2, "Push a 2-range onto the stack, i.e. [0 1]. The first value is irrelevant but the second value is the base case of the recursion."; { }j "Compute F(N)."; _( "Duplicate i and decrement to i-1."; jj "Compute F(F(i-1))."; - "Subtract from i."; j "Compute F(n-F(F(i-1)))."; ) "Increment the result."; ``` [Answer] # J, 16 bytes ``` <:{1($1+I.)^:[~] (<:{1($1+I.)^:[~]) every 1+i.20 NB. results for inputs 1..20 1 2 2 3 3 4 4 4 5 5 5 6 6 6 6 7 7 7 7 8 ``` This solution is **heavily** based on [algorithmshark's solution](https://codegolf.stackexchange.com/a/26560/7311) to a similar problem. You can find some explanation about this method there. # J, 33 bytes In this approach I build up a sequence `h(k)` with the values of the first indexes `i` where the `g(i)=k` so `h = 1 2 4 6 9 12 16...`. We can get `h(k)` fairly simply from `h(1..k-1)` with the expression `({:+1+[:+/#<:])` where the input is `h(1..k-1)`. Computing the output from `h` is straightforward. `h ([:+/]>:[) input` ``` [:+/]>:1 2(,{:+1+[:+/#<:])@]^:[~] ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 13 bytes ``` 1|-₁↰↰:?-ṅ↰+₁ ``` [Try it online!](https://tio.run/nexus/brachylog2#@29Yo/uoqfFR2wYgsrLXfbizFcjQBgr9/29o9D8KAA "Brachylog – TIO Nexus") ### Explanation ``` 1 Input = 1 = Output | Or -₁↰ a(Input - 1) ↰ a(a(Input - 1)) :?-ṅ Input - a(a(Input - 1)) ↰ a(Input - a(a(Input - 1)) +₁ 1 + a(Input - a(a(Input -1)) ``` [Answer] # Python - 76 chars ``` n=20;g=[1,2,2];[[g.append(i)for j in range(g[i-1])]for i in range(3,n)];g[n] ``` [Answer] # JavaScript - 48 Characters ``` for(g=[,i=j=k=1,2];i<1e5;k=--k?k:g[++j])g[i++]=j ``` Creates a 1-indexed array `g` containing the sequence values. # Edit - JavaScript - 46 Characters ``` v=[,1];for(x=2;x<1e5;)v[x]=1+v[x-v[v[x++-1]]] ``` Creates a 1-indexed array `v` containing the sequence values. # Edit 2 - ECMAScript 6 - 27 Characters ``` g=x=>x-1?1+g(x-g(g(x-1))):1 ``` *The first two are reasonably fast - the third is very slow* [Answer] # Haskell, 63 bytes ``` f n|n<3=n|n<4=2|1>0=foldr1(++)[replicate(f m)m|m<-[1..]]!!(n-1) ``` This is the naive approach, I was not aware of the very short recurison when I wrote this, but I thought I'd post it anyway, even tough it is longer than all other Haskell implementations, as e.g. [Calculate the nth term of Golomb's self-describing sequence](https://codegolf.stackexchange.com/questions/8374/calculate-the-nth-term-of-golombs-self-describing-sequence#comment16511_8374) and <https://codegolf.stackexchange.com/a/23979/24877> ]
[Question] [ What is the shortest program that can predict the next time Friday will fall on the 13th day of the month? * Must be an complete functioning program (not just a function/subroutine) * Must print out date in the following format: `YYYY-MM-DD` * Allow user to provide a start date either as a command line argument or through `STDIN` * If user provides no start date, use today as the start date. * If the start date is a Friday the 13th, the program should find the *next* Friday the 13th. If I were to run the program today (Feb 16 2011) I should get the following output. ``` $ ./fr13th 2013-05-09 2013-09-13 $ ./fr13th 2007-06-29 2007-07-13 $ ./fr13th 2007-07-13 2008-06-13 $ ./fr13th 2011-05-13 ``` [Answer] ## Windows PowerShell, 74 ``` for($d="date $args"|iex;($d+='1').day*$d.dayofweek-65){}'{0:yyy-MM-d}'-f$d ``` Fairly straightforward. One perhaps confusing bit is the use of `"Get-Date $args" | Invoke-Expression` to get either the current date (if `$args` is empty) or the date specified in `$args` without raising an error. ## 72-byte variant: ``` for($d="date $args"|iex;($d+=9).day*$d.dayofweek-65){}'{0:yyy-MM-d}'-f$d ``` Takes ages, though ... this doesn't increment the datetime by a whole day each iteration but instead only 900 nanoseconds. But two bytes shorter. ## 67-byte variant: ``` for($d="date $args"|iex;($d+='1').day*$d.dayofweek-65){}'{0:d}'-f$d ``` [This is a bit locale-sensitive; if it fails on your machine, try setting your date format to ISO-8601 beforehand.](https://codegolf.stackexchange.com/questions/976/next-friday-the-13th/986#986) :-) Oh, and it can be made into 65 bytes just like the 72-byte version. History: * 2011-02-17 00:33 (92) First attempt. * 2011-02-17 00:35 (85) Improved getting an initial date. * 2011-02-17 00:37 (79) Compared the product instead of day and day of week individually. Admittedly stolen from Ventero. * 2011-02-17 00:40 (76) Pulled the first line into the `for`. Comparison just as subtraction instead of `-eq` which saves another two bytes. * 2011-02-17 00:53 (75) Unix `date` format string is a bit shorter. * 2011-02-17 11:42 (74) Reverted to the default date pattern but `yyy-MM-d` suffices (since the year is always longer than three characters and the day is always 13. Thanks to Ty Auvil for this. [Answer] ## bash, 75 ``` until set `date +%F -d$1+day` date -d$1|grep -q '^F.* 13' do : done echo $1 ``` This is a bit locale-sensitive; if it fails on your machine, try `export`ing `LC_ALL=C` beforehand. ``` $ bash fri13th.sh 2013-05-09 2013-09-13 $ bash fri13th.sh 2007-06-29 2007-07-13 $ bash fri13th.sh 2007-07-13 2008-06-13 $ bash fri13th.sh 2011-05-13 ``` [Answer] ## Ruby, ~~96~~ 75 characters ``` require"date" d=Date.parse(gets||"thu")+1 d+=1 while d.wday*d.day!=65 $><<d ``` Takes the date from stdin. To not specify a date press ctrl-d. Thanks very much for Ventero's help. Ungolfed: ``` require "date" # Date.parse("thu") will return this week's thursday date = Date.parse(gets || "thu")+1 date += 1 while d.wday * d.day != 5 * 13 $stdout << date ``` Sample IO: ``` $ ruby fr13th.rb 2013-05-09 2013-09-13 $ ruby fr13th.rb 2007-06-29 2007-07-13 $ ruby fr13th.rb 2007-07-13 2008-06-13 $ ruby fr13th.rb 2011-05-13 ``` [Answer] ## C#, 185 Based on [Andrew Koester's C# solution](https://codegolf.stackexchange.com/questions/976/next-friday-the-13th/984#984), but heavily modified along the way. I eventually arrived at a solution similar to my PowerShell solution: ``` using System;class P{static void Main(string[]a){var n=a.Length>0?DateTime.Parse(a[0]):DateTime.Now;for(;(n=n.AddDays(1)).Day*(int)n.DayOfWeek!=65;);Console.Write("{0:yyy-MM-d}\n",n);}} ``` [Answer] ## Perl (and others), 114 ``` for(($y,$m,$d)=(shift//`date +%F`)=~/\d+/g,$d>12&&$m++;$m >12&&($y++,$m=1),`cal $m $y`!~/14$/m;$m++){}say"$y-$m-13" ``` Perl 5.10 or later, run with `-E 'code here'` or `-M5.010 file`. Needs `date` (from coreutils for Linux) and `cal` (from util-linux) Sample run: ``` $ perl -M5.010 fr13.pl 2013-05-09 2013-9-13 $ perl -M5.010 fr13.pl 2007-06-29 2007-07-13 $ perl -M5.010 fr13.pl 2007-07-13 2008-6-13 $ perl -M5.010 fr13.pl 2011-5-13 ``` I'm not sure when the leading zero for months before October is kept. It's obviously lost when the year rolls over; it seems to be kept when the answer is just next month. Let's call that undefined behavior--hey, this is golfing! [Answer] **BASH** ``` #!/bin/bash from=$1 if [ "$from" = "" ]; then from=`date +%Y-%m-%d` fi i=1 while [ "$isFri" = "" ] || [ "$is13" = "" ] do isFri=`date -d "${from} ${i} days" | grep Fri` is13=`date -d "${from} ${i} days" +%Y-%m-%d | grep "\-13"` ((i++)) done ((i--)) date -d "${from} ${i} days" +%Y-%m-%d ``` CONCEPT USED: ``` $ date -d "2011-02-16 2 days" +%Y-%m-%d 2011-02-18 ``` SAMPLE I/O ``` :~/aman> ./fr13th.sh 2011-05-13 :~/aman> ./fr13th.sh 2013-05-09 2013-09-13 :~/aman> ./fr13th.sh 2007-06-29 2007-07-13 :~/aman> ./fr13th.sh 2007-07-13 2008-06-13 ``` [Answer] ## C# 240 characters. C# needs a "run inside of a function only" mode! ``` using System;class P{static void Main(string[] a){var n=DateTime.Now;if(a.Length>0)DateTime.TryParse(args[0],out n);while(true){n=n.AddDays(1);if((n.Day==13)&&(n.DayOfWeek==(DayOfWeek)5))break;}Console.WriteLine(n.ToString("yyyy-MM-dd"));}} ``` Un-golfed: ``` using System; class P { static void Main(string[] a) { var n = DateTime.Now; if (a.Length > 0) DateTime.TryParse(args[0], out n); while (true) { n = n.AddDays(1); if ((n.Day == 13) && (n.DayOfWeek == (DayOfWeek)5)) break; } Console.WriteLine(n.ToString("yyyy-MM-dd")); } } ``` Test output ``` \Debug> f13.exe 2013-05-09 2013-09-13 \Debug> f13.exe 2007-06-29 2007-07-13 \Debug> f13.exe 2007-07-13 2008-06-13 \Debug> f13.exe 2011-05-13 ``` [Answer] # D: 227 Characters ``` import std.datetime,std.stdio;void main(string[]a){auto d=a.length<2?cast(Date)(Clock.currTime()):Date.fromISOExtendedString(a[1]);for(;d.dayOfWeek!=DayOfWeek.fri||d.day!=13;d+=dur!"days"(1)){}writeln(d.toISOExtendedString());} ``` More Legibly: ``` import std.datetime, std.stdio; void main(string[] a) { auto d = a.length < 2 ? cast(Date)(Clock.currTime()) : Date.fromISOExtendedString(a[1]); for(; d.dayOfWeek != DayOfWeek.fri || d.day != 13; d += dur!"days"(1)) {} writeln(d.toISOExtendedString()); } ``` The fun part is that while D's std.datetime makes this sort of code very easy to write, it's also incredibly verbose - due primarily to the precise (and therefore long) function names. So, the usability and maintainability of the code is very high, but it's code golfability is rather low. [Answer] ## Python - 166 chars Reads from stdin, so you need to feed a blank line if you want todays date ``` from datetime import* D=datetime e=timedelta(1) I=raw_input() d=e+(I and D.strptime(I,"%Y-%m-%d")or D.now()) while(d.weekday()+1)*d.day-65:d+=e print d.strftime("%F") ``` [Answer] ## SQLite, 374 characters (Line breaks added here for readability; not included in the count.) Requirement to "Allow user to provide a start date either as a command line argument or through STDIN" omitted due to technical limitations. ``` CREATE TABLE R(N UNIQUE); INSERT INTO R VALUES(0); INSERT INTO R VALUES(1); REPLACE INTO R SELECT A.N*2048|B.N*1024|C.N*512|D.N*256|E.N*128|F.N*64| G.N*32|H.N*16|I.N*8|J.N*4|K.N*2|L.N FROM R A,R B,R C,R D,R E,R F,R G,R H,R I,R J,R K,R L; CREATE TABLE F AS SELECT DATE('2000-01-13','+'||N||'months') AS D FROM R WHERE STRFTIME('%w',D)='5'; SELECT MIN(D) FROM F WHERE D>DATE('now'); ``` The first 4 statements create a table (R) with a single column containing all the integers from 0 to 4095. The 5th statement builds a table (F) of all Friday the 13ths between 2000-10-13 and 2340-12-13. The 6th statement simply returns the first Friday the 13th after the current (UTC) date. [Answer] # PHP - 103 (brute force) ``` <?for($d=date_create(@$argv[1]);$d->modify('next fri')&&$d->format(@d)-13;);die($d->format("Y-m-d\n")); ``` Ungolfed: ``` <? $d = new DateTime(@$argv[1]); while ($d->modify('next fri')) { if ($d->format('d') == 13) { die($d->format("Y-m-d\n")); } } ``` Test: ``` $ php 979.php 2013-05-09 2013-09-13 $ php 979.php 2007-06-29 2007-07-13 $ php 979.php 2007-07-13 2008-06-13 $ php 979.php 2011-05-13 ``` [Answer] ## C#, 206 194 characters **Update** This is a slightly different take on the problem, so I left my other attempt here in full. ``` using System:class p{static void Main(string[]a){var n=a.Length>0?DateTime.Parse(a[0]):DateTime.Now;for(;(n=n.AddDays(5-(int)n.DayOfWeek).AddDays(7)).Day!=13;);Console.Write("{0:yyy-MM-d}",n);}} ``` Here, I'm finding the "current" week's Friday and then incrementing by 7 until I find one that's a 13. I also used Joey's for loop and output formatting to shave a few characters. Ungolfed: ``` using System; class p { static void Main(string[] a) { var n = a.Length > 0 ? DateTime.Parse(a[0]) : DateTime.Now; for (; (n = n.AddDays(5 - (int)n.DayOfWeek).AddDays(7)).Day != 13; ) ; Console.Write("{0:yyy-MM-d}", n); } } ``` Original: This is similar to Andrew's above, but there were enough differences I decided to post a separate answer rather than comment and suggest edits. ``` using System;class p{static void Main(string[]a){var n=a.Length>0?DateTime.Parse(a[0]):DateTime.Now;do n=n.AddDays(1);while(!(n.Day==13&&n.DayOfWeek+""=="Friday"));Console.Write(n.ToString("yyyy-MM-dd"));}} ``` Ungolfed: ``` using System; class p { static void Main(string[] a) { var n = a.Length > 0 ? DateTime.Parse(a[0]) : DateTime.Now; do { n = n.AddDays(1); } while (!(n.Day == 13 && n.DayOfWeek + "" == "Friday")); Console.Write(n.ToString("yyyy-MM-dd")); } } ``` [Answer] ## R, 113 characters ``` f="%Y-%m-%d";o=format;a=c(as.Date(scan(,""),f),Sys.Date())[1];repeat{a=a+1;if(o(a,"%w%d")==513)break};cat(o(a,f)) ``` Example runs: ``` > f="%Y-%m-%d";o=format;a=c(as.Date(scan(,""),f),Sys.Date())[1];repeat{a=a+1;if(o(a,"%w%d")==513)break};cat(o(a,f)) 1: 2007-06-29 2: Read 1 item 2007-07-13 > f="%Y-%m-%d";o=format;a=c(as.Date(scan(,""),f),Sys.Date())[1];repeat{a=a+1;if(o(a,"%w%d")==513)break};cat(o(a,f)) 1: Read 0 items 2013-12-13 > f="%Y-%m-%d";o=format;a=c(as.Date(scan(,""),f),Sys.Date())[1];repeat{a=a+1;if(o(a,"%w%d")==513)break};cat(o(a,f)) 1: 2013-12-13 2: Read 1 item 2014-06-13 ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 69 bytes ``` $_=Date.new(@*ARGS[0]//Date.today);.++while .day*.day-of-week-65;.say ``` [Try it online!](https://tio.run/##K0gtyjH7/18l3tYlsSRVLy@1XMNByzHIPTjaIFZfHyxWkp@SWKlpraetXZ6RmZOqoAfkaoEI3fw03fLU1GxdM1NrveLEyv//AQ "Perl 6 – Try It Online") Thanks to @ASCII-only for -5 [Answer] Javascript ``` F13=function(x){ z=function(x){return (''+x).replace(/^(.)$/,'0$1')} D=x?new Date(x):new Date(),Z=864e5,X=D.getDay()%7,X+=+D+(X?Z*(5-X):0); do{ X+=Z*7; D=new Date(X); }while(D.getDate()!=13) return D.getFullYear()+"-"+z(D.getMonth()+1)+"-"+z(D.getDate()); } ``` ps: yeah, I know, I broke the first rule (couldn't be just a function) Tests on [javascript shell](http://www.squarefree.com/shell/shell.html) ``` F13("2013-05-09") // 2013-09-13 2013-09-13 F13("2007-06-29") // 2007-07-13 2007-07-13 F13("2007-07-13") // 2008-06-13 2008-06-13 F13() //2011-05-13 2011-05-13 ``` [Answer] ## T-SQL ~~359~~ ~~285~~ 253 Characters ``` CREATE PROCEDURE f13(@d DateTime=null)AS SET @d=ISNULL(@d,GETDATE()) ;WITH d AS (SELECT @d+1 d UNION ALL SELECT d+1 FROM d WHERE DATEPART(dw,d)<>6 OR DAY(d)<>13)SELECT CAST(d AS DATE) FROM d WHERE DATEPART(dw,d)=6 AND DAY(d)=13 OPTION (MAXRECURSION 999) ``` I just wanted to lay the smack down on the SQLite solution with my non-clever verbose date function using T-SQL procedure. Update: My original fear that doing a day increment would take more space than a month increment was *very* incorrect. Test results (SSMS): ``` f13 '2013-05-09'; GO f13 '2007-06-29'; GO f13 '2007-07-13'; GO f13; GO -- d ---------- 2013-09-13 d ---------- 2007-07-13 d ---------- 2008-06-13 d ---------- 2011-05-13 ``` [Answer] ## Another Javascript, 153 I post another javascript answer because I can't comment the first... ``` a=new Date(process.argv[2]||Date.now());for(b=1;b;b=a.getDate()!=13||!/^F/.test(a))a.setTime(a.getTime()+864e5);console.log(a.toISOString().substr(0,10)) ``` Execute with nodeJS : ``` $ node fr13th 2013-12-13 $ node fr13th 2007-06-29 2007-07-13 $ node fr13th 2013-05-09 2013-09-13 ``` [Answer] # Python 3.3, 166 characters ``` import datetime as d t=input() t=d.date(*map(int,t.split()))if t!=""else d.date.today() while 1: t+=d.timedelta(1) if t.day==13and t.weekday()==4: print(t);break ``` Input is in the format `2013 1 1`, ``` >>> ================================ RESTART ================================ >>> 2013 1 1 2013-09-13 ``` or just press enter to use today's date (would be 2013/12/11 for this output) ``` >>> ================================ RESTART ================================ >>> 2013-12-13 ``` # (there is actually a mix of my solution and @gnibbler 's that counts 144 chars) ``` import datetime as d t=input() t=d.date(*map(int,t.split()))if t!=""else d.date.today() while t.day*t.weekday()-65: t+=d.timedelta(1) print(t) ``` The very nice line `while t.day*t.weekday()-65:` is from @gnibbler's solution. [Answer] # Japt, 35 bytes ``` ÐUªKs3 ¯A @e ¶5©D¶Uf}a@f1Uf Ä s3 ¯A ``` -8 bytes thanks to @ASCIIOnly! [Try it!](https://ethproductions.github.io/japt/?v=1.4.6&code=0FWqS3MzIK9BCkBlILY1qUS2VWZ9YUBmMVVmIMQKczMgr0E=&input=IjIwMDAtMDEtMDEi) [Answer] # [Swift 4](https://developer.apple.com/swift/), 310 bytes ``` import Foundation let (u,f)=(Calendar.current,DateFormatter()) f.dateFormat="yyyy-MM-dd" var t={(x:Date)->Int in let c=u.dateComponents([.weekday,.day],from:x);return c.weekday!*c.day!},d=readLine().map{f.date(from:$0)!} ?? Date() while t(d) != 65{d=u.date(byAdding:.day,value:1,to:d)!} print(f.string(from:d)) ``` [Try it online!](https://tio.run/##PY7RSsNAEEXf8xWb4sOubEIiViESi1QKgv0C6cOamdTFZDdsZpuG0m@Pm1adp@HeuWduP@ia7qdJt511xDbWG1CkrYkaJMa9rEXJ16rBILu08s6hIfmqCDfWtYoIHRciqlP4l8rFGCbZbhOARXRQjlF54sdiDonk@c0Q04bN@Kr0l9zahu8mgHv@kQ6I36BGGZxxJ2tn2@IonhySd4ZVf3Z8W80H8VlC6VDBuzbIRdqq7nTtwi/Jm0zEZ7Zasfk5F9HwpRtkxEGwuGQPyxP8VuCf4wuANvtixsqDajwWuSRbQCBEndOGeJ32FJb9lQ1CTNNdlj8mWZ5ky@kH "Swift 4 – Try It Online") -4 thanks to TagTaco. Alas...: * needs Foundation for Date/Calendar. * Swift doesn't allow `Int`s to be used as `Bool`. * The shorthand enum syntax is helpful, though not that much. * Space is required around `??`. * `!=` also needs spacing, lest it's interpreted as an unwrapping. [Answer] **VB.net (96c\*)** **Entry** ``` Function NextFridayThe13th(d As Date) As Date While d.DayOfWeek<>DayOfWeek.Friday d=d.AddDays(1) End While While d.Day<>13 d=d.AddDays(7) End While Return d End Function ``` * I think the CodeGolf count for vb.net shouldn't include the **function signature**, closing **end function** and the **return**. So it just makes it about the internal implementation. So my scoring is broken down as so ``` While d.DayOfWeek<>DayOfWeek.Friday '35c d=d.AddDays(1) '13c 48c End While ' 9c 57c While d.Day<>13 '15c 72c d=d.AddDays(7) '14c 86c End While ' 9c 95c Return d ' 1c 96c ``` [Answer] # Rebol, 136 ``` d: any[do system/script/args now]until[d: d + 1 all[d/day = 13 d/weekday = 5]]print format/pad[4"-"-2"-"-2]reduce[d/year d/month d/day] ``` Ungolfed: ``` d: any [do system/script/args now] until [ d: d + 1 all [d/day = 13 d/weekday = 5] ] print format/pad [4 "-" -2 "-" -2] reduce [d/year d/month d/day] ``` Example usage: ``` $ rebol friday13th.reb 2013-05-09 2013-09-13 $ rebol friday13th.reb 2014-06-13 ``` [Answer] # Java 8, ~~200~~ 197 bytes ``` interface M{static void main(String[]a){java.time.LocalDate z=null,r=a.length<1?z.now():z.parse(a[0]);for(;(r=r.plusDays(1)).getDayOfWeek().getValue()*r.getDayOfMonth()!=65;);System.out.print(r);}} ``` **Explanation:** [Try it here](https://tio.run/##PY5Ba8JAEEb/SnqblWbJCm2h29CLR8WD0B7EwxAnceNmN2QmFiP@9m3w4O17PB58LV4wjz2F9nhOyQWhocaKss2NBcVV2SW6Y9ahC7CTwYVmf0B1a@dKi@tIr2OFfoVC2VSG0ftXLlF7Co2cvsz3pEP8A/U56R4HJsB9cVC2jgNY4JJ170de4ZXBKKUbknlv61@iMzzwB/1IoBb8dJsY5ATqpXx/s8rurizU6TiK7udvAqzs/Z5SWhbmIzcmN8U/) (remove the argument to use the current date). ``` interface M{ // Class static void main(String[]a){ // Mandatory main-method java.time.LocalDate z=null, // LocalDate to reduce bytes when using static calls r=a.length<1? // If no argument is given: z.now() // Start at the current date : // Else: z.parse(a[0]); // Start at the date of the first argument for(;(r=r.plusDays(1)) // Before every iteration, go to the next day // Loop as long as: .getDayOfWeek().getValue() // the 1-indexed day of the week (Friday = 5) *r.getDayOfMonth() // multiplied by the day of the month !=65; // is not 65 // (5 and 13 are primes, so only 5*13 results in 65) ); // End of loop System.out.print(r); // Print the result Friday the 13th } // End of main-method } // End of class ``` NOTE: Java's default format when printing is already `yyyy-MM-dd`. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 141 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` gĀi'-¡ëžežfžg)}V[Y`2ô0Kθ4ÖUD2Qi\28X+ë<7%É31α}‹iY¬>0ëY1¾ǝDÅsD12‹i>1ë\1Dǝ¤>2}}ǝVY`UÐ3‹12*+>13*5÷s3‹Xα©т%D4÷®т÷©4÷®·()O7%6QYн13Q*#}YRεDgi0ì]'-ý ``` 05AB1E doesn't have any builtins for Date objects or calculations. The only builtin regarding dates it has is today's year/month/day/hours/minutes/seconds/microseconds. So because of that, almost all of the code you see are manual calculations to go to the next day, and calculating the day of the week. Mostly derived from [my 05AB1E answer in *The Work Day Countdown* challenge](https://codegolf.stackexchange.com/a/173126/52210) (which is why I edited that one about an hour ago when I came across a bug..) Input is a string in the format `dd-MM-yyyy` (but output is in the format `yyyy-MM-dd`, since it's one of the rules of the challenge). [Try it online](https://tio.run/##yy9OTMpM/f8//UhDprruoYWHVx/dl3p0X9rRfematWHRkQlGh7cYeJ/bYXJ4WqiLUWBmjJFFhPbh1Tbmqoc7jQ3Pbax91LAzM/LQGjuDw6sjDQ/tOz7X5XBrsYuhEUjczvDw6hhDl@NzDy2xM6qtPT43LDIh9PAEY6CcoZGWtp2hsZbp4e3FIH7EuY2HVl5sUnUxObz90LqLTUByJZh5aLuGpr@5qllg5IW9hsaBWsq1kUHntrqkZxocXhOrrnt47///Bpa6Bqa6RgaGxgA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9TVnl4gr2SwqO2SQpK9v/TjzRkquseWnh4dczRfalH96Ud3ZeuWRsWHZlgdHiLgfe5HSaHp4W6GAVmxhhZRGgfXm1jrnq409jw3MbaRw07MyMPrbEzOLw60vDQvuNzXQ63FrsYGoHE7QyB5hm6HJ97aImdUW3t8blhkQmhhycYA@UMjbS07QyNtUwPby8G8SPObTy08mKTqovJ4e2H1l1sApIrwcxD2zU0/c1VzQIjL@w1NA7UUq6NDDq31SU90@Dwmtpadd3De//r/Dew1DUw1TUyMDTmMgIyzYBMA3MuQ2NdA3Mo00zXwAikwBAA). **Explanation:** ``` gĀi # If an input is given: '-¡ '# Split it by "-" ë # Else: že # Push today's day žf # Push today's month žg # Push today's year ) # Wrap them into a single list }V # After the if-else statement: pop and store it in variable `Y` [ # Start an infinite loop Y`2ô0Kθ4ÖUD2Qi\28X+ë<7%É31α}‹iY¬>0ëY1¾ǝDÅsD12‹i>1ë\1Dǝ¤>2}}ǝV # Go to the next day # (see my linked The Work Day Countdown answer for an explanation) Y`UÐ3‹12*+>13*5÷s3‹Xα©т%D4÷®т÷©4÷®·()O7% # Calculate the day of the week (0 = Saturday, 1 = Sunday, ..., 6 = Friday) # (see my linked The Work Day Countdown answer for an explanation) 6Q # Check if the day of the week is a Friday Yн # Push the days of the current date 13Q # Check if it's the 13th * # And if both checks are truthy: # # Stop the infinite loop }YR # After the infinite loop: push the resulting date-list, and reverse it ε # Map each value to: Dgi # If it's only a single digit: 0ì # Prepend a leading "0" ] # Close both the if-statement and map '-ý '# Join the result by "-" # (and output the result implicitly) ``` ]
[Question] [ The Venetian election system was... [complicated](https://www.venetoinside.com/hidden-treasures/post/the-election-of-the-doge-of-the-republic-of-venice/). > > The Great Council came together and put in an urn the ballots of all the councilors who were older than 30. The youngest councilor went to St Mark's Square and chose the first boy he met who drew from the urn a ballot for each councillor and only those 30 who got the word ‘elector' remained in the room. The 30 ballots were then placed back in the box and only 9 contained a ticket, so the 30 were reduced to 9, who gathered in a sort of conclave, during which, with the favourable vote of at least seven of them, they had to indicate the name of 40 councillors. > > > With the system of ballots containing a ticket, the 40 were reduced to 12; these, with the favourable vote of at least 9 of them, elected 25 others, which were reduced again to 9 who would elect another 45 with at least 7 votes in favour. The 45, again at random, were reduced to 11, who with at least nine votes in favour elected another 41 that finally would be the real electors of Doge. > > > These 41 gathered in a special room where each one cast a piece of paper into an urn with a name. One of them was extracted at random. Voters could then make their objections, if any, and charges against the chosen one, who was then called to respond and provide any justification. After listening to him, they preceded to a new election, if the candidate obtained the favourable vote of at least 25 votes out of 41, he was proclaimed Doge, if they were unable to obtain these votes a new extraction took place until the outcome was positive. > > > Venice is no longer an independent republic, but if they were, they would be dying to automate this system! (because we all know electronic voting is the future!) Time for you to step in. To streamline the democracy, I've made a few assumptions on voter preference, group sizes, picking logic, etc. Your program is to do the following. * [Here](https://pastebin.com/U5ih7GQs) is the list of members of the Great Council (who are all older than 30). Take this as input, by perhaps reading it from a file, or whatever you prefer. The number of councillors varied over time, so your program should not depend on the number of people. * Take the youngest member of the council. Because there are no ages given, you'll have to guess. Pick a person at random, and print their name. * The boy at the square will pick thirty members from an urn. So, randomly choose 30 people from the list (not including the youngest councillor). Print all their names. * Of those thirty, nine are randomly selected to go to the next round. So randomly choose 9 from that group, and print their names. * Those nine electors have to choose forty different councillors. So, from the list of councillors, excluding the electors (but including the twenty-one people from the previous round of thirty who did not become electors), pick 40 members. Print their names. * The forty were reduced to twelve by lot. Pick 12 from these members at random, print their names. * The dozen elected twenty-five councillors. You know the rules by now: pick 25 councillors excluding the 12 (but including anyone not in the 12 who partook in previous rounds), and print their names. * The twenty-five got reduced to nine again. Pick 9 random people from the 25 and print their names. * Those nine selected forty-five councillors. Pick 45 people not in the 9, and print their names. * The forty-five were reduced to eleven. Pick 11 random councillors from those 45, and print their names. * The eleven picked forty-one councillors who would elect the doge. Pick 41 people not in the 11, print their names. * Finally, these people will elect the Doge of Venice. Pick 1 person, randomly, from the 41. Then print their name. And then you can rest and watch the sun set on a democratic universe. This horrendously complicated system was made to reduce corruption; so however you implement it, every member of the Great Council must have an equal chance of getting elected in the end. In tabular form: | Step | From | Pick | New group | | --- | --- | --- | --- | | 1 | All | 1 | A | | 2 | All except A | 30 | B | | 3 | B | 9 | C | | 4 | All except C | 40 | D | | 5 | D | 12 | E | | 6 | All except E | 25 | F | | 7 | F | 9 | G | | 8 | All except G | 45 | H | | 9 | H | 11 | I | | 10 | All except I | 41 | J | | 11 | J | 1 | Doge | Other rules: * Print the name(s) exactly as given, with the same capitalisation, etc. There's only going to be readable ascii characters, there's no Nicolò on the council. * Print every new step of the algorithm on a new line. * When printing a list of names, separate them in some fashion from one another (not with spaces as the names contain spaces). If you separate them with newlines, then add an extra newline between steps so those remain clearly separated as well. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so your score is the number of bytes in your code. Lowest score wins! [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 24 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` •10¢–‘Þ}Ò•46вvNÉiK}.ry£= ``` Print each intermediate result as a list on a separated line to STDOUT. [Try it online.](https://tio.run/##fVbBbuNGDP0VIedF0QUWvfWQOHHgbdwYcZBDij1QEuMlMBq6I8lADQTIda/tpacetn@wn5D8wH5DfiTlSCMNR3F6sznk4@MjOSOuISd8eXl@@Pr@x8evzw9/PT/8/fTP/dOfYvnw0/dvu1@fvtAv9z@4Px7//fnl5bejFbDh7KItiLNjC3dYN3z0LjtagivQyNE1bsAYAtuZL13N2WILvdMpV2SpaOvsAiU8d7yBhmp/NEdDBWYzduLABrztGrmUyBh/TrzzyNkMt@D90iOwlrI55I4KgoIPQwg5yM6hNQMj7ICWbIW4o1BM62gvFYp3DpQmULbLHA26TokGLTvsrMcb2ymxAtcIky3sB4S2bqR@X8Drs4C@eHW0Imyc6OqgZE81yvo/KG/CLLIZ2HJoz4hNeasb9nb4wfg3nQ96L24OWjNJjdy35YYaMJi4BY7ZEqtqwkgFXjbSbPU/OJ2Ay2WobNrzuYEcBklH64xtI4NgKbGu0ew0tTkYQqcti2xJxWdC08tYooE71n5x1sRPBkcL6MnRZCAd14FFl8FXqiLXmIOMkx@mWwrBl34Wl2J2vB2ynlnn4U5FylSTMeqj7MpWhoBwGzyWvv6UwpWwQh@FvYgXMu12n0QFnES/cSJf5z@XgRbQjc54y26fxq3ZgeTprgj5VWCdFiOdbeRnhRPAY1s6BO0ZUqiGxJXWkZEymzuyutgZmpqG2467ywqcTpfUHpqVyCgXhSwxZzednNpr3QRlr7mqoPbqFyOnWPqc60IydDpC/XvrJ28pJY39njmSK/lOcnaJO/rIwrPkrCRZqa1LllSnCVUIudJB1dc@yqEd@/r9VgmXELthf7tNrGNqL2EJVmtw7qiCQZYusViahhS5C9@@Se8FMD45ELCuHe6o7vGjb1R56ODKUWvChDlZukqbhqSKqhHUbrVV8WrzYoLQjGwmy7axoAZOlTmqcbiI8WobNT/BKmetWSQbqzy8cAs9ntH5TB626Tot2fS9noEzEzydZoQ7Qde0hf8EuDmwTSusYXLj@YdAowZd03VRSsSncso0rtKazA79VadJDA1LO6bfRVWGaqT27lW4avf7lO3KDxglN9jY2UhRTU@/JWFjE6iDS9V/Wl3FmW1L@dzxVUsSe/TpPw) **Explanation:** ``` •10¢–‘Þ}Ò• # Push compressed integer 70284432464563859 46в # Convert it to base-46 as list: [1,30,9,40,12,25,9,45,11,41,1] v # Loop over each of these integers `y`: NÉi } # If the 0-based loop-index is odd: K # Remove all names of the current list from the (implicit) input-list .r # Shuffle the list of names y£ # Only keep the first `y` amount of random names = # Print it with trailing newlines (without popping) ``` [See this 05AB1E tip of mine (sections *How to compress large integers?* and *How to compress integer lists?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `•10¢–‘Þ}Ò•` is `70284432464563859` and `•10¢–‘Þ}Ò•46в` is `[1,30,9,40,12,25,9,45,11,41,1]`. [Answer] # [Python](https://www.python.org), ~~117 113 112 106~~ 105 bytes ``` from random import* def f(l,i=1,x=()): for y in b" (  - )":print(x:=sample(i*x or{*l}-{*x},y));i=1-i ``` [Attempt This Online!](https://ato.pxeger.com/run?1=fVbLbttWEEWWTvMD3RQXWkmGvegucOGFrUSGCgsWLMOLFF0MyZEywOUd5pI0bAUB8h_ZZNP-U_I1ncvnkJa7sjycOXPmzIP89m_2VHxk9_37P2WxPX37g7aeU-PBJfKH0ox9cfw6wa3ZTu0Jnf9-8ng-nc3OXpste_NkyJlo8uq3o-mbX49Of5m9mpxlnlwxfTw7zyHNLE7p-NGw_3xsv5x-Pn78cvI0m_0hOKdUJ_x59HU7_WuyBrZsrsuY2Fw42GJe8OTETFbgY7Ty6A53YC2Bq8w3PmezzKB2escpOYrL3FyjhEeed1BQHh4t0FKMZs5eHNhCsN0hJxLZx18RPwRkM8cMgt_wEThHZgGRp5gg5sMQQg7MFZS2ZYQV0IqdEPfUFFN62kuF4h0BDRMo202EFn2lRIGOPVbWi52rlFiDL4RJBvsWocwLqT8U8PxZg7589mhNWHjR1UPCgWov6_-gvAizNHMZmbY9HTZFpW7Yy-EH4190Pui9vD9oNZIauW7LPRVgceDWcDQrTNMRIxV4U0iz1f-N0yX4SIbKDXu-sBBBK2lnnbMrZBAcDawbtA-a2gIsodeWpVlR_JHQ1jImaGHL2q-fNfGTwdECBnI0GkjPecOiyhAqVZEbjEDGKQzTB2qCb8IsrsTsOWuzvnc-wL0Lh2KgSRf1p-xKJkNAmDUeq1D_kMKtsMIQhbWI1zLtbj-IanAG-nUT-Tz_lQy0gO50xg_s98O4DcuJ21c-C_kVYz4sRjpbyM8UR4AXLvEI2rNJoRrSr7SO7Cmz3ZLTxc7R5tReO66OFXidblB706yBjHIoZInZ3Fdyaq9N0Sh7x2kKeVA_7jj1pS84jyVDpSPkn8oweSspqev33JOcZDn6df8q-sjCM2GTkKxU5gdLqtM0VQi5xENa197JoR3r-sNWCZcmdsfhuo2sXeogYQJOa3DlKYVWliqxWIqCFLnr0L5R7wWwf-VAg3Xn8YHyGr_37VVuO7j2VNpmwrwsXapNbVJF1QpqtdqqeLV5fYKmGWYuy7ZzoAZOldmpcbiI7rR1ml9iGrHWrCfbV3l44ZZ6PHvn9_JiG6_Tim3d6zl4O8LTaTq4S_RFGYdPgPsD27TGHEYXL7wINGqj63BdlBL9q3LMtF-lDdkHDKdOk2gbNuyYfi-qMlQjtXetwm253w_ZrsOA6UFRne0pqumpt6TZ2AHUwaWqP61u-5ktE_ncCVVLEjf5e1Z_iLVfgP8B) Port of Kevin Cruijssen's 05AB1E answer. *-6 thanks to @CursorCoercer* *Fixed thanks to @Neil* [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 49 bytes ``` WS⊞υιFI⪪”)¶∨9⊘%ÀsF<¦J”²«≔⎇›ιLω⁻υωωθ≔⟦⟧ωFι⊞ω‽⁻θω⟦ω ``` [Try it online!](https://tio.run/##dVVNb@M2ED1Xv4LYkwy4gJ3uHoqeEu3acBEjRmzksIs9jCRGHoAiFZKyURf97e5QokjmYw@GQXI@3rx5M6qOoCsF4no9H1Fwlm9k19u91SibfDZju94c837OcPZX9qw0ywswNt93Am3@abH8Y7H48/NieXPzhf6/LJefl4vlpzm7mZHrv9lvt8ZgI/MD1xL0P/lac7Bc5zhn91w29pifZ7M526LsjUtyno2/F0o2@f746e7oPGRHj@g8Z48ga9Xmo/OLM5o5sx0ht/mP8086/He97kAJxe77ChW7lfDMjVXZlmrmgu4PvAEhEKTKHrRRbNMBPX9VLUqsekMoyavUqgGLJltxgRVnhdL0qgRkB65qcvBua1QnF4oVvANnkdyDlMhWUGqsECr11pNAAFtDL4bkfHDeKknoNDq4vcYLFUB2JWAScbp4KLngeijRcqk0V9ltI4cSd6AtJe3gMjj2xlJtDuWbBx9x8/p@h9xq4klDrRwqT9OvnD/23rCCejWwHOJh2QfSf@H13u1js/d2m6f3V4xycdJC9oQWSOjBwGNhW962afLJ/sFSn6aDf74DXZIAZNKulYBy6Hq8KpS01ECJ8WrPxSlAWIFArsNxQ4NQHZELoqXmAp5VsIiiIAtqdSDEgcBUM1oZl3AI6aqYHPa8pMEdGv8dnc@Dk8uW7rTqhhzfpHYhvrqxipWOxn@TZjtqG/LOvW1dVUm2R8rOnTFpL7sn@clLNPa@kYwglzep1iQyCtSE@N@VviTme6WBAmcr@qu4SbBSOyz9tzwNcitrWjfBxsecGI0jFBwiLiWeUYZCCi4MDjtDDbMPOgSPRXmeIyc0iTQxij0N3IT3vZvP7KDaFoxjsBpzx5pWylQUMtuBeemdLLaEeOxQoZG2F@3BkfqMthOBqRWrkeTc6TgUIa7HSSBqDbTVYpHBZCzMKZrSOpdGuR2RXoVEjpIaZChurbGFodghDR2txQnEvWM@7RYF8csXvP9B8xMaChitPF8T@bTOe@FEoEnqbThPKSY8gsIMEzRVlejdR/SEsoJU3kiYBDGVEGr8AOa4GgJ1d7wtVeDAI4oVfKD0TRBONPtGO/2VmrdKUIMK0CKNkcYdQ9xxbfvKfdCe3op5xw2k68LtxhDJk5RoNikxfhleIfJi3qM4cbcqQsqJ8YTy9DMwYU3aEOzGCh/7yyVBtXMywLgKxqZEKFOnR7X6IYnu72U9fvgfvZr6mr7NriKKKrPr7yfxPw "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a list of newline-terminated strings. Explanation: ``` WS⊞υι ``` Input the names. ``` FI⪪”)¶∨9⊘%ÀsF<¦J”²« ``` Loop over the values `01`, `30`, `09`, `40`, `12`, `25`, `09`, `45`, `11`, `41` and `01`, extracted from a compressed string split into pairs of digits. ``` ≔⎇›ιLω⁻υωωθ ``` If there are more names needed than exist in the previously randomised group, choose them from all of the names not in the previous group instead. (Note that the first time around `ω` is actually the predefined empty string; its length is still zero and vectorised subtracting it from the list has no effect, so the initial name is effectively selected from the entire list.) ``` ≔⟦⟧ωFι⊞ω‽⁻θω ``` Create a new group with the desired number of names randomly selected from the list without replacement. ``` ⟦ω ``` Output that group. (I have actually double-spaced the groups from each other to make the output easier to read at the cost of a byte.) [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `o`, 220 bits1, 27.5 [bytes](https://github.com/Vyxal/Vyncode/blob/main/README.md) ``` »ac±†ġq⟑»₆τ2ẇ(Þ℅nhẎ…?$FÞ℅ntẎ…)℅ ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=1#WyJvPSIsIiIsIsK7YWPCseKAoMShceKfkcK74oKGz4Qy4bqHKMOe4oSFbmjhuo7igKY/JEbDnuKEhW504bqO4oCmKeKEhSIsIiIsIltcIlBhb2xvIEx1Y2lvIEFuYWZlc3RvXCIsIFwiTWFyY2VsbG8gVGVnYWxsaWFub1wiLCBcIk9yc28gSXBhdG9cIiwgXCJEb21pbmljdXMgTGVvIEFicm9nYXRpc1wiLCBcIkZlbGljZSBDb3JuaWNvbGFcIiwgXCJUZW9kYXRvIElwYXRvXCIsIFwiR2lvdmlhbm8gQ2VwYW5pY28gSXBhdG9cIiwgXCJHaW92YW5uaSBGYWJyaWNpYWNvXCIsIFwiVGVvZGF0byBJcGF0b1wiLCBcIkdhbGxhIEdhdWxvXCIsIFwiRG9tZW5pY28gTW9uZWdhcmlvXCIsIFwiTWF1cml6aW8gR2FsYmFpb1wiLCBcIkdpb3Zhbm5pIEdhbGJhaW9cIiwgXCJPYmVsZXJpbyBBbnRlbm9yZW9cIiwgXCJBZ25lbGxvIFBhcnRpY2lwYXppb1wiLCBcIkdpdXN0aW5pYW5vIFBhcnRpY2lwYXppb1wiLCBcIkdpb3Zhbm5pIEkgUGFydGljaXBhemlvXCIsIFwiUGlldHJvIFRyYWRvbmljb1wiLCBcIk9yc28gSSBQYXJ0aWNpcGF6aW9cIiwgXCJHaW92YW5uaSBJSSBQYXJ0aWNpcGF6aW9cIiwgXCJQaWV0cm8gSSBDYW5kaWFub1wiLCBcIlBpZXRybyBUcmlidW5vXCIsIFwiT3JzbyBJSSBQYXJ0aWNpcGF6aW9cIiwgXCJQaWV0cm8gSUkgQ2FuZGlhbm9cIiwgXCJQaWV0cm8gUGFydGljaXBhemlvXCIsIFwiUGlldHJvIElJSSBDYW5kaWFub1wiLCBcIlBpZXRybyBJViBDYW5kaWFub1wiLCBcIlBpZXRybyBJIE9yc2VvbG9cIiwgXCJWaXRhbGUgQ2FuZGlhbm9cIiwgXCJUcmlidW5vIE1lbW1vXCIsIFwiUGlldHJvIElJIE9yc2VvbG9cIiwgXCJPdHRvIE9yc2VvbG9cIiwgXCJQaWV0cm8gQmFyYm9sYW5vXCIsIFwiRG9tZW5pY28gRmxhYmFuaWNvXCIsIFwiRG9tZW5pY28gQ29udGFyaW5pXCIsIFwiRG9tZW5pY28gU2Vsdm9cIiwgXCJWaXRhbGUgRmFsaWVyb1wiLCBcIlZpdGFsZSBJIE1pY2hpZWxcIiwgXCJPcmRlbGFmbyBGYWxpZXJvXCIsIFwiRG9tZW5pY28gTWljaGVsZVwiLCBcIlBpZXRybyBQb2xhbmlcIiwgXCJEb21lbmljbyBNb3Jvc2luaVwiLCBcIlZpdGFsIElJIE1pY2hlbGVcIiwgXCJTZWJhc3RpYW5vIFppYW5pXCIsIFwiT3JpbyBNYXN0cm9waWVyb1wiLCBcIkVucmljbyBEYW5kb2xvXCIsIFwiUGlldHJvIFppYW5pXCIsIFwiSmFjb3BvIFRpZXBvbG9cIiwgXCJNYXJpbm8gTW9yb3NpbmlcIiwgXCJSZW5pZXJvIFplbm9cIiwgXCJMb3JlbnpvIFRpZXBvbG9cIiwgXCJKYWNvcG8gQ29udGFyaW5pXCIsIFwiR2lvdmFubmkgRGFuZG9sb1wiLCBcIlBpZXRybyBHcmFkZW5pZ29cIiwgXCJNYXJpbm8gWm9yemlcIiwgXCJHaW92YW5uaSBTb3JhbnpvXCIsIFwiRnJhbmNlc2NvIERhbmRvbG9cIiwgXCJCYXJ0b2xvbWVvIEdyYWRlbmlnb1wiLCBcIkFuZHJlYSBEYW5kb2xvXCIsIFwiTWFyaW5vIEZhbGllcm9cIiwgXCJHaW92YW5uaSBHcmFkZW5pZ29cIiwgXCJHaW92YW5uaSBEb2xmaW5cIiwgXCJMb3JlbnpvIENlbHNpXCIsIFwiTWFyY28gQ29ybmFyb1wiLCBcIkFuZHJlYSBDb250YXJpbmlcIiwgXCJNaWNoZWxlIE1vcm9zaW5pXCIsIFwiQW50b25pbyBWZW5pZXJcIiwgXCJNaWNoZWxlIFN0ZW5vXCIsIFwiVG9tbWFzbyBNb2Nlbmlnb1wiLCBcIkZyYW5jZXNjbyBGb3NjYXJpXCIsIFwiUGFzcXVhbGUgTWFsaXBpZXJvXCIsIFwiQ3Jpc3RvZm9ybyBNb3JvXCIsIFwiTGVvbmFyZG8gZGkgQ2FwcmlvXCIsIFwiUGlldHJvIE1vY2VuaWdvXCIsIFwiQW5kcmVhIFZlbmRyYW1pblwiLCBcIkdpb3Zhbm5pIE1vY2VuaWdvXCIsIFwiTWFyY28gQmFyYmFyaWdvXCIsIFwiQWdvc3Rpbm8gQmFyYmFyaWdvXCIsIFwiTGVvbmFyZG8gTG9yZWRhblwiLCBcIkFudG9uaW8gR3JpbWFuaVwiLCBcIkFuZHJlYSBHcml0dGlcIiwgXCJQaWV0cm8gTGFuZG9cIiwgXCJGcmFuY2VzY28gRG9uYXRvXCIsIFwiTWFyY2FudG9uaW8gVHJldmlzYW5cIiwgXCJGcmFuY2VzY28gVmVuaWVyXCIsIFwiTG9yZW56byBQcml1bGlcIiwgXCJHaXJvbGFtbyBQcml1bGlcIiwgXCJQaWV0cm8gTG9yZWRhblwiLCBcIkFsdmlzZSBJIE1vY2VuaWdvXCIsIFwiU2ViYXN0aWFubyBWZW5pZXJcIiwgXCJQYXNxdWFsIENpY29nbmFcIiwgXCJNYXJpbm8gR3JpbWFuaVwiLCBcIkxlb25hcmRvIERvbmF0b1wiLCBcIk1hcmNhbnRvbmlvIE1lbW1vXCIsIFwiR2lvdmFubmkgQmVtYm9cIiwgXCJBbnRvbmlvIFByaXVsaVwiLCBcIkZyYW5jZXNjbyBDb250YXJpbmlcIiwgXCJHaW92YW5uaSBJIENvcm5hcm9cIiwgXCJGcmFuY2VzY28gRXJpenpvXCIsIFwiRnJhbmNlc2NvIE1vbGluXCIsIFwiQ2FybG8gQ29udGFyaW5pXCIsIFwiRnJhbmNlc2NvIENvcm5hcm9cIiwgXCJCZXJ0dWNjaW8gVmFsaWVyb1wiLCBcIkdpb3Zhbm5pIFBlc2Fyb1wiLCBcIkRvbWVuaWNvIElJIENvbnRhcmluaVwiLCBcIkFsdmlzZSBDb250YXJpbmlcIiwgXCJNYXJjYW50b25pbyBHaXVzdGluaWFuXCIsIFwiRnJhbmNlc2NvIE1vcm9zaW5pXCIsIFwiU2lsdmVzdHJvIFZhbGllcm9cIiwgXCJBbHZpc2UgSUkgTW9jZW5pZ29cIiwgXCJHaW92YW5uaSBJSSBDb3JuYXJvXCIsIFwiU2ViYXN0aWFubyBNb2Nlbmlnb1wiLCBcIkNhcmxvIFJ1enppbmlcIiwgXCJBbHZpc2UgUGlzYW5pXCIsIFwiUGlldHJvIEdyaW1hbmlcIiwgXCJGcmFuY2VzY28gTG9yZWRhblwiLCBcIk1hcmNvIEZvc2NhcmluaVwiLCBcIkFsdmlzZSBHaW92YW5uaSBNb2Nlbmlnb1wiLCBcIlBhb2xvIFJlbmllclwiLCBcIkx1ZG92aWNvIE1hbmluXCJdIl0=) Prints names in a list, except for the final doge. So wow. Much election. Such obvious joke. ## Explained (old) ``` »ac±†ġq⟑»₆τyZ(:Þ℅nhẎ…□$FÞ℅ntẎ…)℅ »ac±†ġq⟑»₆τ # The list ⟨ 1 | 30 | 9 | 40 | 12 | 25 | 9 | 45 | 11 | 41 ⟩ (26500992315347689 in base 64) yZ # uninterleaved and zipped (creates a list of [next_round, count_electors]) (the first choice - the youngest is technically a special case of next round picks) ( ) # for each pair n: :Þ℅ # push a random permutation of the top of the stack nhẎ… # take the first next_round names from that and print without popping □$F # remove these names from the list of potential electors Þ℅ntẎ… # take the first count_electors names from a random permutation of the remaining names, printing without popping ℅ # choose a random name from the last pick of 41 and print it with the o flag. This last name is the doge. ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 27? 28 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) 27 if we may write a function that produces a list of lists of names: ``` ¹©W;“ċ pr⁻Ṛṫ’ḃ45¤¹®ḟ$ƭẊḣɗ\Ḋ ``` [Try it online!](https://tio.run/##dVbNbiNFEH6VPiDlwpE9cUq868irWLHiKIhdONTMVEyverpMz0wkfNqfA9LyAAiExAEuq/05rhKQOBiExGPYL2KqZ3qmqxPnZldXffXVV1Xd8wyN@W63W9@s33zx@fb5L//8oJZu@@LPzc3Pm5u32@c/ba5fffZg/Ts7fNhc//rJv@83f7zeXP/2349fba5f7/7@/svty3fPti/@Wn9cf9ztnh7MgAypkybXpA4tXGJV08GnB1NwOacidY4LMEaD9dZTV5GaLKF1eUiltjpvKnWCHJs5WkCtKz4Zo9E5qhE5PicDbDpHKjhsCD7WdOVB1QiX4L2SE7BWqzFkTucactoXz6RAHUNjAhVsQaZkma/TXQmN0ysui30z0Al2NJ1maNC1xddoyaE3Hi5sW/wMXM0UlrAK4U1Vc82e952jgDy5fTLTWDvW0UFBnuMg4/0Q92FM1AhsEXox4OqsEc25N3Zf8H2u@3wnF/uMirMitU240DUYlE6Bm5piWaZUYtRpzV2Nf4PLEbiMB8cmzR0byCBIOBhHZGtuuNXSOEdzJSiNwWh0wjBRU51/o9G0shVo4JKEVxwn9uLxEIJ5UjqdOEdVl74F99XFsDlmwCPjB@aJ7iJP/bBN2epoGfI9ss5DPWTlEhX6kMe8A0tutcZldz71FSe5z5gN@hBsNTvhQbYrGRIwpFzDwN1JfMzDyoALkesJuVUSNCcHnMKvO//IsUoq4AbW/KvEFOzQFg5B@AX0qH1cUREWmZK51FYUOEJT6XBfUXvjgBOJZLmhK1I13nneSVIXrXrCZ153Op5TWULllc57LrHaMVU5g3vZoPq28YM15Tr6ro6c5rv0krO1KT1pJKZXkCo0r8nSyaUTGQJ3JlU4KNtyBwGEW1ey3xQm0QUuyN9PqXFI6iUrwIqyj50uIQjRpmRDXetI6sT3Ke0wgw0PBAScc4dXumqho@egad@qmdON6UbI8RqVwtKniwwNA7Z7GusVuzRgB@HViPdnYSEOVCxtqH8v9f5qGgQ@wjIjodHAMVa2d4cmYvii6yN@gW7tyJRM29IROJNiyQw91BG6usn943xxd0VmWEF6YfmbWyAGGZMtEMXH9@wWw2FB5tpcob@qRPq@N0lz5OMV2YuWCd@u8rNmtUpYzvwIaXkJ9S2M1OKEdNMfVlDC7FuV7iPnbJjIpuCvD18p49uDr/8H) --- ``` 45“ċ pr⁻Ṛṫ’ḃ¹³ḟ$ƭẊḣY;⁷ṄȧƲʋƒḟ ``` A full program that accepts a list of strings and prints the results with newline and double newline separators. **[Try it online!](https://tio.run/##dVaxbhtHEP2VLQyoSWlXqSRKFGiIECEKAmwjxdzdiFljb4feuxNgVjbsyu7SJQiQIkWKwI1dREo6wRAM/wX1I8zs3d7trER15OzMmzdvZnbvJRrzerN5/OT2ze9fP6qlu3373/rqt/XV37dvfl1fvru@uv6yvvzj0c2n9b8f1pd/Pvvx9u0/66v33/66@fz9480vfLbZbF7szIAMqaMm16R2LZxjVdPODztTcDlnIHWKCzBGg/XWY1eRmiyhddmnUludN5U6Qo7NHC2g1hWfjNHoHNWIHJ@TATadIhUcNgQfarrwoGqES/BeyQlYq9UYMqdzDTlti2dSoA6hMYEKtiBTsszX6a6ExukVl8W@GegEO5qOMzTo2uJrtOTQG3cXti1@Bq5mCktYhfCmqrlmz/veUUCe3D2Zaawd6@igIM9xkPFhiIcwJmoEtgi9GHB11ojmPBi7Lfgh122@k7NtRsVZkdomnOkaDEqnwE1NsSxTKjHquOauxr/BZQ9cxoNjk@aODWQQJByMI7I1N9xqaZyjuRCUxmA0OmGYqKnOf9ZoWtkKNHBOwiuOE3vxeAjBPCmdTpyjqkvfgvvqYtgcM@CR8QPzXHeRx37Ypmx1tAz5DqzzUPusXKJCH/KUd2DJrda47M6nvuIk9wmzQR@CrWZHPMh2JUMChpRrGLh7iQ95WBlwIXI9J7dKgubkgFP4decfOVZJBdzAmn@VmILt2sIhCL@AHrWPKyrCIlMy59qKAkdoKh3uK2pvHHAikSw3dEWqxjvPO0nqrFVP@MzrTsdTKkuovNJ5zyVWO6YqZ3AvG1SvGj9YU66j7@rIab5Lzzlbm9KTRmJ6BalC85osnVw6kSFwZ1KFg7ItdxBAuHUl@01hEl3ggvz9lBqHpF6yAqwo@9DpEoIQbUo21LWOpI58n9IOM9jwQEDAOXV4oasWOnoOmvatmjndmG6EHK9RKSx9usjQMGC7p7FesUsDdhBejXh/FhbiQMXShvq3Uu@vpkHgPSwzEhoNHGNlW3doIoYvuh7wC3RnR6Zk2paOwJkUS2boofbQ1U3uH@ez@ysywwrSC8vf3AIxyJhsgSg@vmd3GA4LMtfmAv1VJdL3vUmaIx@vyF60TPh2lZ80q1XCcuZHSMtLqG9hpBYnpJv@sIISZtuqdB85J8NENgV/ffhKGd/u/PQ/ "Jelly – Try It Online")** ### How? ``` 45“ċ pr⁻Ṛṫ’ḃ¹³ḟ$ƭẊḣY;⁷ṄȧƲʋƒḟ - Main Link: list of strings, Councilors “ċ pr⁻Ṛṫ’ - base 250 integer = 56917435399420996 45 ḃ - bijective base 45 -> [1,30,9,40,12,25,9,45,11,41,1] ƒ - starting with current=Councilors reduce that by: ʋ - last four links as a dyad - f(current, n): ƭ - alternate between: ¹ - a) no-op -> current $ - b) last two links as a monad - f(current): ³ - program input -> Councilors (i.e. "all") ḟ - filter discard (current) -> all except current Ẋ - shuffle } ḣ - head to index (n) } choose n of them Ʋ - last four links as a monad - f(chosen) Y - join with newlines ;⁷ - concatenate a newline Ṅ - print that plus a newline, and yield the result ȧ - logical AND (chosen) -> chosen ḟ - filter discard all -- avoids printing the Doge again ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 131 bytes Returns an array of string arrays. Contains unprintable characters. ``` a=>[...Buffer(" (  - )")].map(n=>p=[...Array(n)].map(g=_=>p.includes(s=a[Math.random()*a.length|0])+n/25&!g[s]?g[s]=s:g()),p=a) ``` [Try it online!](https://tio.run/##dVVNb9w2EEWOUfsHeilUHxqpbdSgQC8FNoW9yRpbWPDCa/gQ1yhmpVmZBcVRSGmBLPrf3aFEkfRHLrvQcObNzJvH4b9wAFNp0fVvFdX4sF88wOL9bVEUZ8N@jzo7efX96@zb716//SZ/dZLfFS10mVq87xbW51Rr@JIpZ24W//BBIVQlhxpNZhZwW0J/X2hQNbVZ/hMUElXT3//37i7/Wf362@8//tDcmrs/7c/C/NFkef5Lt4D8oSJlSGIhqcn2mcbPg9CYvdmbN3mhEeqVkLj9oqrsXV70tO21UBxcmE6KPjv5W53kef6wAZKUXgyVoPRUwR5NT0kJukLJ9mtsQEoBipJLbShdd8DHH6gVSlSDSS@Qo3aaGuiFSVYoRYXpkjSfkoTkGqnmABd2LuhgodIldmA9IjsoJdIV7LSoBFT0NJKLgPQcBjkmxzG4JMXVaWHLHbQ4cgPstwMRIc6Gyx1K1GOLPSrSSMlpo8YWN6B7TtrBcQwcTM@92SqfHDjE9WP7RmCvmScNNdmqHE1fC345ep0uefgjyx5P7AZP@leinoe97Pbcb33z3JRyLmQtJDeiB4nBwdWSlti2cfLZ/7LnOc0f7vgM9I4FoKJxrSTsxqkH05JUzwNUIpi2KA@@hBVIgdp/rtNSVPcCJdNSo4Q9eY8gCvbgUXtCbBEi1owmYxOOkLaLOWCLO@DR28F/Ejbm0sqlZJumbszxUWkL8cHe09Dp5PwXa7bjsQns7Flpu4qyXXF2tM6sveSC5aeOwdnFBjK8XJ6kOmeRMVDj8T@RPkbuW@IdcqRkxX8VmqhWHkfP/y3GIKeq5i3hfRzmzGi4Qj4g1EVyL5RvZInSiHFn0Hj3QXvw0JTjOXDCN5FvDKU3Izf@fGvvZ3JNbQvGMlhNuUNPKzIVQyYbMJ8HK4uSK54mtNSCt9eeM4xpEt5OXExNaS1Yzp0Ol8Ljujq5iFoDb7XQpHeZGrOK5rQ2pCG7I2KTT2QpqUH55s61aGFsdkzDn30v5iIuLPPxtBjELV9w8dcaD8IwYPByfM3kb7QYpBWBZqm3/ntOMdcjGWa8QXNXkd4doiM0XbLKGwWzIOYWfI8vlDmtBk/dGbY78hy4ikIHLyh97YUT3D7yTn@k5pIkD2gJWsYYMe4EcYa6Hyr7oN08FfMGDcTrwu5Gj@RIijQbtRhehkcVOTFvhTygXRU@5cx4RHn8DMy1RmPwflOHV8PxGFW1sTIQYRVMQwmlzJOe1OouSQh/Luvp4b9yahpqfpttR4yq/gc "JavaScript (Node.js) – Try It Online") ### Commented ``` a => // a[] = input array [...Buffer("...")] // list of group sizes .map(n => // for each size n: p = // update p[] to [...Array(n)] // an array of size n where each entry is .map(g = _ => // the result of the recursive function g: p.includes( // test whether p[] includes: s = // the string s a[ // picked from a[] Math.random() // at a random location * a.length // (with uniform distribution) | 0 // ] // we invert the parity of the result if ... ) + n / 25 // ... the group size is ≥ 25 & !g[s] // make sure that s was not already selected ? // if this is a valid selection: g[s] = s // return s and mark it as selected : // else: g() // try again ), // end of inner map() p = a // start with p[] = a[] ) // end of outer map() ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 113 bytes ``` x:=#1~RandomChoice~#2& c:=l~Complement~% l~x~1 l~x~30 %~x~9 c~x~40 %~x~12 c~x~25 %~x~9 c~x~45 %~x~11 c~x~41 %~x~1 ``` Now, unfortunately, *Try It Online* does not have the same implementation of the Mathematica Global Loop as a Mathematica notebook does, so the built-in `%` operator, which yields the output of the previous line, does not work. But, you can [download the Mathematica notebook online.](https://www.wolframcloud.com/obj/d8570527-38c2-41e3-bafc-e7ccba853e41) [Answer] # [Pyth](https://github.com/isaacg1/pyth), 33 bytes ``` Ou <.S-Q <.SGhHeHc5jC"m£*’OŸ"46Q ``` [Try it online!](https://tio.run/##fVbBctNADD1x4Ss8OTLACThxad0mDdNMQtPJoQwH2VZTMevdsLY7Qz6DH@DAn/THgtZee7Wuy6WTaqWnpydp14df9cPptG5ef36/fffV/V08XOFV/vFHOntVPv198/R7/fRn9uHT19Pp22wDRpnkusnJJGca7rGqzextMluBzVHx0S3uQSkC3ZrXtjLJ8gCd04UpSVPeVMk1cnhmzR5qqtzRHBXlmKTGsoNR4Gy3aAqODPELMo8OOUnxAM4vPgKtKZlDZiknyM00BJODZAGN6hlhC7Qymolb8sU0lo5cIXtnQHECYVtnqNC2StSojcXWerbXrRIbsDUzOcCxR2iqmut3BTw/8@jLZ0cbwtqyrhYK46gGWf@D8iLMMklBF317BmzKGtmwl8Mn4190nvRe7iatCadG07VlRzUojNw8x2SFZTliJALXNTdb/O@dzsFmPFQ67vlcQQa9pIM1NbrmQdAUWbeoHiW1OShCKy3LZEX5A6HqZCxQwb2RfmHW2I8HRwroyNFoIK2pPIs2g6tURG4xAx4nN0x35IPXbhZXbLbm0Ge91NbBXbCUsSZD1BfelQMPAeHBe6xc/TGFG2aFLgo7Ea952vUxivI4kX7DRD7Pv@CBZtC9zHhn7DGO2xoLnKe9IvhXjlVcDHe25p8ljgDPdGERpKdPIRoSVlpGBspG3ZOWxaaoKupvO9NeVmBluqh236xIRr4oeIlNsmvllF7b2it7a8oSKqd@PnAKpc9NlXOGVkeofjZu8lZc0tDv1BJfyfecs03c0kfDPAuTFMQrdbDRkso0vgomV1gou9oHOaRjV7/bKubiY/fG3W4j65DaSViAlhosLJXQy9ImZktdkyB37do36j0DhicHPNatxUeqOvzgG1TuO7ix1Cg/YZaXrpSmPqmgqhi1XW1RvNi8kMA3I0l52fYaxMCJMgc1posYrrZB83MsMyM1C2RDldMLt5TjGZwv@WEbr9PKqK7XKVg1wpNpBrhztHWTu0@A3cQ2bbCC0Y3nHgKJ6nWN10UoEZ7KMdOwSltSj@iuOkmib1jcMfkuijJEI6V3p8JNczzGbDduwCi6wYbOBopierot8RsbQU0uVfdpdRNmtin4c8dVzUn07Ps/ "Pyth – Try It Online") ### Explanation ``` # implicitly assign Q = eval(input()) C"..." # convert string to int using base 256 and codepoints, gives us 1527922444881823 j 46 # convert int to list of ints using base 46, gives us [1, 30, 9, 40, 12, 25, 9, 45, 11, 41] c5 # chop into five pieces of equal size u Q # reduce this list on lambda GH, starting with Q .SG # shuffle G < hH # first n elements of, where n is the first value in the pair H # print this -Q # complement in Q .S # shuffle < eH # first n elements of, where n is the second value in the pair H # print this O # print a random element of the result ``` [Answer] # Desmos, 306 bytes Desmos doesn't have strings, so I hope this answer's valid! (Also, I only pasted half the people into it, but copying and pasting was DRIVING ME INSANE, so I just did half.) ``` C=[1...L] Y=floor(Lrandom()) A=s(C,30,Y) B=s(A,9,0) D=r(40,B) E=s(D,9,0) F=r(25,e) G=s(F,9,0) H=r(45,G) I=s(H,11,0) J=r(41,I) l(n,a)=shuffle(a)[[1...n]] r(b,c)=l(b,C[[max({C[i]=c,0})fori=[1...L]]=0]) s(a,b,c)=l(b,a[{a<c,0}+{a>c,0}>0]) Z=[0,0,0] R=join(Y,Z,A,Z,B,Z,C,Z,D,Z,E,Z,F,Z,G,Z,H,Z,I,Z,J,Z,l(1,J)[1]) ``` (Pasting it in will not work, as `[` is not defined normally without typing.) The [graph](https://www.desmos.com/calculator/51tfdlckru) contains some extra interface formatting. I only counted the stuff outside the Interface folder, as Desmos doesn't have strings and I felt that it was fair. `l` returns `n` random elements from the list `a`. `s` is designed to remove an element of value `c` if it exists (for the first case), and `r` removes elements in a list. Then, both `c` and `r` return `b` random elements. [![Randomization](https://i.stack.imgur.com/reO7j.png)](https://i.stack.imgur.com/reO7j.png) Click the button to the right of the plus sign to randomize it again. [Answer] # [R](https://www.r-project.org), 88 bytes *Edit: +6 bytes and change of approach to fix bug in previous version (below)* ``` \(m){g=o=seq(m);for(i in utf8ToInt("!>)H,9)M+I!")-32)show(m[g<-sample(o[g*-(T=-T)],i)])} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=dVbBbttGED2nl_wCo5PYWpfmkiJVAVuJXAUmLFiCUSTNYUiOmAGWO8qSdAAV_ZJenEOQb2q_prPkirtryydRszNv3ryZWfKfr-b-v2fP63kxnayBFSdXXUGcnGvYYdPy5GySgSlQyckWK1CKQFvrtWk4We2hd3nDNWkquia5QonNDVfQUiMnS1RUYLJgI-esQExb5FLCxuBL4jsLmixwD9YrOgGtKVlCbqggKPhUvJCC5BI65ahgD5KxFr6GhhI6QwcpS3xzoAjbm65zVGj64lvUbNAazyvdF78G0wqFPRxceNe0UrPl_ejIIa8enqwJWyM6GijZchxlfBriKYxVsgBdul6MuJR3QXOejD0V_JTrKd_V7SljIlmR-ybcUgsKQyfHLcmwrmMqPuq6la76v87lAkwug6Oj5i4V5OAkHI0L1q00XFNo3KC6CygtQRGawLBKMio-EapethIV7Djw8uMkXjIegWCWFMUTZ7gZ0vfgtjoftsEcZGTswLynIfLaDlsmVsN7l--tNhbqjSgXqXAMeSc7sJdWE-6H88xWHOW-ETZoQ7DX7EoGWR_CEIcRyjUO3KPElzKsAlgFud6zOURBGzYgKey6y0OBTVSBNLCVpxpjsHNdGoTAz6F77f2KBmGeKasd6aDABaqG3H3F_Y0DJkgUluu6EqomOy87ycltr17gs2kHHbdc19BYpYsjF1_tkptCwK1s0Hzu7GBlUsexqwtDcpfuJFuf0pJGFnolJyXJmuxNuHRBBsddSJUG6r7cUYDAbSjZboqQGAIrtvdTbByTWslK0EHZl4ZqcEL0KcXQtuRJXdk-xR0WsPEFAQ5na_COmh7ae46aHlu1NtSpYYSMrFEdWI7pPEMlgP2e-nqDXRqxnfDJQvan0uAHypc21n-S-vFqGgW-wDrnQKORo6_s5A6tguHzrm_lDfRgRzJWfUsXYFSMFWY4Ql2gabvCvpxvH6_IGhuILyx7cweITsZoC4Li_fvsAcNxQTak7tBeVUH6Y2-i5oQvL88-aFngO1R-0x0OEcu1HaFgGnwLPTU_IcP0uxUMYU6tyvCRczNOZFfK14etVPD1JP2h5Arn37p2N3v17x9_Tuv0r2rO8wY_y-Nr2eApJaQTOX-15ZVup5MXv6W_n_2SZj-tXkzS2cuf0-YTf5nWH6pfZw3Ue4VT_lD9OJtu57Nt-vGM0o_p3wP-d5tLYId_9_fD7_8) Function that prints a vector of names for each step of the algorithm; outputted vectors are separated by newlines. --- Previous approach (now fixed at a cost of +7 bytes): # [R](https://www.r-project.org), 89 bytes ``` \(m){s=1;g=o=seq(m);Map(\(i)m[g<<-sample(o[g*-(s<<--s)],i)],utf8ToInt("!>)H,9)M+I!")-32)} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=dVbBbttGED2nl_wCo5PUWoc2lwSJCthK5CowYcESDDRJD0NyxA6w3GF2SR9U9Et6cQ9Bv6n5msySK-7Slg-CxNmZN2_ezCz1z7_m_tuz59Uin042wIqTqzYnTs417NE2PDmbpGByVHKywxKUItDOem0sJ-saOpd3XJGmvLXJFUpsZriEhqycrFBRjsmSjZyzAjHtkAsJG4Ivie8caLLEGpzX6AS0pmQFmaGcIOdT8UIKkktolaeCHUjKWvga6ktoDR2kLPHNgEbYwXSdoULTFd-gZoPOeF7qrvgNmEYo1HDw4a1tpGbH-9GRR14_PNkQNkZ0NFCw4zjI-DTEUxjrZAm68L0YcClro-Y8GXsq-CnXU77r21PGRLIid024pQYUxk6eW5JiVY2phKjrRroaHr3LBZhMBkePmrtSkIGXcDAuWTfScE2xcYvqLqK0AkVoIsM6SSn_k1B1shWoYM-RVxgn8ZLxiARzpGg8cYZtn74Dd9WFsC1mICPjBuYj9ZHXbthSsRqufb732jiod6LcSIVjyAfZgVpaTVj356mreJT7RtigC8FOsysZZH2IQzxGLNcwcI8SX8qwCmAZ5frI5jAK2rIBSeHWXX7kaEcVSAMb-VXhGOxcFwYh8vPoQfuwolFYYMpqTzoqcInKkr-vuLtxwESJ4nJ9V2LVZOdlJzm57dSLfLZNr-OOqwqsUzo_cgnVrtjmAu5kA_uldYOVSh3Hri4NyV26l2xdSkcaWegVnBQka1KbeOmiDJ67kCoMVF25gwCRW1-y2xQh0QeW7O6nsXFI6iQrQEdlXxqqwAvRpRRD01AgdeX6NO6wgA0vCPA4O4N3ZDvo4DloemzVxlCr-hEyskZVZDmmCwyVAHZ7GuqNdmnA9sInS9mfUkMYqFDaUP9J6seraRD4AquMI40GjqGykzu0joYvuL6XN9CDHUlZdS1dglFjrDjDEeoCTdPm7uV8-3hFNmhhfGG5mztC9DKOtiAqPrzPHjAcFmRL6g7dVRWlP_Zm1Jz45RXYRy2LfPvKb9rDYcRy40YomobQwkAtTEg__X4FY5hTq9L_ybkZJrIt5N-Hq1Tw9WT2Q8ElLr62zX7-6v_fP0-r2V928fObcsELi1_k8U0K9fTzlGbVp_Lt27mFqlY45U_lj_OpFcPczv44I_kIxKsdr3Uznbz4dfbb2etZ-tP6xWQ2f_nL7O8-wX8umWD2T_f3_fd3) Function that returns a list with each element containing a vector of the names from one step of the algorithm. ]
[Question] [ The purpose of this challenge is to solve the original [first Project Euler problem](https://projecteuler.net/problem=1), but as the title suggests in [constant time](https://en.wikipedia.org/wiki/Time_complexity#Constant_time) (with respect to the size of the interval). > > Find the sum of all the multiples from a list of numbers in some defined range, in such a way that the running time of your program runs in constant time [\$\mathcal{O}(1)\$] with respect to the size of the range > > > Let us step through the problem statement with an handful of small examples. --- **Example 1:** Let `[3,5]` be our list of numbers, and let our range be `[1, 999]` meaning every natural number starting with `1` up to and including `999`. To do this in linear time we can do as follows. The multiples of 3 and 5 are $$ \begin{align\*} 3 + 6 + 9 + 12 + \color{red}{15}+18+\cdots+999=3(1+2+3+\cdots+333)=3\,T\_{333}\\ 5 + 10 + \color{red}{15} + 20 + \cdots+995=5(1+2+3+\cdots+199)=5\,T\_{199} \end{align\*} $$ Where \$T\_{333}\$ is the 333rd triangular number. \$T\_n=n(n+1)/2\$. However, simply adding \$3T\_{333}\$ and \$5T\_{199}\$, makes us *over count*. We will then count every number that is both a multiple of `3` and `5` (15, 30, 45...) twice. Thus, our final answer, *in constant time with respect to the input range* is $$3T\_{333} + 5T\_{199}-15 T\_{66}$$ Where \$66\$ was chosen because it is the largest value such that \$66\cdot15<999\$. --- **Example 2:** Let `[6,9]` be our list of numbers, we might suspect that our answer will be $$\text{Multiples of } 6 + \text{Multiples of } 9 - \text{Multiples of } 6 \cdot 9=54 $$ However this is leads to an error, as the first number counted in the multiples of \$6\$ and \$9\$ is \$18\$ *not* \$54\$. So $$\text{Multiples of } 6 + \text{Multiples of } 9 - \text{Multiples of } 18 $$ gives the correct answer. Where, for instance, we could have done \$\text{lcm}(6,9)=6\cdot9/\text{gcd}(6,9)=18\$. --- **Example 3:** Let `[3,5,7]` be our list of multiples, were we again is dropping the range for the sake of brevity. The easiest is now to use the [inclusion-exclusion principle](https://en.wikipedia.org/wiki/Inclusion%E2%80%93exclusion_principle). [![enter image description here](https://i.stack.imgur.com/XhkEv.png)](https://i.stack.imgur.com/XhkEv.png) So our answer will be $$ \begin{align} &\text{Multiples of } 3 + \text{Multiples of } 5 + \text{Multiples of } 7 \\ - &\text{Multiples of lcm} (3,5) - \text{Multiples of lcm} (3, 7) - \text{Multiples of lcm} (5, 7) \\ + & \text{Multiples of lcm} (3, 5, 7) \end{align} $$ --- **Input** A list of multiples (or divisors if you will), and a range. You may take input in any [convenient method](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) **Output** A single number/string/float ( representing the sum of every number divisible by at least one of the numbers in `multiples=[3,5,...]` in range `[start, stop]`) --- **Restrictions and assumptions** * **You *only* have to make sure your program runs in constant time with respect to the size of the range we are working over** How, you choose the handle the multiples/divisors is up to you * The range is always assumed to be non-empty, with inclusive endpoints. Meaning `[10, 10]` contains `10`. * We are working over the integers meaning every multiple and range will be whole non-negative numbers. --- **Test cases** Our test cases will be on the form `list of multiples`, `range`, `sum`. ``` [7] [1000, 1000] 0 [3, 5] [1000, 1000] 1000 [3, 5] [ 1, 999] 233168 [3, 5, 7] [ 300, 600] 73558 [9,10] [ 1, 999] 99504 [6, 9] [ 1, 999] 111390 [6, 9, 10, 5, 5, 9] [ 1234, 4321] 3240486 [3, 5] [10**7, 10**8] 2310000085000000 ``` You may use the following code below to test your implementation, note that the implementation below does *not* run in constant time with respect to the input ``` def naive(multiples, start, stop): total = 0 for num in range(start, stop + 1): for m in multiples: if num % m == 0: total += num break return total ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest code wins! [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 20 bytes ``` +Ø.÷€AĊc2ḋIɓN;æl¥ƒ-Ḋ ``` [Try it online!](https://tio.run/##y0rNyan8/1/78Ay9w9sfNa1xPNKVbPRwR7fnycl@1oeX5RxaemyS7sMdXf8PL9cHSv//Hx0dbWhkbKKjYGJsZBiroxBtpqNgqaNgaKCjYApGlrGxOlwKQFUGEACSgwKQcmOgotjYWAA "Jelly – Try It Online") Port of [my own APL answer](https://codegolf.stackexchange.com/a/230991/78410). Trailing `ɓ` chain trick is indeed strong :P ### How it works ``` +Ø.÷€AĊc2ḋIɓN;æl¥ƒ-Ḋ Dyadic link; left=range, right=divisors xxxxxxxxxxxɓyyyyyyyy x(left, y(right, left)) N;æl¥ƒ-Ḋ y: subset LCMs, negative for even-sized ones N Negate the divisors ƒ- Starting with -1, reduce by ;æl¥ current list ++ LCM(current list, next num) Ḋ Remove the leading -1 +Ø.÷€AĊc2ḋI x: range(start, end), subset LCMs -> answer +Ø. Add 1 to the end ÷€AĊ Divide each by subset LCMs, abs, ceil c2 nC2 of each ḋ Dot product of each row with subset LCMs I Increments (2nd - 1st) ``` [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 31 bytes ``` -/+/(⎕+⍳2)(⊢×2!⌈⍤|⍤÷)\∊(⊢,∧)\-⎕ ``` [Try it online!](https://tio.run/##jZG9TsMwEMd3P8WxNamt@iNO4sEPwMQDpB0qNWGpKAMDCFhRVRHEgtgREg@AEBJr38QvEnxxQEmrSo0Uf/39u/v7bn65ZIub@XJ1zsrrq/JiUS4a9/RyeuYenjmp/HjbsMl4MnL1z9jVnzIauc3b9lWeuMe1q9/v/L/9jqZuvUGBuvVHNGWu/mruG8E5h3aoICP9nQJNBBhjurXyp@mfgnc7zXjgf5OCIUKqBBIlRdh72d/XKJQZiDLv4jHGCLf7@e2uCamUSHPb95IprXO768gYzRM79CWEMtz27SmZ8CRP7UGbUmFyznPdTp4e@CYkWlUVKbIZ7H0FktQvcN7TOSkUBT07HsKTAxCqCOHL@mKoVoAoDE0WoEImLNtAaQtKCkMFPzoTtPUmRUrBHA2FhgSI@ve1LnWIUAD2xFPYlR7Udexg9eI4w1BxnM9gt3nwCw "APL (Dyalog Extended) – Try It Online") Full program which takes the list of divisors, and then the `(start,end)` pair. Uses a modified [trick to generate all nonempty subsequences](https://codegolf.stackexchange.com/a/211449/78410). Also abuses the definition of LCM which is `LCM(a,b) = a * b / GCD(a,b)` and GCD is always positive, so LCM follows the sign of `a * b`. ### How it works ``` -/+/(⎕+⍳2)(⊢×2!⌈⍤|⍤÷)\∊(⊢,∧)\-⎕ Input 1: divisors; input 2: range (start,end) ∊(⊢,∧)\-⎕ LCMs of all nonempty subsets of divisors, negative if the subset has odd size (⎕+⍳2) Add 1 to the right end of the range ( )\ Outer product: ⌈⍤|⍤÷ ceil(abs(left ÷ right)) ⊢×2! nC2 to each of above, times right For each pair of (a,b), this evaluates the sum of numbers in [1..a] divisible by b, following sign of b -/+/ Sum of 1st row - sum of 2nd row (each value was negated because odd subsets should be added, not subtracted; the difference order fixes the negation) ``` [Answer] # [Python 3](https://docs.python.org/3/), 229 bytes ``` lambda d,s,e:sum(-(-1)**len(k)*(t(e//l(*k))-t(~-s//l(*k)))*l(*k)for k in p(d)[1:]) t=lambda x:x*-~x//2 p=lambda k:k and[j+a for j in[[],k[:1]]for a in p(k[1:])]or[[]] l=lambda a,*b:b and a*l(*b)//math.gcd(a,l(*b))or a import math ``` [Try it online!](https://tio.run/##hY7LbsMgEEX3/opZMhSKH3nUSPkSygLXduPgl2wquZv8umucuFKrVN0Acy/naPpPd@7aZC5Pr3Ntmiw3kLORFXL8aAgnPEJK66IlFilxpBCiJtQickeufNwmpOtddgNYqFroSY4qkhoDd7pLJzlRfp2EiIN@y6y0YNpcXZ4MePaysEppZpWMtPaJudnsKtPdsLQ6qDfeMJrJzCvA@A0yFKIx7vz8/pYTw9YEvSWomr4bHPhy7oeqdaQk6qgZRGEY3k7E4LtJGOz/LRmkafq7YOCtiecOP7HUmx5yhyX5s/DU6t3ff8XJjsEuiaOHCwOlcNweL4jzFw "Python 3 – Try It Online") -5 bytes thanks to ovs There's probably a less direct approach. I haven't properly golfed in Python in too long. [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal) `s`, 32 bytes ``` $ṗḢƛ:λ₌*ġḭ;R:¹‹÷›"$ḭ:›*2ḭ¯unLe** ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=s&code=%24%E1%B9%97%E1%B8%A2%C6%9B%3A%CE%BB%E2%82%8C*%C4%A1%E1%B8%AD%3BR%3A%C2%B9%E2%80%B9%C3%B7%E2%80%BA%22%24%E1%B8%AD%3A%E2%80%BA*2%E1%B8%AD%C2%AFunLe**&inputs=%5B300%2C%20600%5D%0A%5B3%2C%205%2C%207%5D&header=&footer=) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 25 bytes ``` æ¦ε.¿DIāÉ-s÷D>*2÷Æ®ygmP}O ``` [Try it online!](https://tio.run/##yy9OTMpM/f//8LJDy85t1Tu038XzSOPhTt3iw9td7LSMDm8/3HZoXWV6bkCt////0cY6prFc0YYGEKCjAGMZxAIA "05AB1E – Try It Online") ``` æ¦ε } # map over each non-empty subset of the divisors .¿D # take the LCM of the subset IāÉ- # push the range with the lower bound decreased s÷ # integer divide modified range by LCM D>*2÷ # for both resulting integers, compute the nth triangular number Æ # reduce by subtraction (results in negative values) ®ygm* # multiply with LCM and (-1)**len(subset) O # sum the resulting list ``` [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal), 37 bytes ``` $ṗḢƛ:λ₌*ġḭ;R:¹÷$‹$"$ḭ:²+½$*÷-$Lu$e*;∑ ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%24%E1%B9%97%E1%B8%A2%C6%9B%3A%CE%BB%E2%82%8C*%C4%A1%E1%B8%AD%3BR%3A%C2%B9%C3%B7%24%E2%80%B9%24%22%24%E1%B8%AD%3A%C2%B2%2B%C2%BD%24*%C3%B7-%24Lu%24e*%3B%E2%88%91&inputs=%5B300%2C%20600%5D%0A%5B3%2C%205%2C%207%5D&header=&footer=) This is extremely messy. In case it wasn't clear, I am terrible with stack-based languages. [Answer] # [J](http://jsoftware.com/), 72 69 bytes ``` 1#.(_1*_1^1#.g)*(_1 0+[)(]*[:-~/(2!>:)@<.@%/)]*./@#~g=.1}.2#:@i.@^#@] ``` [Try it online!](https://tio.run/##VY6xbsIwEIZ3nuJoVBGnxbnz2UlsNcgSEhNTVxQYKqDt0rVLefX0EhMpDGf7/Pn/fN/9k15doA2wgldACFJrDdv3/a6nTOcnKk50lNNVFdIAvhxU3hWHsL6VuVlugopvOj6Xqit0GbPbtdX0p00W4peOxyx2vVqcPz5/RNsCIWJaLlCn67F7JAwuMcNMVTNQ8N7PSc3ODYAlUE2hSem9QztLeRHfPyNijzNUgU@EjUXbVAMybMGyoYQlK2Y3vTM8DInYuHEbXedaqkkz/Pb/ "J – Try It Online") -3 thanks to nC2 trick from Bubbler's answer There's some more golf's I believe I can port from Bubbler's APL answer. Will try tomorrow. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~30~~ 29 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) -1 thanks to [caird coinheringaahing](https://codegolf.stackexchange.com/users/66833/caird-coinheringaahing)! ``` ’1¦:בHIƲḢ×ʋⱮⱮœcⱮJæl/€€Ɗ}§Ṛḅ- ``` **[Try it online!](https://tio.run/##y0rNyan8///hjkWPGmZaH@uyOjz9UcMMD89jm4BCh6ef6n60cR0QHZ2cDCS9Di/L0X/UtAaIjnXVHlr@cOeshztadf///x9taKClZa6jAKIsYv9HG@somMYCAA "Jelly – Try It Online")** ### How? ``` ’1¦:בHIƲḢ×ʋⱮⱮœcⱮJæl/€€Ɗ}§Ṛḅ- - Link: [start, stop]; divisors 1¦ - apply to index 1 (of [start, stop]): ’ - decrement -> [start-1, stop] } - using right (divisors): Ɗ - last three links as a monad - f(divisors): J - range of length -> [1,2,...,#divisors] Ɱ - map with (for n in that): œc - all ways to choose n of the divisors € - for each (list of choices of length n): € - for each (way to choose): / - reduce by: æl - least common multiple Ɱ - map across (for each list of LCMs): Ɱ - map across (for each LCM): ʋ - last four links as a dyad - f([start-1, stop],LCM): : - integer divide -> [(start-1)//LCM, stop//LCM] call this "[A,B]" Ʋ - last four links as a monad - f([A,B]): ‘ - increment -> [A+1,B+1] × - multiply -> [A(A+1),B(B+1)] H - halve -> [A(A+1)/2,B(B+1)/2] I - differences -> [B(B+1)/2-A(A+1)/2] Ḣ - head -> B(B+1)/2-A(A+1)/2 × - multiply -> LCM(B(B+1)/2-A(A+1)/2) § - sums -> [sum of single-choices, sum of two-choices, ...] Ṛ - reverse ḅ- - convert from base -1 -> 1×(sum of single-choices)+-1×(sum of two-choices)+... ``` --- With fewer loops using the same approach, also 30 bytes: ``` Ḣ’;Ɗ:בHIƲḢ×ʋæl/}¥ⱮⱮœcⱮJ$}§Ṛḅ- ``` --- With no constraint on computational complexity, 7 bytes (-1 thanks to caird again!): ``` r/ọẸ¥ƇS ``` [Answer] # [Python 3](https://docs.python.org/3/), 146 bytes ``` lambda d,s,e:(e*e+e-s*s+s+g(d,e)-g(d,s-1))//2 g=lambda d,n,m=1:g(d[1:],n,m)-g(d[1:],n,m*d[0]//math.gcd(m,d[0]))if d else~n//m*(n//m)*m import math ``` [Try it online!](https://tio.run/##hY5JjoMwEEX3nKKWLlMEjDOBxEkIC7ptCFJMUMwmm1ydUJmkRGn1pqb3/1cN53F/7PXUFLvpULsfU4MhTzYXVtrQRl760IetMGQx4uYjhRjHadAWL31PrlD5TEuVV7zdpM9FmjKp4tjV437R/hrhiA@IXQMG7MHbSz9TKbiidEHnhuNpBNZPw6nrR9GIclMRqCRJ7hUxeBFNsPoXEmRZ9gkIOFWzb/1uyzjpq289X/4E7Lrlrh6qVC8JljpVXx8GKWHzHLaI0xU "Python 3 – Try It Online") Some tricks explained: `~n//m` is a shorter way to write `-(n//m+1)`, and `e*e+e-s*s+s` is twice the sum of integers in the interval. --- ## Python 3.9, 138 bytes ``` lambda d,s,e:(e*e+e-s*s+s+g(d,e)-g(d,s-1))//2 g=lambda d,n,m=1:g(d[1:],n,m)-g(d[1:],n,math.lcm(m,d[0]))if d else~n//m*(n//m)*m import math ``` Uses the new `math.lcm` in Python 3.9. No TIO link because Python 3.9 is not available there yet. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 41 bytes ``` ≔ΠθεIΣEEε⁺×÷⁻⟦⊖ηζ⟧ιεει∧⊙θ¬﹪κλ÷×↨ι±¹⁺Σιε⊗ε ``` [Try it online!](https://tio.run/##RU49C4MwEN37KzJeIAWldHKydelgEdpNHFI9NDQm1USh/fPpqYMP7riPx3uv7uRYW6lDSJ1TrYFitM1Uexi4YMiTQzEq4@EqnYfH1EMuP2uhYIWeHDxVjw5uxmdqVg1CrgxdywzrEXs0HhvoSOlXCaZWxa2WOTUNpOYLg2B36yEnX23hLZjmnN675uZxkQ5BERdb6RHihbNGWGJt2tQyO700mdKyIAmhLE@Cnck/jjbsU1SF46z/ "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ≔Πθε ``` Calculate the product of the divisors, as it gets used enough times that it saves a byte. ``` Eε⁺×÷⁻⟦⊖ηζ⟧ιεει ``` Map over the product, generating an adjusted half-open range of (first multiple below, last multiple not above] for each possible remainder. ``` ÷×↨ι±¹⁺Σιε⊗ε ``` Calculating the sum of the integers within the range with that remainder as (last - first) \* (last + first + product) / (2 \* product). ``` IΣE...∧⊙θ¬﹪κλ... ``` Map over the list of ranges, calculating the sums for those which are divisible by one of the divisors, and output the overall sum. ]
[Question] [ I was in the bus today, and noticed this sign: ``` seated standing wheelchairs max1 37 30 00 max2 36 26 01 max3 34 32 00 ``` The number of seated passengers, standees, and wheelchairs all have to be no larger than some row in the table. [(See chat for details.)](https://chat.stackexchange.com/transcript/message/46040321#46040321) For the purposes of this challenge we will generalise this idea: Given a non-negative integer list of a strictly positive length N (number of passenger types) and a non-negative integer matrix of strictly positive dimensions (N columns and one row per configuration, or the transpose of this), return a list of indices/truthy-falsies/two-unique-values indicating which configurations limits are fulfilled. E.g. with the above matrix: `30,25,1` → `[1]` (0-indexed) `[2]` (1-indexed) or `[false,true,false]` (Boolean) or `["Abe","Bob","Abe"]` (two unique values) etc. The following test cases use the above matrix and the 0/1 for false/true: `[30,30,0]` → `[1,0,1]` `[30,31,0]` → `[0,0,1]` `[35,30,0]` → `[1,0,0]` `[0,0,1]` → `[0,1,0]` `[0,0,0]` → `[1,1,1]` `[1,2,3]` → `[0,0,0]` The following test cases use the following matrix: `1 2 0 4` `2 3 0 2` `[1,2,1,2]` → `[0,0]` `[1,3,0,1]` → `[0,1]` `[1,2,0,3]` → `[1,0]` `[1,2,0,1]` → `[1,1]` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 5 3 bytes ``` ∧.≤ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24RHHcv1HnUu@f/f2EABiAyAYhM1jM0VjM0UjE00NYBCRkCWkaaGgYKhgoEmF1CJgiEhRYYKRgrGxCgCYrAyIK2pAdQDkjTQ1DABcsHyBlBjsMkDAA) [Answer] ## Haskell, ~~22~~ 20 bytes ``` map.(or.).zipWith(>) ``` Returns `False` if legal and `True` if not. [Try it online!](https://tio.run/##VYs7DsIwEER7TrEFRSINlu2NQgXXoDAurICJRT5WkorDYxY6upn3ZvqwPu/DUCKd6FrGkFU1L6pWr5Qvaeurcy0wTWJv844oL2naaE@RHGuwgfbkHB8hTXs4bmFbmG9qwFaY/38ZMLQM5GUgHo1s7Q9a78u7i0N4rOXQ5fwB "Haskell – Try It Online") Flipping True/False as return values saves 2 bytes (thanks @user202729!). With `True` for legal it's `map.(and.).zipWith(<=)` (22 bytes). [Try it online!](https://tio.run/##VYsxDsIwEAR7XnEFRSIdlu2LQkPeQWGusBJMLBxjkVQ8HnPQ0e3O7M5@vV9TqgEGuNTFF9X4PKlWvWI5x21uTkMrOGbx02MHUJ4xb7CHAI40kkHN4BwdUZpmdNSj7dF8U4dkhfH/yyChloG8DIrHTrb2By1zfY8h@dtaD2MpHw "Haskell – Try It Online") [Answer] # [Octave](https://www.gnu.org/software/octave/), 15 bytes ``` @(a,b)all(a>=b) ``` [Try it online!](https://tio.run/##dY@9CsIwFIX3PEXAwQTucH@qDqHiC/QJSoZUOwhFhRbBp48pQls1HUIyfOfLOffzEJ5tjCcToLGh60w4lo2NQ9sPutTh1itVUXrVcgBBQCd74D2QkwKEAf1WXa79owsvM2ZMRVBLotCht1ZvdE2AQD5P0UThGrX7dWGGSoSjyUSrzOyh7G/k2MmiUfKoisf5BGksFI5B0s1/s/kTTmeO@xwj31V93oNTDVrx8MIzjtHxDQ "Octave – Try It Online") As per sundar's comment, omitting the transpose saves 2 bytes. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes ``` <Ẹ€ ``` [Try it online!](https://tio.run/##y0rNyan8/9/m4a4dj5rW/P//Pzra2FxHwdhAR0HBIFaHSyHa2ExHwQiIFQwhXBOgrBFYNvZ/tLEpRK1BLAA "Jelly – Try It Online") `0` = True, `1` = False. [Answer] # [Ohm v2](https://github.com/nickbclifford/Ohm), 3 bytes ``` >Σy ``` [Try it online!](https://tio.run/##y8/INfr/3@7c4sr//6ONDXQUQNgglis62tgcwgHydBSijc10FIyA2BDMMQFKGYGlYgE "Ohm v2 – Try It Online") Algorithm: vectorized `>` (greater than), `Σ` sum each, `y` sign. [Answer] # [MATL](https://github.com/lmendo/MATL), 3 bytes ``` <~A ``` [Try it online!](https://tio.run/##hYy7DYBADEN7psgI@SAoTIPECHQnJOiho2b1kENXwlFEsexnH9u5@@rDNfo0e7KerCNrYUwaQsEkxEuTjMPDo6qM/DCxAakSAoXlTwolC5/RkpYk7iOzsvze48pm7t0 "MATL – Try It Online") Takes the input matrix as a transpose of the format in the question (as allowed by OP), with one column per configuration. Outputs boolean 0 and 1 for false and true. [Answer] # [R](https://www.r-project.org/), ~~32~~ ~~30~~ 26 bytes ``` function(x,y)!colSums(x<y) ``` [Try it online!](https://tio.run/##XY49CsMwDIX33KKbBW@QLTddmlP0BMVgCDQJpAk4p3fkdqjdQYhP7wetOQ457nPYxmU2CQddwvJ67NPbpPtBOQ3Tc1vHZIKRG4TBkB6uh4V4iAMThLqoUXXwx0E125qvrV7abEM/zcJpMXXVA@XE8EXQ7Qi@NutUYWmqv0n5Y9XzCQ "R – Try It Online") Accepts the matrix in transposed form as `x`, test config as `y`. Returns a vector of booleans. Initial -2 bytes thanks to mnel, and further -4 by JayCe. [Answer] # JavaScript (ES6), 38 bytes Takes input as `(matrix)(vector)`. Returns a Boolean array. ``` m=>v=>m.map(r=>!r.some((t,x)=>v[x]>t)) ``` [Try it online!](https://tio.run/##dZDBbsIwDIbveQrvlkhesRu2HVD6BjxBlEMFZdpECWorxNsXQwWpRCMlhzifftvff32p@133dx4@T3HfjAc3tq66uKot2vqsO1d9dEUf20brAa9Gvvw1VIMx4xYceAXgwf4gWEIggoBT5RuhlEv8qqyFKSdGhY3axVMfj01xjL/6oLdGe0mQQ8EYWK3AMxJyyHCcOMpyX295tMRNAQCvPM5zlDgWbrEvY4l2nvfW12yUSvZYVIkXhPXTlTzto1LmXN17yJ05WJ7EPnZLm@XmFaUzT3mKE8VhvAE "JavaScript (Node.js) – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), 30 bytes ``` map.((.).(==)<*>(zipWith min)) ``` [Try it online!](https://tio.run/##y0gszk7NyfmfZhvzPzexQE9DQ09TT8PWVtNGy06jKrMgPLMkQyE3M09TEyidmadgq1BQWhJcUqSgp1CckV@uoKKQphBtbKADRAaxCtHRxuYQpg5Q1EzHyEzHEMw00TE2AorG/v@XnJaTmF78Xze5oAAA "Haskell – Try It Online") [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 57 bytes ``` \d+ $* ;(?=.*;(.*)) ;$1¶ %(+`,1*(1*)(;.*),\1$ $2 (1*);\1$ ``` [Try it online!](https://tio.run/##dYqxDYAwDAR7zxEkx1gRDnQWomSJFCBBQUOBmI0BWMwkNVC87v/0x3pu@2wVjpOlpQZHoDj0gRQDeQ/q5L6gwnpiIRTyqNlzEgcuQhGau5lw5IY7jdxmRi07B96@UODr33D74@UB "Retina 0.8.2 – Try It Online") Link includes test cases, but the output is all run together. Explanation: ``` \d+ $* ``` Convert to unary. ``` ;(?=.*;(.*)) ;$1¶ ``` Give each row of the matrix its own copy of the list. ``` %( ``` Operate separately on each row of the matrix. ``` +`,1*(1*)(;.*),\1$ $2 ``` Repeatedly remove the last number of the row and list while the last number of the row is at least as big as that of the list. ``` (1*);\1$ ``` There should then be one number left in the list and the number in the row should be at least as big as that. [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~6~~ 5 bytes *-1 bytes from @Shaggy* ``` eȨVv ``` [Try it online!](https://tio.run/##y0osKPn/P/Vwx6EVYWX//0dHG5vrKBgb6CgoGMTqcClEG5vpKBgBsYIhhGsClDUCy8YqcHFFG5vqABUbxCro5v7/DwA "Japt – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 38 bytes ``` lambda m,l:[l==map(min,l,r)for r in m] ``` [Try it online!](https://tio.run/##PYtBCsMgFAX3OcVfJvAWUdsUAp7EurAUqeA3Itnk9FbTktUbhjf52D9bktXrZ42OX29HjLiaqDW7PHJIiCiT3woVConYVhakyRj1gJoxW5BRC@QCceINSjZrh57Enph2u54NxR/vl23zqzucRkBC2XUgyiWknfzIAhSn@gU "Python 2 – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 5 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` εs<›P ``` [Try it online](https://tio.run/##MzBNTDJM/f//3NZim0cNuwL@/4@ONjbXMTbQMYjViTY20zEy0zEEsUx0jI2AYrFc0UA5I1OgIAA) or [verify all test cases](https://tio.run/##MzBNTDJM/W9o6Obp6WKvpPCobZKCkv2hlcX/z209tM7mUcOugP@1Ov@jo43NdYwNdAxidaKNzXSMzHQMQSwTHWMjoFgsVzRQzsgUKMhFjEqwNHEqDYlTaUqsmUApolwJUkeMeYY6RjrGIHUghoGOCVAWKABkGcFkgRiPvDHMPTj1GxAwH6QfAA). **Explanation:** Unfortunately 05AB1E v1 doesn't have a 1-char builtin for `≤` or `≥`, so I decrease each value instead before using `›`. [05AB1E v2](https://chat.stackexchange.com/transcript/message/46036557#46036557) which is currently in development will have these builtins. ``` ε # For-each row of the (implicitly input) matrix: s # Swap, so the (implicitly input) list is at the top of the stack < # Decrease every value in the input-list by 1 # i.e. [30,25,1] → [29,24,0] › # Check for each value in the matrix-row if they're larger # than the input-list value at the same index # i.e. [37,30,0] and [29,24,0] → [1,1,0] P # Then take the product of these checks # i.e. [1,1,0] → 0 ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), 8 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` â ╤┘µrφî ``` [Run and debug it](https://staxlang.xyz/#p=8320d1d9e672ed8c&i=[30,+30,+0],+[[37,+30,+0],+[36,+26,+1],+[34,+32,+0]]%0A[30,+31,+0],+[[37,+30,+0],+[36,+26,+1],+[34,+32,+0]]%0A[35,+30,+0],+[[37,+30,+0],+[36,+26,+1],+[34,+32,+0]]%0A[0,+0,+1],+[[37,+30,+0],+[36,+26,+1],+[34,+32,+0]]%0A[0,+0,+0],+[[37,+30,+0],+[36,+26,+1],+[34,+32,+0]]%0A[1,+2,+3],+[[37,+30,+0],+[36,+26,+1],+[34,+32,+0]]%0A[1,+2,+1,+2],+[[1,+2,+0,+4],+[2,+3,+0,+2]]%0A[1,+3,+0,+1],+[[1,+2,+0,+4],+[2,+3,+0,+2]]%0A[1,+2,+0,+3],+[[1,+2,+0,+4],+[2,+3,+0,+2]]%0A[1,+2,+0,+1],+[[1,+2,+0,+4],+[2,+3,+0,+2]]&a=1&m=2) Explanation: ``` mx\{:vm|A Full program, unpacked, implicit input m Map over rows of the matrix: x\ Zip with input array { m Map over result: :v Check if non-increasing, i.e. matrix element greater than or equal to array element |A All. Implicit output ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 14 bytes ``` zzᵐ{≥₁ᵐ∧1|∧0}ᵐ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/pf/ahtw6Ompoe7Omsfbp3wv6oKSFY/6lz6qKkRyHrUsdywBkgYgCX/RytER0cb6hjpGOiYxOpEG@kYA1lGsbE6CiBhBWMdBQMdBcNYiAAehUaoCo3NFYwNFAxAHGMzBSMzoAyIaaJgbAQUBasxNtAxNtQxIE2HEUSHQiwA "Brachylog – Try It Online") [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 18 bytes ``` Inner[Less,##,Or]& ``` Returns a list of two unique values: `True` means falsy, `False` means truthy. [Try it online!](https://tio.run/##lY69CoNAEIR7n2LhwGoC92NMFbENBJL@uEKCEgstTrvjnv2yWggpEnSr2ZmP2R2a@d0Ozdy/mtTRNd3GsfX23k4ThMDDuzw9fT/ONggR6VRRZ4VwjnKq6zqjwGMuMBIyIpgSuoRaVAGj2YugwOGaR2REO3l1hD8f6@eMvSP0/m4FDbPRyyZRMMMuK70xatX/KfP15@8uuevi2hXTBw "Wolfram Language (Mathematica) – Try It Online") ]
[Question] [ ## Definition If you take the sequence of positive integer squares, and concatenate them into a string of digits (i.e. `149162536496481100...`), an "early bird" square is one that can be found in this string ahead of its natural position. For example, 72 (the number `49`), can be found at an offset of 2 in the string, although the natural position is at offset 10. Thus 7 is the first "early bird" square. Note that for it to be considered an "early bird" square, all the digits in the square must occur before the start of the natural position. A match that partially overlaps the natural position does not count. `a(n)` is the nth positive integer k such that k2 is an "early bird" square. ## Task Given a positive integer `n`, output `a(n)`. You can use 1-based or 0-based indexing, but if you use 0-based indexing, please say so in your answer. You solution should be able to handle at least as high as `a(53)` (or if you're using 0-based indexing, `a(52)`). ## Testcases ``` n a(n) 1 7 2 8 3 21 4 25 5 46 6 97 7 129 8 161 9 196 10 221 ... 13 277 ... 50 30015 51 35000 52 39250 53 46111 ``` ## References * [OEIS A181585](https://oeis.org/A181585) [Answer] # JavaScript (ES6), ~~51~~ ~~49~~ 45 bytes 1-indexed. ``` f=(n,s=k='')=>n?f(n-!!s.match(++k*k),s+k*k):k ``` ### Demo ``` f=(n,s=k='')=>n?f(n-!!s.match(++k*k),s+k*k):k for(n = 1; n <= 20; n++) { console.log('a(' + n + ') = ' + f(n)) } ``` ### Formatted and commented ``` f = ( // f = recursive function taking: n, // n = input s = k = '' // s = string of concatenated squares, k = counter ) => // n ? // if we haven't reached the n-th term yet: f( // do a recursive call with: n - !!s.match(++k * k), // n decremented if k² is an early bird square s + k * k // s updated ) // end of recursive call : // else: k // return k ``` # Non-recursive version, 53 bytes This one does not depend on your engine stack size. ``` n=>{for(k=s='';n-=!!(s+=k*k).match(++k*k););return k} ``` [Try it online!](https://tio.run/##HYxNDoMgGET3nmLcCJRoNI0r@nkXYrU/WGiAdqOenWJ38@Zl5qm/Ooz@8Y61ddcpLVPEDEqWhnV2nhsKxJiyNZUlD5LMyYjmpeN451IeoITyU/x4C7OnY2FB6BQsLoT@nIOUAmsB8H/Vtdi2bAfqW4GqwuhscMvULO7GmeYMMlsJJvLPATO3QhR7@gE "JavaScript (Node.js) – Try It Online") [Answer] # [Pyth](https://github.com/isaacg1/pyth), 12 bytes ``` e.f/jk^R2Z`* ``` **[Try it here!](http://pyth.herokuapp.com/?code=e.f%2Fjk%5ER2Z%60%2a&test_suite=1&test_suite_input=1%0A2%0A3%0A4%0A5%0A6%0A7&debug=0)** ## How it works ``` e.f/jk^R2Z`* ~ Full program. Let Q be our input. .f ~ First Q positive integers with truthy results. Uses the variable Z. ^R2Z ~ Square each integer in the range [0, Z). jk ~ Concatenate into a single string. / ~ Count the occurrences of... `* ~ The string representation of Z squared. Yields 0 if falsy and ≥ 1 if truthy. e ~ Get the last element (Qth truthy integer). Output implicitly. ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~10~~ 9 bytes Saved 1 byte thanks to *Adnan*. ``` µNL<nJNnå ``` [Try it online!](https://tio.run/##MzBNTDJM/f//0FY/H5s8L7@8w0v//zc0AAA "05AB1E – Try It Online") **Explanation** ``` µ # loop until counter equals the input NL # push the range [1 ... iteration_no] < # decrement each n # square each J # join to string Nnå # is iteration_no in the string? # if true, increase counter ``` [Answer] # [Perl 5](https://www.perl.org/), 34 bytes **33 bytes code + 1 for `-p`.** ``` $s.=$\*$\while$_-=$s=~(++$\*$\)}{ ``` [Try it online!](https://tio.run/##K0gtyjH9/1@lWM9WJUZLJaY8IzMnVSVe11al2LZOQ1sbLKhZW/3/v6HBv/yCksz8vOL/ugUA "Perl 5 – Try It Online") [Answer] # [APL (Dyalog)](https://www.dyalog.com/), ~~53~~ 42 bytes ``` {{0<+/(⍕×⍨⍵+1)⍷' '~⍨⍕×⍨⍳⍵:⍵+1⋄∇⍵+1}⍣⍵⊢0} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24TqagMbbX2NR71TD09/1LviUe9WbUPNR73b1RXU68B8mPhmoJQVWPpRd8ujjnYws/ZR72Ig41HXIoNaoHkKh0AKDQ0A "APL (Dyalog Unicode) – Try It Online") **How?** `⍷` - find occurrences of `⍕×⍨⍵+1` - stringified square of `x+1` in the `⍕×⍨⍳⍵` - stringified range of squares `x` `' '~⍨` - without spaces `+/` - sum `0<` - if the sum is positive (occurrences exist), then it returns `x+1`, otherwise, `∇⍵+1` - recurse with `x+1`. `⍣⍵` - apply `n` times. [Answer] # [Haskell](https://www.haskell.org/), 73 bytes ``` import Data.List ([n|n<-[7..],isInfixOf(g n)$g=<<[1..n-1]]!!) g=show.(^2) ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/PzO3IL@oRMElsSRRzyezuIQr0VYjOq8mz0Y32lxPL1Yns9gzLy2zwj9NI10hT1Ml3dbGJtpQTy9P1zA2VlFRkyvdtjgjv1xPI85I839uYmaegq1CQVFmXomCikKihqXmfwA "Haskell – Try It Online") Zero-indexed. **Explanation** Auxiliaries: ``` import Data.List -- import needed for isInfixOf g=show.(^2) -- function short cut to square an int and get the string representation ``` Main function: ``` ( !!) -- Index into the infinite sequence [n|n<-[7..], ] -- of all numbers n greater equal 7 isInfixOf(g n)$ -- whose square appears in the string g=<<[1..n-1] -- of all squares from 1 up to n-1 concatenated. ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~13~~ 11 bytes ``` R²DµṪẇF Ç#Ṫ ``` [Try it online!](https://tio.run/##y0rNyan8/z/o0CaXQ1sf7lz1cFe7G9fhdmUg8/9/QwMA "Jelly – Try It Online") Alternatively this is a 10 bytes solution that prints `n` first values of the sequence: [Try it online!](https://tio.run/##y0rNyan8/z/o0CaXQ1sf7lz1cFe7G9fhduX//40MAA "Jelly – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), ~~62~~ 61 bytes ``` n=input();i=0;s='' while n:i+=1;n-=`i*i`in s;s+=`i*i` print i ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P882M6@gtERD0zrT1sC62FZdnas8IzMnVSHPKlPb1tA6T9c2IVMrMyEzT6HYulgbwuEqKMrMK1HI/P/f0AAA "Python 2 – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes ``` Ḷ²DFɓ²ẇ Ç#Ṫ ``` [Try it online!](https://tio.run/##ASAA3/9qZWxsef//4bi2wrJERsmTwrLhuocKw4cj4bmq//8yNA "Jelly – Try It Online") An alternative to [user202729's solution](https://codegolf.stackexchange.com/a/148888/59487). ### How it works ``` C#Ṫ ~ Main Link. Ç# ~ First N positive integers with truthy results. Ṫ ~ Tail. Take the last one. ----------------------------------------------------------- Ḷ²DFɓ²ẇ ~ Helper link. This is the filtering condition. Ḷ ~ Lowered range. Yields {x | x ∊ Z and x ∊ [0, N)}. ² ~ Square each. D ~ Convert each to decimal (this gets the list of digits). F ~ Flatten. ɓ ~ Starts a new monadic chain with swapped arguments. ² ~ N²; Yields N squared. ẇ ~ Is ^ sublist of ^^^? ``` [Answer] ## [Alice](https://github.com/m-ender/alice), 32 bytes ``` / \io/&wd.*\@! d ? ~ ? F $ /WKdt ``` [Try it online!](https://tio.run/##S8zJTE79/1@fKyYzX1@tPEVPK8ZBUSFFwV6hDojdFFQU9MO9U0r@/zc0BgA "Alice – Try It Online") The wasteful layout of that stretch of Ordinal mode is really bugging me, but everything I try to save some bytes there comes out longer... ### Explanation ``` / \io/...@... ``` Just the usual decimal I/O framework, with the `o` and `@` in slightly unusual positions. The meat of the program is this: ``` &w Push the current IP address to the return address stack n times. This gives us an easy way to write a loop which repeats until we explicitly decrement the loop counter n times. d Push the stack depth, which acts as our running iterator through the natural numbers. .* Square it. \ Switch to Ordinal mode. ! Store the square (as a string) on the tape. d Push the concatenation of the entire stack (i.e. of all squares before the current one). ?~ Retrieve a copy of the current square and put it underneath. ? Retrieve another copy. F Find. If the current square is a substring of the previous squares, this results in the current square. Otherwise, this gives an empty string. $ If the previous string was empty (not an early bird) skip the next command. / Switch back to Cardinal. This is NOT a command. W Discard one address from the return address stack, decrementing our main loop counter if we've encountered an early bird. K Jump back to the beginning of the loop if any copies of the return address are left. Otherwise do nothing and exit the loop. dt Push the stack depth and decrement it, to get the final result. ``` [Answer] ## [Husk](https://github.com/barbuz/Husk), 13 bytes ``` !f§€oṁ₁ŀ₁N d□ ``` [Try it online!](https://tio.run/##yygtzv7/XzHt0PJHTWvyH@5sfNTUeLQBSPhxpTyatvD///@GBgA "Husk – Try It Online") ### Explanation The second line is a helper function which gives us the decimal digits of a number's square: ``` □ Square. d Base-10 digits. ``` We can invoke this function on the main program using `₁`. ``` !f§€oṁ₁ŀ₁N f§ N Filter the list of natural numbers by the following fork g(n). ŀ Get [0, 1, ... n-1] ṁ₁ Get the decimal digits of each value's square and concatenate them into one list. (A) ₁ And get the decimal digits of n² itself. (B) € Check whether (A) contains (B) as a sublist. ! Use the programs input as an index into this filtered list. ``` [Answer] # [Kotlin](https://kotlinlang.org), 79 bytes ``` {n->var m=n;var i=0;var s="";while(m>0){val k="${++i*i}";if(k in s)m--;s+=k};i} ``` [Try it online!](https://tio.run/##HYuxDsIgFEX3fsULcQAbkroWIXF09gsYpL4ATwNYYwjfjq1nuCd3OP5ZAlJfbQA38ysVIc22uleSZrUJoia1G/X0d9aMqc8Dw51HM4m6l16zQx1HPGJjCh33gARZRClVHrVvClt3b4JokbhNS57hkpL9nm8lIS1GQB1g47W9Eog7fpqEGFr/AQ "Kotlin – Try It Online") [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 75 bytes ``` (n=k=0;s="";While[n<#,If[!StringFreeQ[s,t=ToString[++k^2]],n++];s=s<>t];k)& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n1aaZ/tfI88229bAuthWSck6PCMzJzU6z0ZZxzMtWjG4pCgzL92tKDU1MLpYp8Q2JB8iEq2tnR1nFBurk6etHQvUWGxjVxJrna2p9j8AKF0SDTRW3yEoMS89NdrIIDb2PwA "Wolfram Language (Mathematica) – Try It Online") ## How it works `n` keeps the number of early birds found so far, `k` the last number checked, `s` the string `"1491625..."`. While `n` is too small, if `s` contains the next square, another early bird has been found, so we increment `n`. In any case, we extend `s`. Once `n` reaches the input `#`, we return `k`, the last number checked and therefore the last early bird found. On my laptop, takes about 53 seconds to compute the 53rd term of the sequence. [Answer] # [REXX](http://www.rexx.org/), 66 bytes ``` arg n,a k=0 do i=1 until k=n k=k+(pos(i*i,a)>0) a=a||i*i end say i ``` [Try it online!](https://tio.run/##K0qtqPj/P7EoXSFPJ5Er29aAKyVfIdPWUKE0ryQzRyHbNo9LAUhma2sU5BdrZGpl6iRq2hloAgUTbRNraoACQGZqXgpXcWKlQub///8NDQA "Rexx (Regina) – Try It Online") [Answer] # Bash, ~~76~~ 69 bytes Assume `n` is given into variable (i.e. `n=10 foo.sh`). Uses package `grep`. Any middle value is output (if allowed, -3 bytes). ``` while((n));do((b=++a*a));grep -q $b<<<$s&&((n--));s=$s$b;done;echo $a ``` How does it work? ``` while ((n)); do # while n != 0 (C-style arithmetic) ((b = ++a*a)) # Increment a and let b = a*a # Non-existent value is treated as zero grep $b<<<$s # Search for b in s && ((n--)) # If found, decrement n s=$s$b # Append b to s done echo $a ``` ]
[Question] [ # Definitions * Two numbers are **co-prime** if their only positive common divisor is `1`. * A list of numbers is **mutually co-prime** if every pair of numbers within that list are co-prime with each other. * A factorization of number `n` is a list of numbers whose product is `n`. # Task Given a positive number `n`, output the mutually co-prime factorization of `n` with the maximum length that does not include `1`. # Example For `n=60`, the answer is `[3,4,5]`, because `3*4*5=60` and no other mutually co-prime factorization without `1` has length greater than or equal to `3`, the length of the factorization. # Rules and freedoms * You can use any reasonable input/output format. * The entries in the output list do not need to be sorted. # Testcases ``` n output 1 [] 2 [2] 3 [3] 4 [4] 5 [5] 6 [2, 3] 7 [7] 8 [8] 9 [9] 10 [2, 5] 11 [11] 12 [3, 4] 13 [13] 14 [2, 7] 15 [3, 5] 16 [16] 17 [17] 18 [2, 9] 19 [19] 20 [4, 5] 21 [3, 7] 22 [2, 11] 23 [23] 24 [3, 8] 25 [25] 26 [2, 13] 27 [27] 28 [4, 7] 29 [29] 30 [2, 3, 5] 31 [31] 32 [32] 33 [3, 11] 34 [2, 17] 35 [5, 7] 36 [4, 9] 37 [37] 38 [2, 19] 39 [3, 13] 40 [5, 8] 41 [41] 42 [2, 3, 7] 43 [43] 44 [4, 11] 45 [5, 9] 46 [2, 23] 47 [47] 48 [3, 16] 49 [49] 50 [2, 25] 51 [3, 17] 52 [4, 13] 53 [53] 54 [2, 27] 55 [5, 11] 56 [7, 8] 57 [3, 19] 58 [2, 29] 59 [59] 60 [3, 4, 5] 61 [61] 62 [2, 31] 63 [7, 9] 64 [64] 65 [5, 13] 66 [2, 3, 11] 67 [67] 68 [4, 17] 69 [3, 23] 70 [2, 5, 7] 71 [71] 72 [8, 9] 73 [73] 74 [2, 37] 75 [3, 25] 76 [4, 19] 77 [7, 11] 78 [2, 3, 13] 79 [79] 80 [5, 16] 81 [81] 82 [2, 41] 83 [83] 84 [3, 4, 7] 85 [5, 17] 86 [2, 43] 87 [3, 29] 88 [8, 11] 89 [89] 90 [2, 5, 9] 91 [7, 13] 92 [4, 23] 93 [3, 31] 94 [2, 47] 95 [5, 19] 96 [3, 32] 97 [97] 98 [2, 49] 99 [9, 11] ``` # Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Shortest answer in bytes wins. [Answer] ## [Mathics](http://mathics.github.io/), 24 bytes ``` #^#2&@@@FactorInteger@#& ``` [Try it online!](https://tio.run/nexus/mathics#S7P9rxynbKTm4ODglphckl/kmVeSmp5a5KCs9j@gKDOvRMFBSyFNQd9BISgxLz012tDAIPY/AA "Mathics – TIO Nexus") [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 4 bytes ``` ḋḅ×ᵐ ``` [Try it online!](https://tio.run/nexus/brachylog2#@/9wR/fDHa2Hpz/cOuH/f2Oz/1EA "Brachylog – TIO Nexus") **Explanation** ``` # output is the list of ×ᵐ # products of each ḅ # block of consecutive equal elements ḋ # of the prime factors # of the input ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~3~~ 5 [bytes](https://github.com/Adriandmen/05AB1E/blob/master/docs/code-page.md) +2 bytes to fix the edge case of `1`. Thanks to Riley for the patch (and for the test suite, my 05ab1e is not that strong!) ``` ÒγP1K ``` Test suite at **[Try it online!](https://tio.run/nexus/05ab1e#DZBLUUVREAMN9eJk/qOBDXsKG68KG1hBAnssXY6AJN15fT2/338/73p7eD6E4QRJ0QyLDhIy5ChQokKNBi12sJsxzLHAEiusscEWP7jwW@l44IkX3vjgSxxChBF3MYgkimhiiCUPKdJIJy9QkkU2OeRShxJllFNBXd6imhpq6UOLNtrpoJO@Ok0PvcxhxBjjTDDJFHNth1n2sGKNdTbYZItt9p6xn/8)** ### How? ``` Ò - prime factorisation, with duplicates γ - split into chunks of consecutive equal elements P - product of each list 1 - literal one K - removed instances of top from previous - implicitly display top of stack ``` [Answer] ## [CJam](https://sourceforge.net/p/cjam), 9 bytes ``` {mF::#1-} ``` [Try it online!](https://tio.run/nexus/cjam#q9b8X53rZmWlbKhb@7@uoNbQwED/PwA "CJam – TIO Nexus") Simply separates the input into its constituent prime powers and removes `1`s (only necessary for input `1`). [Answer] # [Haskell](https://www.haskell.org/), 51 bytes `(2#)` is an anonymous function taking an integer and returning a list. Use as `(2#) 99`. ``` m#n|m>n=[]|x<-gcd(m^n)n=[x|x>1]++(m+1)#div n x (2#) ``` [Try it online!](https://tio.run/nexus/haskell#FZDLahtBEEX3@YqD5cUMg8VUVXd1F0T6kcQBYcm2wNMOkh9a6N@VzvJeuM9ld2ybY/s4nHZPH/ef7e3YDuf1svs7DL/bw/b8@v59pq2HO7ibpvH@PzE808ZxfTrs9uP6@/20P9@WVbsu27b59Xi9/Hx4edoPy582dny5XrbyOE3DMsm42h@/aFx@PG8GXY23m6AYiYxTqAQyI4IoYkhCMuJIQSoS6Ix2jaKGJjSjjha0ooHNmGDd0rCEZcyxglUsSDNJSErqiYmUSU4qpEoK8kwWspKN3AtlspMLuZIDn3HBFTc84b2v4wWveFBmilCUYpREyZQ@p1AqJagzVahKNWqiZqpT@9pKDWImhFDCiERkwolC9DPiHw "Haskell – TIO Nexus") Inspired by the power trick some people used in the recent [squarefree number challenge](https://codegolf.stackexchange.com/questions/120078/abandon-all-squares-ye-who-divide-me). * `m#n` generates factors of `n`, starting with `m`. * If `m>n`, we stop, concluding we've already found all factors. * `x=gcd(m^n)n` is the largest factor of `n` whose prime factors are all in `m`. Note that because smaller `m` are tested first, this will be `1` unless `m` is prime. * We include `x` in the resulting list if it's not 1, and then recurse with the next `m`, dividing `n` by `x`. Note that `x` and `div n x` cannot have common factors. * `(2#)` takes a number and starts finding its factors from `2`. [Answer] # [MATL](https://github.com/lmendo/MATL), 7 bytes ``` &YF^1X- ``` [Try it online!](https://tio.run/nexus/matl#@68W6RZnGKH7/7@FAQA "MATL – TIO Nexus") Or [verify all test cases](https://tio.run/nexus/matl#s1JyCFNX0LVTUM9w@K8W6RZnGKH7Pyzjv6UlAA). ### Explanation Consider input `80` as an example. ``` &YF % Implicit input. Push array of unique prime factors and array of exponents % STACK: [2 3 5], [4 0 1] ^ % Power, element-wise % STACK: [16 1 5] 1 % Push 1 % STACK: [16 1 5], 1 X- % Set difference, keeping order. Implicitly display % STACK: [16 5] ``` --- *EDIT (June 9, 2017): `YF` with two outputs has been modified in [release 20.1.0](https://github.com/lmendo/MATL/releases/tag/20.1.0): non-factor primes and their (zero) exponents are skipped. This doesn't affect the above code, which works without requiring any changes (but `1X-` could be removed).* [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 [bytes](https://github.com/DennisMitchell/jelly) ``` ÆF*/€ ``` Test suite at **[Try it online!](https://tio.run/nexus/jelly#@3@4zU1L/1HTmv9BR/ccbgcyvIEYiLJAVMMcBV07hUcNcyP//7e0BAA)** ### How? ``` ÆF*/€ - Main link: n ÆF - prime factors as [prime, exponent] pairs /€ - reduce €ach with: * - exponentiation ``` [Answer] ## [Alice](https://github.com/m-ender/alice), 10 bytes ``` Ifw.n$@EOK ``` [Try it online!](https://tio.run/nexus/alice#@@@ZVq6Xp@Lg6u/9//@HdVsbAA "Alice – TIO Nexus") Unfortunately, this uses [code points as integer I/O again](http://meta.codegolf.stackexchange.com/questions/4708/can-numeric-input-output-be-in-the-form-of-byte-values). The test case in the TIO link is input **191808** which decomposes into **64**, **81** and **37**. Note that this solution prints the prime powers in order from largest to smallest prime, so we get the output `%Q@`. For convenience, here is a 16-byte solution with decimal I/O which uses the same core algorithm: ``` /O/\K \i>fw.n$@E ``` [Try it online!](https://tio.run/nexus/alice#@6/vrx/jzRWTaZdWrpen4uD6/7@hpaGFgQUA "Alice – TIO Nexus") ### Explanation As the other answers, this decomposes the input into prime powers. ``` I Read a code point as input. f Compute its prime factorisation a prime/exponent pairs and push them to the stack in order from smallest to largest prime. w Remember the current IP position on the return address stack. This starts a loop. . Duplicate the current exponent. This will be zero once all primes have been processed. n$@ Terminate the program if this was zero. E Raise the prime to its corresponding power. O Output the result as a character. K Return to the w to run the next loop iteration. ``` [Answer] ## mathematica 46 bytes ``` #[[1]]^#[[2]]&/@If[#==1,#={},FactorInteger@#]& ``` [Try it online!](https://tio.run/nexus/mathics#S7P9rxwdbRgbGwekjGJj1fQdPNOilW1tDXWUbatrddwSk0vyizzzSlLTU4sclGPV/gcUZeaVKDhoKaQp6DsoBCXmpadGGxoYxP4HAA) [Answer] # PHP, 62 Bytes prints a associative array with the prime as key and how often the prime is use as value and nothing for input `1` ``` for($i=2;1<$n=&$argn;)$n%$i?++$i:$n/=$i+!++$r[$i];print_r($r); ``` [Try it online!](https://tio.run/nexus/php#s7EvyCjgUkksSs@zVTI0UrL@n5ZfpKGSaWtkbWijkmerBpay1lTJU1XJtNfWVsm0UsnTt1XJ1FYEcoqiVTJjrQuKMvNK4oG6ijSt//8HAA "PHP – TIO Nexus") Output for `60` ``` Array ( [2] => 2 [3] => 1 [5] => 1 ) ``` # PHP, 82 Bytes ``` for($i=2;1<$n=&$argn;)$n%$i?++$i:$n/=$i+!($r[$i]=$r[$i]?$r[$i]*$i:$i);print_r($r); ``` [Try it online!](https://tio.run/nexus/php#JYy9DkBAEAZ7b0E@4lwhlNbmHkRENNhmXTbe//xVU8xkxhCPmGG1Xbno@oLSdloN4Z66EcrVp8hBS0jwHjJAW4b4vIZNkJl/hB/NG4ijaKLX8pzMUUo3 "PHP – TIO Nexus") prints nothing for input `1` if you wish a empty array instead and a sorted array it will be a little longer ``` for($r=[],$i=2;1<$n=&$argn;)$n%$i?++$i:$n/=$i+!($r[$i]=$r[$i]?$r[$i]*$i:$i);sort($r);print_r($r); ``` [Answer] # [Actually](https://github.com/Mego/Seriously), 6 bytes ``` w⌠iⁿ⌡M ``` [Try it online!](https://tio.run/nexus/actually#@1/@qGdB5qPG/Y96Fvr@/29mAAA "Actually – TIO Nexus") Explanation: ``` w⌠iⁿ⌡M w factor into [prime, exponent] pairs ⌠iⁿ⌡M for each pair: i flatten ⁿ prime**exponent ``` [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 28 bytes ``` n->[x[1]^x[2]|x<-factor(n)~] ``` [Try it online!](https://tio.run/nexus/pari-gp#S1OwVfifp2sXXRFtGBtXEW0UW1Nho5uWmFySX6SRp1kX@z8NxACqMtRRsLTUUSgoyswr0cjTUVBS0LVTUNJRSAMq09T8DwA "Pari/GP – TIO Nexus") [Answer] # [miniML](https://github.com/feresum/acml/tree/master/miniml), 47 bytes Challenges involving prime factorization are terribly over-represented here, so we are all sadly forced to have factorization in the standard library. ``` fun n->map(fun p->ipow(fst p)(snd p))(factor n) ``` Note that the 'mini' in miniml refers to the size of the feature set, not the size of source code written in it. [Answer] # Ruby, 61 bytes ``` require 'prime' ->n{(2..n).select{|e|n/e.to_f%1==0&&e.prime?}} ``` I'm really disappointed after looking 6-7 byte solutions -)) [Answer] # Mathematica, 24 bytes ``` Power@@@FactorInteger@#& ``` Too bad `@@@*` is not a thing. Also, I'd like `/@*`, `@@*`, and in fact, change `@@@` to `/@@`, `//@` to `@@@` or whatever and add the infinite family of `//@`, `///@`, ... ]
[Question] [ As in, the 5 speed transmission from the original VW Golf GTI. Print the transmission pattern in as few bytes as possible. Yes I know this isn't what it actually looks like but the GTI 5 speed shift knob pattern is a lot worse. ``` 1 3 5 | | | |--|--| | | | 2 4 R ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 25 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` 7Ç%3?-:°U+'|³+°U÷û Õr6'R ``` [Test it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=N8clMz8tOrBVKyd8syuwVcO3%2byDVcjYnUg) ~~Japt beatsties with Jelly!~~ The Jelly submission has improved a lot, but unfortunately I don’t think this solution can. I'll explain this part by part as it's a bit hard to visualize without seeing the in-between results. ``` 7Ç%3?-:°U+'|³+°U÷­⁡​‎‎⁡⁠⁡‏⁠‎⁡⁠⁢‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁣‏⁠‎⁡⁠⁤‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁢⁡‏⁠‎⁡⁠⁢⁢‏‏​⁡⁠⁡‌⁤​‎‎⁡⁠⁢⁣‏‏​⁡⁠⁡‌⁢⁡​‎‎⁡⁠⁢⁤‏⁠‎⁡⁠⁣⁡‏‏​⁡⁠⁡‌⁢⁢​‎‎⁡⁠⁣⁢‏⁠‎⁡⁠⁣⁣‏⁠‎⁡⁠⁣⁤‏⁠‎⁡⁠⁤⁡‏‏​⁡⁠⁡‌⁢⁣​‎‎⁡⁠⁤⁢‏⁠‎⁡⁠⁤⁣‏⁠‎⁡⁠⁤⁤‏‏​⁡⁠⁡‌⁢⁤​‎‎⁡⁠⁢⁡⁡‏‏​⁡⁠⁡‌⁣⁡​‎‎⁡⁠⁢⁡⁢‏‏​⁡⁠⁡‌­ 7Ç # ‎⁡For each number from 0 to 6: %3 # ‎⁢ Take it modulo 3. ?- # ‎⁣ If it's truthy (nonzero), return a dash "-". : # ‎⁤ Otherwise: °U # ‎⁢⁡ Increment variable U (starts at zero). +'|³ # ‎⁢⁢ Append "|" three times. +°U # ‎⁢⁣ Append U incremented again. à # ‎⁢⁤End map over range. · # ‎⁣⁡Join this list on newlines. 💎 ``` Created with the help of [Luminespire](https://vyxal.github.io/Luminespire). This gives: ``` 1|||2 - - 3|||4 - - 5|||6 ``` Next, `û` centers each line: ``` 1|||2 - - 3|||4 - - 5|||6 ``` And `Õ` transposes the rows and columns: ``` 1 3 5 | | | |--|--| | | | 2 4 6 ``` Finally, `r6'R` replaces the final 6 with "R" to get the proper image: ``` 1 3 5 | | | |--|--| | | | 2 4 R ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~ 26 25 ~~ 24 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) -1 thanks to [Unrelated String](https://codegolf.stackexchange.com/users/85334/unrelated-string)! ``` 6s2j€”|$⁺Zj"⁾ -KŒBḤ¤YṖ”R ``` A full program that prints. **[Try it online!](https://tio.run/##y0rNyan8/9@s2CjrUdOaRw1za1QeNe6KylJ61LhPQdf76CSnhzuWHFoS@XDnNKBk0P//AA "Jelly – Try It Online")** ### How? ``` 6s2j€”|$⁺Zj"⁾ -KŒBḤ¤YṖ”R - Main Link: no arguments 6 - six s2 - split into twos -> [[1,2],[3,4],[5,6]] j€”|$ - join each with '|' -> [[1,'|',2],[3,'|',4],[5,'|',6]] ⁺ - repeat that -> [[1,'|','|','|',2],[3,'|','|','|',4],[5,'|','|','|',6]] Z - transpose -> [[1,3,5],['|','|','|'],['|','|','|'],['|','|','|'],[2,4,6]] ¤ - nilad followed by link(s) as a nilad: ⁾ - - [' ', '-'] -> [' ','-'] K - join with spaces -> [' ',' ','-'] ŒB - bounce -> [' ',' ','-',' ',' '] Ḥ - double (vectorises) -> [" "," ","--"," "," "] - (multiplying each character by 2 in Python) " - zip with: j - join -> [[1," ",3," ",5],['|'," ",'|'," ",'|'],['|',"--",'|',"--",'|'],['|'," ",'|'," ",'|'],[2," ",4," ",6]] Y - join with newlines -> [1," ",3," ",5,'\n','|'," ",'|'," ",'|','\n','|',"--",'|',"--",'|','\n','|'," ",'|'," ",'|','\n',2," ",4," ",6] Ṗ - pop (remove the 6) - implicit, smashing print ”R - 'R' - implicit print ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 20 bytes ``` ⁶⸿⸿↑E⪪2143R5²⟦⟦⪫ι||| ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMNM05oLwlKKKYopUoJzrUILdBR8Ews0ggtyMoGyRoYmxkGmSjoKRpo6CtHRXvmZeRqZOgpKNTU1SpqxsZqa1v///9ctywEA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ⁶ ``` Output `6` `-`s to the canvas. ``` ⸿⸿ ``` Move to the start of the line below next. ``` ↑E⪪2143R5²⟦⟦⪫ι||| ``` Loop over `21`, `43`, `R5`, inserting `|||` between each pair, and output vertically and triple-spaced. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 154 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 19.25 bytes ``` \|3*5ɾ\RJ2ẇvj\-dd½½YføĊ§ ``` (24 bytes SBCS) [Try it Online!](https://vyxal.pythonanywhere.com/?v=2&c=1#WyI9IiwiIiwiXFx8Myo1yb5cXFJKMuG6h3ZqXFwtZGTCvcK9WWbDuMSKwqciLCIiLCIiXQ==) | | [-6 bits with `L`](https://vyxal.pythonanywhere.com/?v=2&c=1#WyI9TCIsIiIsIlxcfDMqNcm+XFxSSjLhuod2alxcLWRkwr3CvVlmw7jEiiIsIiIsIiJd) Optimizing this was a fun process, especially with Vyncode! Bitstring: ``` 0110101010001111001101000011000011101011101011110001101000001010010011110100010010101010100111111110100100011011101101100010011011010001010111110000101110 ``` ``` \|3*5ɾ\RJ2ẇvj\-dd½½YføĊ§­⁡​‎‎⁡⁠⁡‏⁠‎⁡⁠⁢‏⁠‎⁡⁠⁣‏⁠‎⁡⁠⁤‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁢⁡‏⁠‎⁡⁠⁢⁢‏⁠‎⁡⁠⁢⁣‏⁠‎⁡⁠⁢⁤‏⁠‎⁡⁠⁣⁡‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁣⁢‏⁠‎⁡⁠⁣⁣‏⁠‎⁡⁠⁣⁤‏⁠‎⁡⁠⁤⁡‏‏​⁡⁠⁡‌⁤​‎‎⁡⁠⁤⁢‏⁠‎⁡⁠⁤⁣‏⁠‎⁡⁠⁤⁤‏⁠‎⁡⁠⁢⁡⁡‏⁠‎⁡⁠⁢⁡⁢‏⁠‎⁡⁠⁢⁡⁣‏‏​⁡⁠⁡‌⁢⁡​‎‎⁡⁠⁢⁡⁤‏⁠‎⁡⁠⁢⁢⁡‏‏​⁡⁠⁡‌⁢⁢​‎‎⁡⁠⁢⁢⁢‏⁠‎⁡⁠⁢⁢⁣‏⁠‎⁡⁠⁢⁢⁤‏‏​⁡⁠⁡‌­ \|3* # ‎⁡Push `|||` 5ɾ\RJ # ‎⁢Append "R" to range [1,5] 2ẇvj # ‎⁣Split into chunks of length 2, join by "|||" \-dd½½ # ‎⁤Double "-" twice, halve twice (Push [["-","-"],["-","-"]]) Yf # ‎⁢⁡Interleave and flatten øĊ§ # ‎⁢⁢Centre, transpose and join by newlines 💎 ``` [Answer] # APL+WIN, 47 bytes ``` 5 7⍴(,⍉(7⍴2)⊤⎕av⍳'II⌷II')\'135||||--|--||||24R' ``` [Try it online!Thanks to Dyalog Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcQJanP5BlwPWooz3tv6mC@aPeLRo6j3o7NUAsI81HXUuAahLLHvVuVvf0fNSz3dNTXTNG3dDYtAYIdHVBCAiMTILU/wON4PqfxsUFAA "APL (Dyalog Classic) – Try It Online") Explanation: ``` ⎕av⍳'II⌷II' Convert characters to integers 73 73 127 73 73 ,⍉(7⍴2)⊤ Convert to boolean matrix, transpose and flatten to a vector 1 1 1 1 1 0 0 1 0 0 0 0 1 0 0 1 1 1 1 1 0 0 1 0 0 0 0 1 0 0 1 1 1 1 1 1 0 0 1 0 0 1 1 0 0 1 0 0 1 1 1 1 1 1 1 1 1 0 0 1 0 0 1 1 0 0 1 0 0 1 1 0 0 1 0 0 1 1 0 0 1 0 0 1 1 1 1 1 1 1 1 1 0 0 1 0 0 1 1 0 0 1 0 0 1 This vector has as many 1s as the characters to be displayed. \'135||||--|--||||24R' Inserts spaces into the character vector corresponding to the 0s 1 3 5| | ||--|--|| | |2 4 R 5 7⍴ Reshapes output as a matrix ``` Trivial answer for 41 bytes ``` 5 7⍴'1 3 5| | ||--|--|| | |2 4 R' ``` [Answer] # [///](https://esolangs.org/wiki////), 36 bytes ``` /a/ //b/ |a|a| /1a3a5b|--|--|b2a4aR ``` [Try it online!](https://tio.run/##K85JLM5ILf7/Xz9RX0FBXz9Jn6smEQi59A0TjRNNk2p0dUEoySjRJDHo/38A "/// – Try It Online") [Answer] # [Haskell](https://www.haskell.org), 53 bytes ``` "1 3 5"++a++"|--|--|"++a++"2 4 R" a="\n| | |\n" ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m708I7E4OzUnZ0W0km5yQYFS7OI025ilpSVpuhY3TZUMFRSMFRRMlbS1E7W1lWp0dUEIyjNSUDBRUAhS4kq0VYrJq1FQAKGYPCWI5rW5iZl5tgWlJcElRSppELEFCyA0AA) The boring 45 byte answer: ``` "1 3 5\n| | |\n|--|--|\n| | |\n2 4 R" ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m708I7E4OzUnZ0W0km5yQYFS7OI025ilpSVpuhY3dZUMFRSMFRRMY_JqFBRACMjQ1QUhJBEjBQUTBYUgJYimtbmJmXm2BaUlwSVFKmkQsQULIDQA) [Answer] # [Retina](https://github.com/m-ender/retina), 35 bytes ``` 1x3x5y|--|--|y2x4xR y ¶|x|x|¶ x ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72sKLUkMy9xwYKlpSVpuhY3VbkMK4wrTCtrdHVBqNKowqQiiKuS69C2mgogPLSNq4JLQWFJcVJyMVQLTCsA) The last line contains two spaces. Replaces the input the fixed string `1x3x5y|--|--|y2x4xR`, then replaces `y` with `¶|x|x|¶`, where the pilcrows are newlines, and finally replaces `x` with two spaces. ## Old Answer, ~~45~~ 39 bytes bytes ``` 135$&7*|24R . $& 3`\| |--|--| L`.{9} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72sKLUkMy9xwYKlpSVpuhY31bkMjU1V1My1aoxMgrj0uFTUFBS4jBNiarhqdHVBiMsnQa_asnZJcVJyMVQTTDMA) -6 bytes thanks to [Neil](https://codegolf.stackexchange.com/users/17602) ### How it works 1. Ignored the input and replaces it by `135`, 7 `|`s (we actually need 9, but these are inserted in step 4) and `24R` 2. Replaces every character by itself, followed by two spaces 3. Replaces the third pipe (0-indexed) by `|--|--|` 4. Formats into lines of 9 characters each [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~28~~ ~~25~~ 24 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` 0'|…|--)û.B7δ∍»¾5L'Rªι.; ``` [Try it online.](https://tio.run/##ASwA0/9vc2FiaWX//zAnfOKApnwtLSnDuy5CN8604oiNwrvCvjVMJ1LCqs65Ljv//w) **Explanation:** ``` 0 # Push "0" '| '# Push "|" …|-- # Push "|--" ) # Wrap all three values into a list û # Palindromize it: ["0","|","|--","|","0"] .B # Box it: add trailing spaces to make all strings the same length: # ["0 ","| ","|--","| ","0 "] δ # Map over each string: 7 ∍ # Extend it to length 7: # ["0 0 0","| | |","|--|--|","| | |","0 0 0"] » # Join by newlines: # "0 0 0\n # | | |\n # |--|--|\n # | | |\n # 0 0 0" ¾ # Push 0 5L # Push list [1,2,3,4,5] 'Rª '# Append "R" ι # Uninterleave it into two parts: [[1,3,5],[2,4,"R"]] .; # Replace every first 0 one by one with the flattened values of this list # (after which the result is output implicitly) ``` [Answer] # Python 3, ~~52~~ 51 bytes Boring, straightforward answer. Prints to STDERR. ``` exit("1 3 5\n| | |\n|--|--|\n| | |\n2 4 R") ``` In a REPL, or Notepad & PHP (39 bytes), or paper (0 bytes), we can shorten that to this: ``` '''1 3 5 | | | |--|--| | | | 2 4 R''' ``` [Answer] # JavaScript, 55 bytes Another one of those boring answers: ``` console.log(`1 3 5 | | | |--|--| | | | 2 4 R`) ``` I am aware the shaving off the pair of those pesky parentheses saves 2 bytes, but sadly the result is not as requested. Trying to do some *actual* cool golfing performs worse (**~~59~~ 56 bytes in this case from noodle man**): ``` console.log(`1 3 5${v=` | | | `}|--|--|${v}2 4 R`) ``` (No Try It Online button because you can run the snippets right here!) [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 41 bytes Unfortunately, the shortest I could create was simple a string of the required output... quite boring I know! ``` "1 3 5 | | | |--|--| | | | 2 4 R" ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/X8lQQcFYQcGUq0ZBAYS4anR1QQjON1JQMFFQCFL6/x8A "PowerShell – Try It Online") [Answer] # C# .NET 6, 152 146 bytes ``` int a=124,b=45,c=10;foreach(var x in new[]{49,0,51,0,53,c,a,0,a,0,a,c,a,b,b,a,b,b,a,c,a,0,a,0,a,c,50,0,52,0,82})Console.Write((x>0?(char)x:" ")); ``` Edit: Stored 124 '|', 45 '-', and 10 '\n' into vars to eliminate a char each call ]
[Question] [ ## Description "Imtiaz Germain primes" is not a technical name in Mathematics, but my weird creation, in the memoir of the famous mathematician Sophie Germain. These primes can be generated by the following process: ``` 1. Take a Safe prime 2. Apply 2p + 1 on it to obtain a composite number 3. Apply 2p + 1 once more to obtain a prime number ``` The idea can be further illustrated in the example. ## Example We check if `3` is a Sophie Germain prime. It has a safe prime `7` using `2p+1` so `3` is a Sophie Germain prime and can/cannot be an Imtiaz Germain prime. We take the safe prime, apply `2p+1` on it, and get `15` which must be composite according to the second step of the description, applying the same, we must get a prime next, which is `31` so `3` is an Imtiaz Germain prime. All Imtiaz Germain primes below 100M are available in Chapter 1 of the book I wrote [here](https://aitzazimtiaz.github.io/A-Young-Mathematician/). ## Task Write a program, which inputs any number, and mentions all Imtiaz Germain primes below the number. As long as fulfills the full output, you may output the Imtiaz Germain primes in reversed order. Since it is code golf, the shortest code in bytes win, if bytes are equated then the earliest posted program wins. ## Test Cases ``` 10 => 3 1500 => 3 23 29 53 113 233 293 419 593 653 659 683 1013 1103 1223 1439 10000 => 3 23 29 53 113 233 293 419 593 653 659 683 1013 1103 1223 1439 1559 1583 1973 2039 2273 2339 2549 2753 3299 3359 3593 3803 3863 4019 4409 4733 4793 4919 4943 5003 5279 5639 6173 6263 6269 6323 6563 6983 7433 7643 7823 8243 8273 8513 ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~14~~ 13 bytes ``` ÅPʒ>3Lo*<pāÉQ ``` [Try it online!](https://tio.run/##yy9OTMpM/f//cGvAqUl2xj75WjYFRxoPdwb@/29oYGAAAA "05AB1E – Try It Online") -1 thanks to @Kevin Cruijssen ~~I found a bunch of different ways for 14 bytes, but I can't find any 13 bytes solution ):~~ ``` Lʒ>3Ýo*<pā3ÊQ ÅPʒ>3Lo*<pJC5Q ÅPʒ>3Lo*<pJƵ0Q ÅPʒ>3Lo*<p2β5Q ÅPʒ>3Lo*<p3LÉQ ÅPʒ>3Lo*<pā+ÈP Lʒ>3Ýo*<pJC13Q Lʒ>3Ýo*<p2β13Q Lʒ>3Ýo*<pJŽ4ιQ Lʒ>3Ýo*<p4L3ÊQ ``` ## Explanation ``` ÅP generate all primes up to (and including) the input number ʒ only keep those such that > p+1 3L the list [1, 2, 3] o 2^[1, 2, 3] = [2, 4, 8] * times p+1 = [2p+2, 4p+4, 8p+8] < -1 = [2p+1, 4p+3, 8p+7] p is prime ā length range, [1, 2, 3] É is odd? [1, 0, 1] Q equal to the results of is prime ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), ~~13~~ 12 bytes ``` '‡d›↔4ẎæB13= ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCIn4oChZOKAuuKGlDThuo7DpkIxMz0iLCIiLCIxNTAwIl0=) If I've understood the challenge correctly, for a number to be Imtiaz Germain, it has to first be prime, and applying `2p+1` 3 times must produce the required pattern. Hence, the list `[p, 2p + 1, 2(2p + 1) + 1, 2((2(2p + 1) + 1) + 1)]` must equal `[1, 1, 0, 1]`, which is `13` when converted from binary. Accidentally the same algorithm as Jelly, which was posted while I was writing the explanation :p ## Explained ``` '‡d›↔4ẎæB13= ' # From the range [1, input], keep numbers N where: 4Ẏ # the first 4 items of ‡d›↔ # applying `lambda x: 2 * x + 1` until fixed-point (yes it's infinite, but lazy evaluation means it doesn't get stuck here) æ # tested for primality B # converted from binary 13= # equals 13. This works for the reason explained in the introduction. ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 13 bytes ``` Ḥ‘$3СẒḄ=ʋƇ13 ``` [Try it online!](https://tio.run/##y0rNyan8///hjiWPGmaoGB@ecGjhw12THu5osT3Vfazd0Pi/zuF2b5WsRw1zFGztFB41zNWM/P/f0EBHwdDUAEQaAAEA "Jelly – Try It Online") ## How it works ``` Ḥ‘$3СẒḄ=ʋƇ13 - Main link. Takes an integer n on the left ʋ 13 - Last 4 links as a dyad f(i, 13): $ - Last 2 links as a monad g(i): Ḥ - 2i ‘ - 2i+1 3С - Collect [i, g(i), g(g(i)), g(g(g(i)))] Ẓ - Is prime? Ḅ - Convert from binary = - Does that equal 13? I.e. is the pattern [prime, prime, composite, prime]? Ƈ - Filter 1 ≤ i ≤ n by f(i, 13) ``` [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 107 bytes ``` .+ $* 1 8$* 1{8} $`7$*1¶ A`^(11+)\1+$ 1(1?) $1 G`^(11+)\1+$ 1(1?) $1 A`^(11+)\1+$ 1(1?) $1 A`^(11+)\1+$ %`1 ``` [Try it online!](https://tio.run/##K0otycxL/P9fT5tLRYvLkMsCRFZb1HKpJJiraBke2sblmBCnYWiorRljqK3CZahhaK/JpWLI5Y5V1JGwqGqC4f//hgYGAA "Retina 0.8.2 – Try It Online") Explanation: ``` .+ $* ``` Convert to unary. ``` 1 8$* ``` Multiply by `8`. ``` 1{8} $`7$*1¶ ``` Generate all numbers of the form `8k+7` less than that. ``` A`^(11+)\1+$ ``` Delete all composite numbers. ``` 1(1?) $1 ``` Integer divide by `2`. ``` G`^(11+)\1+$ ``` Delete all prime numbers. ``` 1(1?) $1 ``` Integer divide by `2`. ``` A`^(11+)\1+$ ``` Delete all composite numbers. ``` 1(1?) $1 ``` Integer divide by `2`. ``` A`^(11+)\1+$ ``` Delete all composite numbers. ``` %`1 ``` Convert the results to decimal. [Answer] # [Arturo](https://arturo-lang.io), ~~67~~ ~~65~~ 64 bytes ``` $=>[select..1&'x[map@++repeat[1+2*<=]3x=>prime?=@[<=x>0x=0x>0]]] ``` [Try it](http://arturo-lang.io/playground?cI7wi3) ``` $=>[ ; a function select 1..& 'x [ ; select numbers from 1 to <input> and assign current elt to x map [...] => prime? ; map over a block for primality @ ; evaluate a block ++ [...] x ; append x to the end of a block repeat [1+2*<=] 3 ; create the block [1+2*<=1+2*<=1+2*<=] = ; is this equal to... @[<=x>0x=0x>0] ; shortest way I could think of to make [true true false true] ] ; end select ] ; end function ``` [Answer] # [Thunno](https://github.com/Thunno/Thunno) `+`, \$ 17 \log\_{256}(96) \approx \$ 13.99 bytes ``` g1+4R2@*1-NiJB13= ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72sJKM0Ly9_abSStlLsgqWlJWm6FhvTDbVNgowctAx1_TK9nAyNbSHiUOkFSwwNDAwgbAA) #### Explanation ``` g1+4R2@*1-NiJB13= # Implicit input: + flag adds one g # Filter the range by the following: p 1+ # Add one p+1 4R # Push range(4) p+1, [0, 1, 2, 3] 2@ # Push 2 ** each p+1, [1, 2, 4, 8] * # Multiply each [p+1, 2p+2, 4p+4, 8p+8] 1- # Subtract one [p, 2p+1, 4p+3, 8p+7] Ni # Are they prime? J # Join into a single string B # Convert from binary 13= # Equals 13 (0b1101)? ``` [Answer] # JavaScript (ES6), 79 bytes Returns a list. ``` f=n=>--n?(g=d=>q%--d?g(d):(q-=~q,d<2))(q=n)&g(q)&!g(q)&g(q)?[...f(n),n]:f(n):[] ``` [Try it online!](https://tio.run/##HcXBCoMwDADQb9lhkoApbrBLMe2HiAcxtkwkXXTsuF/vcJf31ukzHfP@fL1Jiyy1JlYORBohs3CwK5HEDIIejPhrrfR3RDBWbDIYNpe/J3FwziVQbHX0534Y61z0KNvitpIhwe3RdYj1Bw "JavaScript (Node.js) – Try It Online") ### Commented ``` f = n => // n = upper bound --n ? // decrement n; if it's not 0: ( g = d => // g is a helper function taking d = q q % --d ? // decrement d; if d is not a divisor of q: g(d) // do recursive calls until it is : // else: ( q -= ~q, // update q to 2q + 1 d < 2 // return true if d = 1 ) // i.e. the original q was prime )(q = n) & // test n (should be prime) g(q) & // test 2n+1 (should be prime) !g(q) & // test 4n+3 (should be composite) g(q) // test 8n+7 (should be prime) ? // if all tests pass: [ ...f(n), // append the result of a recursive call n // followed by n ] // : // else: f(n) // just do a recursive call : // else: [] // stop ``` --- # [JavaScript (V8)](https://v8.dev/), 75 bytes Prints the terms in reverse order. ``` n=>{for(;--n;)(g=d=>q%--d?g(d):(q-=~q,d<2))(q=n)&g(q)&!g(q)&g(q)&&print(n)} ``` [Try it online!](https://tio.run/##HcTBCkBAEADQb3GwzZQplBKGb5FtNw7DLO1F/Poq7/C2Oc7nEtbjotgmx0l4vN0eoCeSHsGz5VFzIjt5sNiBEr9a2KFGBGVB40HRZP9/5girXCD4JAdVU5aYPg "JavaScript (V8) – Try It Online") [Answer] # [Python](https://www.python.org), ~~118 114 112~~ 111 bytes ``` lambda n:[i for i in range(n+1)if[*map(lambda x:all(x%k for k in range(2,x)),[i,i-~i,4*i+3,8*i+7])]==[1,1,0,1]] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY383MSc5NSEhXyrKIzFdLyixQyFTLzFIoS89JTNfK0DTUz06K1chMLNKDKKqwSc3I0KlSzwWqzEWqNdCo0NXWiM3UydesydUy0MrWNdSyApHmsZqytbbShjqGOgY5hbCzE2nUFRZl5JRppGoYGBgaamhDBBQsgNAA) ## [Python](https://www.python.org), ~~123 119~~ 118 bytes ``` f=lambda n,i=2:i<n and([*map(lambda x:all(x%k for k in range(2,x)),[i,i-~i,4*i+3,8*i+7])]==[1,1,0,1])*[i]+f(n,i+1)or[] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=LY4xDoIwGIV3T9FF08KvoWgiMXKSpkMVqn8oLSnV4OJFXFh09D7cRgwM773hDd_3-jSPcHW2H1ZYN84H0j7axZhNWwZfnm--RWcN1hhomiQJe9-CXmfDXedG1adCEQuYpwc8WqJsQUVUq4bOV3dQxtBuWRHtPKkIWuKVvZQ0hY4xEAi4fiLsIoy3kI29l0zmueDAIQEuWSRQxpqOiJgz54Wc6N_Gow1UU_43mpX6ftof) Probably can be improved. *-1 from both by using a trick from @KevinCruijssen's Java answer* #### Commented ``` lambda n: [i for i in range(n + 1) if # Anonymous function, taking an integer n # Filter [0..n] by the following: [*map( # Apply a function to each item of a list: lambda x:all(x%k for k in range(2, x)) # Prime check function , [i, i-~i, 4*i+3, 8*i+7]) # Applied to the list [i, 2*i+1, 4*i+3, 8*i+7] ] == [1, 1, 0, 1]] # i, 4*i+3, and 8*i+7 are prime, and 2*i+1 is not ``` ``` f=lambda n, i=2: i<n and ( # Define a recursive function, f, taking an integer n, # and using an integer, i, as the recursive variable # If i is less than n: [...] == [1, 1, 0, 1] # (same as above) ) * [i] + f(n, i+1) or [] # If true, add i. Make a recursive call with i+1 # Stop if i >= n ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 61 bytes ``` Select[Range@#,Boole@PrimeQ@NestList[2#+1&,#,3]=={1,1,0,1}&]& ``` [Try it online!](https://tio.run/##Dcq9CoAgEADgVwkEl27oahakOaKfURwkDhOyIG@Lnv3qm78ceKccOG1BopGVDtrYLeGMZBX013WQne6UabYjFR5SYdeqGjUo6LwxDwJCA/hqr@WPJ1c2Omx@XuQD "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 25 bytes ``` IΦN⁼1101⭆⊖E⁴×⊕ιX²λ⬤…²λ﹪λν ``` [Try it online!](https://tio.run/##RYzJCsIwFEV/JXT1AhEScedKHMBFpag/ENNHDbwkNYN@fox04V3dgXvMU0cTNNU6ROsz7HXKcLKUMcLZzyVfins0zwU7voqmBJ1SUnWC3XI7TL2e4YAmokOfcYRf3gh2tw5TA/wH2whD@DTUWjDivMUdEVy1n3CpBOvDWCgACeb5om2tSsq6etMX "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` N Input limit Φ Filter on implicit range ⁴ Literal integer 4 E Map over implicit range ι Outer value ⊕ Incremented × Multiplied by ² Literal integer `2` X Raised to power λ Inner value ⊖ Vectorised decrement ⭆ Map over values and join … Range from ² Literal integer `2` λ To inner value ⬤ All values satisfy λ Inner value ﹪ Modulo i.e. is not a multiple of ν Innermost value ⁼ Equals 1101 Literal string `1101` I Cast to string Implicitly print ``` [Answer] # [J](http://jsoftware.com/), ~~27~~ 26 bytes ``` [:I.0</@:p:0 1 7 3*&.>:/i. ``` [Try it online!](https://tio.run/##y/r/P03B1koh2spTz8BG38GqwMpAwVDBXMFYS03Pzko/U@9/anJGvkKagqGpgcF/AA "J – Try It Online") * `i.`: Make a list of the integers from 0 (inclusive) to the given number (exclusive). * `0 1 7 3` `*` `&.` `>:` `/`: + First, apply `>:` (increase by 1) to both `0 1 7 3` and the list from above. + Then, multiply (`*`) them; `/` modifies the rank to produce a table of values. + Finally, apply the inverse of `>:`, decreasing the values by 1. * `0` `<` `/` `@:` `p:`: + `0` `p:` produces 0 for primes and 1 for non-primes. + Then (`@:`, composition), `<` `/` inserts (`/`) `<` ('less than') between items, turning `a b c d` into `a < (b < (c < d))`. For Boolean (0/1) arguments, `a < b` is 1 if and only if `a` is 0 and `b` is 1. Therefore, the result of this is 1 precisely when its input is `0 0 0 1`. * `[:` `I.`: Make a list of the indices of 1s. A cap (`[:`) is used to make this monadic. [Answer] # [R](https://www.r-project.org), ~~78~~ 75 bytes *Edit: -1 byte thanks to pajonk* ``` f=\(x)if(x)c(x[all(sapply(x*2^(0:3)-1,\(y)sum(!y%%2:y)<2)-!-2:1)]-1,f(x-1)) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGCpaUlaboWN73TbGM0KjQz04BEskZFdGJOjkZxYkFBTqVGhZZRnIaBlbGmrqFOjEalZnFproZipaqqkVWlpo2Rpq6irpGVoWYsUBaoWddQUxNi5LI0DVMDAygHZg8A) `n`, `2*n+1`, `2*(2*n+1)+1` and `2*(2*(2*n+1)+1)+1` can be reformulated as `x*2^(0:3)-1` using `x=n+1`. So, we just check these for primes, and test that the desired result (`TRUE TRUE FALSE TRUE`) is always different to `!-2:1` (`FALSE FALSE TRUE FALSE`), returning `x-1` if so. [Answer] # [Raku](https://raku.org/), 50 bytes ``` {grep {is-prime $_&2*$_+1&8*$_+7&none 4*$_+3},^$_} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/Or0otUChOrNYt6AoMzdVQSVezUhLJV7bUM0CRJmr5eXnpSqYgNjGtTpxKvG1/4sTKxXSNAxNDQw0/wMA "Perl 6 – Try It Online") * `grep { ... }, ^$_` returns all nonnegative integers less than the input argument `$_` that satisfies the bracketed predicate. * `$_ & 2*$_+1 & 8*$_+7 & none 4*$_+3` is a conjunction of `$_`, the number being tested, as well as twice that number plus one, eight times that number plus seven, and a `none` junction of four times that number plus three. * `is-prime` tests the primality of that junction, returning a truthy value if `$_`, `2*$_+1`, and `8*$_+7` are all prime, and `4*$_+3` is NOT prime. [Answer] # Java 8, ~~133~~ ~~126~~ 123 bytes ``` i->{for(;i-->3;)if(p(i)+p(i-~i)+p(8*i+7)<4&p(4*i+3)>1)System.out.println(i);};int p(int i){for(int k=i;k%--i>0;);return i;} ``` Outputs each Imtiaz Germain prime on a separated newline in reversed order. [Try it online.](https://tio.run/##LU9BjsIwDLzzCl9YxVSpQCAtkpf@AC4cVxyyIUWmJY3SFLRC5etdt4sP47Elj2eu5m709VwNtjZtC3vD/jkDYJ9cLI11cBhHgHvDZ7BK9sBIsupnAgfwsBtYF8@yiYpY62JNyKUKijET0K@pbxecfeLX5iOojdA1Fis8/rbJ3fKmS3mIolt7uaGexhfh/WiSHWm1Y6rmWnOxJKToUhc9MPUDjTZC91OzhTaZJG2yepMg6phE@PJ9MvgfwrvHlFBh7nOrVkupd5h@@AM) **Explanation:** ``` i->{ // Method with integer parameter and no return-type for(;i-->3;) // Loop `i` in the range (input,3]: if(p(i) // If `i` is a prime number +p(i-~i) // and `2i+1` is a prime number +p(8*i+7) // and `8i+7` is a prime number <4 // (by checking if all three are 0 or 1) &p(4*i+3) // and `4i+3` is NOT a prime number >1) // (by checking whether it's NOT 0 or 1) System.out.println(i);} // Print `i` with trailing newline // Separated method with integer as both parameter and return-type, // to check whether the given number (≥2) is a prime number (0 or 1) int p(int i){ for(int k=i; // Set `k` to the given integer `i` k%--i>0;); // Decrease `i` before every iteration with `--i` // Keep looping as long as `k` is NOT divisible by `i` return i;} // After the loop, return `i` // (if it's 1 or 0, it means it's a prime number) ``` [Answer] # [Factor](https://factorcode.org/) + `combinators.extras math.primes`, 78 bytes ``` [ iota [ [ dup 2 * 1 + ] thrice 4array [ prime? ] map { t t f t } = ] filter ] ``` [Try it online!](https://tio.run/##HYyxCsJAEET7fMXUCiERbRSxFBsbsQop1nNDDnOXuLcBg/jtcQnDTPGGmYac9jLfb5freQ/Xh4ePZCTl/FGhhMTvkaPjhBdL5A6BtF0iH8QH4yRCU8IgrDoZi4pDlpW7opgr@F4Jlek5DthghRJr1NBWvGNsl621y9XJikADvlBTY/7haKzxnbKgnh11HfL5Dw "Factor – Try It Online") * `iota [ ... ] filter` select numbers up to input * `[ dup 2 * 1 + ] thrice` push `n, n*2+1, tos*2+1, tos*2+1` to the stack * `4array` gather them into a sequence * `[ prime? ] map` primality test each element * `{ t t f t } =` is it equal to `{ t t f t }`? [Answer] # [PARI/GP](https://pari.math.u-bordeaux.fr/), 145 bytes can find all desirable numbers up to 1e7 under the time limit in TIO. Golfed version, [try it online!](https://tio.run/##JYxBDoIwEEX3nILljA4JJSQu6lyBCzQsCGlJEy21RTfK2eugm8nL/Pd/nJJvlliKg4D8zvbBLztva4KePLWonaBnRT1JZvzIQQfuTuGsNGrjc0z@biHjJ18bMUZmo0hRS2rcqwUGGU02sxmPpb8cuaOBvAMHEelI5zXM0waCFBFRC@xFzvO21VwvoOwFdSXt8JPkjbp8AQ) ``` f(n)={seq=vector(4,i,0);for(i=1,4,seq[i]=n;n=2*n+1;);[isprime(s)|s<-seq]==[1,1,0,1]} g(N)={res=[];forprime(p=2,N,if(f(p),res=concat(res,p)));res} ``` Ungolfed version ``` is_satisfying_condition(n) = { seq = vector(4, i, 0); for(i=1, 4, seq[i] = n; n = 2*n + 1;); return([isprime(s) | s <- seq] == [1, 1, 0, 1]); } select_primes(N) = { result = []; forprime(p = 2, N, if(is_satisfying_condition(p)==1, result = concat(result, p))); return(result); } g = select_primes(10000); print(g); ``` ]
[Question] [ Write a program/function that finds the amount of fuel needed to escape Earth's gravity well given the exhaust velocity of the fuel and the amount of mass to transport using the [Tsiolkovsky rocket equation](https://en.wikipedia.org/wiki/Tsiolkovsky_rocket_equation): $$\Delta v = v\_\text{exhaust}\ln\dfrac{m\_\text{start}}{m\_\text{end}}$$ where * \$\Delta v\$ is the change in velocity from start to finish (in this case, escape velocity is about 11.2 km/s, so you will use that) * \$v\_\text{exhaust}\$ is the exhaust speed of the fuel (you will be given this) * \$m\_\text{start}\$ is the starting mass of the ship (i.e. including fuel) * \$m\_\text{end}\$ is the ending mass of the ship (i.e. excluding fuel) (you will also be given this) Equivalently, you have to calculate \$m\_\text{start}-m\_\text{end},\$ which is the mass of the fuel. The mass you need to get away from Earth will be given in kg\*, and the exhaust speed in km/s with precision in the tenths. Return the mass of fuel in kg\*. You can take input in any acceptable format, including (but not limited to): * Mass as integer, exhaust speed as double/float * Mass as integer, exhaust speed as integer representing tenths (for example, 24 would represent 2.4) * Mass as string, exhaust speed as string Output at least with precision to the integer (that is, when rounded to the nearest integer, your answer should be correct), and in any reasonable format (integer, float, string). Standard loopholes apply. Scoring is shortest answer per language wins, as is standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Sample implementation in Python: ``` import math DELTA_V = 11.2 def fuel(mass: int, exhaust_speed: float) -> float: ratio = math.exp(DELTA_V / exhaust_speed) # m_start / m_end return mass * (ratio - 1) ``` [Try it online!](https://tio.run/##dZJNasMwFIT3OsXD3VjBVSX5ybYMKRTaXZelmxKCaWRiiH@wFGgJOUUX3fR0vUiq2PlpoPXCSM8z39gad@9u2TZx1vW7XVV3be@gLtySkPuHx6e7@TNMQQgmCVmYEsq1WYV1YW0OVeMiMG/LYm3d3HbGLHIoV23hKFzfjqucgL/6wlWtp@ypzLx14RF8c2mncAX13LrCv8GNX5lmMfqNW/cN7FNhAuGIuwZBCXHGm18La6znbwZ1yCMQjNMcOOPROBIRSIZ@JLhiMcokVbHORKIUHhWc/9LEyP7T@NsA90eSKSGzhCeoOCqRHlRKpxHgoNFScoYKhZQxoo6zS4n0klRrZDqNNc8yjpipcxY/YoRCRJZgkqaC65Sj52wJKdseTt8f@VOy65XzrZyHllXO1DakYw9d7ysLyyDcnBQvfLaN4NdezLZDfZsRt6WB77hZTIMcAjpQqsNPMDmZKEynh/gx6BwWfH99HHxmZc0fjz8Dutv9AA "Python 3.8 (pre-release) – Try It Online") Test cases (note that they aren't exact): ``` (0, 1) -> 0 (1, 2.4) -> 105.34267539816554 (100, 2.4) -> 10534.267539816554 (100, 100) -> 11.851286064504517 (1000, 4) -> 15444.646771097048 (597, 4) -> 9220.454122344938 (597, 4.2) -> 7994.973908804485 ``` ## Leaderboards Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language. To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template: ``` # Language Name, N bytes ``` where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance: ``` # Ruby, <s>104</s> <s>101</s> 96 bytes ``` If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header: ``` # Perl, 43 + 2 (-p flag) = 45 bytes ``` You can also make the language name a link which will then show up in the leaderboard snippet: ``` # [><>](http://esolangs.org/wiki/Fish), 121 bytes ``` ## ``` var QUESTION_ID=252264; var OVERRIDE_USER=114332; var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;function answersUrl(d){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+d+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(d,e){return"https://api.stackexchange.com/2.2/answers/"+e.join(";")+"/comments?page="+d+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(d){answers.push.apply(answers,d.items),answers_hash=[],answer_ids=[],d.items.forEach(function(e){e.comments=[];var f=+e.share_link.match(/\d+/);answer_ids.push(f),answers_hash[f]=e}),d.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(d){d.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),d.has_more?getComments():more_answers?getAnswers():process()}})}getAnswers();var SCORE_REG=function(){var d=String.raw`h\d`,e=String.raw`\-?\d+\.?\d*`,f=String.raw`[^\n<>]*`,g=String.raw`<s>${f}</s>|<strike>${f}</strike>|<del>${f}</del>`,h=String.raw`[^\n\d<>]*`,j=String.raw`<[^\n<>]+>`;return new RegExp(String.raw`<${d}>`+String.raw`\s*([^\n,]*[^\s,]),.*?`+String.raw`(${e})`+String.raw`(?=`+String.raw`${h}`+String.raw`(?:(?:${g}|${j})${h})*`+String.raw`</${d}>`+String.raw`)`)}(),OVERRIDE_REG=/^Override\s*header:\s*/i;function getAuthorName(d){return d.owner.display_name}function process(){var d=[];answers.forEach(function(n){var o=n.body;n.comments.forEach(function(q){OVERRIDE_REG.test(q.body)&&(o="<h1>"+q.body.replace(OVERRIDE_REG,"")+"</h1>")});var p=o.match(SCORE_REG);p&&d.push({user:getAuthorName(n),size:+p[2],language:p[1],link:n.share_link})}),d.sort(function(n,o){var p=n.size,q=o.size;return p-q});var e={},f=1,g=null,h=1;d.forEach(function(n){n.size!=g&&(h=f),g=n.size,++f;var o=jQuery("#answer-template").html();o=o.replace("{{PLACE}}",h+".").replace("{{NAME}}",n.user).replace("{{LANGUAGE}}",n.language).replace("{{SIZE}}",n.size).replace("{{LINK}}",n.link),o=jQuery(o),jQuery("#answers").append(o);var p=n.language;p=jQuery("<i>"+n.language+"</i>").text().toLowerCase(),e[p]=e[p]||{lang:n.language,user:n.user,size:n.size,link:n.link,uniq:p}});var j=[];for(var k in e)e.hasOwnProperty(k)&&j.push(e[k]);j.sort(function(n,o){return n.uniq>o.uniq?1:n.uniq<o.uniq?-1:0});for(var l=0;l<j.length;++l){var m=jQuery("#language-template").html(),k=j[l];m=m.replace("{{LANGUAGE}}",k.lang).replace("{{NAME}}",k.user).replace("{{SIZE}}",k.size).replace("{{LINK}}",k.link),m=jQuery(m),jQuery("#languages").append(m)}} ``` ``` body{text-align:left!important}#answer-list{padding:10px;float:left}#language-list{padding:10px;float:left}table thead{font-weight:700}table td{padding:5px} ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="https://cdn.sstatic.net/Sites/codegolf/primary.css?v=f52df912b654"> <div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td><a href="{{LINK}}">{{SIZE}}</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td><a href="{{LINK}}">{{SIZE}}</a></td></tr></tbody> </table> ``` \* Technically, you can use any unit, as long as it's the same for input and output - it doesn't really matter. [Answer] # [Raku](https://raku.org/), ~~19~~ 18 bytes ``` *×(e**(11.2/*)-1) ``` *saved one byte by using the built-in constant e instead of the exp function* [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPtf6/B0jVQtLQ1DQz0jfS1NXUPN/9YKxYmVCkoq8Qq2dgrVaQo1KvG1Sgpp@UUKNgYKhnY6CjaGCkZ6JmCGgQEyE4jt/gMA "Perl 6 – Try It Online") This is a "WhateverCode" expression, a short way of defining an anonymous function where the lone asterisks mark where the function arguments will go. [Answer] # [Factor](https://factorcode.org), 24 bytes ``` [ 11.2 swap / e^ 1 - * ] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=dZC9SsRAEMexzVOMrZB1dndmPxQOO7GxEStRCCHBQy8J2T1EjnsSmzTa2fssPo355LRwYD74_38ww7x9lFke67b7Prq4vbm6vjyDLIQ6D_BUtFXxDJssPo5FlNsqj-u6CtC0RYyvTbuuIpwnyS6BPnaAIGE_jHAM6QpwliUoQaMxyhJZaFLGsvZOGmZaOMSZXDhN4h9uyIWTwrFUzqAhRmJpDxzCuHjimIiEIWOtRG-R3Myxt_DrPq8UCmKSSmkir_9gQi1rrfckvNUenUMix8n-fRvL1H3dDScpCC9ZA6dQPPQPSOEE7if7s5wevNr0tpi0rpv6Dw) ``` ! 1 2.4 11.2 ! 1 2.4 11.2 swap ! 1 11.2 2.4 / ! 1 4.666666666666667 e^ ! 1 106.3426753981655 1 ! 1 106.3426753981655 1 - ! 1 105.3426753981655 * ! 105.3426753981655 ``` [Answer] # JavaScript (ES7), 22 bytes ### Approximation Expects `(ending_mass)(exhaust_speed)`. ``` m=>s=>m*73130**(1/s)-m ``` [Try it online!](https://tio.run/##hc7NbsJADATge5@C424kHHt3vF4fwrsgfqpWhFQN4vVTQtpDoVJ98GW@keZ9e92Ou8@3j8v6POwP07Gb@m4zdpu@sSyZmyZIO8Z1P@2G8zicDnQaXsMxcAwS42q@tl3xy@9UYkiEe35LhZUyUjHNXqWo4pEz/xQWnkH/8fktXKiqpFq4QBkq9sxv/r5m5gqACoqZsBujPnB1@9Yz95SYoJCUMuD5b01p2WLuILfsXCsDVacv "JavaScript (Node.js) – Try It Online") This is: $$m\times \left(e^{11.2}\right)^{1/s}-m$$ with \$e^{11.2}\approx 73130\$ Maximum error for the test cases: \$\approx0.027\$ --- # JavaScript (ES6), 25 bytes *-1 by using tenths for the exhaust speed, as pointed out by [@CommandMaster](https://codegolf.stackexchange.com/users/92727/command-master)* ### Exact formula Expects `(ending_mass)(exhaust_speed)` where the exhaust speed is expressed in tenths. ``` m=>s=>m*Math.exp(112/s)-m ``` [Try it online!](https://tio.run/##hc5NbsIwEAXgfU/B0kbCmRm/sT2LcAMOEdHQHxGCGlT19ikG0aq0Umcxm/c96b127920fXs5nlaH8bGfd@08tOupXQ/LTXd6Dv3H0TFLM/nVMG/HwzTu@7Afn9zOkXdM3i/qNc2CHn7G7J3gO2bSECEpa7TCSRX3nuircfUR4T9/fnVC9RyKspRECUpQzr/9uYDL4uoVQEhIOTNZJpQ7r5ZvvHoToQAFi0TA4t9cbjybIViORqUQUHT@BA "JavaScript (Node.js) – Try It Online") [Answer] # [Fig](https://github.com/Seggan/Fig), \$11\log\_{256}(96)\approx\$ 9.054 bytes ``` *{^mE\x11.2 ``` [Try it online!](https://fig.fly.dev/#WyIqe15tRVxceDExLjIiLCIyLjRcbjEiXQ==) Forgot to mention that it expects exhaust speed first and then mass. ``` *{^mE\x11.2 : Full program \x11.2 : Divides 11.2 by first input ^mE : e^result { : Decrement * : Multiply given only one argument so second input is implied ``` [Answer] # [Python](https://www.python.org), 31 bytes ``` lambda m,e:m*(1+7e-9/e)**16e8-m ``` [Attempt This Online!](https://ato.pxeger.com/run?1=bY9LSgQxEIb3fYpiVkmbjpWk8hoY7-DeTQ-mmUC_mGkFz-JmQPQa7r3B3Ma2WwXBTVHF99UP__Pb-DQdhv780uzuXh-mpgrvbd3t72voRNp2JVNXPlXxOvGyVC6Fqluty20zHKGF3MMwpp4h3xaQxQA76OqRpce6Fa08jW2e2AaqG9hwXsB4zP3EZk00rMxc1PsTW7Zq4HwNPl8-GApQ_OsJC6YEaEnLpdBKQ9p5a2JQzlqaMeIfwZD8R5jHKigZrNLBoSOLZJVfhNn4DrBEJB057xVGjxQKZqP_wVFrlGRJaW2IovmlUi_cx0gyehMxBCQKdq30CQ) Avoids the math import by using \$e^x\approx(1+x/n)^n\$ for large n. [Answer] # [Rust](https://www.rust-lang.org), ~~28~~ 27 bytes ``` |m,v:f64|m*(11.2/v).exp()-m ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72kqLS4ZMG2tDyF3MTMPA1NhWqunNQShbTS1BwF26WlJWm6FrtrcnXKrNLMTGpytTQMDfWM9Ms09VIrCjQ0dXMhKm4xBlpzFRRl5pXk5ClqKFXXKoCRko6BnoGOIRCDjNOAcjQ1sasFqTPSM4GohXJwqjUwQFEN4-JXDyGRdIBJPHpAakyQtED5uHSYWpoja4BzCak3QlVvBFJfCwnZBQsgNAA) * -1 byte by @Steffan [Answer] # [Desmos](https://desmos.com/calculator), 20 bytes ``` f(m,v)=me^{11.2/v}-m ``` [Try It On Desmos!](https://www.desmos.com/calculator/kvqvae8hof) [Try It On Desmos! - Prettified](https://www.desmos.com/calculator/xszvkvtbsn) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~ 9 ~~ 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) -1 by taking the exhaust velocity in 10ths - thanks [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen)! ``` 112÷Æe’× ``` A dyadic Link that accepts the exhaust velocity on the left, in tenths, and the mass on the right and yields the fuel mass. **[Try it online!](https://tio.run/##y0rNyan8/9/Q0Ojw9sNtqY8aZh6e/v//fyOT/4YGBgAA "Jelly – Try It Online")** ### How? ``` 112÷Æe’× - Link: number v, number m 112 - 112 ÷ - divide by v Æe - Exp(that) ’ - decrement × - multiply by m ``` [Answer] # [I](https://github.com/mlochbaum/ILanguage), 50 bytes I does not have exponentiation, so e^x is approximated with the Taylor series. ``` *H 1/(inf. i+1p2f *.r)*(11.2/]. *p inf.i H]). +.r ``` [Answer] # [Go](https://go.dev), 64 bytes ``` import."math" func f(m,v float64)float64{return m*Expm1(11.2/v)} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70oPX_BzoLE5OzE9FSF3MTMPK7M3IL8ohIFpbTcEqWlpSVpuhY3HSBiekq5iSUZSlxppXnJCmkauTplCmk5-YklZiaaULq6KLWktChPIVfLtaIg11DD0FDPSL9MsxZizi1GDbBWkDUamgrVQINScxSsbBXSuICW6QUUZeaV5ORpGOgZ6BgCMUgWxtHURFECkjbSM4EogXLQlRgYoCiCcbEqg5BICsEkplKQlAmSSigfTaGppTmyOjgXhzIjVGVGQGXQAFuwAEIDAA) [Answer] # [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), ~~10~~ 8 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py) ``` 8D*╠e▬(* ``` Inputs in the order: \$v\_{exhaust}, m\_{end}\$, where \$v\_{exhaust}\$ is taken as a ***float****†* representing tenths (e.g. `24.0`). [Try it online.](https://tio.run/##y00syUjPz0n7/9/CRevR1AWpj6at0dD6/9/QQM9AwYDLyARIGUIpAwMuIDaAMk2gDAyWqaU5l4kRhAEA) **Explanation:** ``` 8D* # Multiply 8 by 14: 112 ╠ # Divide it by the first (implicit) input-float (exhaust speed as tenths) e▬ # Push e (2.718281828459045) to the power this ( # Decrement it by 1 * # Multiply it to the second (implicit) input-integer (mass) # (after which the entire stack is output implicitly as resulting fuel mass) ``` *†* : `/` is used for both integer division (if both arguments are integers) and regular division (if either or both arguments are floats). So I can't take the first input \$v\_{exhaust}\$ as tenths as an integer. [Answer] # [C (gcc)](https://gcc.gnu.org/), 29 bytes ``` #define f(m,v)m*exp(11.2/v)-m ``` [Try it online!](https://tio.run/##jZBha8MgEIa/@yukY6AjcXo9TaR/ZV9KFkugCSXrymDsr88ZU126sa4i3nt374N6TblrGu/vnlvXDS11rC9OvH9o3w5MKQGPJ172vhuOtN92A@PkndCwDmMoOba6dzTup2FVUClkQdV0OJY055u/gegFgROQ9HVAyiWSs1ugc8hYDP@B0YmZS@lVTNtqQX1nt0FwAUGCxvb4Og5UbsiHD6@Ia5rfLFKF5EoYytkjtVgjGG1J/PHv9jpcY7QBvTQspRK1VlAbMk9grmJua0QUBg3WSOLDfxgsgBSoUUm47MMsKmtR2EpLW382br/dvfhy338B "C (gcc) – Try It Online") *Update:* Removed typdef and unnecessary includes. Thanks to @AZTECCO [Answer] # Python, 27 Bytes ``` lambda m,e:m*73130**(1/e)-m ``` [Try it online](https://ato.pxeger.com/run?1=bY9LSsRAEIb3OUUxq-7Qaau7q_oxMN7BvZsMJhjIi5koeJbZDAx6CW_gDeY2xkQFwU1RxffVD__pbXyZHof-fKl3969PU13E97bs9g8ldKradnlwxmGeC3NTyaJbjetdPRyghaaHYax6gXKbQaMG2EFXjqJ6LlvV6uPYNpPYQHELGykzGA9NP4lZU7XIG6nK_VEsWzFIuQafrx8CFRj59YSZMAqspuUyyNqR9YFdisYz04wR_wiO9D_CPFbB6MjGRo-eGIlNWITZ-A5gItKefAgGU0CKmeAUfnCyFjUxGWsdUXK_VNuFh5RIp-ASxohEkddKnw) [Answer] # [BQN](https://mlochbaum.github.io/BQN/), ~~14~~ ~~13~~ 12 bytes *Edit: -1 byte thanks to faun locke* *Edit 2: -1 byte by taking input in tenths of km/s (thanks to [Kevin Cruijssen's comment](https://codegolf.stackexchange.com/questions/252264/its-just-rocket-science#comment561644_252273))* ``` ⊣×1-˜⟜⋆112⊸÷ ``` [Try it at BQN REPL](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAg4oqjw5cxLcuc4p+c4ouGMTEy4oq4w7cKCjEwMCBGIDI0) Exhaust speed given as an integer representing tenths of km/s. Or as a function for 1 more byte: `{𝕨×1-˜⋆112÷𝕩}` ([try it](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAge/CdlajDlzEty5zii4YxMTLDt/Cdlal9CgoxMDAgRiAyNA==)) ``` 11.2⊸÷ # 11.2 divided by right arg ⋆ # exponent of that 1-˜⟜ # one minus that ⊣× # times left arg ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~11~~ 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` žrƵBI/m<* ``` Inputs in the order: \$v\_{exhaust}, m\_{end}\$, where \$v\_{exhaust}\$ is taken as an integer representing tenths. [Try it online](https://tio.run/##yy9OTMpM/f//6L6iY1udPPVzbbT@/zcx4DI0MDAAAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWVCcej/o/uKjm11itDPtdH6r/M/OtrQQMcgVifayETHEEoZgPhA0gDKNAEzoCxTS3MQwwjMiAUA). **Explanation:** ``` žr # Push constant e: 2.718281828459045 ƵB # Push compressed integer 112 I/ # Divide it by the first input (exhaust speed as tenths) m # Take e to the power this < # Decrease it by 1 * # Multiply it to the second (implicit) input (mass) # (after which the resulting fuel mass is output implicitly) ``` [See this 05AB1E tip of mine (section *How to compress large integers?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `ƵB` is `112`. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), ~~9~~ 8 bytes ``` ⁺»?/∆e‹* ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJB4biLIiwiIiwi4oG6wrs/L+KIhmXigLkqIiwiIiwiMjQsMTAwIl0=) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 18 bytes ``` I×N⊖X≕math.e∕¹¹·²N ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEIyQzN7VYwzOvoLTErzQ3KbVIQ1NHwSU1uSg1NzWvJDVFIyC/HCjonloSlliUmZiUk6qhlJtYkqGXqgRSmFmWmZKqYWioZ6SjgGIIBFj//29qac5lomf0X7csBwA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` N First input as a number × Multiplied by ≕math.e Python variable `math.e` X Rasied to power ¹¹·² Literal number `11.2` ∕ Divided by N Second input as a number ⊖ Decremented I Cast to string Implicitly print ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 9 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Takes mass as the first input and speed, represented as tenths, as the second. ``` nU*Me#p/V ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=blUqTWUjcC9W&input=NTk3CjQy) ``` nU*Me#p/V :Implicit input of integers U=mass & V=speed n :Subtract U from U* : U multiplied by Me : Euler's Constant raised to the power of #p : 112 /V : Divided by V ``` [Answer] # [Python](https://www.python.org), ~~45~~ 43 bytes ``` lambda m,e:m*math.exp(11.2/e)-m import math ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3tXMSc5NSEhVydVKtcrVyE0sy9FIrCjQMDfWM9FM1dXO5MnML8otKFEAyEC0bCooy80o00jQMdRSM9Ew0NSHCCxZAaAA) Uninteresting answer. --- -2 bytes from @att [Answer] # MATLAB, 45 bytes ``` function y=fuel(m,v) y=m*(exp(11.2/v)-1); end ``` ]
[Question] [ # Background In programming, there is a recursive algorithm called [binary exponentiation](https://en.wikipedia.org/wiki/Exponentiation_by_squaring), which allows for large integer powers to be calculated in a faster way. Given a non-zero base \$x\$ and a non-negative exponent \$n\$, the algorithm goes something like this (based on the example code from [Wikipedia](https://en.wikipedia.org/wiki/Exponentiation_by_squaring#Recursive_version)): ``` Function exp_by_squaring(x, n) if n = 0 then return 1; else if n is even then return exp_by_squaring(x * x, n / 2); else if n is odd then return x * exp_by_squaring(x * x, (n - 1) / 2); ``` Basically, the code "reduces" the exponent term by first checking whether the current exponent is odd or even, then if it is even, just square root it; otherwise, divide by the base then square root it. Then repeat until the exponent reaches \$0\$. If the exponent is initially \$0\$, then just return \$1\$ directly. This allows for an exponent term to be calculated faster than just multiplying the base by itself one at a time. # Example Here is an example of the algorithm being applied on \$x=3,n=21\$. 1. \$n=21\$ is odd and non-zero, so we divide by the base, then square root. In this case, the number reduces to \$\sqrt{\frac{3^{21}}3}=3^{10}\$. 2. \$n=10\$ is even and non-zero, so we simply take the square root. \$\sqrt{3^{10}}=3^5\$. 3. \$n=5\$ is odd and non-zero, so we divide by the base, then square root. \$\sqrt{\frac{3^5}3}=3^2\$. 4. Continuing the process, we get \$3^1\$ then \$3^0\$, after which the recursion stops. # Task Notice how at each step in the example above, we have a value which resulted from reducing the original number. Your task is to return a list of these numbers, given a non-zero integer base \$x\ne-1\$ and a non-negative integer exponent \$n\$. The list should always contain the initial value as the first element. The list can be returned in reverse order if you want to. # Test Cases ``` x, n -> Output 3, 21 -> [10460353203, 59049, 243, 9, 3, 1] 1000, 0 -> [1] 2, 15 -> [32768, 128, 8, 2, 1] 1, 40000 -> [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] 21, 3 -> [9261, 21, 1] 2, 30 -> [1073741824, 32768, 128, 8, 2, 1] ``` --- This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins! [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 5 bytes ``` ‡½⌊↔e ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJBUCIsIiIsIuKAocK94oyK4oaUZSIsIiIsIjIxLCAzXG4wLCAxMDAwXG4xNSwgMlxuNDAwMDAsIDFcbjMsIDIxIl0=) Takes inputs in reverse order. # [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes ``` HḞ$Ƭ*@ ``` [Try it online!](https://tio.run/##y0rNyan8/9/j4Y55KsfWaDn8///fyPC/MQA "Jelly – Try It Online") Takes inputs in reverse order. ## Explanation ``` HḞ$Ƭ*@ Dyadic link f(n, x) Ƭ Repeatedly apply on n until the results are no longer unique $ Last two links as a monad: H Halve Ḟ Floor *@ x to the power of each ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes ``` :Ƭ2*@ ``` [Try it online!](https://tio.run/##y0rNyan8/9/q2BojLYf///8bGf43BgA "Jelly – Try It Online") Takes `n` on the left, and `x` on the right. Based on [Steffan's answer](https://codegolf.stackexchange.com/a/249464/66833), so be sure to give them an upvote as well. ## How it works ``` :Ƭ2*@ - Main link. Takes n on the left and x on the right Ƭ - Repeatedly apply until a duplicate value is found: : 2 - Floor divide n by 2 *@ - Raise x to each power ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 7 bytes ``` bη0šÙCm ``` [Try it online!](https://tio.run/##yy9OTMpM/f8/6dx2g6MLD890zv3/38iQyxgA "05AB1E – Try It Online") ``` b convert the exponent to binary η takes all prefixes 0š append the prefix "0", to include 1 in the list Ù uniquify, since if the exponent was 0 then "0" was already a prefix C convert each prefix from binary to a number m exponentiation ``` # [05AB1E](https://github.com/Adriandmen/05AB1E), 7 bytes ``` ·.Γ;ï}m ``` [Try it online!](https://tio.run/##yy9OTMpM/f//0Ha9c5OtD6@vzf3/38iQyxgA "05AB1E – Try It Online") A port of the Vyxal and Jelly answer [Answer] # [JavaScript (Node.js)](https://nodejs.org), 30 bytes ``` x=>g=n=>[x**n,...n?g(n>>1):[]] ``` [Try it online!](https://tio.run/##ZctBCoAgEIXhfSeZiRLN2gTaQcJFlEoRY1REt7dahtvv/W8ZruEY93k7SwqTjU7FW2mvSOn@znMqGGPUeSCtBba9MXEMdITVsjV4cCARKoGY/VVwzhFSr15s0hqh/g5J/Q4SMT4 "JavaScript (Node.js) – Try It Online") [Answer] # [PARI/GP](https://pari.math.u-bordeaux.fr), 34 bytes ``` f(x,n)=[x^m\=2|i<-binary(m=2*n+1)] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMGCpaUlaboWN5XSNCp08jRtoyvicmNsjWoybXSTMvMSiyo1cm2NtPK0DTVjoSpDEwsKcio1EhV07RQKijLzSoBMJRBHSSE5MSdHI01HIVFTU0chOtpYx8gwFsgwNDAw0DEAsYx0DE3BIjomQDGIkKGOcWysJsRwmHMA) --- # [PARI/GP](https://pari.math.u-bordeaux.fr), 29 bytes ``` f(a,n)=if(n,f(a,n\2)*x+a^n,1) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMGCpaUlaboWe9M0EnXyNG0z0zTydMDsGCNNrQrtxLg8HUNNiJqboYkFBTmVGokKunYKBUWZeSVAphKIo6SQnJiTo5Gmo5CoqamjEB1trGNkGAtkGBoYGOgYgFhGOoamYBEdE6AYRMhQxzg2Fmo4zCEA) This returns a polynomial whose coefficients are the results. [Answer] # [C (GCC)](https://gcc.gnu.org), ~~66~~ 53 bytes *-13 bytes thanks to [@att](https://codegolf.stackexchange.com/users/81203/att)* ``` r;f(x,n){printf("%d ",r=n?f(x,n/2),(n%2?x:1)*r*r:1);} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=NU9LCoMwEF3HUwyCkGhKE61Qmoo38AIipVhSsmgqUUEQL9ArdNONh-ptOordzDzej5n3XF_udf35zH2nd8dv6pSmA7dsbJyxnaZ-cAOfu8zmK7-PGac2iPPhJFnoQodLTVv49bgaS9noEYxCARmkHIa2rBCNCQcphOAQI8ApJw5202IkUJFoP4jVlEzKI_rp6NJkMqHAnAsFUWSWeoK3tKWp1gZTMfSSpu9a6vsLnrztov9bPw) [Answer] # Desmos, 42 bytes ``` f(x,n)=x^{floor(n/2^{[0...ceil(log_2n)]})} ``` [Try it on Desmos!](https://www.desmos.com/calculator/wsjsxxrck0) [Answer] # [Python 2](https://docs.python.org/2/), 37 bytes (-1 @Steffan, -2 @dingledooper) ``` f=lambda x,n:[1][n:]or[x**n]+f(x,n/2) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=lY9NasMwEIX3PsUQKMiu4kryT2NDehGjhVrbRGBLQlJLcpZuvCk9S4-Q23ScpNkXhpnR9-bNoM9vd4oHa8SyfL3Hcbs7P4z7Sc2vvYIjNW3HZWdaaX13zDIjH0eC9Emkt-E3PTvrI4RTSEbrYdJmAG3Wdx5ir03uB9WvNJC0TUBTC3uYlSPDh5roKuTBTTqSDWxfYJOmCTivTSSajiTTKbW3U8v5BwAKCoJjXYc7zsqaFVUhGOKqYWWDaok9VsxcJpwxRoHB3SET7ARq1R8qxHO9QyAwYYiLDzVOoUQ3u_oo_C_WFQKb4n66ETWnF8bl9Ue_) ### Old [Python](https://www.python.org), 40 bytes ``` f=lambda x,n:[x**n]+(n*[n]and f(x,n//2)) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=lY9BbsIwEEX3OcWIlZ0aGNtJSpDoMbqJvHCVWLUUbCsERM_STTbtXXoEbtMJUPaVRjNf788fy5_f6WN8j2Gavo6jW24uzO16u39rLZxF2DbnPA_miYW8CcaGFhwjvF4rzu_7ry4O0PvQgQ8QUxcY8tXQ2XZmB8a3GXgRYQd7m1h3sr2YjdUh9X5kC1i-wILzDNLgw8i8cCz3XMT79enyAwBagJI05-VGYlGhLrVCwmWNRU1uQZomdWkyiYgCEB4Jk5FS5JV_SKvnakNAUaNS1xx5UkBBabzlBPyv5hOKhH48XatKiiuT5vajXw) Doesn't actually implement the algorithm. But produces correct output. [Answer] # Java, 59 bytes ``` x->n->{for(n*=2;n>0;)System.out.println(Math.pow(x,n/=2));} ``` [Try it online!](https://tio.run/##bY69TsMwFIVn8hQe7aoxEIkpxAtSpQ6dOiIG4zrBwb627OvSKsqzBwNhgrvd7@j8jPIs6/H0vhgXfEQylp9nNJb3GRQaD3zTVn/E/1jCqKX7kkJ@tUYRZWVK5CANkKki5RJKLHy3Jj/uAfWg45Y8eUjZ6fhLhCB9t1xqAbWYeh8pbLqmBXHXsuM1oXbcZ@QhGkAL9CDxjQf/QS9buO0axtp5ab8L1yFr79mbE3FlDj1isQ7PL0TGIbGpuum5DMFeacO4VEoHpPcP7CdjrublEw) [Answer] # [BQN](https://mlochbaum.github.io/BQN/), 16 bytes ``` ⊣⋆{×𝕩?𝕩∾𝕊⌊𝕩÷2;0} ``` [Try it at BQN REPL](https://mlochbaum.github.io/BQN/try.html#code=QmluRXhwIOKGkCDiiqPii4Z7w5fwnZWpP/CdlaniiL7wnZWK4oyK8J2VqcO3MjswfQozIEJpbkV4cCAyMQo=) ``` { } # Recursive function acting on right argument 𝕩 : ? # if ×𝕩 # sign of 𝕩 is non-zero 𝕩∾ # join 𝕩 to 𝕊 # the result(s) of a recursive call to this function # with argument: ⌊ # floor of 𝕩÷2 # 𝕩 divided by 2. # Now, get ⊣ # the left argument ⋆ # raised to these powers ``` [Answer] # [Prolog (SWI)](http://www.swi-prolog.org), 45 bytes ``` _*0*[1]. X*N*[P|R]:-P is X^N,T is N//2,X*T*R. ``` [Try it online!](https://tio.run/##KyjKz8lP1y0uz/z/P17LQCvaMFaPK0LLTys6oCYo1ko3QCGzWCEizk8nBMTw09c30onQCtEK0vtvr6tgpGVoquWoo1BQlJlXouGoqfcfAA "Prolog (SWI) – Try It Online") [Answer] # x86-64 machine code, 24 bytes Or 1 less for 32-bit mode, with 1-byte `dec ecx`. If anyone has any other ideas for golfing further, please comment; I expect there's room for improvement. A straightforward binary exponentiation that doesn't have to produce the exact same proof-of-"work" array output is only 19 bytes. ### Actually implements a binary-exponentiation algorithm, not doing a separate `pow` for every output element. Only one or two other answers do this, and I think this is the only iterative (non-recursive) one of those. This is a function that takes an output pointer in RDI, to an array of DWORDs. `x` in ESI, `n` in EBX. (EDX is clobbered by `mul`. This can be signed if you want; `mul` and `imul` are the same binary operation *on EAX*, differing only in the EDX high half. They're the same size.) Outputs: Array of steps in the memory the caller passed, RDI points to one-past-end. EAX = `x**n`. trimmed NASM listing: address, machine-code (the answer), source ``` expint: ; uint32_t *out (rdi), x = esi n = ebx 00 6A01 push 1 02 58 pop rax ; mov eax,1 03 AB stosd ; *rdi++ = eax 04 0FBDCB bsr ecx, ebx ; bit-scan-reverse. we need to loop bits high to low; a set bit cares about (gets squared by) how many bits are *below* it, not above. ; ECX = bit-index of highest set bit 07 740E jz .n0 ; exponent=0 is a special case .loop: 09 F7E0 mul eax ; square total 0B 0FB3CB btr ebx, ecx ; bit-test-reset. Or just BT, clearing n as we go wasn't helpful. 0E 7302 jnc .was_even 10 F7E6 mul esi ; total *= x; (destroys EDX with the high-half result, but this saves a byte vs. imul eax, esi) .was_even: 12 AB stosd 13 FFC9 dec ecx 15 7DF2 jge .loop ; }while(--bitpos >= 0); // loop runs for ECX=0, can't use LOOP unless we left-shifted EBX or something .n0: 17 C3 ret size: 0x18 = 24 bytes ``` It feels like there should be room to golf more, but it's tricky to cover the corner cases (like `n==0` is costing 2 bytes) and the off-by-ones (e.g. having to run the loop body for ECX=0 means I can't use `loop`). Starting with `1` isn't as much of a burden as I'd thought it might be, mostly just requiring an extra `stosd` to output before the first multiply and after the last. We need to start with the MSB, not LSB, so we always have a `1` bit so the first iteration can do `1*1 * x` to get us started with total=x. That does let us fall into the loop with `total=1` after all. If not for having to store the `n`, though, I'd likely start with EAX=`x` and adjust the loop somehow. (The test-case I asked for with a non-trivial even power turned out not to be relevant for this; I hadn't realized you needed to start from the high end for an iterative version. But it makes sense if you think about it: a `1` in the lowest bit of `n` results in a `*x` at the end. But if you do that at the *start*, a bunch of squaring happens so that odd power becomes an even power. If you just `shr ebx, 1` / `jnc` to divide by 2 and check for odd/even, you'd effectively be bit-reversing the exponent, or something like that. Which works for exponents like `15` that have no significant zeros, but not others.) **Update: you don't have to start from the MSB, I just had a brain fart**: the normal algorithm would do `x *= x;` every iteration, only multiplying it into the total for set bits in `n`. The algorithm is identical to multiplication by shifting-and-adding, in case it helps to think about how adding partial products works. ([Stepanov's lectures on algorithms](https://youtu.be/PtGVOGui7q4?t=230) uses binary exponentiation as one of the main examples, pointing out that replacing `+` with `*` makes exponentiation instead of multiplication.) This question's presentation in terms of square-rooting the total in reverse got me stuck on squaring the total instead of x, and if you do that then you have to go from MSB downward. No CPU I'm aware of has an integer sqrt instruction, or a single-instruction `pow` to give a starting point. (x87 has some exponential stuff, but takes multiple instructions to do pow. Still maybe worth considering. Hopefully we can still recover all the same intermediate values this question wants, while doing `shr ecx,1` / `jnc`. But that would make starting with `1` inconvenient. --- BMI2 `mulx` is a 5-byte instruction, so even if we could reuse FLAGS to save a dec or test, it wouldn't pay for itself. [Try it online!](https://tio.run/##xVXBjuJGEL37K15OmWGAwbC7kQaRSLMzySXKrpIcRooi1LYLbNJ0O@42mEj59tmqbsCQ1UrJKZYAu1xd9epV1UM5R9tMH0ZGue3rK3V1ZfwD5mj5dzZdegxs63HTFNXtEOiwALkKgJG7rEv4FnXrSqTx1tZAozocr7l8be0OpLphdHHeugL9xS4DDn93JxFVjJi5BqC8G0qO4LMnGKIC3kJbTpJV3qGs1mW07OdQcOTFjlw15KCygHxN7Oj@bNlWIDvcorR7bJU5xBBsxiAjjjBA5Ycw1svJHY0TfHbN8fz@hWHyyVFlCupgVwEEOX/KHo5t/uKvsZn0B5lZa8j4xQSVE6w15ZXSjNVRMpaSHsLJbashNByPReBco1c6MuOFmUyYybtrbLbBpmUgj78OkWtSTWXW3CflhLy1xV4587VHSbpetTrWtzE5xvxiSTsyseKIIDRZoobUGCzQSS9vCi61sQeH56cX7CvP/JcUOBiVSq/AzLeaecyYe19yqU7tpBlMvSfs3BiVJJBxkCS3yTn7Qz8d4a6gPMxAxLkmBJaOqP7el5Wmm9GIGa@tw7cLTG4Z4P19HI@mNQ4rZoQbtpgwH0pKbx3hxw8fPqI1mlzgRdPKj1xZrTyPx/Pji7Do7JYYu1kn3MIIqyH/OmcypNG50pqaMfBkKTBaM9MePG11y5U7Pqhp5DzVPFGoDH54ekwSpau1QfouWWubMaNL51Xjk/hzrL3N0Lh6iDeTSXJaHF6NoViTfpUcW9IJ@/QmWZX@TPCY9o8yLunb8CzgEdc8@TzHVYDZdYBpGqdsR82K18WdJaKHcUp8YQip3/3X1Ok317kvSguVdul09ubtefJDW5y2dX3A4y8/c1PVToZfRYXgAal8taM4Grltjf8yIJnM6ewoVQcnPkmSRK/lLl1mjf2Dh/XfSuRxfv@hg/ML2Zxf6mZ8smf1O1k22/piT4OJi4xOvzV5d8cf3CH9/aoOAXLeJYEy71fsqDnz66ULy998WX5ceYKWynuD@wWmXPX777lYqwuR4l4Fr8WF9yckXbIMNoeHC@USvVtwxEFgbjweQ5lCUDX0HfCTrWl4Vv9gPf7bRLT/v1SF@YsNO@mV4X@AUG1kuDJHMYutkzns5Uywb3Ajgv6V6FgwzaaibdzKguC2QXJOSpS8fgI "Assembly (nasm, x64, Linux) – Try It Online") with `_start` test caller (doesn't print: use GDB `display *(int[8]*)($rsp+8)` to display the output array state as you single-step, given that the caller passes RDI=RSP as the output.) ### 19 bytes, different array from a more normal algorithm: ``` expint_v2: ; uint32_t *out (rdi), x = esi n = ebx push 1 pop rax ; mov eax,1 stosd .loop: ;do{ shr ebx, 1 ; n /= 2, CF = old low bit jnc .was_even mul esi ; total *= x; (destroys EDX with the high-half result, but this saves a byte vs. imul eax, esi) .was_even: stosd ; *out++ = eax imul esi, esi ; square x test ebx, ebx jnz .loop ;}while(n!=0); ret ``` Same inputs as before, same result in EAX and the highest array element (since the last bit shifted out before it becomes zero is a `1`, unless `n=0` in which case we leave the loop without having done `mul esi`.) e.g. for 3^21 it produces these steps, where `1870418611` is 3^21 mod 2^32. ``` {1, 3, 3, 243, 243, 1870418611} ``` The `x*=x` steps where `n` doesn't have a set bit don't change the running product. (Like for multiply by addition, where you're not adding a partial product at that shift.) I don't think it's possible to recover the same proof-of-work temporaries from this (even with a `mov`/`imul` into another temp), because we're working from the low bit up, not from the high bit down. Starting with `1` is actually helpful, since we actually need to *not* start with `total = x` if `n` is even, but after we square x this iteration we no longer have any odd power of the original `x` left to multiply by, so the total would remain an odd power. Starting with `total=1` also makes the n=0 case Just Work for free. Anyway, this order of temporaries is perhaps less interesting, but could probably also be recovered from a recursive implementation. I'm curious whether another challenge, perhaps titled iterative binary exponentiation, would get different answers in other languages. Probably still easier to use `**` or `^` built-ins in languages that have them, after generating the right array of what, prefix-sum of bit-indices of non-zero bits or something? [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 69 bytes ``` ^ 1, \d+$ * +`(.+),(.+),\b(_*)\3(_?) $1¶$.($($.4*$2,1)***),$2,$3 ,.+ ``` [Try it online!](https://tio.run/##HYwxCsNADAT7fYcCkk4cJ59Tu8wnjtgJSZHGhfHb/AB/7CzSDDuwzPbdf@vL@40fS3/CDe2TCIq0cE5if7Q3zyqt8jwJyM@DMhNTHpUGc1FVsVhUYTmhE86jVxscXkqxgjjdIz2GhbjVCw "Retina – Try It Online") Link includes test cases. Outputs the list in ascending order. Explanation: ``` ^ 1, ``` Prefix a `1` which is the working value for the result. ``` \d+$ * ``` Convert `n` to unary. ``` (.+),(.+),\b(_*)\3(_?) ``` Match the previous result, `x`, `n/2` and `n%2`. ``` $1¶$.($($.4*$2,1)***),$2,$3 ``` Keep a copy of the previous result, then square it and multiply it by `x` or `1` depending on whether `n` was odd. (Retina only uses the first integer it finds in a string, so multiplying `3,1`, `59049,3,_` and `59049,3,_` is equivalent to multiplying `3`, `59049` and `59049`.) Append `x` and `n/2` for the next pass through the loop. ``` +` ``` Repeat the above until `n=0`. ``` ,.+ ``` Delete `x`. Retina doesn't have exponentiation. Retina 1 does however have both eval and multiplication, so exponentiation can be (slowly) performed in 30 bytes: ``` ~`(.+),(.+) .+¶$$.($2*$($1$*)_ ``` [Try it online!](https://tio.run/##K0otycxLNPyvquGe8L8uQUNPW1MHRHDpaR/apqKip6FipKWioWKooqUZ//@/sY6RIZehgYGBjgGXkY6hKZehjgmQB@QY6hgDAA "Retina – Try It Online") Link includes examples. [Answer] # [Husk](https://github.com/barbuz/Husk), 6 bytes ``` M^U¡÷2 ``` [Try it online!](https://tio.run/##yygtzv7/3zcu9NDCw9uN/v//b2Tw3xgA "Husk – Try It Online") Another port of [Steffan's answers](https://codegolf.stackexchange.com/a/249464/95126): upvote those. ``` ¡ # Apply function repeatedly, collect values in infinite list: # (using arg1 as starting value) ÷2 # Integer-divide by 2 U # Longest prefix with all unique elements M # Map over this: ^ # arg2 to the power of this ``` [Answer] # [APL (Dyalog Unicode)](https://dyalog.com), 20 bytes [SBCS](https://github.com/abrudz/SBCS) ``` {⍵=0:1⋄(⍺*⍵),⍺∇⌊⍵÷2} ``` [Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=q37Uu9XWwMrwUXeLxqPeXVpArqYOkPGoo/1RTxeQd3i7US0A&f=M1JIUzA0BQA&i=AwA&r=tryapl&l=apl-dyalog&m=dfn&n=f) -2 bytes thanks to Vadim Tukaev [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 18 bytes ``` IXθE⊕L↨η²↨²✂↨粦⁰ι ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEIyC/PLVIo1BHwTexQMMzL7koNTc1ryQ1RcMnNS@9JEPDKbE4VSNDR8FIU1NTRwHMM9JRCM7JTE5FktNRMNBRyNQEA@v//6ONgYKGsf91y3IA "Charcoal – Try It Online") Link is to verbose version of code. Outputs the list in ascending order (+1 byte to output in the order given in the question). Explanation: ``` θ First input `x` X Vectorised raised to power η Second input `n` ↨ ² Converted to base 2 L Take the length ⊕ Incremented E Map over implicit range η Second input `n` ↨ ² Converted to base 2 ✂ ⁰ Sliced to length ι Current value ↨² Converted from base 2 I Cast to string Implicitly print ``` Although Charcoal's `BaseString()` function would convert `0` to `"0"`, its `Base()` function returns an array rather than a string, and this array is empty when `n=0`, so it doesn't have the problem that, say, the 05AB1E answer has. Instead, it has the problem that `CycleChop([], 0)` throws a `ZeroDivisionError`, so I have to use `Slice()` instead. ]
[Question] [ A [Gray code](https://en.wikipedia.org/wiki/Gray_code) is a permutation on binary numbers where incrementing or decrementing a number only ever causes a single bit to change. For example, a Gray code for the binary numbers up to 7 (so, with 3 bits) are: ``` 000 001 011 010 110 111 101 100 ``` You can see that only one bit is different between each consecutive pair. This is only one valid 3-bit Gray code; others are possible by permuting the columns or reversing the list. An [\$ N \$-ary Gray Code](https://en.wikipedia.org/wiki/Gray_code#n-ary) is a generalised Gray code which operates on \$ N \$ symbols instead of just two. For example, a Gray code with \$ N = 3 \$, and of length 2: ``` 00 01 02 12 11 10 20 21 22 ``` Note that a single digit can change up or down by more than one from one step to the next. For example, the following **is allowed**: (as a partial output for \$ N = 4 \$, \$ k = 3 \$) ``` 001 003 ``` Here is another possible output, which is also allowed: ``` 21 22 20 00 10 11 01 02 12 ``` ## Task Given two integers, \$ N \$ and \$ k \$, output an \$ N \$-ary Gray code of length \$ k \$. You may output using any consistent set of \$ N \$ distinct symbols; they don't necessarily have to be digits or integers. You may assume both \$ N \ge 2 \$ and \$ k \ge 2 \$. There are multiple orderings for all inputs; you only need to output at least one of these, but you may output multiple. ## Test cases I list only one possible output for each. ``` N k output 2 2 00, 01, 11, 10 3 2 00, 01, 02, 12, 11, 10, 20, 21, 22 2 3 000, 001, 011, 010, 110, 111, 101, 100 5 2 00, 01, 02, 03, 04, 14, 10, 11, 12, 13, 23, 24, 20, 21, 22, 32, 33, 34, 30, 31, 41, 42, 43, 44, 40 4 4 0000, 0001, 0002, 0003, 0013, 0010, 0011, 0012, 0022, 0023, 0020, 0021, 0031, 0032, 0033, 0030, 0130, 0131, 0132, 0133, 0103, 0100, 0101, 0102, 0112, 0113, 0110, 0111, 0121, 0122, 0123, 0120, 0220, 0221, 0222, 0223, 0233, 0230, 0231, 0232, 0202, 0203, 0200, 0201, 0211, 0212, 0213, 0210, 0310, 0311, 0312, 0313, 0323, 0320, 0321, 0322, 0332, 0333, 0330, 0331, 0301, 0302, 0303, 0300, 1300, 1301, 1302, 1303, 1313, 1310, 1311, 1312, 1322, 1323, 1320, 1321, 1331, 1332, 1333, 1330, 1030, 1031, 1032, 1033, 1003, 1000, 1001, 1002, 1012, 1013, 1010, 1011, 1021, 1022, 1023, 1020, 1120, 1121, 1122, 1123, 1133, 1130, 1131, 1132, 1102, 1103, 1100, 1101, 1111, 1112, 1113, 1110, 1210, 1211, 1212, 1213, 1223, 1220, 1221, 1222, 1232, 1233, 1230, 1231, 1201, 1202, 1203, 1200, 2200, 2201, 2202, 2203, 2213, 2210, 2211, 2212, 2222, 2223, 2220, 2221, 2231, 2232, 2233, 2230, 2330, 2331, 2332, 2333, 2303, 2300, 2301, 2302, 2312, 2313, 2310, 2311, 2321, 2322, 2323, 2320, 2020, 2021, 2022, 2023, 2033, 2030, 2031, 2032, 2002, 2003, 2000, 2001, 2011, 2012, 2013, 2010, 2110, 2111, 2112, 2113, 2123, 2120, 2121, 2122, 2132, 2133, 2130, 2131, 2101, 2102, 2103, 2100, 3100, 3101, 3102, 3103, 3113, 3110, 3111, 3112, 3122, 3123, 3120, 3121, 3131, 3132, 3133, 3130, 3230, 3231, 3232, 3233, 3203, 3200, 3201, 3202, 3212, 3213, 3210, 3211, 3221, 3222, 3223, 3220, 3320, 3321, 3322, 3323, 3333, 3330, 3331, 3332, 3302, 3303, 3300, 3301, 3311, 3312, 3313, 3310, 3010, 3011, 3012, 3013, 3023, 3020, 3021, 3022, 3032, 3033, 3030, 3031, 3001, 3002, 3003, 3000 11 2 0 0, 0 1, 0 2, 0 3, 0 4, 0 5, 0 6, 0 7, 0 8, 0 9, 0 10, 1 10, 1 0, 1 1, 1 2, 1 3, 1 4, 1 5, 1 6, 1 7, 1 8, 1 9, 2 9, 2 10, 2 0, 2 1, 2 2, 2 3, 2 4, 2 5, 2 6, 2 7, 2 8, 3 8, 3 9, 3 10, 3 0, 3 1, 3 2, 3 3, 3 4, 3 5, 3 6, 3 7, 4 7, 4 8, 4 9, 4 10, 4 0, 4 1, 4 2, 4 3, 4 4, 4 5, 4 6, 5 6, 5 7, 5 8, 5 9, 5 10, 5 0, 5 1, 5 2, 5 3, 5 4, 5 5, 6 5, 6 6, 6 7, 6 8, 6 9, 6 10, 6 0, 6 1, 6 2, 6 3, 6 4, 7 4, 7 5, 7 6, 7 7, 7 8, 7 9, 7 10, 7 0, 7 1, 7 2, 7 3, 8 3, 8 4, 8 5, 8 6, 8 7, 8 8, 8 9, 8 10, 8 0, 8 1, 8 2, 9 2, 9 3, 9 4, 9 5, 9 6, 9 7, 9 8, 9 9, 9 10, 9 0, 9 1, 10 1, 10 2, 10 3, 10 4, 10 5, 10 6, 10 7, 10 8, 10 9, 10 10, 10 0 ``` ## Rules * You may use any [standard I/O method](https://codegolf.meta.stackexchange.com/q/2447) * For compactness in the test-cases, when \$ N \le 10 \$, I've squished the output digits together. However, your output format must always have an unambiguous separation of the digits when \$ N > 10 \$ * [Standard loopholes](https://codegolf.meta.stackexchange.com/q/1061) are forbidden * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins [Answer] # [BQN](https://mlochbaum.github.io/BQN/), 12 bytes[SBCS](https://github.com/mlochbaum/BQN/blob/master/commentary/sbcs.bqn) Based on an algorithm [given on Wikipedia](https://en.wikipedia.org/wiki/Gray_code#n-ary_Gray_code). Takes `k` as left and `N` as right argument. ``` ‚ä¢|-‚üú¬ª¬®‚àò‚•ä‚àò‚Üï‚àò‚•ä ``` [Run online!](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAg4oqifC3in5zCu8Ko4oiY4qWK4oiY4oaV4oiY4qWKCgpyZXN1bHRzIOKGkCDin6gKMiBGy5wgMgozIEbLnCAyCjIgRsucIDMKNSBGy5wgMgo0IEbLnCA0CjEwIEbLnCAyCuKfqQoKIyBBc3NlcnQgYWxsIHJlc3VsdHMgYXJlIHZhbGlkIGdyYXkgY29kZXM6CklzR3JheSDihpAgeyjwnZWp4omh4o238J2VqSniiKfCtDE9K8udy5h8w5ctwrTLmDLihpXwnZWpfQoh4oinwrQgSXNHcmF5wqggcmVzdWx0cwoK4oiY4oC/MeKlinJlc3VsdHMK) `‚•ä‚àò‚Üï‚àò‚•ä` Generate a list of all base-`N` numbers of length `k`. Then each number is transformed to Gray code, lets look at an example: ``` N=3, k=3, number is 2 1 2 -‚üú¬ª # Shift a 0 into the number and subtract that from the number. 2 1 2 - 0 2 1 ‚Üí 2 ¬Ø1 1 ‚ä¢| # modulo N; This relies on Python-like modulo, otherwise you might need to add N before 3 | 2 ¬Ø1 1 ‚Üí 2 2 1 ``` Slightly ungolfed: ``` {k ùïä n: n|{ùï©-¬ªùï©}¬®‚•ä‚Üïk‚•än } ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 10 bytes ```  Å√û·∫ä·πñ'¬Ø:fTl ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLKgcOe4bqK4bmWJ8KvOmZUbCIsIiIsIjNcbjIiXQ==) ``` ·πñ' # Find all permutations of... √û·∫ä # Cartesian power of input and...  Å # Range(input) ' # Where... ¬Ø # Differences (vectorising) : l # Length is unchanged when... fT # Flattening and getting truthy indices. ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ·πó@≈ª‚ǨI% ``` A dyadic Link that accepts the length, \$k\$, on the left and the number of symbols, \$N\$ on the right and yields a list of lists of non-negative integers. **[Try it online!](https://tio.run/##y0rNyan8///hzukOR3c/alrjqfr//3/j/6YA "Jelly ‚Äì Try It Online")** ### How? This is the same cyclic Gray code that the algorithm displayed on [Wikipedia](https://en.wikipedia.org/wiki/Gray_code#n-ary_Gray_code) will produce (for values \$[1,N^k]+[0]\$) with each result reversed. ``` ·πó@≈ª‚ǨI% - Link: k, N @ - with swapped arguments: ·πó - [1..N] Cartesian product [1..k] ≈ª‚Ǩ - prefix a zero to each I - incremental differences % - modulo N ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 45 bytes ``` Mod[#-{0,##&@@Most@#}&/@Range@#~Tuples~#2,#]& ``` [Try it online!](https://tio.run/##RchLCsIwFEbhrVz4IaMUa4pD5W6gINJZyCBoqgX7wKajS7r1aEVwdPhO7@Mj9D52V59bOuZ6vFkUUmpAMdfjHBlJ7fjih3tgrM0yPcO8wmg4lc@vbohWgETFiVoLOEeKmJlEjCaTNEn168fV1sP/f70vt5HyGw "Wolfram Language (Mathematica) ‚Äì Try It Online") A port of [@ovs's BQN answer](https://codegolf.stackexchange.com/a/243887/9288). --- # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 59 bytes ``` IntegerDigits[FindHamiltonianPath@GridGraph@Table@##-1,##]& ``` [Try it online!](https://tio.run/##RYqxCsIwEEB/5eCgUwq2xVG5QaxuHdxCh9Om7UETJWYL/faYiuD0eI9nOczGcpAHpxEO6eqCmYw/ySThrc/ihgtbWcLTCbsuz9R6GVrPr5lufF8MIZaVQuyL1HlxQUfEFcojjDrHHgogIoixVlCvCmLzY/Zm4/7fv17ttrCmDw "Wolfram Language (Mathematica) ‚Äì Try It Online") Finds a Hamiltonian path of the \$\underbrace{N\times\cdots\times N}\_{k}\$ grid graph. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~11~~ ~~10~~ 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` LI√£Œµ0≈°¬•¬π% ``` -1 byte porting [*@ovs*' BQN answer](https://codegolf.stackexchange.com/a/243887/52210), using the approach [described on Wikipedia](https://en.wikipedia.org/wiki/Gray_code#n-ary_Gray_code). Inputs in the order \$N,k\$. Outputs a single result using 0-based integers in the range \$[0,N)\$, like the challenge description. [Try it online](https://tio.run/##yy9OTMpM/f/fx/Pw4nNbDY4uPLT00E7V//@NuYwA) or [verify all test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpSbKWgZF@ZUKzkZ3t4v45CNpBU0uFS8i8tAUoC5XSAcodW/vcpPrz43FaDowsPLT20TvV/rc6hbfb/o6ONdIxidaKNwaSRjjGQNAWzTXRMgKShIZATCwA). **Original ~~11~~ 10 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) answer:** ``` LI√£≈ì í√º-ƒÄOP ``` Inputs in the order \$N,k\$. Outputs using 1-based integers in the range \$[1,N]\$, and will output all possible results (and is very slow because of that). [Try it online](https://tio.run/##yy9OTMpM/f/fx/Pw4qOTT006vEf3SIN/wP//xlxGAA) or [verify some of the smaller test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpSbKWgZF@ZUKzkZ3t4v45CNpBU0uFS8i8tAUoC5XSAcv99ig8vPjpZ79yUw3t0jzT4B/yv1Tm0zf5/dLSRjlGsTrQxmDTSMY6NBQA) (with the filter `í` replaced with a find\_first `.Œî` to speed things up a bit). **Explanation:** ``` L # Push a list in the range [1, first (implicit) input N] I√£ # Get the second input k's cartesian product of this list Œµ # Map over each inner k-tuple: 0≈° # Prepend a 0 ¬• # Pop and push the deltas/forward-differences ¬π% # Modulo-N on each value # (after which the list of lists is output implicitly as result) LI√£ # Same as above ≈ì # Get all possible permutations of these k-tuples  í # Filter this list of permutations by: √º # For each overlapping k-tuple: - # Subtract the values at the same positions in the tuples ƒÄ # Check for each that it's NOT 0 (0 if 0; 1 otherwise) O # Sum to get the amount of values that differ per overlapping pair P # Get the product of these sums # (only 1 is truthy in 05AB1E, so only the permutations where each # overlapping k-tuple has a single value different are kept) # (after which the filtered list of k-tuple permutations is output # implicitly as result) ``` [Answer] # JavaScript (ES7), ~~¬†82¬†~~ 78 bytes Expects `(N)(k)`. ``` N=>k=>[...Array(N**k)].map(g=(s=i=k,v)=>i--?[x=~~(s+v/N**i)%N,...g(s-x,v)]:[]) ``` [Try it online!](https://tio.run/##lcy7DoIwFIDh3acgJibncKnh4mJyMK4OODgiA0FoKkhJSwgsvDo2PoCB/fv/dz7kulCi671WvsqloiWhuKY4ZYxdlconSGy7xox98g44gSZBtTsgxcLzLulI8wzaGY5GCTwkrsk4aG80JDunGS6FbLVsStZIDrfHPWG6V6LlopqgAitACBAtx9o/2z3u/uNwCzbncDU@bTlHCNFa7Pu/My5f "JavaScript (Node.js) ‚Äì Try It Online") ### Commented This is based on [the algorithm given on Wikipedia](https://en.wikipedia.org/wiki/Gray_code#n-ary_Gray_code). ``` N => // N = number of symbols k => // k = code length [...Array(N ** k)] // build an array of N ** k entries .map(g = ( // g is a recursive callback function taking: s = // s = step \__ initially set to k i = k, // i = position / // NB: we should start with s = 0, but since // we're working modulo N, it actually // doesn't matter v // v = current value in [0 .. N ** k - 1] ) => // i-- ? // decrement i; if it was not 0: [ // update the output: x = // define x as: ~~(s + v / N ** i) // floor(s + v / N ** i) % N, // modulo N ...g(s - x, v) // append the result of a recursive call // with s - x and v unchanged ] // end of output update : // else: [] // stop the recursion ) // end of map() ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~30~~ ~~29~~ 28 bytes ``` Ժƌ∏Ժƌ∑Ôº©Ôº•Ôº∏Œ∏Œ∑Ôº•√∑ŒπÔº∏Œ∏‚Æå‚Ķ‚Å∞Œ∑‚åäÔπ™‚ü¶‚äñ¬±ŒªŒª‚üß‚äóŒ∏ ``` [Try it online!](https://tio.run/##TYs9D4MgFEX3/grGZ0KTDm6OZXHQGFfTAeFFSPhQBPvzKaRJ07ude88Vigfhucm5d3uKY7IrBjia7vbPqvAUtIvw5GeEge8w@XcVKVENJbXoXWT60hJBU/JbZ7wwnAgzdxvCo@ol5aGdtsnC4GUyHhaGIqBFF1HCiBuPCKZ65kUJ82k1pT@ab7qcW9Lm@2U@ "Charcoal ‚Äì Try It Online") Link is to verbose version of code. Outputs each digit of the gray code as a base 10 number on its own line, with each gray code double-spaced from the next. Explanation: ``` Ժƌ∏ Input `N` as a number Ժƌ∑ Input `k` as a number Œ∏ Input `N` Ôº∏ To the power of Œ∑ Input `k` Ôº• Map over implicit range Œπ Current value √∑ Vectorised integer divide Œ∏ Input `N` Ôº∏ Vectorised to power ‚Ķ Range from ‚Å∞ Literal integer `0` Œ∑ To input `k` ‚Æå Reversed Ôº• Map over list Œª Current value ¬± Negated ‚äñ Decremented ‚ü¶ ‚üß List of that and Œª Current value Ôπ™ Vectorised modulo Œ∏ Input `N` ‚äó Doubled ‚åä Take the minimum Ôº© Cast to string Implicitly print ``` [Answer] # [Haskell](https://www.haskell.org/), 59 bytes Uses `[1..N]` for the digits. ``` n!0=[[]] n!k=[a:x|a<-[1..n],x<-iterate reverse(n!(k-1))!!a] ``` [Try it online!](https://tio.run/##RY7BasMwEETv@ooxhCCBnMZpeil2T6Wl0N4CPRhRNkQQEVk2klzckn93JWrIaXfe7s7smcJFWzubbuh9xDNF2rybEMHdeBSzK7ZN2yrFXHFpWnqcrlSXbbXZOCWnujRRe4oaXn9rHzR3Bb@UlRBFQWo@9r099G8u4uBHjQYVu6EXsiGzLWMmvHr6wZRUDs1Ng0lgvQa5E9oq6zB24LfzevWEXzN8mnjmd40A4ShwBSeZal3mGXgkY7PRpBjryLgUcOrBAKtjejmMNobEFh/wQqDdyXu5kw9yL6utyvIf7OVOpcPBmxS@AlmL5e3FJw07Gj6@lpWFzn8 "Haskell ‚Äì Try It Online") This uses a simple recursive construction: Given the Gray code for `k-1`, alternate between this and its reverse for each of the new digits. `iterate reverse x !! a` reverses `x` for odd `a` (and can probably be shortened). The approach is described in more detail [on Wikipedia](https://en.wikipedia.org/wiki/Gray_code#Constructing_an_n-bit_Gray_code). The other approach is a byte longer: ``` n!k=map(`mod`n).(zipWith(-)<*>(0:))<$>mapM(\_->[1..n])[1..k] ``` [Try it online!](https://tio.run/##NY9Bb4MwDIXv/IpXqaqSKbDCuksFnDrtsp13YKh1BVMjkoBIkNi0/86SjZ1sv2d/tm9ku1apReqhHx1O5Ch5kdaBmenKF7PpCk0Du@i@uRiesC85vEl3YzHP70q2P3Keb0vf8crez3FZpUliah5CVy/SPo/0iRnFLy0kBWaO3Q5kGlRpqO2kwT7GXj8Zn3kY/lfcFxyEK8c3GAkf8zh4YI6kCpy5jiJN0nh@0yMCVOswtnZSznpt5YBtOKpMPIhMPIqDSPd1KP@Eg8hqPziM0jhsQUphvXrleDN8d15bVnX5AQ "Haskell ‚Äì Try It Online") The part left of `<$>` can be either `zipWith(((`mod`n).).(-))<*>(0:)` or `zipWith(\a b->mod(a-b)n)<*>(0:)` at no byte difference. [Answer] # [Perl 5](https://www.perl.org/), 94 bytes ``` sub g{($N,$k)=@_;--$k?do{@a=g($N,$k);map{//;map[$',@$_],@a=reverse@a}0..$N-1}:map[$_],0..$N-1} ``` [Try it online!](https://tio.run/##RZHfb4IwEMefx19R3WlBiwrqi6SzL3tlia/MEIxIGAKm1RlD@NvdtbCNNFzvx/fT6/WSyvP6@VS3A8kaG0IGhcNFHLguFNtj3YiEZ304KJNLM59rEwFlAuI9w7RMv1OpUpG0i9kMQtdrN6YCs78Bg89VnMnkQZryAamUwamWtjrnx7zK7Ehgte84mLMhYXDAHiAOdN2Uq1tpIxEg0dAqBTj80V8hcQbcawe6tLX0OT2TGJZicDf3QQCJBChUoiyewt319ntGEIJRF@69@FaaBlUAasohJtglqkG1lu438pmPomjZGZ8ttVl33oqttPE8dJ3GIvjpFvqR4nX6EBHnXF3/x2rCF5lX1xMZjhQ6IUdTcLMfqc9qyKyXfny2ETvjcQfhEE4m@FK0LuiGvu92HzuKxUgmUODmq84rmzKCS0/AuHjum7fYUoIK6uh3xJ@hBlb7/AE "Perl 5 ‚Äì Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~163~~ \$\cdots\$ ~~149~~ 146 bytes ``` s;w;i;p;*f(n,k){int*g=calloc(p=pow(n,k),4*k),b[p*k];for(;p--;){for(w=p,i=0;s=w;w/=n)b[p*k+i++]=w%n;for(;i--;s+=n-g[w])g[w]=(b[w=p*k+i]+s)%n;}s=g;} ``` [Try it online!](https://tio.run/##3ZfdbuJWFEbv8xRWpBnxYzTee2N@6qJeVH2KDBoRD0kJGYJCJKJGvHrTs8/xMpCh6n0jzeaM/X1m2SyQXQ/u6/r9fVftq1W1rXp3nU2@7r6tNi@9@1m9eHx8qjvb2fZpH7fnw14Ytzfb3npe3T09d6rtYFB133y5n23z1ayodrN9tf8y23RjrL/q9@ez/adNiq9CfNefbQb3N/t518esc3sTqp6c93fdEDzsZvfV4T0gZD8Wq02nm71dZeHPN7wsdy/fNjfzbJa9aZ5ZnoVZ5tkwz0QO1Xlu3ebaaMjpSWz5ul3WL8vvkpJFXoTjpCF5VuRyIasfs5pGKjRVyeO7qm@79IZ2PEhzmOZNi3SU5qU5nKRIfIfLUMOLUOZjmMYZXqS1NOJVSaCn3Jqb7zXfa77XfG8cfhF9mI@hjyIfXoAqT0@yPc0GrgCwWTTXoMjPLkZzZZuFElbCSrhdGGEjbIRPFkJYCAthAaz5FArCRd5eWQFMgD/5yAo@tAZMgBfgBfh2oYSVsBJWwBR4BV6BV8Daj12BV@AVsNZXBV6BbxdG2AgbYQPMgDfgDXgDzIA34A14A8yAN@AN@JOFEBbCQlgAE@AFeAFeABPgBXgBXgAT4AV4AV4QSZBNkE2QTRC7@cIWwBfAF4AVwBfAt1/SArAC@AL4Avh20f7oCGEhLIAJ8AK8AC@ACfDS/tocf33aXyNBfkF@QX5BJEE2QTZBNkFsQX5BfkF@QWxBfkF@QX5BbEF@QX5B/nahhJWwElbAFHgFXoFXwBR4BV6BV8AUeAVegVdEUmRTZFNkU8RW5FfkV@RXxFbkV@RX5FfEVuRX5FfkV0RSZFNkU2RTxFbkV@RX5FfEVuRX5FfkV8RW5FfkV@RXRFJkU2RTZFPEVuRX5FfkV8RW5FfkV@RXxFbkV@RX5G8XRtgIG2EDzIA34A14A8yAN@ANeAPMgDfgDXhDJEM2QzZDNkNsQ35DfkN@Q2xDfkN@Q35DbEN@Q35DfkMkQzZDNkM2Q2xDfkN@Q35DbEN@Q35DfkNsQ35DfkN@QyRDNkM2QzZDbEN@Q35DfkNsQ35DfkN@Q2xDfkN@Q367cF80@o@btdLHyMfYx8THNIaLZv7LzVy8yyt9jHyMfUx8TNPQWP75Xu94E1j6GPkY@5ikYV62WD67Ffxwj1j6GPkYpzH08tDLw1hOd4qXbyFLH6M0Si@XXi69XMZy6WVf@lAflsc7/9LLcYy8PPLyyMsjL49ieeRlX/pQH@ZjmMbYy2Mvj7089vLYy@NYHnvZlz7Uh6Ux8fLEyxMvT7w88fLEy5NYnnjZlz40jamXp16eennq5amXp16eenkay1Mv@zINSfdi6UYs3dVHXST6IlEYicZIVEYaW9JNXXFUsde6mFRsn4Py42POcWnH5fC4LI/LUXPk@mmze8nqPxfPvTCX9Xr5nI5//fX1D/36Ov09/Cuv8@z0/3bdtMMDYtbx78lq8335GmpF1Sx/zXarv5ZPdx3esPul2dBrt1RZvx/T3Xiw9MjIN28TjtY8OsbMvDrbvWb3@uLu3iLsTw/GH3Ysw472Sl6qbhe7XcjI@dbbsIlH6uOe9vwf0rk/hPO@9dN66J6czlmyTsk6JNeerD8m/W/7HKJ3netPu0/fw7Wvf/MP4Jfrt/CyuHkID971/ISibSXy@PL5c5vMZuGMm/V56XB16U0P2XU4@NXPoSPV141TNbr4@53iEBv8T//CyZ8q8LxcdhbNhsPV4f3v@u5xcb97H@zfB48//gE "C (gcc) ‚Äì Try It Online") *Saved 3 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!!* Inputs two integers \$N\$ and \$k\$. Returns a pointer to a (flattened) \$N\$-ary Gray code of length \$k\$. ]
[Question] [ We all know about the Fibonacci sequence. We start with two 1s and keep getting the next element with the sum of previous two elements. n-bonacci sequence can be defined in similar way, we start with `n` 1s and take the sum of previous `n` elements to get the next element. **Challenge** Given a positive integer `m` > 1, output the smallest `n` of the n-bonacci sequence that contains `m`, and the index of `m` in that sequence (either 0 or 1 indexed). There should be two integers in output, one will be which n-bonacci sequence the number is in, and another for the 0 or 1-indexed index in it. I/O is flexible, you may choose to output either list, string or two numbers with optional trailing whitespace. **Test cases** First integer is which n-bonacci sequence and second is 0-indexed position: ``` 2 -> 2,2 3 -> 2,3 4 -> 4,4 5 -> 2,4 6 -> 6,6 7 -> 4,5 8 -> 2,5 9 -> 3,5 10 -> 10,10 11 -> 6,7 12 -> 12,12 13 -> 2,6 14 -> 14,14 15 -> 8,9 16 -> 16,16 17 -> 3,6 18 -> 18,18 19 -> 10,11 20 -> 20,20 21 -> 2,7 22 -> 22,22 23 -> 12,13 24 -> 24,24 25 -> 4,7 26 -> 26,26 27 -> 14,15 28 -> 28,28 29 -> 8,10 30 -> 30,30 31 -> 3,7 32 -> 32,32 33 -> 5,8 34 -> 2,8 35 -> 18,19 36 -> 36,36 37 -> 10,12 38 -> 38,38 39 -> 20,21 40 -> 40,40 41 -> 6,9 42 -> 42,42 43 -> 22,23 44 -> 44,44 45 -> 12,14 46 -> 46,46 47 -> 24,25 48 -> 48,48 49 -> 4,8 50 -> 50,50 51 -> 26,27 52 -> 52,52 53 -> 14,16 54 -> 54,54 55 -> 2,9 56 -> 56,56 57 -> 3,8 58 -> 58,58 59 -> 30,31 60 -> 60,60 61 -> 16,18 62 -> 62,62 63 -> 32,33 64 -> 64,64 65 -> 5,9 66 -> 66,66 67 -> 34,35 68 -> 68,68 69 -> 18,20 ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest answer wins. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 17 bytes ``` Lã.ΔR`©Å1λè®L₆O}Q ``` [Try it online!](https://tio.run/##ASUA2v9vc2FiaWX//0zDoy7OlFJgwqnDhTHOu8Oowq5M4oKGT31R//83 "05AB1E – Try It Online") or [Try all cases!](https://tio.run/##S0oszvifnFiiYKeQnJ@SqpdfnJiUmapgY6Og7urvpv7f5/BivXNTghIOrTzcanhu9@EVh9b5PGpq868N/A@U5@JKyy9SyFTIzFOoNtLTM7Os5UrJ51JQKCjKzCtJU1BSNUpR0LVTUFJQyQSKpiZn5ANZCjUK@vkFJfoQq6AUsu1AM/JS/xuBdBrpGHEZQxjGXCYghomOCZcpRMSEywzEMNMx4zKHSJlyWUCkTLksQQxjIMPQAMQyNNAxNAAA) ``` L # range from 1 to the input ã # all pairs [n,k] where n and k are from the range # this is sorted by the first element .Δ # find the first such pair which satisfies: R` # reverse and splat, such that n is above k on the stack © # store n in the register Å1 # a list of n 1's as a start for the n-bonacci sequence λè } # get the kth element of the recursively defined sequence ®L # push the range [1..n] ₆ # for each of those numbers i, get the ith previous value O # sum those values Q # is this equal to the input ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes ``` b©1ḋ®;Ɗ¡)Uœi ``` [Try it online!](https://tio.run/##NY8xTsQwEEX7fwq3SIPk/@04jlbiFrQUaFMsWlEiuAKUewJKGmrqSHAPThIcD@neeMbz5j/M5/PLut4vH/z9els@Dz@vy/vV7ffltK4K1zdBJiSHhLxBtozBXzLKBsUKRm8NqN4aMG2QGjBuxGiMIP3DCPb1lFHgv6GAXcFszGC3VJvArmExtonR9zbqKlZjBafdQaj7FE0Rom8eIY/T8ghKuztB3ahsytDgKdp0N6qYCjTuNw2Qx6umCk1@X4uVujJFSxF3IYbT43F@no@H8BS4Fyv5Bw "Jelly – Try It Online") Multidimensional first index rocks again. Outputs `(which n-bonacci sequence, 1-based index in it)`. ### How it works ``` b©1ḋ®;Ɗ¡)Uœi Full program; Input = n, the number to search for ) For each of i=1..n, b©1ḋ®;Ɗ¡ Generate i-bonacci sequence up to n+i terms: b©1 i copies of 1; save it to register ¡ Repeat n times: ḋ®;Ɗ Prepend the sum of first 3 terms to the current list U Reverse each list œi Find the multi-dimensional index of the first occurrence of n ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 64 bytes ``` LinearRecurrence[o=1~Table~n,o,#+1]~Table~{n,#}~FirstPosition~#& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zg@98nMy81sSgoNbm0qCg1Lzk1Ot/WsC4kMSkntS5PJ19HWdswFsqtztNRrq1zyywqLgnIL84syczPq1NW@@@SHx1QlJlXEp2noGunkBadFxurowBUq2Cko2BmWRv7HwA "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~50~~ 42 bytes ``` Nθ≔E⊕θEι¹ηFθUMη∧κ⊞OκΣ…⮌κλ≔§Φη№ιθ⁰ζI⟦⌕ηζ⌕ζθ ``` [Try it online!](https://tio.run/##PU7LCsIwELz7FTluoYLi0VMJCD34QI/iIbarCc2j5iHan48bBReW3Z0ZZraTwndO6JxbO6a4S@aKHh7VetaEoO4WtmKE1nYeDdqIPVE1K5iq2bKiXZL05jwjouDcGSNsD7JmDY2hZocU5H5EL6Lz5T4lA/zdaeTSjXDEJ/qAMJCVrkr9k5vY2h5fsFE60k/kyF2ysSQ/SvKCeiL5wStCuQgRzhv1y56I@@5TEV/INeflKs@f@gM "Charcoal – Try It Online") Link is to verbose version of code. Edit: Saved 8 bytes by using @Bubbler's idea of calculating the first `n+i` elements of each `i`-bonacci series. Explanation: ``` Nθ ``` Input `n`. ``` ≔E⊕θEι¹η ``` Create a list of `n+1` lists of `1`s. ``` Fθ ``` Repeat `n` times... ``` UMη∧κ⊞OκΣ…⮌κλ ``` ... append the sum of the latest `k` terms to each list. ``` ≔§Φη№ιθ⁰ζ ``` Find the first list which contains `n`. ``` I⟦⌕ηζ⌕ζθ ``` Output its index and the index of `n` in the list. [Answer] # [JavaScript (V8)](https://v8.dev/), 105 bytes ``` a=>{for(i=1;i++;)for(j=Array(i).fill(1);(k=eval(j.slice(-i).join`+`))<=a;h=j.push(k))if(k==a)return[i,h]} ``` [Try it online!](https://tio.run/##FcrRCsIgFIDh1zmHNWFXBXaCniOCHUTzONGhmxDRs9u6/Pn@wI2rKbJuY7t0R53p9nG5gNCkZRg0/iPQvRR@g6ByEiNMqGEh2zhCUDWKsTAeFrKkeZgRr8TaU1DrXj0siOKOnRiL3faSHnLyz283OdUcrYr5BQ7OiP0H "JavaScript (V8) – Try It Online") ## Explanation ``` a => { // Defining a function that takes a single argument for (i = 1; i++; ) // With the variable i (sequence #) infinitely increasing for ( // Iterate... j = Array(i).fill(1); // Initialise j to array of 1s (k = // Assigning k to... eval(j.slice(-i).join`+`) // Sum of last i elements of j ) <= a; // Continue with this as long as we haven't passed a number greater than the input h = j.push(k) // Push k to j, and assign h to index in sequence ) if( k == a)return[i,h] // If we've found it, return } ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 82 bytes returns 1-indexed ``` (k=2;While[(l=LinearRecurrence[s=1~Table~k,s,#+1])~FreeQ~#,k++];{k,l~Position~#})& ``` [Try it online!](https://tio.run/##BcGxCsMgEADQXwkIJUEhJEOhBCFTpg5pKHQQByuHOTQG1E6l9@v2vcOUHQ5T0JrqZG29HKfXjgFUG@QdI5i0gf2kBNGCynKgp3kHIC@yYHzQHS0J4EFMeM719PUi0HpmLHhGYr/uUteEsTT97Pq52Ux0oEZxvela/w "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 105 bytes ``` f=lambda n,b=2,p=1,l=[1,1]:l[-1]==n and(b,p)or f(*[n]+[[b,p+1,l+[sum(l[-b:])]],[b+1,b,[1]*-~b]][l[-1]>n]) ``` [Try it online!](https://tio.run/##HYwxCsMwDAC/4tGKlUHtUAioHxEaLIJpwVFMmg5d@nXXdLzjuPY5H7tfey9c82ZrDo7GF2xMWFkISZcqMymzh@xrNGywH6HESVyTyOA00iSv9xZHaYuCKooNayik0/w1VflP7q7Q2/H0M5Z4A@g/ "Python 3 – Try It Online") may reach recursion limit, 0-indexed **Explanation** Simple recursive search algorithm * `f` is the recursive function which takes an integer `n` * Three variables are defined at start + `b` is the current number of n-bonacci sequence we are trying, which is initially Fibonacci aka 2 + `p` is the 0-indexed position of current value we are trying which is also set to 1 + `l` is the list from which will contain the `b`-bonacci numbers, which is for Fibonacci is `[1,1]` * If the tail/last element of `l` is equal to `n` (tail of `l` is the last computed `b-bonacci` number) + We found our element so we return `b` and `p` * Else + (We hold the possible values for the new recursive call as 2 lists in a list and index them with condition, get it and unpack on `f` to make recursive call) + If the tail of `l` is greater than `n` - Which means we have exceeded the limit and `n` is not in the current `b`-bonacci sequence, so - Make a recursive call with * `n` without any changes * `b` incremented by 1 to get to the next b-bonacci sequence * `p` as the old value of `b` because the search skips the 1s at the beginning so we need to offset by `b` * `l` as list of one more 1s (`b` minus 1 times) + If less than - We need to continue the search in current `b`-bonacci sequence - Make a recursive call with * `n` without any changes * `b` without any changes to continue the search * `p` increment by 1 to get to new index * Take `b` values from the tail of old `l` with negative indexing, sum them and append to old `l` to pass as new `l` [Answer] Lua's a terrible language for code-golfing by any standard, but it was still a ton of fun. # Lua, 250 bytes ``` T=table.unpack function S(t,a)return#t==0 and a or S({T(t,2,#t)},a+t[1])end function f(n,s)a={}for c=1,s do a[c]=1 end::B::l=S({T(a,#a-s+1,#a)},0)if l==n then return s,#a end a[#a+1]=l if l<n then goto B end return f(n,s+1) endprint(f(io.read"*n",2)) ``` # Lua, 280 bytes ``` function S(t,a)if #t==0 then return a end return S({table.unpack(t,2,#t)},a+t[1]) end function f(n,s)a={} for c=1,s do a[c]=1 end ::B:: l = S({table.unpack(a,(#a-s)+1,#a)},0)if l==n then return s,#a end a[#a+1]=l if l<n then goto B end return f(n,s+1)end print(f(io.read("*n"),2)) ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 77 bytes ``` m=>(h=i=>(g=(i,k=n)=>i<k||k&&g(--i)+g(i,k-1))(i)-m?h(i<m?++i:++n):[n,i])(n=2) ``` [Try it online!](https://tio.run/##FcwxDoMwDEDRq3RCtkyqNiOJ4SBVB0RJcANOBVUn7p7C8pcvvXf/67dhlc/XaH6NJXBZuIWJ5WhkkDqxIrfi076nqopgjCDFc5g7IgiapZtA/NIRSUOk2Dy0lieCssUS8grC1om3NydEOGTd8jxe53wil3AI6Mof "JavaScript (Node.js) – Try It Online") Very slow but a bit shorter. --- # [JavaScript (Node.js)](https://nodejs.org), 79 bytes ``` m=>(h=i=>(g=(i,k=n)=>t=i<k||k&&g(--i)+g(i,k-1))(i)-m?h(t<m?++i:++n):[n,i])(n=2) ``` [Try it online!](https://tio.run/##FcxBDoIwEEDRq7giMxlqlI0J7cBBjAuCtIylrYHGFXevsPmbn7zP8Bu2cZVvVjG9p2K5BO5gZjnqGKT2HJG7zGL8vvuqcqCUILlzqTsiCKrQz5BN6ImkJYrYPmMtL4TIDRabVhButJjHTQsRjiluaZmuSzqRiz0E1OUP "JavaScript (Node.js) – Try It Online") A bit faster... [Answer] # [Ruby](https://www.ruby-lang.org/), ~~81~~ 74 bytes ``` g=->x,y=2{s,n=[1]*y,0 s<<n=s[-y,y].sum while x>n x<n ?g[x,y+1]:[y,s.size]} ``` [Try it online!](https://tio.run/##NZNNb9swDIbv/BVCekibsa6oD9ou6uy084Bes2DouqANlrpF7GLJEv/2jKYs@PJCIvnoJen956/j5fLS3C4PeGzcqcO2WdF6cUQL3cND23Sr2yMe10X3@Wb@vm53G3NYtnB4aM3Xl5XkfKH1/eqIXdFt/23Ww6XfdH3XzJy5XRqHDnwSHsIoAgaI6SQAj4KRoUxXEap0FaEehRdBdlRkkSwQpYQSSMuTQ3JAE4GBFEEBKQAppcIaSDHESBJRprqiFEUVUgVUZwaBU56z6Cw4SpVLcMmO@HHgfGZ7cEp0AV0AF5MLiVaiY3QMrsxviuCSvQpdBa5O7xNbXpHeohdN6YEleEV66Zz0UJERK/AJOKqYDdTgFegZPYMvsxnJU6Cv0Et8nY0RBCUGi8FCmJpaQ1BikMk4CD4blsGlycnoAoSYzYtWamAMDKHMjYgQlBoqDBWEOjWlgqjMaDFaiJQbVEJUapShO4g@N4shKjXKVsjGTCtTQ1RmZIwSMQ1TaisxVhhF17mbBKxMtsgWmPIaVMDKZNkZB@xznz2wMjkgy3LG1PMaOO2pLCoDJ2ZAH4GVyhWyVKynaTg7K7qP3ba/nv1oZzfF29PH6dyf@3w4hs1uhnTe4v68aov@/ecWF/spZI7zKe1wPujdsB4A9L8qNk/Pr2Ne/4rb34cz7DedacxL8fy02123N/Dx2XdmdnVqB9MszdVJ7gdzd5dU06xSnvyz5quZv/@Zm3szX5jx@/b4@P1R1WI@zGC4/Ac "Ruby – Try It Online") * Saved 7Bytes thanks to @Dingus suggestions * 1 indexed ``` g=-> x,y=2{ # recursive lambda testing each y-fib returning the first valid result s,n=[1]*y,0 # s = current serie initialized to 1's n = next term while x> n # add terms up to x =s[-y..-1].sum # which is sum of last y terms s<&ltn end # add it x==n ? # if last term is x [y,s.size] # return y and length :g[x,y+1]} # else try next y-fib ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~139~~ 130 bytes ``` t;*b;j;s;i;*f(n){b=calloc(n,8);for(t=*b=s=1;t;)for(b[i=s++]=1;t&&n/++i;t=b[i]-n)for(b[j=i]=0;j-->i-s;)b[i]+=b[j];*b++=s;*b=i;--b;} ``` [Try it online!](https://tio.run/##bZTRbtowFIbv@xQWUlEgiRo7tknkpTfTnqKNJghJZ9aliEQaWsWrj/3OOaV0KsJgjj8fH3@xadKnpjmfR7fcuJ0bnHfLLuoXr5uqWT8/vzRRnxQL170corFabqqhkm50i/B78@CrIY7rEJnP@7s49m6sEK3TnoFd5esqc7s0vffp4BZhMAayq7FcHFcDvirv0nTjTmffj@LX2vfRQrzeCLxCYGyHcXioRSVeVSLyROhEmETYRKwSUSSiTITM0CQaAAlCApFgJCAJSgKT4BQ4BU6BU@AUOAVOgVPgFDgFLgeXg8vDguBycDm4HFwOLgeXg9PgNDgNTofKwGlwGpwGp8FpcAacAWfAGXAmbAGcAWfAGXAGnAVnwVlwFpwFZ8NewVlwFpwtT@7ipj3u22Zst9/7iyA1CVKTIOrkJMiSH0V6CrKTs5yM5ZCbidM03xIf1BRshsQYylWQlpAhaAlZNK2mOVuwEjIGK1PWgp5hRtkNV2SoWkNVGV4sKAmFBiVhVctP39JTCUZk8ZkR/9@R0VNN5u0d6l1RXbzDkhdiI5L2smIjfFpWbMSQkWnXRIXiyFE4aTnbnpRIUlKyEj4oYc1JiSElBStZsRJLSkpSUrASyUoKVsKnpGQlhpSojJU0P9aHJT7b5md7ICOzx@M39Xgsv6KZWSKuf@cznofLK6Lg0/fb9ohpmePuFzH4P@1LF72fvcUdh5ZXMSfwbxBmvN3ly31GNrrT03DtPowu9xjuonHxMdwjenXYP5vprxH/KbJfDwOo/UNWV1Uv5nN0Jbr@HdsfAHbR7HYr0ntxu03QxO3w2MPUmIg@ET65@Az56qtKu0PbRnsOnG5O579N97x@Gs7p738 "C (gcc) – Try It Online") Inputs integer \$n>1\$. Returns a pointer to an array \$a\$ where \$a[0]=s\$ (the sequence number) and \$a[1]=i\$ (the \$0\$-based index) of the first occurrence of \$n\$ in an \$n\$-bonacci sequence. [Answer] # JavaScript (ES6), 84 bytes ``` f=(n,i=k=2)=>(g=(i,h=j=>j&&g(--i)+h(j-1))=>v=i<k||h(k))(i)-n?f(n,v<n?i+1:!k++):[k,i] ``` [Try it online!](https://tio.run/##Dcs9DoMwDEDhq7gLshVSFZZKNIaDVB0Q5ccJchBUTNw9zfSGp8/3Z38Mu2w/q/E7pjQxaikcuCZucWaUcmHPrS@KGa0VMgt6W1G@J4sL17VgIEIhq92U7em0E1M1t2AMNe9QyidNcUcFhvoFCg6ej9x8YYh6xHW8r3HOEjInSn8 "JavaScript (Node.js) – Try It Online") [Answer] # [APL (Dyalog Classic)](https://www.dyalog.com/), 62 bytes ``` {l←1+⍵⋄⊃(,∘.,⍨⍳l)/⍨⍵=,1⌽↑l{⍺{d←⍵⋄({⍵,+/⍵↑⍨-d}⍣(⍺-⍵))d⍴1}¨⍵}⍳l} ``` [Try it online!](https://tio.run/##xdC9SsRAFIbh3qtImbCJy5k/3cKLCRtWhIDCVrKkUoKoA25nb2OvaQQbL@XcSDxvvAiLb5gZnnPmp73pm@627a8vm23f7vdX23k@9Dq@yErzpE/3@nhX1vrwelprftf80VfrZTJd1KLP3zoe@4Pmr0NnNX8Vpa2nerVmNR4NN92g@a001dheVXWaP2X4oclAx2HeFVZd/Me57mRXeEuwREuynFnOLRuLCANKYIIToCAFKlgBO7ADO7ADO7ADO7ADO7AH@@V8sAd7sAd7sAd7cAAHcFhuCw7gAA7gAA7gCI7gCI7L28ARHMERHMEJnMAJnMBp@QlwAidw2vwC) [Answer] # [R](https://www.r-project.org/), 92 bytes ``` function(m)while(F<-F+1)for(i in 0:m+1)if((T[i]=`if`(i>F,sum(T[i-1:F]),1))==m)return(c(F,i)) ``` [Try it online!](https://tio.run/##NY7BCsIwEETvfsWCl11swVwEi/WYL/AmYtOY4IJJSjZV@vU1HjzOMI83ec3ufY9jiv3q52gLp4iBPk9@OdSnVu8U@ZSRgSPsu1Aje8TLlW/9wH5APutG5vBrWtXpGzWKqO8DZVfmHNGibphoLShmml4Lqu5wbP5Sai3uu0rAZgsyjyUbW0CBzymAakcj7lHND7ZOoP4AZ2QBm8JkMkuKUBIUJwVsXcr6BQ "R – Try It Online") Returns 1-based indices. ]
[Question] [ # Vowels rhyme: Apples and Bananas There is a traditional children's song that repeats the same text over and over, only each time every vowel is replaced with a random vowel, but constant across the current stanza. ## Challenge The objective is to propose the shortest code that performs such a transformation on an input text. ## Rules 1. You must print the rhyme as many times as there are distinct vowels in it. 2. Each print must be separated with a line break (platform-specific combo of `\n` and `\r` is accepted). 3. For iteration `i`, replace each vowel with the `i`th distinct vowel in the original text. 4. The input text is a sequence of printable ASCII characters (range `[32, 126]`. 5. Input will not contain embedded line breaks. 6. Only vowels characters must be affected, other must be output exactly as input. 7. Only vowels characters count: nasal vowels, although sounding like vowels (like in French *"Tintin"*), must not be handled as a single vowel. 8. Case matters for the output, but is positional (replacing an uppercase vowel is done with the uppercase replacement vowel) 9. Uppercase vowels are not distinct from their lowercase counterpart (ie `a` <=> `A`) 10. Consecutive vowels are always considered separately (ie. `Boat` yields both `Boot` and `Baat`) 11. Since the letter `y` represents either a vowel or consonant soun (as we're speaking English), handling it as a vowel or a consonant is allowed, however answers must explicitly state whether they handle `y` as a vowel or not. ## Examples: **Hello world** ``` Hello world! ``` gives: ``` Helle werld! Hollo world! ``` **Excerpt from the original French text (translated), with `y` handled as a vowel:** ``` An elephant that was rambling all gently in the woods... ``` gives: ``` An alaphant that was ramblang all gantla an tha waads... En elephent thet wes rembleng ell gentle en the weeds... In iliphint thit wis rimbling ill gintli in thi wiids... Yn ylyphynt thyt wys rymblyng yll gyntly yn thy wyyds... On olophont thot wos romblong oll gontlo on tho woods... ``` Note the behaviour on leading uppercase vowel: case is kept at its index (rules 8 and 9). **Vowelless example** Input that does not contain any vowel, like: ``` lgn@hst:~$ rm -rf ./* ~ / ``` must produce no output, or a single line break. **Single-vowel input** Input containing a single vowel is output as is. ``` Dad sat at a car and saw a fat bat. ``` gives: ``` Dad sat at a car and saw a fat bat. ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so fewest bytecount code wins (nothing but eternal PPCG glory)! [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 45 bytes ``` ~(K`A\EI\OU L$`\\?(.) ./$1/i&$*\T`Vv`5*$&$L$& ``` [Try it online!](https://tio.run/##K0otycxLNPz/v07DO8ExxtUzxj@Uy0clISbGXkNPk0tPX8VQP1NNRSsmJCGsLMFUS0VNxUdF7f9/xzyF1JzUgozEvBKFkozEEoXyxGKFosTcpJzMvHSFxJwchfTUvJKcSoXMPKB8qkJ5fn5KsZ6eHgA "Retina – Try It Online") Does not count `y` as a vowel. Explanation: ``` K`A\EI\OU ``` Replaces the text with the literal string `A\EI\OU`. ``` L$`\\?(.) ``` Matches each letter optionally preceded by a backslash. ``` ./$1/i&$*\T`Vv`5*$&$L$& ``` Outputs a line of Retina code for each letter. ``` ~( ``` Evaluates the generated code (shown below) using the original input. The `.` causes the code not to output the (final) buffer. The `/<vowel>/i&` causes the rest of the line to run only if the input contains the given vowel (case-insensitively). The `*` causes the result of the line to be ignored, so that the next vowel can be tested. The `\` causes the result to be printed on its own line before it is ignored. The `T`Vv`AAAAAa` transliterates uppercase `V`owels to `AAAAA`s and all lowercase `v`owels to `a`. `\A` is an escape that refers to ASCII 07 (BEL), but `E`, `O` and `o` are built-in character classes that needs to be escaped to give their literal values (`e` is not a character class, but fortunately it is also not an escape.) ``` ./A/i&*\T`Vv`AAAAAa ./E/i&*\T`Vv`\E\E\E\E\E\e ./I/i&*\T`Vv`IIIIIi ./O/i&*\T`Vv`\O\O\O\O\O\o ./U/i&*\T`Vv`UUUUUu ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 78 bytes ``` ->s{s.downcase.scan(/[aeiou]/).uniq.map{|v|s.tr"AEIOUaeiou",v.upcase*5+v}*?\n} ``` [Try it online!](https://tio.run/##TYw5a8NAEIX7/IrJkiKR41HlJpDDYINTpUplqxhJqwNWs8rOroTx8deVVSBgeM373uFCfpyq12n5JifB0o5ckGiUgvgx3ZNubcjSJwzc/mBH/ek8nAW9U@vt59f3X6yeBwz9vEpWi@GSvB/4MvXBC1R7tdPGWBitM@W9yu7@8ZpBG903xB58Qx5GEnDU5ablGsgYqDV7c4SWY67jgS0FEW8uNlSCxOUsKMgB8QzG6KrIcvK3bVPzRyP@5foAroOlqwDTBK6Qqmz6BQ "Ruby – Try It Online") A quick and naive approach. Y is not considered a vowel. [Answer] ## bash, 96 bytes Two equal-length solutions: ``` v=aeiouAEIOU;for x in `grep -o [$v]<<<$1|sed 's/./\L&&&&&\U&/'|awk !a[\\$0]++`;{ tr $v $x<<<$1;} v=aeiouAEIOU;for x in `tr -cd $v<<<$1|sed 's/./\L&&&&&\U&\n/g'|awk !a[\\$0]++`;{ tr $v $x<<<$1;} ``` [Try it online!](https://tio.run/##Hc1BC4IwHIbxr/IGQw/SrLN28NAhCDp5UsG/uFRam2xLjeyzL@y5/3gasr3304nEoF/Z@XLLk7s2WDAo1J0RI/YaBZuqNE3ZcbWiRWhjHpfXYKvMgzhcaX5gR0VZskMVRXXygTNgE9jyV8nXe58pCCnGnpSD68lhJgtDz0YOqgNJiU4oJ9/b2PUCs9at5Zz/AA) Takes input as a command line argument and outputs to STDOUT. [Answer] # [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/tree/fb4a2ce2bce6660e1a680a74dd61b72c945e6c3b), 19 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) (Indirectly) saved one byte thanks to [Kevin](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen) (printing directly inside the loop rather than joining, only work in the legacy version). ``` lžMÃÙεžMDu«s5×Du«‡= ``` [Try it online!](https://tio.run/##MzBNTDJM/f8/5@g@38PNh2ee2wpkuJQeWl1seng6iH7UsND2/3/HPIXUnNSCjMS8EoWSjMQShfLEYoWixNyknMy8dIXEnByF9NS8kpxKhcw8oHyqQnl@fkqxnp4eAA "05AB1E (legacy) – Try It Online") ### Using the Elixir rewrite, 20 bytes ``` lžMÃÙεžMDu«s5×Du«‡}» ``` **[Try it online!](https://tio.run/##yy9OTMpM/f8/5@g@38PNh2ee2wpkuJQeWl1seng6iH7UsLD20O7//x3zFFJzUgsyEvNKFEoyEksUyhOLFYoSc5NyMvPSFRJzchTSU/NKcioVMvOA8qkK5fn5KcV6enoA "05AB1E – Try It Online")** (without `y`) | **[Try it online!](https://tio.run/##yy9OTMpM/f8/5@g@/8PNh2ee2wpkuJQeWl1sdng6iH7UsLD20O7//x3zFFJzUgsyEvNKFEoyEksUyhOLFYoSc5NyMvPSFRJzchTSU/NKcioVMvOA8qkK5fn5KcV6enoA "05AB1E – Try It Online")** (with `y`, `žM` being replaced by `žO` – same applies for the legacy version) ### How it works ``` lžMÃÙεžMDu«s5×Du«‡}» Full program. Example: "Hello" l Convert the input to lowercase. "Hello" –> "hello" žMà Keep only lowercase vowels. "hello" –> "eo" Ù Remove duplicates. "eo" –> "eo" ε } For each of the characters (example with "e"): žMDu« Yield "aeiouAEIOU" s5× Swap, and repeat the current char 5 times. "e" –> "eeeee" Du« Duplicate, uppercase and merge. "eeeee" –> "eeeeeEEEE" ‡ Transliteration. For each item in B, replace it in A with the corresponding item in C. » Join on newlines. ``` [Answer] # Japt v2.0a0 `-R`, ~~24~~ 22 bytes Treats `y` as a vowel. Change both occurences of `\y` to `\v` to treat it as a consonant. ``` v f\y â £r\y_Xc^H*ZøZu ``` [Try it](https://ethproductions.github.io/japt/?v=2.0a0&code=diBmXHkg4iCjclx5X1hjXkgqWvhadQ==&input=IkhlbGxvIFdvcmxkISIKLVI=) --- ## Explanation ``` v :Lowercase \y :RegEx /[aeiouy]/gi (\v is /[aeiou]/gi) f :Get all matches as an array â :Deduplicate £ :Map each X r\y : Replace all matches of the RegEx above in the input _ : Pass matches through a function as Z Xc^ : XOR the character code of X with H* : 32 multiplied by Zø : Does Z contain Zu : Uppercase Z :Implicitly join with newlines and output ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~23 20 18~~ 17 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) -2 Thanks to Erik the Outgolfer ``` ØcŒHZx5fƇðØc,yð€Y ``` To treat `y` as a vowel replace both `c`s with `y`s. **[Try it online!](https://tio.run/##HY0xDoJAFESvMqGxEZsfKzorrTUx2n3AZTErP1kWcFsbeysPYeEdiB7Ei6yr3Uzy3szxYIwPYbwXr9tyf56r93V8xjb14/NzeexCCMlGE/KudWzLSQtGT9YjrysoGUyGra4LDc0tLHFcQyO/1EoDJ6jsH1pzTyWUlROcZofhLw3SmRI5ZViZ1FBa1S6tTykXPsPCR5KizwVBVPxVYl3XsCP0MpCZJV8 "Jelly – Try It Online")** ### How? ``` ØcŒHZx5fƇðØc,yð€Y - Link: list of characters, S Øc - vowels -> "AEIOUaeiou" ŒH - split in half -> ["AEIOU", "aeiou"] Z - transpose -> ["Aa", "Ee", "Ii", "Oo", "Uu"] x5 - times 5 -> ["AAAAAaaaaa", "EEEEEeeeee", "IIIIIiiiii", "OOOOOooooo", "UUUUUuuuuu"] Ƈ - filter keep if: f - filter keep only -> those of X which have required vowels - ...i.e. if S = "blah" then ["AAAAAaaaaa"] ð ð€ - dyadic chain for €ach: Øc - vowels -> "AEIOUaeiou" , - pair e.g. ["AEIOUaeiou","AAAAAaaaaa"] y - translate e.g. swap A for A, E for A, ... Y - join with newlines ``` [Answer] # [Red](http://www.red-lang.org), 229 bytes Taking `y` for a non-vowel ``` func[s][v: charset"aoeiu"w: charset"AOEIU"p: copy""parse s[any[[copy c[v | w](if not find p c[append p c lowercase c parse s[any[[copy n to[v | w | end]](prin n)opt[v(prin c)|[w(prin uppercase copy c)]| skip]]]print""])]| skip]]] ``` [Try it online!](https://tio.run/##ZY6xasUwDEX3fMWtp5clH/C2NxTaqVDoZDy4tvJi6srGdmIC@ffUaQotdBBIR9wjJbL7K1mpuvG6jzMbmZVcrjCTTpmK0IHcLOovuL08Pr@J2ECIqxDxoMhS8yrlgWDkgg1VXdwIDgWjY4vYsI6RzhY@VEpGt6Tp/hsYJZySVi2i1CUmx@A@xCKXczD9JuvZzk38Y/t@oFcb8oeLSqljX4RQf9A@QjyR9wE1JG8fRNfAjUGe4qS5oEy6oOqMpD/fveM7tPe4Exe/op0rE7VosHkYBrF/AQ "Red – Try It Online") Slightly more readable: ``` f: func [ s ] [ v: charset "aoeiu" w: charset "AOEIU" p: copy "" parse s[ any [ [ copy c [ v | w ] ( if not find p c [ append p c lowercase c parse s [ any [ [ copy n to [ v | w | end ] ] ( prin n ) opt [ v ( prin c ) | [ w ( prin uppercase copy c ) ] | skip ] ] ] print "" ] ) ] | skip ] ] ] ``` [Answer] # [R](https://www.r-project.org/), ~~138~~, 129 bytes ``` function(x,U=utf8ToInt,a=U(V<-'aeiouAEIOU'))for(i in (which(a%in%U(x))-1)%%5)cat(chartr(V,intToUtf8(rep(a[i+c(1,6)],e=5)),x),' ') ``` [Try it online!](https://tio.run/##Fc2xbsIwEIDhnae4Ropyp5pIDFQdmoEBCaYumA5Vh6uxsSX3jMxFSZ8@pQ/wf39dwrCEUZymIjgbO4waXk/lKGp4sHh@W3fsUxl3@@O77YhCqZggCeAUk4vIbZLW4ky03lDbbsmxootcteLZJNFTsQ8Rq78hf6ZnhxvzQl/GD1siM5PpVh0tAZudgM/@FlkUNLLCxHeo/POdk1yBc4arF82//2@NHqZSLve@7xtaPeqDz7nAR6n5Ak8NLX8 "R – Try It Online") * `y` is not considered a vowel [Answer] ## Python, 129 119 112 bytes ``` import re f=lambda s:'\n'.join(r('[AEIOU]',v.upper(),r('[aeiou]',v,s))for v in'aeiou'if v in s.lower());r=re.sub ``` [Try it Online!](https://tio.run/##HcuxDsIgEIDh3adgO0gIi5umg4OJTp2c1IGmEM9QjhzQxqfH0PH/kj/9yofisTVcEnER7A5@CHaZZivyCV4RzJcwSpbwvFzv4@MNejU1JcdS6a7WIdWuOivlicUqMMKugH4vkU2grR/qzAM7k@vUEmMs0ku4uRBIbCOHGZRqfw) Doesn't treat \$y\$ as vowel. -7 bytes thanks to @Mr.Xcoder [Answer] # [JavaScript (Node.js)](https://nodejs.org), 99 bytes Treats \$y\$ as a consonant. ``` s=>(g=F=>Buffer(s).map(c=>2130466>>c&c>64?F(c):c)+` `)(v=>g[v&=31]||(g[v]=S+=g(c=>c&96|v)),S='')&&S ``` [Try it online!](https://tio.run/##bU1ba8MgFH7vrzgrI9V1tetaAivoLozS9zyOQq1Rk2E0qEsYhP71zLyOwnn4znf95h0PwtdtXFlXylHRMVCGND1Q9vGjlPQoYNLwFgnKnjfbp12eMyYywfLd6wEJvBd4eZ6dMeoo019dRreb0zCgBE@0WFI95UT2kg8dxo8FXSxwlhWjcDY4I4lxGik0P0pjHPTOm/JujvHsn/xuQRrZVtxGiBWP0PMAnjcXU1sN3BjQ0kbzC7VNukxFrgyEkBtVRtu3KsT99R58AyuvgKwf4ArrG95PXkJIa9OB4B64nYg@fSpxFx6nhfEP "JavaScript (Node.js) – Try It Online") ### Commented ``` s => ( // s = input string g = F => // g = helper function taking a callback function F Buffer(s) // turn s into a Buffer .map(c => // for each ASCII code c in s: 2130466 // 2130466 is a vowel bitmask: 1000001000001000100010 // u o i e a >> c // the ECMAScript specification enforces that the shiftCount is // the result of masking out all but the least significant 5 bits & c > 64 // also make sure to ignore non-letter characters ? // if a vowel is identified: F(c) // invoke F with c : // else: c // just yield c ) + `\n` // end of map(); coerce back to a string and append a newline )(v => // invoke g with a callback that takes v: g[v &= 31] || ( // unless this vowel has already been encountered: g[v] = // mark it as encountered S += // and append to the output string S g( // the result of another call to g: c => c & 96 | v // where vowels are replaced with v, using the original case ) // end of inner call to g ), // S = '' // start with S = '' ) && S // end of outer call to g; return S ``` [Answer] # Java 10, ~~196~~ 188 bytes ``` s->{var d=new int[99];for(var c:s.toUpperCase().replaceAll("[^AEIOU]","").toCharArray())if(d[c]++<1)System.out.println(s.replaceAll("[AEIOU]",c+"").replaceAll("[aeiou]",(char)(c+32)+""));} ``` -8 bytes thanks to *@joH1*. Without `y` as vowel to save bytes. [Try it online.](https://tio.run/##jZHBbsIwDIbvPIVX7ZCMEbTtBB3TKjZpO4wdECfUSSZNaVlIqyRQIQSv3rmsOyDtgBRFsh1/9v9nhVvsrZLvWmp0Dj4wN/sOQG68silKBZMmBNgWeQKSTb3NzRIcDyl76NDlPPpcwgQMjKB2vaf9Fi0kI6OqhjIfDOIwLSxrsnLohC9mZansGJ1iXFhVapoSac2C@Vf0@v45i4PbIOD0bpyhjazFHeM8T1kyl3G3@3jHpzvn1VoUGy9K2sZrw9w56I8juw3prIQqLzZUYpLonMnuwz1vXvHwUIeNnnKz0KSnlXWSvSZTWuXzGJD/OmKEZMGb0rqAqrA6uQpOpgD8s19bObVEBpRWZYbGg8/QQ4UOLK5pLDmLWsNSUdOO3KO6IniROCHEhfgXTMARtTkgyXQ0TaKiKKXcAv2lJL00z5nzw@M12DX0bAqifwNH6Aft7x/qHw) **Explanation:** ``` s->{ // Method with String parameter and no return-type var d=new int[99]; // Integer-array indicating which vowels we've already output for(var c:s.toUpperCase()// Convert the input to uppercase .replaceAll("[^AEIOU]","") // Remove all non-vowels .toCharArray())// Convert it to a character array) // And loop over those vowel-characters if(d[c]++ // Increase the vowel-count by 1 <1) // And if it was 0 this iteration: System.out.println( // Print with trailing newline: s // The input, .replaceAll("[AEIOU]",c+"") // with every uppercase vowel replace with the current vowel .replaceAll("[aeiou]",(char)(c+32)+""));} // and every lowercase vowel replaced as well ``` [Answer] # [Python 2](https://docs.python.org/2/), 112 bytes ``` s=input() V='aeiouAEIOU' for v in V: if v in s.lower():print''.join([c,[v.upper(),v][c>'Z']][c in V]for c in s) ``` [Try it online!](https://tio.run/##RY7BagIxEIbP7lNMoTBaNEKPi0qFWtqTl9ZCxUN2d9ZNG5Mwybp68dW3iRYaQjL5P@bLuHNorHnsS1sRzIERsfdzZVwbhqNsM0dJyrbL1dv6A7PaMhxBGdjkGaj6VnuhbUc8HOWOlQmI4tsqM9yW4@1RtM4lND7utuUCv3AX76tgl1zX0o/6@GnWNUoTvHNLeTYIfI7n4CoEnM0mt4UxoxOVkKb95390sYicTiW5AKv1y4rZcrIUTPIn6/GVtLbwaVlXd5jh0gBpco2MitDIAJ30wPJQaGX2ILWGPZmgz2nG0BB01lZeCBFb9d48NT7kl3vgA0y4BjF9gAtMI3uWFfhoSxtKySBNCrr4qmNWyCDwFw "Python 2 – Try It Online") Treats `y` as a consonant. [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 64 bytes ``` {m:g:i/<[aeiou]>/».lc.unique».&{$^v;say S:g:ii[<[aeiou]>]=$v}} ``` [Try it online!](https://tio.run/##PcqxTgJBFIXhnqc4xYbVxAydBYiJ0c6SkqC5sHd3bjJzB2dmISvhWWx8Czt5sHVo7E7@7@w5uvvRD5i2WI4nP@/mMntYE0voN4@z3x/jdqZX@ei57OmpejssEg1YXY@y/n9ultXhfB7bm@r9Fm2Ik/olsuDZinJihZeMhj1eg@ZIW0oJiS5fRahvi0SsSi8BvTbg@Hn5ti4XTrKzOFIy9d2kflKw470lzciW8hUQyW@daAdyDh1rdgNEizOOITTJGFMvxj8 "Perl 6 – Try It Online") [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), 184 bytes y is a vowel ``` s->s.chars().mapToObj(c->""+(char)(c>96?c:c+32)).filter("aeiouy"::contains).distinct().forEach(c->System.out.println(s.replaceAll("[aeiouy]",c).replaceAll("[AEIOUY]",c.toUpperCase()))) ``` [Try it online!](https://tio.run/##VY9BawIxFIT/SsgpqfUdWihU2y0iHnooHqyHIj08s08322wSkreKiL99G7GXznEGvplp8YDjEMm39c9guxgSi7Z40LN1sOu9YRs83E2Nw5zFB1p/zoxsjZgHn/uO0suKk/X7Kr0OeVxlMA2mrDR0GD/DctsqM66kHKmrr5Wpnp/ezMSMHh@0hp11TElJJBv6k5xMTPBcOrKG2ma2pb6QdiEt0DRX0OqUmToIPUMsrey8ypAoOjQ0c07JzQ31Le@N/h/MFu/L9dc1AA7rGCnNMZPSRcM09ltXPv1dOwRbi67sULdvm2/U5wRoDEVWcuYFOYoNehbcIIsjZpGwKwi/F@ic2FOZdhLWl5zEMYQ6A4DU08tl@AU "Java (OpenJDK 8) – Try It Online") ]
[Question] [ ## Challenge We all know about normal Christmas trees - but how about an [upside-down Christmas tree](https://www.thespruce.com/upside-down-christmas-trees-1976407)! This is a fairly easy, Christmas themed challenge. The objective of this challenge is to make me an ASCII upside-down Christmas tree. Here are the rules for this challenge: 1. Accept an odd, positive integer. You can assume it will always be between `7` and `51`. 2. The base of the tree will be made of the characters: ``` ___ \ / | ``` 3. The top of the tree (the star), will be made up of a single `*`. 4. Each line of the tree will be constructed using the format `<?>` where `?` is any number of `-`s. For example, if making a line of length `5`, the line should be `<--->`. Or if making a line of length `8`, the line should be `<------>`. 5. Here is how the body of the tree should be constructed: 1. Take the odd number `n` given as input, and create a line of the tree that length. 2. Subtract `4` from `n` and create a line of the tree that length. 3. Subtract `2` from `n` and create a line of the tree that length. 4. Decrement `n` by `2`. After that, unless **`n` equals `5`**, go back to step 2. 6. The base (see step 2.) the star (see step 3.) and each line of the tree (see steps 4. and 5.) should all be centered using the *original* odd number input (see step 1.) as the maximum width. ## Examples/Test Cases ``` odd number inputed: 7 ___ \ / | <-----> line length -> 7 <-> line length -> 7 - 4 = 3 <---> line length -> 7 - 2 = 5 * odd number inputed: 13 ___ \ / | <-----------> line length -> 13 <-------> line length -> 13 - 4 = 9 <---------> line length -> 13 - 2 = 11 <-----> line length -> 11 - 4 = 7 <-------> line length -> 11 - 2 = 9 <---> line length -> 9 - 4 = 5 <-----> line length -> 9 - 2 = 7 <-> line length -> 7 - 4 = 3 <---> line length -> 7 - 2 = 5 * odd number inputed: 9 ___ \ / | <-------> line length -> 9 <---> line length -> 9 - 4 = 5 <-----> line length -> 9 - 2 = 7 <-> line length -> 7 - 4 = 3 <---> line length -> 7 - 2 = 5 * odd number inputed: 17 ___ \ / | <---------------> line length -> 17 <-----------> line length -> 17 - 4 = 13 <-------------> line length -> 17 - 2 = 15 <---------> line length -> 15 - 4 = 11 <-----------> line length -> 15 - 2 = 13 <-------> line length -> 13 - 4 = 9 <---------> line length -> 13 - 2 = 11 <-----> line length -> 11 - 4 = 7 <-------> line length -> 11 - 2 = 9 <---> line length -> 9 - 4 = 5 <-----> line length -> 9 - 2 = 7 <-> line length -> 7 - 4 = 3 <---> line length -> 7 - 2 = 5 * ``` ## Rules * [Standard loopholes apply](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default). * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins! [Answer] # [Python 3](https://docs.python.org/3/), ~~127~~ ~~121~~ ~~105~~ ~~103~~ ~~100~~ 98 bytes This is an unnamed lambda function which returns a list of lines: ``` lambda o:[s.center(o)for s in['___','\ /','|',*[f'<{"-"*(o-i+2-i%2*3)}>'for i in range(4,o)],'*']] ``` **[Try it online!](https://tio.run/##FYtBCsIwEADP@oqlIJvEVLEVxKJ@pC2laqIR3S1pLqK@PTaXuczM8A53pjLaYxOf/et87YGrelxdDAXjBUvLHkZwVGPXdaixgfXEL2pVWzx8sjxTgnO3LHK3KFQpfydMi5sW8D3djNhqlq1GhW0bkwpmDMnuNOw1bMpqPhu8oyCwIVw92JGwIkVSyvgH "Python 3 – Try It Online")** The main part of this answer is `(o-i+2-i%2*3)`, which works out the number of dashes to have on a line. The rest of the answer is simply converting this into the desired ASCII-art. *Many thanks to [Mr. Xcoder](https://codegolf.stackexchange.com/users/59487/mr-xcoder), for shaving 6 bytes, and discussing golfs with me in chat.* *Thanks also to [Lynn](https://codegolf.stackexchange.com/users/3852/lynn) for noticing that `3*(i%2)` can be `i%2*3`, 2 bytes shorter!* [Answer] # C, 163 bytes ``` #define P;printf( i;g(l){P"%*c",1+i-l--/2,60);for(;--l P"-"))P">\n");}f(n){i=n/2 P"%*c__\n%*c /\n%*c|\n",i,95,i,92,i,32);for(g(n);n>5;g(n-=2))g(n-4)P" %*c",i,42);} ``` [Try it online!](https://tio.run/##bU7bCoJAEH33K5aNYKd2MVctZNFv8AMECWtlwSYxezK/fRutt5qHc@BwLtOotmm831yu1uGVlaYfHI5WBM60ooOp5Ntdw2W0d6pTKtTyeABj74MwSnWs5IoDlLyokIOZrUCYXI6hZmuuriskYuFKLzJJJ7N0AU0Q609VSzGDRUqLqHINsHBCtWzddjIh4@zpL3Y7OxQQTAGjs@IEpn@OD8Fp/StF8a@W/bFRNJj9Gw) **Unrolled:** ``` #define P;printf( i; g(l) { P"%*c", 1+i-l--/2, 60); for (; --l P"-")) P">\n"); } f(n) { i=n/2 P"%*c__\n%*c /\n%*c|\n", i, 95, i, 92, i, 32); for(g(n); n>5; g(n-=2)) g(n-4) P" %*c", i, 42); } ``` [Answer] # [Proton](https://github.com/alexander-liao/proton), 83 bytes Thanks to [FlipTack](https://codegolf.stackexchange.com/users/60919/fliptack) for saving 4 bytes, and for collaborating in [chat](https://chat.stackexchange.com/rooms/240/the-nineteenth-byte) (we actually form a great team). Indirectly saved 2 bytes thanks to [Lynn](https://codegolf.stackexchange.com/users/3852/lynn). ``` o=>[s.center(o)for s:['___','\ /','|']+['<'+"-"*(o-i+2-i%2*3)+'>'for i:4..o]+['*']] ``` [Try it online!](https://tio.run/##FctBCsMgEEDRqwShzIxWC2mhEJpcxIiLEmG6mAnGZe9um81fvb9XbSq9zF3nJR7hvUnbKioVrcMxRcg5wxXW4fbvF5KL8AJnvLGont3o@TLaOzlY4Dx4eoSgp7KQUt8rS0OzigkfZcGCTyLqPw "Proton – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 28 bytes ``` __⸿ /⸿|F⮌…¹⊘N«⸿⊕ι>⸿⊖ι>»‖B← * ``` [Try it online!](https://tio.run/##dcwxC8JADAXg2f6Ko1MqinQSFBzEwYKIdC7Ieb7TwvUqMS2I@tvPFgriYLbkfS/mqtnU2oVw4NILxcdjwWpW8CtOlpGtWVGOFnwH5dpfQOlEbbVrcabM3xrZN9UJTEk/6hmNhi8F9/Vhy7xhVPDSlcrke49XP2yDf6xH7yiHdTCybkTA1j1osYOVLhqYGncuhHQepq37AA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` __⸿ /⸿| ``` Print the base. ``` F⮌…¹⊘N« ``` Loop from half of the input number down to 1. ``` ⸿⊕ι>⸿⊖ι>» ``` Print two lines, the first with one more `-` than the loop index, the second with one fewer. ``` ‖B← ``` Mirror to complete the tree. ``` * ``` Place the star. [Answer] # [SOGL V0.12](https://github.com/dzaima/SOGLOnline), ~~35~~ 30 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) ``` ┌* <++L %⁽⁄6‘√.⁾δ№{⁽LFL}j *+§Γ ``` [Try it Here!](https://dzaima.github.io/SOGLOnline/?code=JXUyNTBDKiUyMCUzQysrTCUwQSUyNSV1MjA3RCV1MjA0NDYldTIwMTgldTIyMUEuJXUyMDdFJXUwM0I0JXUyMTE2JTdCJXUyMDdETEZMJTdEaiUyMCorJUE3JXUwMzkz,inputs=Nw__,v=0.12) Uses [Neil's Charcoal algorithm](https://codegolf.stackexchange.com/a/151740/59183), takes input as the index in the odd numbers - so 13 would correspond to the input 7 [Answer] # [Retina](https://github.com/m-ender/retina), 89 bytes ``` .+ $*-> ^-- < +`( *<)----(-+>)$ $&¶ $1$2¶ $1--$2 s`.*¶( +)<->.* $1___¶$1\ /¶$1 |¶$&¶$1 * ``` [Try it online!](https://tio.run/##HYYxDsMgEAT7e8UVKwsOHdG5cYN4iRWcwoWbFElKv4sH8DFMPMXMfPbf8X71HgNBNNNTlRKFzbEkrwOnIXsQplaZYZhHYaqY6btFadVx8ElzFIKVUlqFrfz4h8/h6T7p3ZYL "Retina – Try It Online") Explanation: The first stage converts the input to unary and appends a `>`. The second stage replaces two `-`s with a `<` to correct the line length. The third stage then replicates the branch but slightly shorter each time until the branch cannot be shortened any further. The final stage adds the base and the star. [Answer] **Javascript** 506 bytes Golf-version: ``` function tree(i){const mid=(i+1)/2;const leg1=' '.repeat((mid-2))+`___ `;const leg2=' '.repeat((mid-2))+`\\ \/ `;const leg3=' '.repeat((mid-1))+`| `;let xmasTree=leg1+leg2+leg3;for(let j=0;j<(i-4);j++){if(j%2===0){let v=j/2;let t=i-2*v-2;let body1=" ".repeat(j/2)+"<"+"-".repeat(t)+">"+` `;xmasTree=xmasTree+body1}else{let k=1+Math.ceil(j/2);let h=i-2*k-2;let body2=' '.repeat(k)+'<'+'-'.repeat(h)+">"+` `;xmasTree=xmasTree+body2}} const head=' '.repeat((mid-1))+'*' xmasTree=xmasTree+head;return xmasTree} ``` Ungolf-version: ``` function tree(i){ const mid = (i+1)/2; const leg1 = ' '.repeat((mid-2)) + `___ `; const leg2 = ' '.repeat((mid-2)) + `\\ \/ `; const leg3 = ' '.repeat((mid-1)) + `| `; let xmasTree = leg1 + leg2 + leg3; for (let j = 0; j<(i-4); j++) { if (j%2===0) { let v = j/2; let t = i-2*v-2; let body1 = " ".repeat(j/2)+"<"+"-".repeat(t) +">"+` `; xmasTree = xmasTree + body1; } else { let k = 1 + Math.ceil(j/2); let h = i-2*k-2; let body2 = ' '.repeat(k)+ '<'+ '-'.repeat(h) + ">"+` `; xmasTree = xmasTree + body2; } } const head = ' '.repeat((mid-1)) + '*' xmasTree = xmasTree + head; return xmasTree; } ``` Usage: `console.log(tree(13)), console.log(tree(17)),` **ES6** 165 bytes (from my friend) Golf-version: ``` p=n=>{l=_=>console.log(`${' '.repeat((n-_.length)/2)}${_}`);t=_=>_==1?'*':'<'+'-'.repeat(_-2)+'>';x=n;l('___');l('\\ /');l('|');for(;x!==3;){l(t(x));l(t(x-4));x-=2}} ``` Ungolf-version: ``` p = n => { l = _ => console.log(`${' '.repeat((n-_.length)/2)}${_}`); t = _ => _ == 1 ? '*' : '<' + '-'.repeat(_-2)+'>'; x = n; l('___');l('\\ /');l('|'); for(;x!==3;) { l(t(x)); l(t(x-4));x-=2; } } ``` Usage: `p(31); p(17);` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 131 bytes ``` $i=2;$x="$args"..5|%{' '*($j=if($_%2){$i-2}else{($i++)})+'<'+'-'*($_-(5,2)[$_%2])+'>'};($y=' '*++$j)+"___";"$y\ /";"$y |";$x;"$y *" ``` [Try it online!](https://tio.run/##HY1BCsIwFESvUj6/JOk3FQPFRYwXUQkuoqYElGahJc3ZY9PVPJjHzOf9dVN8uRBKQW@Uxp8BvE/PCH0/LG1iDes4jsY/ONpWiYRequxCdImjJxJZEDsxYrJ6VvJhp8Slqre1OLOsOc6mrhDhKAistaAB52uz37JZYD3dqINSyuH4Bw "PowerShell – Try It Online") Well, this is a right mess to anyone not conversant in PowerShell... so, let's see how well I can explain how it works. For the explanation, I'll be using `input = 17`. We start off simple enough, with setting helper variable `$i=2` and setting `$x` to `<something>`, with the `<something>` starting as a range from the input `$args` down to `5`, so `17,16,15,...,6,5`. That range is pumped into a for loop. Each iteration, we start with setting helper variable `$j` to be the result of an `if` statement, `if($_%2){$i-2}else{($i++)}`. If it's odd, `$j=$i-2`, otherwise `$j=($i++)`. This, coupled with `$i=2` at the beginning, gives us the sequence `0, 2, 1, 3, 2, 4, 3, 5...` which just so happens to correspond exactly to how many spaces we need to prepend to our tree line. ;-) We take `' '` and string-multiply it out by that number. Next we need our branches. This is done with `'<'` plus the middle part `'-'` multiplied out, plus the end `'>'`. The multiplication is done by recognizing that the `-` alternate in a `2, 5, 2, 5, 2...` pattern based on the input number `$_`, so we're selecting from a pseudo-ternary based on that pattern. For further clarification, here are the first couple terms in each section: ``` $_ = 17 16 15 14 13 12 11 10 $j = 0 2 1 3 2 4 3 5 mid= 2 5 2 5 2 5 2 5 '-'= 15 11 13 9 11 7 9 5 ``` So now we've set `$x` to be an array of branches (i.e., strings). Outside the loop, we now build our tree "top" with the appropriate number of spaces saved into `$y`, then display our branches `$x`, and then the tree "bottom" with the `*`. Each of those are left on the pipeline and output is implicit with a newline between items. [Answer] # JavaScript (ES6), ~~150~~ 147 bytes ``` N=>{for(s=' '[r='repeat'](N/2-1),s+=`___ ${s}\\ / ${s} | `,n=N,l=n=>' '[r](N/2-n/2)+(n-1?`<${'-'[r](n-2)}> `:'*');n-3;n-=2)s+=l(n)+l(n-4) return s} ``` ``` f= N=>{for(s=' '[r='repeat'](N/2-1),s+=`___ ${s}\\ / ${s} | `,n=N,l=n=>' '[r](N/2-n/2)+(n-1?`<${'-'[r](n-2)}> `:'*');n-3;n-=2)s+=l(n)+l(n-4) return s} console.log(f(7)) console.log(f(9)) console.log(f(13)) console.log(f(17)) ``` [Answer] # [Canvas](https://github.com/dzaima/Canvas), 28 bytes ``` -×>+∔ __¶ /¶|╶┤r⇵{├⁸¹⁸}k*∔↔│ ``` [Try it here!](https://dzaima.github.io/Canvas/?u=LSVENyUzRSV1RkYwQiV1MjIxNCUwQV9fJUI2JTIwLyVCNiU3QyV1MjU3NiV1MjUyNCV1RkY1MiV1MjFGNSV1RkY1QiV1MjUxQyV1MjA3OCVCOSV1MjA3OCV1RkY1RCV1RkY0QioldTIyMTQldTIxOTQldTI1MDI_,i=Nw__,v=0) A port of my SOGL answer which is a port of Neil's Charcoal answer. [Answer] ``` N=>{for(s=' '[r='repeat'](N/2-1),s+=`___ ${s}\\ / ${s} | `,l=n=>' '[r](N/2-n/2)+n-1?`<${'-'[r](n-2)}> `:'*');N-=2;s+=l(N)+l(N-4);return s} ``` My attempt at JS ESGoogoltriplex. ``` f= N=>{for(s=' '[r='repeat'](N/2-1),s+=`___ ${s}\\ / ${s} | `,l=n=>' '[r](N/2-n/2)+n-1?`<${'-'[r](n-2)}> `:'*');N-=2;s+=l(N)+l(N-4);return s} console.log(f(7)) console.log(f(9)) console.log(f(13)) console.log(f(17)) ``` ]
[Question] [ ## Task Given a representation of a line, output the number of [quadrants](https://en.wikipedia.org/wiki/Quadrant_(plane_geometry)) that that line passes through. ## Valid Representations of a Line You can represent a line as * Three signed integers `A`, `B`, and `C` which share no common factor and where `A` and `B` are not both zero, representing the line `Ax + By = C`, * Four signed integers `X1`, `Y1`, `X2`, and `Y2`, representing the line passing through the points `(X1, Y1)` and `(X2, Y2)`, or * A data type that describes a line, if your language has one (it must support vertical lines). You may *not* take input in any format that does not allow for a vertical line (e.g. slope-intercept form). If you choose to take integers as input, you can assume that they lie in the inclusive range `[-127, 128]`. ## Specifications * The output will always be 0, 2, or 3 (a line can never pass through all four quadrants, nor can it pass through only a single one). * A line on an axis is considered not to pass through any quadrants. A line through the origin is considered to only pass through 2 quadrants. * You do not have to return which quadrants are being passed through (though the test cases include them for clarity). * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest valid answer (measured in bytes) wins. ## Test Cases You will have to convert these to a suitable format before using them. ``` 1x + 1y = 1 -> 3 (quadrants I, II, and IV) -2x + 3y = 1 -> 3 (quadrants I, II, and III) 2x + -3y = 0 -> 2 (quadrants III and I) 1x + 1y = 0 -> 2 (quadrants II and IV) 3x + 0y = 6 -> 2 (quadrants I and IV) -3x + 0y = 5 -> 2 (quadrants II and III) 0x + -8y = 4 -> 2 (quadrants III and IV) 0x + 1y = 0 -> 0 (lies on the x-axis) 1x + 0y = 0 -> 0 (lies on the y-axis) ``` [Answer] # [Python 3](https://docs.python.org/3/), 24 bytes ``` lambda a:3<<a.count(0)&3 ``` [Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSHRytjGJlEvOb80r0TDQFPN@H9BUSaQmaYRbagDhLGamlxwEV0jHWM0ISMdXWMdAxQhkD5UEaAKHTNUk0BCpihCBjq6FjomaELoJsFE/gMA "Python 3 – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes ``` TL’ȧ$ ``` [Try it online!](https://tio.run/##y0rNyan8/z/E51HDzBPLVf4fbn/UtCby//9oQx0gjNVRiNY10jGGsIx0dI11DEAskCSYAeTrmIFVgVimIJaBjq6FjgmEBVUFYQAA "Jelly – Try It Online") * -1 byte thanks to Challenger5 * -1 byte thanks to Leaky Nun * -2 bytes thanks to H.PWiz No longer based off Leaky's answer! [Answer] # Javascript (ES6), ~~30~~ ~~24~~ 22 bytes This is my first time trying to golf in Javascript. ~~There's gotta be a better way to count zeros...~~ ``` (a,b,c)=>3<<!a+!b+!c&3 ``` -6 bytes thanks to Herman Lauenstein, -2 bytes to remembering operator precedences. Alternate 24-bytes solution to return a string instead: ``` (a,b,c)=>"320"[!a+!b+!c] ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 6 bytes ``` Ƶܹ0¢è ``` [Try it online!](https://tio.run/##MzBNTDJM/f//2NbDcw7tNDi06PCK//@jDXQUdC10FExiAQ "05AB1E – Try It Online") Based on Leaky Nun's answer. [Answer] # [SOGL V0.12](https://github.com/dzaima/SOGL), 8 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) ``` 0233{.‽X ``` [Try it Here!](https://dzaima.github.io/SOGLOnline/?code=MDIzMyU3Qi4ldTIwM0RY,inputs=MyUwQTAlMEE2) Based off Leaky Nun's [answer](https://codegolf.stackexchange.com/a/148601/59183). [Answer] # [GolfScript](http://www.golfscript.com/golfscript/), ~~16~~ 14 bytes ``` ~{!!}%{+}*.1>* ``` [Try it online!](https://tio.run/##S8/PSStOLsosKPn/v65aUbFWtVq7VkvP0E7r//9oEwUjBYNYAA "GolfScript – Try It Online") * @Challenger5 -2 bytes This program takes an array of 3 integers representing the coefficients in the equation `Ax + By = C` **Example Input/Output** ``` [1 1 1] -> 3 [-2 3 1] -> 3 ``` **How it Works** ``` ~ - Eval string (input) { }% - Map to array !! - Double not (equivalent to != 0) {+}* - total array (fold addition) . - Duplicate top of stack 1> - Greater than 1? * - Multiply ``` This was a little tricky at first for me to figure out a mathematical way to calculate this. However there are only 8 possible configurations such that `a != 0 & b != 0 & c != 0` ``` 0 0 0 = 0 a 0 0 = 0 0 b 0 = 0 0 0 c = 0 a 0 c = 2 0 b c = 2 a b 0 = 2 a b c = 3 ``` I eventually came to the following function. ``` F(a,b,c) { var r = sign(a)+sign(b)+sign(c); if(r > 1) r; else return 0; } ``` and the whole thing can be condensed to a single math problem ``` F(a,b,c) { return (sign(a)+sign(b)+sign(c)) * (sign(a)+sign(b)+sign(c) > 1); } ``` [Answer] # [Retina](https://github.com/m-ender/retina), 13 bytes ``` M`\b0 T`d`320 ``` [**Try it online**](https://tio.run/##K0otycxL/K@q4Z7w3zchJsmAKyQhJcHYyOD/f0MdIOQy0jGGkgZcIBEDLiBLxwxMmnIZ6FjomABJkDiYBAA) Also based on Leaky Nun's [answer](https://codegolf.stackexchange.com/a/148601/34718). [Answer] # JavaScript, 25 bytes ``` _=>3<<!_[0]+!_[1]+!_[2]&3 ``` Based off Leaky Nun's answer. [Answer] # [Haskell](https://www.haskell.org/), 22 bytes ``` f l="320"!!sum[1|0<-l] ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P00hx1bJ2MhASVGxuDQ32rDGwEY3J/Z/bmJmnoKtQm5iga@CRkFpSXBJkU@egp6ChpWCkpImkJGmyaUABNEK0YY6CiAUC@brKETrGukoGCMLAPm6QAEDuABEB4IPktRRMEOYABEwhQsAOboWOgomyAKGaCYagPgKsf8B "Haskell – Try It Online") ## Point-free solution, 27 bytes ``` ("320"!!).(\l->sum[1|0<-l]) ``` [Try it online!](https://tio.run/##XYxBDoIwEEX3nuLTVZu0pIAaY8QT6MplYdEQUWNLGoGdZ7cWSYA4@Yt5bzL/rtvn1Rhf54WnJEsliSIW08KIY9tblbzlQZiSeasfDXJY7c6gru8u3evUIAbdgxAWlpqtEEZBJRxDyh9zKJFyZEsRWAQhJzF@zDwcObZzwyg2kwggdhzrpUj@GuXAKP2nqo2@tV5Uzn0B "Haskell – Try It Online") [Answer] ## Perl 6, 18 bytes ``` {3+<@_.grep(0)+&3} ``` [Answer] # [ABCR](https://github.com/Steven-Hewitt/ABCR), 30 bytes Input is in the form `A,B,C` where the commas can be replaced by any non-numeric, non-`-` character. ``` BBi7baxci7baxci7bax@7)A7(xxo ``` No online interpreter yet, but here's an explanation: ``` BB Add two values to the B queue. (Values are unimportant) i7 ax Read in a number. If it's non-zero... b Dequeue one item from the B queue. c Read in the delimiter... i ... And promptly overwrite it with the next number. 7baxci7bax Repeat the whole "if 0, dequeue from B" for the other two input numbers. @ Get the current length of the B queue. [2, 1, or 0] 7 If the length isn't 0... ) ... Increment it to our required [3,2,0] A ... And enqueue it to A. (We don't need to add to A otherwise, because it defaults to 0 already if there's no value in it. I used that to exit the queue with 7_ax earlier.) 7(xx Set the register to 0 to exit from loop. o Peek A and print as a number. ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~14~~ 11 bytes ``` 0⌈3-×⍨+/0=⎕ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkGXI862tP@Gzzq6TDWPTz9Ue8KbX0DW6Dsf6D4fwUwSOMyVDBUMAAA "APL (Dyalog Unicode) – Try It Online") `⎕IO` is `0`. Thanks to @Adám for -3 bytes! [Answer] # [Deorst](https://github.com/cairdcoinheringaahing/Deorst), 12 bytes ``` l0EN))A:k?Z+ ``` [Try it online!](https://tio.run/##S0nNLyou@f8/x8DVT1PT0SrbPkr7//9oQx0gjAUA "Deorst – Try It Online") Somewhat based off [Leaky's answer](https://codegolf.stackexchange.com/a/148601/66833); uses the same premise, but a different mapping method. ## How it works Deorst has a count occurrences builtin, but doesn't (for some reason) have an indexing command, so I had to create the following mapping, where the left is `a.count(0)` and the right is the wanted result ``` 0 -> 3 1 -> 2 2 -> 0 ``` The program itself works like this (example input of `[1,1,1]`) ``` l0 - Push 0; STACK = [[1 1 1] 0] EN - Count; STACK = [0] )) - Subtract 2; STACK = [-2] A - Absolute; STACK = [2] : - Duplicate; STACK = [2 2] k?Z - Positive?; STACK = [2 1] + - Sum; STACK = [3] ``` [Answer] # [Add++](https://github.com/cairdcoinheringaahing/AddPlusPlus), 23 bytes ``` D,f,@@@,!$!@!s2$_|d0$>+ ``` [Try it online!](https://tio.run/##S0xJKSj4/99FJ03HwcFBR1FF0UGx2EglvibFQMVO@////wZAaAwA "Add++ – Try It Online") Based off both [my Deorst answer](https://codegolf.stackexchange.com/a/148607/66833) and [Leaky's Python answer](https://codegolf.stackexchange.com/a/148601/66833) ## How it works ``` D,f,@@@, - Create a triadic function. Example arguments; [1 1 1] ! - Logical NOT; STACK = [1 1 0] $ - Swap; STACK = [1 0 1] ! - Logical NOT; STACK = [1 0 0] @ - Reverse; STACK = [0 0 1] ! - Logical NOT; STACK = [0 0 0] s - Sum; STACK = [0] 2 - Push 2; STACK = [0 2] $ - Swap; STACK = [2 0] _ - Subtract; STACK = [-2] | - Absolute; STACK = [2] d - Duplicate; STACK = [2 2] 0 - Push 0; STACK = [2 2 0] $ - Swap; STACK = [2 0 2] > - Greater to; STACK = [2 1] + - Sum; STACK = [3] ``` However, I think I've been using functions too much in Add++, rather than the main code body. So I attempted to do this using both functions, and the code body, and resulted in a much nicer 50 byte piece (yes, that is the longest answer here): ``` # Example input: 1 1 1; # x and y are the accumulators D,f,@@@,!$!@!s # Count the 0s $f>?>?>? # Call f with the input. -2 # Subtract 2; x: -2; y: 0 ^2 # Square; x: 4; y: 0 S # Square root; x: 2.0; y: 0 \1 # To integer; x: 2; y: 0 y:x # Assign x to y; x: 2; y: 2 } # Switch to y; x: 2; y: 2 >0 # Is positive?; x: 2; y: 1 } # Switch to x; x: 2; y: 1 +y # Add y to x; x: 3; y: 1 O # Print x ``` [Try it online!](https://tio.run/##S0xJKSj4/99FJ03HwcFBR1FF0UGxmEslzc4eBLl0jbjijLiCuWIMuSqtKrhquewMgIR2JZf/////DUEQAA "Add++ – Try It Online") ]
[Question] [ The Lehmer-Comtet sequence is a sequence such that **a(n)** is the **n**th derivative of **f(x) = xx** with respect to **x** as evaluated at **x = 1**. # Task Take a non-negative integer as input and output the **n**th term of the Lehmer-Comtet sequence. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so you should minimize the file size of your source code. # Test Cases [OEIS 5727](http://oeis.org/A005727) Here are the first couple terms in order (copied from the OEIS) ``` 1, 1, 2, 3, 8, 10, 54, -42, 944, -5112, 47160, -419760, 4297512, -47607144, 575023344, -7500202920, 105180931200, -1578296510400, 25238664189504, -428528786243904, 7700297625889920, -146004847062359040, 2913398154375730560, -61031188196889482880 ``` [Answer] # [Haskell](https://www.haskell.org/), ~~77~~ 75 bytes, no differentiation builtins ``` x@(a:b)&y@(c:d)=a*c:zipWith(+)(b&y)(x&d) s=1:s&(1:scanl(*)1[-1,-2..]) (s!!) ``` [Try it online!](https://tio.run/##DcQxDsIgFADQvaegC/m/ChHcSEh6A0eHpsMvFUukhEiH1sOLvuEtVF6PGGvdeyAzIT96cGZGS50zn5DvYVvghDDxA2HnMzbFKlM4/HOUInSoBqHOQks5YuMtlLbFulJIzLL8DmljsFJmng0XKfV1xPp1PtKzVHHTPw "Haskell – Try It Online") ### How it works We represent a function as its infinite list of Taylor series coefficients about \$x = 1\$: $$ f(x) = \sum\_{n=0}^\infty \frac{f^{(n)}(1)}{n!} (x - 1)^n $$ is represented by \$[f(1), f'(1), f''(1), ...]\$. The `&` operator multiplies two such functions using the product rule. This lets us recursively define the function \$s(x) = x^x\$ in terms of itself using the differential equation $$ s(1) = 1, \\ s'(x) = s(x) \cdot (1 + \ln x), $$ where $$ \ln x = \sum\_{n=1}^\infty \frac{(-1)^{n-1}(n - 1)!}{n!}(x - 1)^n. $$ [Answer] # Mathematica, 19 bytes ``` D[x^x,{x,#-1}]/.x->1& ``` *-18 bytes from @Not a tree* [Answer] # [Octave](https://www.gnu.org/software/octave/) with Symbolic Package, ~~36~~ 32 bytes ``` syms x @(n)subs(diff(x^x,n),x,1) ``` The code defines an anonymous function which outputs a symbolic variable with the result. [**Try it online!**](https://tio.run/##y08uSSxL/f@/uDK3WKGCy0EjT7O4NKlYIyUzLU2jIq5CJ09Tp0LHUPN/moKtQmJesbVCWn6RQh6QY2BlZKyjkJJZXKCRBtSlaa2QmpfyHwA) [Answer] # [Haskell](https://www.haskell.org/), 57 bytes ``` f 0=1 f n=f(n-1)-foldl(\a k->f(k-1)/(1-n/k)-a*k)0[1..n-1] ``` [Try it online!](https://tio.run/##DcoxDoMwDAXQvaf4Q4ekkkN8gPQilMESWCAnJmp7/8D69Hb52VbrGIpc@KHwosGJI@lZ1xo@AqO3BrtpCkw@WSR5Wcwzp3THZTQ5HAX9e/gfTzTpUMw5Jc7LuAA "Haskell – Try It Online") No built-ins for differentiating or algebra. Outputs floats. [Answer] # Python with [SymPy](http://www.sympy.org/en/index.html), ~~77~~ ~~75~~ ~~58~~ 57 bytes *1 byte saved thanks to @notjagan* *17 bytes saved thanks to @AndersKaseorg* ``` from sympy import* lambda n:diff('x^x','x',n).subs('x',1) ``` [Answer] # [SageMath](http://www.sagemath.org/), ~~33~~ 32 bytes ``` lambda n:diff(x^x,x,n).subs(x=1) ``` [Try it on SageMathCell](https://sagecell.sagemath.org/?z=eJxLs81JzE1KSVTIs0rJTEvTqIir0KnQydPUKy5NKtaosDXU5OWKTtPI01RIyy9SyFPIzFMoSsxLT9UwMtGMBQBrsRMp&lang=sage) [Answer] # [Python 3](https://docs.python.org/3/), 150 bytes ``` lambda n:0**n or sum(L(n-1,r)for r in range(n)) L=lambda n,r:0<=r<=n and(0**n or n*L(n-2,r-1)+L(~-n,r-1)+(r-~-n)*L(~-n,r)if r else n<2or-~-n*L(n-1,0)) ``` [Try it online!](https://tio.run/##RY0xDoJAEEV7TzHlzMomgIkFYW/AEWzWwOom8DEDFjZeHReR2P0/P2/e4zXfR5yW4C5L74dr6wlVbgxoVJqeAzcMW2QqIXWlCFKPW8cQOTRuJzKt8tpp7UAeLe88zEqXmdpCjg2/LbbIalMW8ztJDOl1108doS7H72g2by6yrOb4NxdnqR4aMXPgmOYP "Python 3 – Try It Online") Exponential runtime complexity. Uses the formula given in the OEIS page. [Answer] # [Python 3](https://docs.python.org/3/), ~~288~~ 261 bytes Differentiation without differentiation built-in. ``` p=lambda a,n:lambda v:v and p(a*n,n-1)or a l=lambda v:v and p(1,-1) e=lambda v:v and m(e,a(p(1,0),l))or 1 a=lambda f,g:lambda v:v and a(f(1),g(1))or f(0)+g(0) m=lambda f,g:lambda v:v and a(m(f(1),g),m(g(1),f))or f(0)*g(0) L=lambda n,f=e:n and L(n-1,f(1))or f(0) ``` [Try it online!](https://tio.run/##fY9BCoMwEEX3niLLGTsFQ1cNeAMvMcUkDZhRRISePk1ES7HQzfDh/cdnptfyHOWW0tQOHB89KyYxe1zNqlh6NQHXQnLVOM6Kq6H94ZoyrOwZRLDEUHCDNGDRdcVHy5E/LzE40Eg@n1J20ODF51PFv1LcNaQIxSX30etN7w5dyLXWyOZ1kF8i97WVXA5BBVEzi7dwRzPNQRboICCmNw "Python 3 – Try It Online") ## How it works Each of the first five lines define functions and their derivatives and their results when evaluated at `1`. Their derivatives are also functions. * `p` is power i.e. `a*x^n` * `l` is logarithm i.e. `ln(x)` * `e` is exponential i.e. `exp(x)` * `a` is addition i.e. `f(x)+g(x)` * `m` is multiplication i.e. `f(x)*g(x)` Usage: for example, `exp(ln(x)+3x^2)` would be represented as `e(l()+p(3,2))`. Let `x=e(l()+p(3,2))`. To find its derivative, call `x(1)`. To find its result when evaluated at `1`, call `x(0)`. Bonus: [symbolic differentiation](https://tio.run/##pZLRaoMwFIbvfQoRhHNsVia7E3yVSaiJC8QsmLRkT29jk6wrUzvYhRiOH/m//6D@sh@f6m2eT5Iak@smy3vG864TStiuA8MkJ5QobJbTkZLbS7V@FMj@hmAzMXueVK4hcFXgIv5SY6Avj3RgU6SxU0xMQFEK916KooSHdMyCrWw2HGqylfi6EyYVOCzi3Wx1Ezzugbd8NXoEFlQ5Bld@7AHXVeodFeY0lAaL0n9LF0Yxui5GhqQWgofWj1YdKdzNIrstGdEL4CGi/rgjvlgfgjr8cCff5wFTkfH/RcbfVZDE4XAf8qflqj@Xq56Um13LvNfyD9ZIpN8rZnoSyoJbhNKD8xU) [Answer] # Python3+mpmath 52 bytes ``` from mpmath import* lambda n:diff(lambda x:x**x,1,n) ``` -3 bytes, Thanks @Zachary T [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 32 bytes ``` n->n!*Vec((y=1+x+O(x^n++))^y)[n] ``` [Try it online!](https://tio.run/##K0gsytRNL/ifpmD7P0/XLk9RKyw1WUOj0tZQu0LbX6MiLk9bW1MzrlIzOi/2f1p@kUaegq2CoY6CoYGBjkJBUWZeCVBESUHXDkikaeRpamr@BwA "Pari/GP – Try It Online") ]
[Question] [ Paul is one of your Belgian acquaintances, and he would like you to create a program that **outputs at least one of the following five strings**: ``` 12496=>14288=>15472=>14536=>14264 14264=>12496=>14288=>15472=>14536 14536=>14264=>12496=>14288=>15472 15472=>14536=>14264=>12496=>14288 14288=>15472=>14536=>14264=>12496 ``` It represents the friends he's most proud of, and he would like to eat with them. Paul also thinks that the number 6 is perfect, and that is the only number worth using. So **you cannot use any other digit than "6"** in your code (0 to 5 and 7 to 9 are forbidden). Your program cannot take any inputs. The output can contain garbage before and/or after the string but should contain at least one of the above strings. For example this is a valid output : ``` 220frefze f**14288=>15472=>14536=>14264=>12496**fczfe fz**15472=>14536=>14264=>12496=>14288**zfe fzehth ``` I "ligthly" hinted in the question as how I expect this to be resolved, but how knows ? Maybe there is a better way... Hope you have fun. This is code-golf : lowest score in bytes wins. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~18~~ 17 bytes ``` •w[•Y·FDѨO})„=>ý ``` [Try it online!](https://tio.run/nexus/05ab1e#@/@oYVF5NJCIPLTdzeXwxEMr/Gs1HzXMs7U7vPf/fwA "05AB1E – TIO Nexus") **Explanation** ``` •w[• # base 214 encoding of 12496 Y·F # loop 2*2 times D # duplicate top of stack Ñ # push divisors ¨ # remove the last element (itself) O # sum } # end loop ) # wrap in list „=>ý # join list on "=>" ``` In short, we calculate each number as `f(n+1) = sum(divisors(f(n)) - f(n)` [Answer] ## Pyke, 16 bytes ``` wヰw$VDlsh)J"=> ``` [Try it here!](http://pyke.catbus.co.uk/?code=w%E3%83%B0w%24VDlsh%29J%22%3D%3E) ``` wヰ - 12496 w$ - 4 V ) - repeat ^: D - duplicate(^) l - factors(^) s - sum(^) h - ^ + 1 J - v.join(^) "=> - "=>" ``` Anytime a string literal is at the end of a program, it swaps it with the token just before it, saving 1 byte in cases such as this. Pyke's `factors` function doesn't include the number itself nor 1. If numbers were allowed, 1 byte could be saved by replacing `w$` with `4` ## Pyke, 21 bytes ``` uバ㟐㱰㣈㞸J"=> ``` [Try it here!](http://pyke.catbus.co.uk/?code=u%05%E3%83%90%E3%9F%90%E3%B1%B0%E3%A3%88%E3%9E%B8J%22%3D%3E&input=12496+14288+15472+14536+14264) Create a list of the numbers required and joins them. Not very interesting apart from the trick with the strings. [Answer] # MATLAB, 44 bytes ``` ['','=>@EBIJ=@>DDIJ=A@C>IJ=@A?BIJ=@>B@'-6-6] ``` [**Try it online!**](https://tio.run/#0vhvW) I haven't found a pattern in the numbers (and it would be hard to use the pattern to anything anyways, since I can't use numbers), so I'll just go for the naive approach. `'=>@EBIJ=@>DDIJ=A@C>IJ=@A?BIJ=@>B@'` is the string `'12496=>14288=>15472=>14536=>14264'` when 12 is added to the ASCII-values. Now, input that string, subtract `6+6`, and concatenate with the empty string `''` to convert it to a character array. [Answer] # JavaScript (ES6), 57 bytes/47 (UTF-8) characters *Thanks to user5090812 for 10 B save* ``` _=>[...'バ㟐㱰㣈㞸'].map(a=>a.charCodeAt()).join`=>` ``` ## Explanation First we create an array and fill it with the characters in the string `バ㟐㱰㣈㞸`. Then we loop over the string (`a` has the value of the current element) and we change the character into its character code. Then we join all values in the array by `=>`. ## Old: 67 bytes ``` _=>[6,6,6,6,6].map((_,a)=>`バ㟐㱰㣈㞸`.charCodeAt(a)).join`=>` ``` ### Explanation First we create an array of length 5. Then we change the values of the array at each index for the character code of the character at that same index in the string `バ㟐㱰㣈㞸`, which are the numbers of all of Paul's friends in order. When we got that, we join the array together, and we use `=>` as separator. ## Usage To use it, simply run this: ``` f=_=>[...'バ㟐㱰㣈㞸'].map(a=>a.charCodeAt()).join`=>`;alert(f()) ``` ## Output ``` 12496=>14288=>15472=>14536=>14264 ``` [Answer] ## Ruby, 36 bytes (26 characters) ``` p"バ㟐㱰㣈㞸".unpack("U*")*"=>" ``` Because, why not. Boring as hell. ## older version - 53 bytes ``` p %w(jol mld oim n6b mke).map{|x|x.to_i ~-6*~-6}*'=>' ``` Explanation: encoding the numbers in base 25 gives the 5 six-free strings, to decode them I only have to represent the number 25 using only 6: (6-1)*(6-1) => ~-6*~-6 [Answer] # [Perl 6](http://perl6.org/), ~~63~~ 59 bytes ``` {$/=6;$/--;join "=>",<JOL MLD OIM N6B MKE>».parse-base($/*$/)} ``` ``` {join "=>",<JOL MLD OIM N6B MKE>».parse-base(--($_=6)*$_)} ``` Decodes the numbers from base 25, because that's the only base supported by `.parse-base` (2 to 36) where none of them have invalid digits. *Thanks to Neil for -3 bytes.* # [Perl 6](http://perl6.org/), ~~82~~ 75 bytes ``` {my \a="BXS".parse-base(6*6);join "=>",(a,{sum grep $_%%*,^$_}...^{$_==a if $++})} ``` ``` {my \a="BXS".parse-base(6*6);join "=>",({$/=$_//a;sum grep $/%%*,^$/}...a)} ``` Decodes the number `15472` in base 36, and then generates the sequence by calculating each number as the sum of proper divisors of the previous number. # [Perl 6](http://perl6.org/), 69 bytes (47 characters) - noncompeting ``` {"{١٢۴۹6}=>{١۴۲۸۸}=>{١۵۴۷۲}=>{١۴۵۳6}=>{١۴۲6۴}"} ``` Doesn't use any of the forbidden ASCII digits, uses Unicode digits from the Arabic-Indic block instead (2 bytes each)! The `{ }` string interpolations make sure they're parsed as Perl 6 number literals, and then stringified to their ASCII representations. Okay, this is cheating - that's why I didn't use it as my main answer... :) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~5~~ 4 bytes ``` ȷṗȷỌ ``` Prints all five strings. Takes advantage of the fact that "garbage" output is allowed and buries the five strings in **103003** characters of output. ### How it works ``` ȷṗȷỌ Main link. No arguments. ȷ Set the return value to 1000. ṗȷ Cartesian power; form all arrays of length 1000 that consist of integers in [1, ..., 1000]. Ọ Unordinal; convert all integers to characters. ``` [Answer] # C, ~~94~~ ~~84~~ 77 Bytes Stoopid simple. Special thanks @Neil ``` g(){char*m="!mnpuryzmpnttyzmqpsnyzmpqoryzmpnrp";for(;*++m;)putchar(*m-66+6);} ``` ~~f(){printf("%d=>%d=>%d=>%d=>%d",'~'*'r'-'d','~'*'d'-'h','~'*'r'-'L','~'*'z'+'d','~'\*'t'-'P');}~~ [Answer] # PHP, ~~73~~ ~~63~~ 60 bytes ``` for(;$c="|`*X6H-$*@"[$i];)echo!!$i&++$i?"=>".!!6:"",ord($c); ``` Run with `-nr`. a little less lazy: took string as list of `=>1(ascii)(ascii)` i.e.: `124`,`96`,`=>1`,`42`,`88`,`=>1`,`54`,`72`,`=>1`,`45`,`36`,`=>1`,`42`,`64`; print `=>1` by string index, append ascii code **breakdown** ``` # loop through string with index $i for(;$c="|`*X6H-$*@"[$i];)echo # string ascii values: 124,96,42,88,54,72,45,36,42,64 !!$i # true if $i>0 &++$i # odd if (old) $i is 0,2,4,6,8 # -> true for 2,4,6,8 ?"=>".!!6 # if true, print "=>1" :"", # else print nothing ord($c); # print ascii value ``` [Answer] ## C++, 92 bytes ``` #include <cstdio> int main(){for(char c:"UVX]ZabUXV\\abUYX[VabUXYWZabUXVZX")putchar(c-6*6);} ``` [Answer] # PHP, 53 bytes ``` <?=join('=>',unpack('v*',gzinflate('�`p������s'))); ``` Hex dump: ``` 00000000: 3c3f 3d6a 6f69 6e28 273d 3e27 2c75 6e70 <?=join('=>',unp 00000010: 6163 6b28 2776 2a27 2c67 7a69 6e66 6c61 ack('v*',gzinfla 00000020: 7465 2827 bb60 70c1 bcc0 e684 c50e 7300 te('.`p.......s. 00000030: 2729 2929 3b '))); ``` Output: ``` 12496=>14288=>15472=>14536=>14264 ``` Explanation: Each of the five-digit integer sections is encoded as an unsigned short little endian, then concatenated together and the result is gzipped. This happens to produce a byte steam that has no offending digit characters, which is then hard-coded into a string. To extract, un-gzip the stream, unpack the two-byte shorts, interpret each as a string, and join with `>=`. [Answer] # Java 8, 134 bytes Golfed: ``` ()->{String s="";for(String a:new String[]{"JOL","MLD","OIM","N6B","MKE"}){if(!s.isEmpty())s+=("=>");s+=Long.valueOf(a,25);}return s;} ``` Ungolfed, full program: ``` import java.util.function.*; public class FindFiveFriendsToEatChickenWithPaul { public static void main(String[] args) { System.out.println(toString(() -> { String s = ""; for (String a : new String[] { "JOL", "MLD", "OIM", "N6B", "MKE" }) { if (!s.isEmpty()) s += ("=>"); s += Long.valueOf(a, 25); } return s; })); } private static String toString(Supplier<String> s) { return s.get(); } } ``` [Answer] ## Batch, 191 bytes ``` @set/as=n=66*(66+66+66+6*6)+66/6+66/6+6,u=6/6 @call:t @call:t @echo %s: ==^>% @exit/b :t @call:c :c @for /l %%i in (%u%,%u%,%n%)do @set/an-=%%i*!(%n%%%%%i) @set/an=-n @set s=%s% %n% ``` I estimate that it would take a minimum of 32 bytes to calculate each number using only `6`s plus another 32 to print them all out, which is already 192 bytes, so I'm winning by computing the amicable chain. Also, I think five `%`s in a row is a record for me. Also, neat Batch trick: the `%n%` is substituted before the `for` loop is evaluated, so the loop calculates all the factors of `n`, and subtracts them from `n`, thus resulting in the negation of the desired result. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes ``` “<ọ’ÆṣÐĿj“=> ``` Prints the fourth string and nothing else. [Try it online!](https://tio.run/nexus/jelly#@/@oYY7Nw929jxpmHm57uHPx4QlH9mcBxWzt/v8HAA "Jelly – TIO Nexus") ### How it works ``` “<ọ’ÆṣÐĿj“=> Main link. No arguments. “<ọ’ Yield the 1-based indices of '<' and 'ọ' in Jelly's code page, i.e., [61, 222], and convert the array from base 250 to integer. This yields 15472. ÐĿ Iteratively call the link to the left until the results are no longer unique and return the array of all unique results. Æṣ Compute the proper digit sum of the previous value (initially 15472). j“=> Join, separating by the string "=>". ``` [Answer] ## Python 2, ~~78~~ 72 bytes ``` print''.join(chr(ord(x)-6-6)for x in'=@>DDIJ=A@C>IJ=@A?BIJ=@>B@IJ=>@EB') ``` **Edit** - Thanks to [Stewie Griffin](https://codegolf.stackexchange.com/users/31516/stewie-griffin) for saving 6 bytes! Also, another solution would be to output all the possible permutations. OP says garbage is fine. ``` from itertools import permutations print str(list(permutations(''.join(str(x)+'.'for x in range(int('9'*5)).replace(',','').replace('\'','') # also 9 and 5 need to be converted using ord and chr ``` There is too much redundancy in converting from `int` or `list` to `str`. I guess this would be easier in some esoteric languages, but I know none of them. ]
[Question] [ The [cosmic call](https://en.wikipedia.org/wiki/Cosmic_Call) is a message sent into space in 1999 and 2003. It's made of 23 127\*127px monochrome bitmap images, as detailed [here](http://blog.plover.com/aliens/dd/intro.html). Your mission is to write a program that displays the entire 127\*2921px message, either as a text (made of zeros, ones and line breaks) or as an image (drawn on screen or saved on disk). There will be two categories of winners: one for text output and one for image output. All the tricks are permitted, except common loopholes. It is allowed to output the 23 pages separately. It is allowed to write up to 23 programs (like, one for each page) and sum their size to determine your score. It is allowed to use up to 23 binary files alongside your program(s). Their weight is counted in your score. The shortest code (in byte) wins. At 1 bit per pixel, the image contains 127\*127\*23/8 = 46370 bytes + 7 bits of data. (warning: it's not allowed to output an extra zero if you store pixel values into 46371 bytes) Trailing newline/space is allowed for the text output. Visual output can not contain any black pixel besides the black pixels of the cosmic call. It can be drawn in one column (ordered correctly), or split in 23 images, or animated (like a gif), also ordered correctly. Attachment: [the text output](http://pastebin.com/Nhg0qKLC), and the image output to reproduce: [![cosmic call](https://i.stack.imgur.com/u1MU6.png)](https://i.stack.imgur.com/u1MU6.png) [Answer] # GIF, 27386 bytes Here are the pages of the original transmission sliced into individual GIF frames, it turned out not to be as small as 1 PNG of all of them :( [![cosmic call animated GIF](https://i.stack.imgur.com/kQ6ld.gif)](https://i.stack.imgur.com/kQ6ld.gif) [Answer] # HTML, 16012b I compressed the image in PNG8, opened it in a text editor, appended `<svg onload="document.body.innerHTML='<img src=#>'">` at the end, and voilà: Demo: <http://xem.github.io/miniCosmicCall/> --- NB: appending just `<img src=#>` works too but it lets a lot of garbage visible, so I prefer not to. --- PS: for the fun, I also put the entire message in a single, executable tweet (you can copy-paste it in a browser console and the image appears): <https://twitter.com/MaximeEuziere/status/742440423994580992> [Answer] # Python 2.7 - ~~10971~~ 8077 bytes **update:** * LZMA actually for some reason doesn't work for me, so I went back to Deflate. * I found an [online tool](https://tinypng.com/) to compress the PNG even further (they say they use lossy compression, but the array remains unchanged) * I golfed the `__main__.py` script a bit more... * I found I was omitting a step (extracting the data files from zip archive) * Added DL link (see bottom) Most compression algorithms look at data as a 1 dimensional array, and therefore cannot capture the repeating 2 dimensional characters displayed in the cosmic call (IMO also makes it harder for aliens to understand too :P). First, I selected each character as a 7\*5 array and made a list of all unique characters (101 if I recall). Then I iterated over the image, and when a character was found, the position and index of that character (in the character list) were recorded. Those positions could be represented with a single int, however with over 2K chars found, and positions ranging from 0-370966 (divmod form) require up to 3 bytes each. I collected the character positions in order however, so I instead converted absolute position to offset position, making most of the numbers less than 1 byte. I encoded this list in utf-8 to account for the few numbers that were greater than 1 byte After recording and removing all the matched characters, I saved the png with maximum compression. I then packaged the python reconstruction script (reverse same process), the png, the chatacter template, and the character position list all into a zip file to take advantage of the fact that python can take a folder or zip file as an argument, and it will begin execution at any file in the top level named `__main__.py`. I played around with 7z a bit to get the best compression, which turned out to be LZMA with a 1M dict and 32bit words. here's the decoder script (golfed but with comments still) ``` import sys,zipfile as z z.ZipFile(sys.argv[0]).extractall() #extract data files from zip to cwd from numpy import* o=open #next line overwrites open, which I need from PIL.Image import* from scipy.ndimage import* a=imread('p')[:,:,0]/255 #read image file a[:2414,0]=0 #draw vertical borders a[2541:,0]=0 a[2412:,-1]=0 a[:2287,-1]=0 for x in range(0,2921,127):a[[x,x+126],:]=0 #draw horizontal borders with o('c','rb') as f:t=f.read();C=[int(i)for c in t for i in'{0:08b}'.format(ord(c))] #read character template file and convert to list of bytes C=array(C[:-1]).reshape([101,7,5]) #re-slice (extra 0 appended to make even number of bytes) and re-shape with o('l','rb') as f:L=array([ord(x)for x in f.read().decode('utf_8')]).reshape([2158,2]) #read decode and reshape positional list p=0 #relative position accumulator for e in L:p+=e[0];x,y=p%127,p/127;a[y:y+7,x:x+5]=C[e[1]] #divmod for x,y position and paste character template onto array at position i=fromarray(a*255) i.show() ``` [link to download for the zip file...](http://s000.tinyupload.com/?file_id=75432161212869597524) [Answer] # ~~Gzip~~ `bzip2` in the shell, ~~20914~~ 18965 bytes Make the output data file with the text output provided in the question, `bzip2` it and rename the file to `s`. This then allows: ``` bzcat s ``` to do the job. So it adds up to 18958 bytes of data and a 7 byte command. [Answer] # Bash + WebP binary, 11 + 15330 = 15341 bytes As the rules state this: > > Your mission is to write a program that displays the entire 127\*2921px > message … or as an image (drawn on screen **or saved on disk**). > > > **It is allowed to use up to 23 binary files alongside your program(s).** Their weight is counted in your score. > > > and > > All the tricks are permitted, except common loopholes. > > > …I could not resist to post something stupidly simple. The program is in bash and it outputs the image by saving it on disk. It uses 1 binary file, which also happens to be image file (yeah WebP is an image format), therefore the program can do as little as… make a copy of that file. So, the code (11 bytes): ``` cp b a.webp ``` Assuming the companion binary is named "b", the code writes the image file to disk with correct extension ("a.webp"). I see little reason to upload the binary, because it's trivially created by running ``` cwebp -z 9 <downloaded input file> b ``` it produces the file with 15330 bytes. If anyone wants, I can upload it somewhere. NB: `-z` option in `cwebp` activates lossless compression mode. `9` is the compression strength (max). [Answer] # Pyth, 46381 bytes For obvious reasons it cannot be posted here. ``` jc.BC"<too long>"127 ``` [Sample.](http://pyth.herokuapp.com/?code=jc.BC%22%3F%C3%BF%C3%BF%C3%BF%C3%BF%C3%BF%C3%BF%C3%BF%C3%BF%C3%BF%C3%BF%C3%BF%C3%BF%C3%BF%C3%BF%C3%BF%C3%BF%C3%BF%C3%BF%C3%BF%C3%BF%C3%BF%C3%BF%C3%BF%C3%BF%C3%BF%C3%BF%C3%BF%C3%BF%C3%BF%C3%BF%C3%BF%22127&debug=0) [Pastebin of hexdump of program.](http://pastebin.com/A4PBRTAA) [Answer] ## Python 3, 64513 bytes Use only ASCII ! <http://pastebin.com/PMLb4Xti> Old version, 64529 bytes: <http://pastebin.com/nteYkUtM> ]
[Question] [ Write a program using only [printable ASCII characters](https://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters) that takes no input. For reference, here are the 95 printable ASCII characters in order: ``` !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ ``` When your program is run it should print `0` (plus an optional trailing newline) to stdout, then terminate normally. When each character in your program is replaced by the character N spaces to its right in printable ASCII, looping around from `~` to space, the resulting printable ASCII string will *ideally* be a program runnable in the same language that takes no input and outputs N (plus an optional trailing newline) to stdout, then terminates normally, for N = 1 to 94. For example, if your original program was ``` @Cat~(88 !) ``` running it should output `0` and shifting all the characters up the printable ASCII scale by one ``` ADbu )99!"* ``` should result in another program that outputs `1`. Doing so again will ideally result in another program that outputs `2` ``` BEcv!*::"#+ ``` and so on with 3 and 4, etc. up to the point of shifting 94 times ``` ?B`s}'77~ ( ``` which ideally is a program that outputs `94`. The relief is that this is only the ideal behavior. Your program and its 94 derivatives do not all need to work, but the more that consecutively do from the start the better. (Programs that do not work may have any behavior whatsoever.) # Scoring Your score is the number of *consecutive* programs starting from the original (the one that outputs `0`) that do work, i.e. correctly output their corresponding N. The answer with the highest score (a maximum of 95) wins. If there's a tie then the program with the shortest length in bytes wins. For example, if `@Cat~(88 !)` output `0` and `ADbu )99!"*` output `1` but `BEcv!*::"#+` errored, then your score would be 2. It's 2 even if `?B`s}'77~ (` accurately outputs `94` and even if all the programs for N = 30 to 40 worked. Only the *consecutive* number of working programs, starting at zero, are counted. # Notes * To combat potential contention and loopholes, competing answers must output their numbers in decimal with no leading zeroes or signs or decimal points (i.e. plain `0` `1` `2` ... `94`). * Languages that use different bases or number formats are allowed but are not eligible to win. * The presence of an optional trailing newline does not need to be consistent across programs. * Functions and REPL commands are not allowed, only full programs. [Answer] ## [Ook!](https://esolangs.org/wiki/Ook!), 95 programs, ~~19992~~ 14066 bytes ``` Ook!Ook!Ook!Ook?Ook.Ook?Ook.Ook.Ook?Ook.Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook?Ook!Ook.Ook?Ook!Ook!Ook!Ook!Ook!Ook!Ook!Ook.NJ_.NJ_.NJ_.NJ}.NJl.NJ}.NJl.NJl.NJ}.NJl.NJ_.NJ_.NJ_.NJ_.NJ_.NJ_.NJ_.NJ_.NJ_.NJ_.NJ}.NJ_.NJl.NJ}.NJ_.NJl.NJ_.NJl-)>l-)>l-)>l-)\l-)Kl-)\l-)Kl-)Kl-)\l-)Kl-)>l-)>l-)>l-)>l-)>l-)>l-)>l-)>l-)>l-)>l-)\l-)>l-)Kl-)\l-)Kl-)Kl-)Kl-)Kl-)Kl-)Kl-)>l-)Kl-)>l-)Kkg|Kkg|Kkg|Kkg;Kkg*Kkg;Kkg*Kkg*Kkg;Kkg*Kkg|Kkg|Kkg|Kkg|Kkg|Kkg|Kkg|Kkg|Kkg|Kkg|Kkg;Kkg|Kkg*Kkg;Kkg*Kkg*Kkg|Kkg*JF[*JF[*JF[*JFy*JFh*JFy*JFh*JFh*JFy*JFh*JF[*JF[*JF[*JF[*JF[*JF[*JF[*JF[*JF[*JF[*JFy*JF[*JFh*JFy*JF[*JFh*JFh*JFh*JFh*JFh*JFh*JFh*JFh*JFh*JF[*JFh)%Gh)%Xh)%:h)%:h)%:h)%Xh)%Gh)%Gh)%Gh)%Gh)%Gh)%Xh)%Gh)%Gh)%:h)%Xh)%Gh)%Gh)%Xh)%Gh)%Xh)%:h)%Gh)%Xh)%Xh)%:h)%Gh)%Xh)%:h)%:h)%:h)%Gh)%:h)%:h)%:h)%:h)%:h)%:h)%:h)%:h)%:h)%:h)%:h)%:h)%:h)%:h)%:h)%Ggc&Ggc7GgcxGgcxGgcxGgc7Ggc&Ggc&Ggc&Ggc&Ggc&Ggc7Ggc&Ggc&GgcxGgc7Ggc&Ggc&Ggc7Ggc&Ggc7GgcxGgc&Ggc7Ggc7GgcxGgc&Ggc7GgcxGgc&FBW&FBW&FBW&FBu&FBd&FBu&FBd&FBd&FBu&FBd&FBW&FBW&FBW&FBW&FBW&FBW&FBW&FBW&FBW&FBW&FBu&FBW&FBd&FBu&FBd&FBd&FBW&FBd&FBW&FBW&FBW&FBW&FBW&FBW&FBW&FBd%!Cd%!Td%!6d%!6d%!6d%!Td%!Cd%!Cd%!Cd%!Cd%!Cd%!Td%!Cd%!Cd%!6d%!Td%!Cd%!Cd%!Td%!Cd%!Td%!6d%!Cd%!Td%!Td%!6d%!Cd%!Td%!6d%!6d%!6d%!Cd%!6d%!6d%!6d%!6d%!6d%!6d%!6d%!Cc_tCc_tCc_tCc_3Cc_"Cc_3Cc_"Cc_"Cc_3Cc_"Cc_tCc_tCc_tCc_tCc_tCc_tCc_tCc_tCc_tCc_tCc_3Cc_tCc_"Cc_3Cc_tCc_tCc_tCc_tCc_tCc_"Cc_"Cc_"Cc_tCc_"B>S"B>S"B>S"B>q"B>`"B>q"B>`"B>`"B>q"B>`"B>S"B>S"B>S"B>S"B>S"B>S"B>S"B>S"B>S"B>S"B>q"B>S"B>`"B>q"B>`"B>`"B>S"B>`"B>`"B>`"B>S"B>`!|?`!|P`!|2`!|2`!|2`!|P`!|?`!|?`!|?`!|?`!|?`!|P`!|?`!|?`!|2`!|P`!|?`!|?`!|P`!|?`!|P`!|2`!|?`!|P`!|P`!|2`!|?`!|P`!|2`!|2`!|2`!|?`!|?`!|?`!|2`!|?_[p?_[p?_[p?_[/?_[}?_[/?_[}?_[}?_[/?_[}?_[p?_[p?_[p?_[p?_[p?_[p?_[p?_[p?_[p?_[p?_[/?_[p?_[}?_[/?_[p?_[p?_[p?_[p?_[p?_[}?_[}?_[}?_[}?_[}?_[}?_[}?_[}?_[}?_[}?_[}?_[p?_[}>:O}>:O}>:O}>:m}>:\}>:m}>:\}>:\}>:m}>:\}>:O}>:O}>:O}>:O}>:O}>:O}>:O}>:O}>:O}>:O}>:m}>:O}>:\}>:m}>:\}>:\}>:O}>:\}>:\}>:\}>:\}>:\}>:\}>:\}>:\}>:\}>:\}>:\}>:O}>:\|x;\|xL\|x.\|x.\|x.\|xL\|x;\|x;\|x;\|x;\|x;\|xL\|x;\|x;\|x.\|xL\|x;\|x;\|xL\|x;\|xL\|x.\|x;\|xL\|xL\|x.\|x;\|xL\|x.\|x;\|x.\|x.\|x.\|x.\|x.\|x.\|x.\|x.\|x.\|x.\|x.\|x.\|x.\|x;[Wl;[Wl;[Wl;[W+;[Wy;[W+;[Wy;[Wy;[W+;[Wy;[Wl;[Wl;[Wl;[Wl;[Wl;[Wl;[Wl;[Wl;[Wl;[Wl;[W+;[Wl;[Wy;[W+;[Wl;[Wl;[Wl;[Wy;[Wl;[Wl;[Wl;[Wl;[Wl;[Wy:6Ky:6Ky:6Ky:6iy:6Xy:6iy:6Xy:6Xy:6iy:6Xy:6Ky:6Ky:6Ky:6Ky:6Ky:6Ky:6Ky:6Ky:6Ky:6Ky:6iy:6Ky:6Xy:6iy:6Xy:6Xy:6Xy:6Xy:6Ky:6Xy:6Ky:6Ky:6Ky:6Ky:6Ky:6Xxt7XxtHXxt*Xxt*Xxt*XxtHXxt7Xxt7Xxt7Xxt7Xxt7XxtHXxt7Xxt7Xxt*XxtHXxt7Xxt7XxtHXxt7XxtHXxt*Xxt7XxtHXxtHXxt*Xxt7XxtHXxt*Xxt7Xxt*Xxt*Xxt*Xxt*Xxt*Xxt7WSh7WSh7WSh7WS'7WSu7WS'7WSu7WSu7WS'7WSu7WSh7WSh7WSh7WSh7WSh7WSh7WSh7WSh7WSh7WSh7WS'7WSh7WSu7WS'7WSh7WSh7WSh7WSu7WSu7WSu7WSu7WSu7WSh7WSu62Gu62Gu62Gu62eu62Tu62eu62Tu62Tu62eu62Tu62Gu62Gu62Gu62Gu62Gu62Gu62Gu62Gu62Gu62Gu62eu62Gu62Tu62eu62Tu62Tu62Tu62Tu62Gu62Tu62Tu62Tu62Tu62Tu62Gu62Ttp3TtpDTtp&Ttp&Ttp&TtpDTtp3Ttp3Ttp3Ttp3Ttp3TtpDTtp3Ttp3Ttp&TtpDTtp3Ttp3TtpDTtp3TtpDTtp&Ttp3TtpDTtpDTtp&Ttp3TtpDTtp3Ttp3Ttp&Ttp3Ttp&Ttp&Ttp&Ttp&Ttp&Ttp&Ttp&Ttp&Ttp&Ttp&Ttp&Ttp&Ttp&Ttp&Ttp&Ttp&Ttp&Ttp&Ttp&Ttp3SOd3SOd3SOd3SO#3SOq3SO#3SOq3SOq3SO#3SOq3SOd3SOd3SOd3SOd3SOd3SOd3SOd3SOd3SOd3SOd3SO#3SOd3SOq3SO#3SOd3SOd3SOd3SOq3SOq3SOq3SOq3SOq3SOq3SOq3SOq3SOq3SOq3SOq3SOq3SOq3SOd3SOq2.Cq2.Cq2.Cq2.aq2.Pq2.aq2.Pq2.Pq2.aq2.Pq2.Cq2.Cq2.Cq2.Cq2.Cq2.Cq2.Cq2.Cq2.Cq2.Cq2.aq2.Cq2.Pq2.aq2.Pq2.Pq2.Pq2.Pq2.Pq2.Pq2.Cq2.Pq2.Cq2.Cq2.Cq2.Cq2.Cq2.Cq2.Cq2.Cq2.Cq2.Cq2.Cq2.Ppl/Ppl@Ppl"Ppl"Ppl"Ppl@Ppl/Ppl/Ppl/Ppl/Ppl/Ppl@Ppl/Ppl/Ppl"Ppl@Ppl/Ppl/Ppl@Ppl/Ppl@Ppl"Ppl/Ppl@Ppl@Ppl"Ppl/Ppl@Ppl/Ppl/Ppl"Ppl/Ppl"Ppl"Ppl"Ppl"Ppl"Ppl"Ppl"Ppl"Ppl"Ppl"Ppl"Ppl/OK`/OK`/OK`/OK~/OKm/OK~/OKm/OKm/OK~/OKm/OK`/OK`/OK`/OK`/OK`/OK`/OK`/OK`/OK`/OK`/OK~/OK`/OKm/OK~/OK`/OKm/OK`/OK`/OK`/OKm.*?m.*?m.*?m.*]m.*Lm.*]m.*Lm.*Lm.*]m.*Lm.*?m.*?m.*?m.*?m.*?m.*?m.*?m.*?m.*?m.*?m.*]m.*?m.*Lm.*]m.*Lm.*Lm.*Lm.*Lm.*Lm.*Lm.*?m.*Lm.*?m.*?m.*?m.*Llh}Llh}Llh}Llh<Llh+Llh<Llh+Llh+Llh<Llh+Llh}Llh}Llh}Llh}Llh}Llh}Llh}Llh}Llh}Llh}Llh<Llh}Llh+Llh<Llh}Llh+KG\+KG\+KG\+KGz+KGi+KGz+KGi+KGi+KGz+KGi+KG\+KG\+KG\+KG\+KG\+KG\+KG\+KG\+KG\+KG\+KGz+KG\+KGi+KGz+KG\+KGi+KGi+KGi+KGi+KGi+KGi+KGi+KG\+KGi*&;i*&;i*&;i*&Yi*&Hi*&Yi*&Hi*&Hi*&Yi*&Hi*&;i*&;i*&;i*&;i*&;i*&;i*&;i*&;i*&;i*&;i*&Yi*&;i*&Hi*&Yi*&Hi*&Hi*&Hi*&Hi*&Hi*&Hi*&;i*&Hi*&Hi*&Hi*&Hi*&Hi*&Hi*&Hi*&;i*&Hhd'Hhd8HhdyHhdyHhdyHhd8Hhd'Hhd'Hhd'Hhd'Hhd'Hhd8Hhd'Hhd'HhdyHhd8Hhd'Hhd'Hhd8Hhd'Hhd8HhdyHhd'Hhd8Hhd8HhdyHhd'Hhd8HhdyHhdyHhdyHhd'GCX'GCX'GCX'GCv'GCe'GCv'GCe'GCe'GCv'GCe'GCX'GCX'GCX'GCX'GCX'GCX'GCX'GCX'GCX'GCX'GCv'GCX'GCe'GCv'GCe'GCe'GCX'GCe'GCX'GCX'GCX'GCX'GCX'GCX'GCX'GCX'GCX'GCe&"De&"Ue&"7e&"7e&"7e&"Ue&"De&"De&"De&"De&"De&"Ue&"De&"De&"7e&"Ue&"De&"De&"Ue&"De&"Ue&"7e&"De&"Ue&"Ue&"7e&"De&"Ue&"7e&"7e&"7e&"De&"7e&"7e&"7e&"7e&"7e&"7e&"7e&"7e&"7e&"Dd`uDd`uDd`uDd`4Dd`#Dd`4Dd`#Dd`#Dd`4Dd`#Dd`uDd`uDd`uDd`uDd`uDd`uDd`uDd`uDd`uDd`uDd`4Dd`uDd`#Dd`4Dd`uDd`uDd`uDd`uDd`uDd`#Dd`uDd`#C?T#C?T#C?T#C?r#C?a#C?r#C?a#C?a#C?r#C?a#C?T#C?T#C?T#C?T#C?T#C?T#C?T#C?T#C?T#C?T#C?r#C?T#C?a#C?r#C?a#C?a#C?T#C?a#C?T#C?a"}@a"}Qa"}3a"}3a"}3a"}Qa"}@a"}@a"}@a"}@a"}@a"}Qa"}@a"}@a"}3a"}Qa"}@a"}@a"}Qa"}@a"}Qa"}3a"}@a"}Qa"}Qa"}3a"}@a"}Qa"}3a"}3a"}3a"}@a"}3a"}@`\q@`\q@`\q@`\0@`\~@`\0@`\~@`\~@`\0@`\~@`\q@`\q@`\q@`\q@`\q@`\q@`\q@`\q@`\q@`\q@`\0@`\q@`\~@`\0@`\q@`\q@`\q@`\q@`\q@`\~@`\~@`\~@`\~@`\~@`\~@`\~@`\~@`\~@`\q@`\~?;P~?;P~?;P~?;n~?;]~?;n~?;]~?;]~?;n~?;]~?;P~?;P~?;P~?;P~?;P~?;P~?;P~?;P~?;P~?;P~?;n~?;P~?;]~?;n~?;]~?;]~?;P~?;]~?;]~?;]~?;]~?;]~?;]~?;]~?;]~?;]~?;P~?;]}y<]}yM]}y/]}y/]}y/]}yM]}y<]}y<]}y<]}y<]}y<]}yM]}y<]}y<]}y/]}yM]}y<]}y<]}yM]}y<]}yM]}y/]}y<]}yM]}yM]}y/]}y<]}yM]}y/]}y<]}y/]}y/]}y/]}y/]}y/]}y/]}y/]}y/]}y/]}y/]}y/]}y/]}y/]}y/]}y/]}y<\Xm<\Xm<\Xm<\X,<\Xz<\X,<\Xz<\Xz<\X,<\Xz<\Xm<\Xm<\Xm<\Xm<\Xm<\Xm<\Xm<\Xm<\Xm<\Xm<\X,<\Xm<\Xz<\X,<\Xm<\Xm<\Xm<\Xm<\Xm<\Xz<\Xz<\Xz<\Xz<\Xz<\Xz<\Xz<\Xz<\Xz<\Xz<\Xz<\Xz<\Xz<\Xz<\Xz<\Xz<\Xz<\Xm<\Xz;7Lz;7Lz;7Lz;7jz;7Yz;7jz;7Yz;7Yz;7jz;7Yz;7Lz;7Lz;7Lz;7Lz;7Lz;7Lz;7Lz;7Lz;7Lz;7Lz;7jz;7Lz;7Yz;7jz;7Yz;7Yz;7Yz;7Yz;7Lz;7Yz;7Lz;7Lz;7Lz;7Lz;7Lz;7Lz;7Lz;7Yyu8YyuIYyu+Yyu+Yyu+YyuIYyu8Yyu8Yyu8Yyu8Yyu8YyuIYyu8Yyu8Yyu+YyuIYyu8Yyu8YyuIYyu8YyuIYyu+Yyu8YyuIYyuIYyu+Yyu8YyuIYyu+Yyu8Yyu+Yyu+Yyu+Yyu+Yyu+Yyu+Yyu+Yyu8XTi8XTi8XTi8XT(8XTv8XT(8XTv8XTv8XT(8XTv8XTi8XTi8XTi8XTi8XTi8XTi8XTi8XTi8XTi8XTi8XT(8XTi8XTv8XT(8XTi8XTi8XTi8XTv8XTv8XTv8XTi8XTv73Hv73Hv73Hv73fv73Uv73fv73Uv73Uv73fv73Uv73Hv73Hv73Hv73Hv73Hv73Hv73Hv73Hv73Hv73Hv73fv73Hv73Uv73fv73Uv73Uv73Uv73Uv73Hv73Uv73Uv73Uv73Hv73Uuq4UuqEUuq'Uuq'Uuq'UuqEUuq4Uuq4Uuq4Uuq4Uuq4UuqEUuq4Uuq4Uuq'UuqEUuq4Uuq4UuqEUuq4UuqEUuq'Uuq4UuqEUuqEUuq'Uuq4UuqEUuq'Uuq4Uuq4Uuq4Uuq'Uuq4TPe4TPe4TPe4TP$4TPr4TP$4TPr4TPr4TP$4TPr4TPe4TPe4TPe4TPe4TPe4TPe4TPe4TPe4TPe4TPe4TP$4TPe4TPr4TP$4TPe4TPe4TPe4TPr4TPr4TPr4TPr4TPr4TPr4TPr4TPr4TPr4TPr4TPr4TPe4TPr3/Dr3/Dr3/Dr3/br3/Qr3/br3/Qr3/Qr3/br3/Qr3/Dr3/Dr3/Dr3/Dr3/Dr3/Dr3/Dr3/Dr3/Dr3/Dr3/br3/Dr3/Qr3/br3/Qr3/Qr3/Qr3/Qr3/Qr3/Qr3/Dr3/Qr3/Dr3/Dr3/Dr3/Dr3/Dr3/Dr3/Dr3/Dr3/Dr3/Dr3/Dr3/Dr3/Dr3/Qqm0QqmAQqm#Qqm#Qqm#QqmAQqm0Qqm0Qqm0Qqm0Qqm0QqmAQqm0Qqm0Qqm#QqmAQqm0Qqm0QqmAQqm0QqmAQqm#Qqm0QqmAQqmAQqm#Qqm0QqmAQqm0Qqm0Qqm#Qqm0Qqm#Qqm#Qqm#Qqm#Qqm#Qqm#Qqm#Qqm#Qqm#Qqm#Qqm#Qqm#Qqm#Qqm0PLa0PLa0PLa0PL 0PLn0PL 0PLn0PLn0PL 0PLn0PLa0PLa0PLa0PLa0PLa0PLa0PLa0PLa0PLa0PLa0PL 0PLa0PLn0PL 0PLa0PLn0PLa0PLa0PLa0PLa0PLa0PLn/+@n/+@n/+@n/+^n/+Mn/+^n/+Mn/+Mn/+^n/+Mn/+@n/+@n/+@n/+@n/+@n/+@n/+@n/+@n/+@n/+@n/+^n/+@n/+Mn/+^n/+Mn/+Mn/+Mn/+Mn/+Mn/+Mn/+@n/+Mn/+@n/+@n/+@n/+@n/+@n/+Mmi~Mmi~Mmi~Mmi=Mmi,Mmi=Mmi,Mmi,Mmi=Mmi,Mmi~Mmi~Mmi~Mmi~Mmi~Mmi~Mmi~Mmi~Mmi~Mmi~Mmi=Mmi~Mmi,Mmi=Mmi~Mmi~Mmi~Mmi,LH],LH],LH],LH{,LHj,LH{,LHj,LHj,LH{,LHj,LH],LH],LH],LH],LH],LH],LH],LH],LH],LH],LH{,LH],LHj,LH{,LH],LHj,LHj,LHj,LHj,LHj,LH],LHj+'<j+'<j+'<j+'Zj+'Ij+'Zj+'Ij+'Ij+'Zj+'Ij+'<j+'<j+'<j+'<j+'<j+'<j+'<j+'<j+'<j+'<j+'Zj+'<j+'Ij+'Zj+'Ij+'Ij+'Ij+'Ij+'Ij+'Ij+'<j+'Ij+'Ij+'Ij+'Ij+'Ij+'<j+'IiezIiezIiezIie9Iie(Iie9Iie(Iie(Iie9Iie(IiezIiezIiezIiezIiezIiezIiezIiezIiezIiezIie9IiezIie(Iie9Iie(Iie(Iie(Iie(Iie(Iie(IiezIie(HDY(HDY(HDY(HDw(HDf(HDw(HDf(HDf(HDw(HDf(HDY(HDY(HDY(HDY(HDY(HDY(HDY(HDY(HDY(HDY(HDw(HDY(HDf(HDw(HDY(HDf(HDf(HDf(HDf(HDf(HDf(HDf(HDf(HDf(HDf(HDf(HDf(HDf(HDY(HDf'#Ef'#Vf'#8f'#8f'#8f'#Vf'#Ef'#Ef'#Ef'#Ef'#Ef'#Vf'#Ef'#Ef'#8f'#Vf'#Ef'#Ef'#Vf'#Ef'#Vf'#8f'#Ef'#Vf'#Vf'#8f'#Ef'#Vf'#8f'#8f'#8f'#Ef'#8f'#8f'#8f'#8f'#8f'#8f'#8f'#8f'#8f'#8f'#8f'#EeavEeavEeavEea5Eea$Eea5Eea$Eea$Eea5Eea$EeavEeavEeavEeavEeavEeavEeavEeavEeavEeavEea5EeavEea$Eea5EeavEeavEeavEeavEeavEea$EeavEeavEeavEea$D@U$D@U$D@U$D@s$D@b$D@s$D@b$D@b$D@s$D@b$D@U$D@U$D@U$D@U$D@U$D@U$D@U$D@U$D@U$D@U$D@s$D@U$D@b$D@s$D@b$D@b$D@U$D@b$D@U$D@U$D@U$D@b#~Ab#~Rb#~4b#~4b#~4b#~Rb#~Ab#~Ab#~Ab#~Ab#~Ab#~Rb#~Ab#~Ab#~4b#~Rb#~Ab#~Ab#~Rb#~Ab#~Rb#~4b#~Ab#~Rb#~Rb#~4b#~Ab#~Rb#~4b#~4b#~4b#~Ab#~4b#~4b#~4b#~Aa]rAa]rAa]rAa]1Aa] Aa]1Aa] Aa] Aa]1Aa] Aa]rAa]rAa]rAa]rAa]rAa]rAa]rAa]rAa]rAa]rAa]1Aa]rAa] Aa]1Aa]rAa]rAa]rAa]rAa]rAa] Aa] Aa] Aa] Aa] Aa] Aa] Aa]rAa] @<Q @<Q @<Q @<o @<^ @<o @<^ @<^ @<o @<^ @<Q @<Q @<Q @<Q @<Q @<Q @<Q @<Q @<Q @<Q @<o @<Q @<^ @<o @<^ @<^ @<Q @<^ @<^ @<^ @<^ @<^ @<^ @<^ @<Q @<^~z=^~zN^~z0^~z0^~z0^~zN^~z=^~z=^~z=^~z=^~z=^~zN^~z=^~z=^~z0^~zN^~z=^~z=^~zN^~z=^~zN^~z0^~z=^~zN^~zN^~z0^~z=^~zN^~z0^~z=^~z0^~z0^~z0^~z0^~z0^~z0^~z0^~z0^~z0^~z0^~z0^~z0^~z0^~z0^~z0^~z0^~z0^~z=]Yn=]Yn=]Yn=]Y-=]Y{=]Y-=]Y{=]Y{=]Y-=]Y{=]Yn=]Yn=]Yn=]Yn=]Yn=]Yn=]Yn=]Yn=]Yn=]Yn=]Y-=]Yn=]Y{=]Y-=]Yn=]Yn=]Yn=]Yn=]Yn=]Y{=]Y{=]Y{=]Y{=]Y{=]Y{=]Y{=]Y{=]Y{=]Y{=]Y{=]Y{=]Y{=]Y{=]Y{=]Yn=]Y{<8M{<8M{<8M{<8k{<8Z{<8k{<8Z{<8Z{<8k{<8Z{<8M{<8M{<8M{<8M{<8M{<8M{<8M{<8M{<8M{<8M{<8k{<8M{<8Z{<8k{<8Z{<8Z{<8Z{<8Z{<8M{<8Z{<8M{<8M{<8M{<8M{<8M{<8M{<8M{<8M{<8M{<8Zzv9ZzvJZzv,Zzv,Zzv,ZzvJZzv9Zzv9Zzv9Zzv9Zzv9ZzvJZzv9Zzv9Zzv,ZzvJZzv9Zzv9ZzvJZzv9ZzvJZzv,Zzv9ZzvJZzvJZzv,Zzv9ZzvJZzv,Zzv9Zzv,Zzv,Zzv,Zzv,Zzv,Zzv,Zzv,Zzv,Zzv,Zzv9YUj9YUj9YUj9YU)9YUw9YU)9YUw9YUw9YU)9YUw9YUj9YUj9YUj9YUj9YUj9YUj9YUj9YUj9YUj9YUj9YU)9YUj9YUw9YU)9YUj9YUj9YUj9YUw9YUj9YUw84Iw84Iw84Iw84gw84Vw84gw84Vw84Vw84gw84Vw84Iw84Iw84Iw84Iw84Iw84Iw84Iw84Iw84Iw84Iw84gw84Iw84Vw84gw84Vw84Vw84Vw84Vw84Iw84Vw84Iw84Vvr5VvrFVvr(Vvr(Vvr(VvrFVvr5Vvr5Vvr5Vvr5Vvr5VvrFVvr5Vvr5Vvr(VvrFVvr5Vvr5VvrFVvr5VvrFVvr(Vvr5VvrFVvrFVvr(Vvr5VvrFVvr(Vvr5Vvr(Vvr5UQf5UQf5UQf5UQ%5UQs5UQ%5UQs5UQs5UQ%5UQs5UQf5UQf5UQf5UQf5UQf5UQf5UQf5UQf5UQf5UQf5UQ%5UQf5UQs5UQ%5UQf5UQf5UQf5UQs5UQs5UQs5UQs5UQs5UQs5UQs5UQs5UQs5UQf5UQs40Es40Es40Es40cs40Rs40cs40Rs40Rs40cs40Rs40Es40Es40Es40Es40Es40Es40Es40Es40Es40Es40cs40Es40Rs40cs40Rs40Rs40Rs40Rs40Es40Rs40Rs40Rs40Rs40Rs40Rs40Rs40Rs40Rs40Es40Rrn1RrnBRrn$Rrn$Rrn$RrnBRrn1Rrn1Rrn1Rrn1Rrn1RrnBRrn1Rrn1Rrn$RrnBRrn1Rrn1RrnBRrn1RrnBRrn$Rrn1RrnBRrnBRrn$Rrn1RrnBRrn1Rrn1Rrn$Rrn1Rrn$Rrn$Rrn$Rrn$Rrn$Rrn$Rrn$Rrn$Rrn$Rrn$Rrn$Rrn$Rrn$Rrn$Rrn$Rrn1QMb1QMb1QMb1QM!1QMo1QM!1QMo1QMo1QM!1QMo1QMb1QMb1QMb1QMb1QMb1QMb1QMb1QMb1QMb1QMb1QM!1QMb1QMo1QM!1QMb1QMo1QMb1QMb1QMb1QMb1QMb1QMb1QMb1QMo0,Ao0,Ao0,Ao0,_o0,No0,_o0,No0,No0,_o0,No0,Ao0,Ao0,Ao0,Ao0,Ao0,Ao0,Ao0,Ao0,Ao0,Ao0,_o0,Ao0,No0,_o0,No0,No0,No0,No0,No0,No0,Ao0,No0,Ao0,Ao0,Ao0,Ao0,Ao0,Ao0,Ao0,Nnj Nnj Nnj Nnj>Nnj-Nnj>Nnj-Nnj-Nnj>Nnj-Nnj Nnj Nnj Nnj Nnj Nnj Nnj Nnj Nnj Nnj Nnj>Nnj Nnj-Nnj>Nnj Nnj Nnj Nnj Nnj Nnj-MI^-MI^-MI^-MI|-MIk-MI|-MIk-MIk-MI|-MIk-MI^-MI^-MI^-MI^-MI^-MI^-MI^-MI^-MI^-MI^-MI|-MI^-MIk-MI|-MI^-MIk-MIk-MIk-MI^-MIk,(=k,(=k,(=k,([k,(Jk,([k,(Jk,(Jk,([k,(Jk,(=k,(=k,(=k,(=k,(=k,(=k,(=k,(=k,(=k,(=k,([k,(=k,(Jk,([k,(Jk,(Jk,(Jk,(Jk,(Jk,(Jk,(=k,(Jk,(Jk,(Jk,(=k,(Jjf{Jjf{Jjf{Jjf:Jjf)Jjf:Jjf)Jjf)Jjf:Jjf)Jjf{Jjf{Jjf{Jjf{Jjf{Jjf{Jjf{Jjf{Jjf{Jjf{Jjf:Jjf{Jjf)Jjf:Jjf)Jjf)Jjf)Jjf)Jjf{Jjf)IEZ)IEZ)IEZ)IEx)IEg)IEx)IEg)IEg)IEx)IEg)IEZ)IEZ)IEZ)IEZ)IEZ)IEZ)IEZ)IEZ)IEZ)IEZ)IEx)IEZ)IEg)IEx)IEZ)IEg)IEg)IEg)IEg)IEg)IEg)IEg)IEg)IEg)IEg)IEg)IEZ)IEg($Fg($Wg($9g($9g($9g($Wg($Fg($Fg($Fg($Fg($Fg($Wg($Fg($Fg($9g($Wg($Fg($Fg($Wg($Fg($Wg($9g($Fg($Wg($Wg($9g($Fg($Wg($9g($9g($9g($Fg($9g($9g($9g($9g($9g($9g($9g($9g($9g($9g($9g($9g($9g($Ffb%Ffb6FfbwFfbwFfbwFfb6Ffb%Ffb%Ffb%Ffb%Ffb%Ffb6Ffb%Ffb%FfbwFfb6Ffb%Ffb%Ffb6Ffb%Ffb6FfbwFfb%Ffb6Ffb6FfbwFfb%Ffb6Ffb%Ffb%FfbwFfb%EAV%EAV%EAV%EAt%EAc%EAt%EAc%EAc%EAt%EAc%EAV%EAV%EAV%EAV%EAV%EAV%EAV%EAV%EAV%EAV%EAt%EAV%EAc%EAt%EAc%EAc%EAV%EAc%EAV%EAV%EAV%EAV%EAV%EAc$ Bc$ Sc$ 5c$ 5c$ 5c$ Sc$ Bc$ Bc$ Bc$ Bc$ Bc$ Sc$ Bc$ Bc$ 5c$ Sc$ Bc$ Bc$ Sc$ Bc$ Sc$ 5c$ Bc$ Sc$ Sc$ 5c$ Bc$ Sc$ 5c$ 5c$ 5c$ Bc$ 5c$ 5c$ 5c$ 5c$ 5c$ Bb^sBb^sBb^sBb^2Bb^!Bb^2Bb^!Bb^!Bb^2Bb^!Bb^sBb^sBb^sBb^sBb^sBb^sBb^sBb^sBb^sBb^sBb^2Bb^sBb^!Bb^2Bb^sBb^sBb^sBb^sBb^sBb^!Bb^!Bb^!Bb^!Bb^!Bb^sBb^!A=R!A=R!A=R!A=p!A=_!A=p!A=_!A=_!A=p!A=_!A=R!A=R!A=R!A=R!A=R!A=R!A=R!A=R!A=R!A=R!A=p!A=R!A=_!A=p!A=_!A=_!A=R!A=_!A=_!A=_!A=_!A=_!A=R!A=_ {>_ {O_ {1_ {1_ {1_ {O_ {>_ {>_ {>_ {>_ {>_ {O_ {>_ {>_ {1_ {O_ {>_ {>_ {O_ {>_ {O_ {1_ {>_ {O_ {O_ {1_ {>_ {O_ {1_ {1_ {1_ {>_ {>_ {>_ {>_ {>_ {1_ {>^Zo>^Zo>^Zo>^Z.>^Z|>^Z.>^Z|>^Z|>^Z.>^Z|>^Zo>^Zo>^Zo>^Zo>^Zo>^Zo>^Zo>^Zo>^Zo>^Zo>^Z.>^Zo>^Z|>^Z.>^Zo>^Zo>^Zo>^Zo>^Zo>^Z|>^Z|>^Z|>^Z|>^Z|>^Z|>^Z|>^Z|>^Z|>^Z|>^Z|>^Z|>^Z|>^Zo>^Z|=9N|=9N|=9N|=9l|=9[|=9l|=9[|=9[|=9l|=9[|=9N|=9N|=9N|=9N|=9N|=9N|=9N|=9N|=9N|=9N|=9l|=9N|=9[|=9l|=9[|=9[|=9[|=9[|=9N|=9[|=9N|=9N|=9N|=9N|=9N|=9N|=9N|=9N|=9N|=9N|=9N|=9[{w:[{wK[{w-[{w-[{w-[{wK[{w:[{w:[{w:[{w:[{w:[{wK[{w:[{w:[{w-[{wK[{w:[{w:[{wK[{w:[{wK[{w-[{w:[{wK[{wK[{w-[{w:[{wK[{w-[{w:[{w-[{w-[{w-[{w-[{w-[{w-[{w-[{w-[{w-[{w-[{w-[{w:ZVk:ZVk:ZVk:ZV*:ZVx:ZV*:ZVx:ZVx:ZV*:ZVx:ZVk:ZVk:ZVk:ZVk:ZVk:ZVk:ZVk:ZVk:ZVk:ZVk:ZV*:ZVk:ZVx:ZV*:ZVk:ZVk:ZVk:ZVx:ZVk:ZVk:ZVk:ZVx95Jx95Jx95Jx95hx95Wx95hx95Wx95Wx95hx95Wx95Jx95Jx95Jx95Jx95Jx95Jx95Jx95Jx95Jx95Jx95hx95Jx95Wx95hx95Wx95Wx95Wx95Wx95Jx95Wx95Jx95Jx95Jx95Wws6WwsGWws)Wws)Wws)WwsGWws6Wws6Wws6Wws6Wws6WwsGWws6Wws6Wws)WwsGWws6Wws6WwsGWws6WwsGWws)Wws6WwsGWwsGWws)Wws6WwsGWws)Wws6Wws)Wws)Wws)Wws6VRg6VRg6VRg6VR&6VRt6VR&6VRt6VRt6VR&6VRt6VRg6VRg6VRg6VRg6VRg6VRg6VRg6VRg6VRg6VRg6VR&6VRg6VRt6VR&6VRg6VRg6VRg6VRt6VRt6VRt6VRt6VRt6VRt6VRt6VRg6VRt51Ft51Ft51Ft51dt51St51dt51St51St51dt51St51Ft51Ft51Ft51Ft51Ft51Ft51Ft51Ft51Ft51Ft51dt51Ft51St51dt51St51St51St51St51Ft51St51St51St51St51St51St51St51Ft51Sso2SsoCSso%Sso%Sso%SsoCSso2Sso2Sso2Sso2Sso2SsoCSso2Sso2Sso%SsoCSso2Sso2SsoCSso2SsoCSso%Sso2SsoCSsoCSso%Sso2SsoCSso2Sso2Sso%Sso2Sso%Sso%Sso%Sso%Sso%Sso%Sso%Sso%Sso%Sso%Sso%Sso%Sso%Sso%Sso%Sso%Sso%Sso2RNc2RNc2RNc2RN"2RNp2RN"2RNp2RNp2RN"2RNp2RNc2RNc2RNc2RNc2RNc2RNc2RNc2RNc2RNc2RNc2RN"2RNc2RNp2RN"2RNc2RNc2RNc2RNp2RNp2RNp2RNp2RNp2RNp2RNp2RNp2RNp2RNp2RNp2RNp2RNp2RNp2RNp2RNc2RNp1-Bp1-Bp1-Bp1-`p1-Op1-`p1-Op1-Op1-`p1-Op1-Bp1-Bp1-Bp1-Bp1-Bp1-Bp1-Bp1-Bp1-Bp1-Bp1-`p1-Bp1-Op1-`p1-Op1-Op1-Op1-Op1-Op1-Op1-Bp1-Op1-Bp1-Bp1-Bp1-Bp1-Bp1-Bp1-Bp1-Bp1-Bp1-O ``` The easy way to do this challenge is with a tokenised language which doesn't need newlines and ignores invalid tokens. Tested using [this interpreter](http://www.geocachingtoolbox.com/index.php?page=brainfuckOok)\*. Assumes 8-bit cells for extra golfiness. Programs are also overlapped slightly to save some bytes. \*This interpreter has a strange quirk whereby the last token needs a char after it to be registered, which affects `n = 62`. There's offline 8-bit interpreters without this quirk, but this was the best online one I could find. [Answer] # PHP, 95 programs, ~~2439~~ 2063 bytes ``` <?=0;die?>;></*na^bkd`m'(:chd>=:=;/)m`]ajc_l&'9bgc=<9<:/(l_\`ib^k%&8afb<;8;9/'k^[_ha]j$%7`ea;:7:8/&j]Z^g`\i#$6_d`:9697/%i\Y]f_[h"#5^c_98586/$h[X\e^Zg!"4]b^87475/#gZW[d]Yf !3\a]76364/"fYVZc\Xe~ 2[`\65253/!eXUYb[Wd}~1Z_[54142&% dWTXaZVc|}0Y^Z43031%%~cVSW`YUb{|/X]Y32/20$%}bURV_XTaz{.W\X21.1/#%|aTQU^WS`yz-V[W10-0."'}`SPT]VR_xy,UZV0/,/-!%z_ROS\UQ^wx+TYU/.+., %y^QNR[TP]vw*SXT.-*-+~%x]PMQZSO\uv)RWS-,),*}%w\OLPYRN[tu(QVR,+(+)|%v[NKOXQMZst'PUQ+*'*(|zuZMJNWPLYrs&OTP*)&)'{ztYLIMVOKXqr%NSO)(%(&zzsXKHLUNJWpq$MRN('$'%yzrWJGKTMIVop#LQM'&#&$xzqVIFJSLHUno"KPL&%"%#w|rUHEIRKGTmn!JOK%$!$"vzoTGDHQJFSlm INJ$# #!uznSFCGPIERkl~HMI#"~" tzmREBFOHDQjk}GLH"!}!~szlQDAENGCPij|FKG! | }spkPC@DMFBOhi{EJF ~{~|rpjOB?CLEANghzDIE~}z}{qpiNA>BKD@MfgyCHD}|y|zpphM@=AJC?LefxBGC|{x{yopgL?<@IB>KdewAFB{zwzxnpfK>;?HA=Jcdv@EAzyvywmrgJ=:>G@<Ibcu?D@yxuxvlpdI<9=F?;Habt>C?xwtwukpcH;8<E>:G`as=B>wvsvtjpbG:7;D=9F_`r<A=vurusjfaF96:C<8E^_q;@<utqtrif`E859B;7D]^p:?;tspsqhf_D748A:6C\]o9>:srorpgf^C637@95B[\n8=9rqnqoff]B526?84AZ[m7<8qpmpnef\A415>73@YZl6;7polomdf[@304=62?XYk5:6onknlch\?2/3<51>WXj495nmjmkbfY>1.2;40=VWi384mliljafX=0-1:3/<UVh273lkhkia\W</,092.;TUg162kjgjh`\V;.+/81-:STf051jifig_\U:-*.70,9RSe/40ihehf^\T9,)-6/+8QRd.3/hgdge]\S8+(,5.*7PQc-2.gfcfd\\R7*'+4-)6OPb,1-febec[\Q6)&*3,(5NOa+0,edadbZ\P5(%)2+'4MN`*/+dc`caZTQ4'$(1*&3LM_).*cb_b`X\N3&#'0)%2KL^(-)ba^a_XRM2%"&/($1JK]',(a`]`^WRL1$!%.'#0IJ\&+'`_\_]VRK0# $-&"/HI[%*&_^[^\URJ/"~#,%!.GHZ$)%^]Z][TRI.!}"+$ -FGY#($]\Y\ZSRH- |!*#~,EFX"'#\[X[YRRG,~{ )"}+DEW!&"[ZWZXQRF+}z~(!|*CDV %!ZYVYWPRE*|y}' {)BCU~$ YXUXVPJF){x|&~z(ABT}#~XWTWUOHC(zw{%}y'@AS|"}WVSVTNHB'yvz$|x&?@R{!|VURUSMHA&xuy#{w%>?Qz {UTQTRLH@%wtx"zv$=>Py~zTSPSQKH?$vsw!yu#<=Ox}ySRORPJH>#urv xt";<Nw|xRQNQOIH="tqu~ws!:;Mv{wQPMPNHH<!spt}vr 9:LuzvPOLOMGH; ros|uq~89KtyuONKNLFH:~qnr{tp}78JsxtNMJMKF>9}pmqzso|67IrwsMLILJE>8|olpyrn{56HqvrLKHKID>7{nkoxqmz45GpuqKJGJHC>6zmjnwply34FotpJIFIGB>5ylimvokx23EnsoIHEHFA>4xkhlunjw12DmrnHGDGE@>3wjgktmiv01ClqmGFCFD?>2vifjslhu/0BkplFEBEC>>1uheirkgt./AjokEDADB=>0tgdhqjfs-.@injDC@CA=4/sfcgpier,-?hmiCB?B@<4.rebfohdq+,>glhBA>A?;4-qdaengcp*+=fkgA@=@>:4,pc`dmfbo)*< ``` Requires the option [output\_buffering](http://php.net/manual/en/outcontrol.configuration.php#ini.output-buffering) to be On or some values such as 4096. It defaults to 4096 for the web service (but not CLI) at least for my installation. The doc says `ob_clean` doesn't return anything. But it returned true nevertheless. Shifted programs look like these: ``` 9: ...dmfbo)*<ejf@?<?=8+ob_clean();die?>;><8*na^bkd`m(:chd>=:=;/.)... 15: ...dmfbo)*<ejf@?<?=16-ob_clean();die?>;><04*na^bkd`m'(:chd>=:=;... 94: ...dmfbo)*<ejf@?<?=93+ob_clean(); ``` Generated using this CJam program: ``` "<?=0;die?>"95,(;{["<?="1$(_Ab:--3={))'-}'+?"ob_clean();die?>"]sf{i\- 95+ 32- 95% ' +}}%s-5< ``` [Answer] # [CJam](http://cjam.aditsu.net/#code=0), 10 programs, 1 byte I thought I'd better add this right off the bat before someone else gets cheeky and does it :P ``` 0 ``` A CJam program with just a plain number outputs that number, so this is an easy way to get 10 programs that work, namely: `0`, `1`, `2`, `3`, `4`, `5`, `6`, `7`, `8`, and `9`. The next program `:` unsurprisingly does not output `10` but gives an "unfinished operator" error. This undoubtedly works in many languages. ]
[Question] [ **Minimum Scalar Product** The inspiration for this code golf problem is from [Google's code jam competition](https://code.google.com/codejam/contest/32016/dashboard#s=p0). The premise behind the problem is, given the input of two vectors of varying lengths, find the minimum possible scalar. A scalar can be found using the following formula: ``` x1 * y1 + x2 * y2 + ... + xn * yn ``` The problem, however, is that multiple values for the scalar can be found depending on the order of the numerals in the input case (seen below). Your goal is to determine the minimum possible scalar integer solution by plugging in the input case numbers into the equation and solving for it. You may use every number in the input only once, and must use all of the numbers. Allow me to provide an example with the following vectors. **Input** ``` 3 1 3 -5 -2 4 1 ``` **Output** ``` -25 ``` The first integer on the line represents the number of numbers, n, in each vector. In this case, we have three numbers in each vector. The number n may vary with each test case, but there will always be two vectors. In the example input, the minimum scalar product would be -25. ``` (-5 * 4) + (1 * 1) + (3 * -2) = 25 ``` **Rules** * You may only use each integer in both vectors once. * You must use all integers in the vectors. * Your output must only include the final product * I'll select the solution with the least amount of code, which follows all of the specifications listed above, in any language! > > Hint: You don't need to brute force this problem, unless it makes your code shorter. There is a specific method involved in finding the minimum spanning scalar :). > > > [Answer] # Jelly, 6 bytes ``` ṢṚ×Ṣ}S ``` [Try it online!](http://jelly.tryitonline.net/#code=4bmi4bmaw5fhuaJ9Uw&input=&args=WzEsIDMsIC01XQ+Wy0yLCA0LCAxXQ) Using brute force is equally short: ``` Œ!×S€Ṃ ``` ### How it works ``` ṢṚ×Ṣ}S Main link. Arguments: u (vector), v (vector) Ṣ Sort the components of u. Ṛ Reverse. Ṣ} Sort the components of v. × Multiply the results, element by element. S Compute the sum of the products. ``` [Answer] ## [Seriously](http://github.com/Mego/Seriously), 6 bytes ``` ,SR,S* ``` [Try it online!](http://seriously.tryitonline.net/#code=LFNSLFMq&input=WzEsIDMsIC01XQpbLTIsIDQsIDFd) Explanation: ``` ,SR,S* ,SR input first vector, sort, reverse ,S input second vector, sort * dot product ``` [Answer] # APL, 15 bytes ``` {+/⍺[⍒⍺]×⍵[⍋⍵]} ``` This is a dyadic function that accepts arrays on the left and right and returns an integer. It uses the same approach as my Julia [answer](https://codegolf.stackexchange.com/a/75415/20469): dot product of the sorted arrays, one descending and one ascending. [Try it here](http://tryapl.org/?a=1%203%20%AF5%20%7B+/%u237A%5B%u2352%u237A%5D%D7%u2375%5B%u234B%u2375%5D%7D%20%AF2%204%201&run) [Answer] # [MATL](http://github.com/lmendo/MATL), 6 bytes Code: ``` SiSP*s ``` My first MATL answer :) Explanation: ``` S # Sort the first array iS # Take the second array and sort it P # Flip the array * # Multiply both arrays with each other s # Sum of the result ``` [Try it online!](http://matl.tryitonline.net/#code=U2lTUCpz&input=WzEgMyAtNV0KWy0yIDQgMV0) [Answer] # Mathematica, ~~30~~ 17 bytes *-13 bytes by murphy* ``` Sort@#.-Sort@-#2& ``` Function, input is vector1(list),vector2(list) Several revisions: ``` Plus@@(Sort@#*Reverse@Sort@#2)&(*me*) Total[Sort@#*Reverse@Sort@#2]& Sort@#.Reverse@Sort@#2& (*alephalpha*) Sort@#.Sort[#2,#>#2&]& (*murphy*) Sort@#.SortBy[#2,-#&] (*me*) Sort@#.-Sort@-#2& (*murphy*) ``` [Answer] # Julia, ~~32~~ 25 bytes ``` x->y->-sort(-x)⋅sort(y) ``` This is an anonymous function that accepts two arrays and returns an integer. To call it, assign it to a variable and do `f(x)(y)`. For inputs *x* and *y*, we simply compute the dot product of *x* sorted in reverse order with *y* sorted. We get *x* in reverse sorted order by negating all values, sorting, then negating again. Saved 7 bytes thanks to Dennis! [Answer] # Pyth - ~~14~~ 8 bytes I think I figured out the trick. ``` s*VSQ_SE ``` [Try it online here](http://pyth.herokuapp.com/?code=s%2aVSQ_SE&input=1%2C+3%2C+-5%0A-2%2C+4%2C+1&debug=0). [Answer] # Javascript ES6, 69 bytes ``` a=>b=>a.sort((x,y)=>x-y).map((x,y)=>i+=b.sort((x,y)=>y-x)[y]*x,i=0)|i ``` Wow, this is way too long. [Answer] # Perl 6, ~~33~~ 30 bytes ``` {sum @^a.sort Z*@^b.sort.reverse} ``` [Answer] # CJam, 11 Bytes ``` q~$\$W%.*:+ ``` [Try it online!](http://cjam.aditsu.net/#code=q%7E%24%5C%24W%25.*%3A%2B&input=%5B1%203%20-5%5D%20%5B-2%204%201%5D%0A) [Answer] # Python, 139 bytes ``` def mdp(n, a, b): a = list(reversed(sorted(a))) b = sorted(b) res = sum([a[i] * b[i] for i in range(len(a))]) return res ``` [Answer] # C++, 124 bytes ``` #include<algorithm> int m(int*a,int*b,int n){std::sort(a,a+n);std::sort(b,b+n);int r=0;while(--n>=0)r+=a[n]**b++;return r;} ``` ungolfed: ``` #include<algorithm> int m(int*a,int*b,int n){ std::sort(a,a+n); std::sort(b,b+n); int r=0; while(--n>=0) r+=a[n]*(*b++); return r; } ``` At first i used `std::greater<int>()` for the sort in `b` but just reversing the order in the summation is easier. [Answer] # Haskell, 59 bytes ``` import Data.List v?u=sum$zipWith(*)(sort v)$reverse$sort u ``` [Answer] # [RETURN](https://github.com/molarmanful/RETURN), 29 bytes ``` [{␆␃}\{␆}␄␅[¤¥][×␌]#}␁[¤][+]#] ``` `[Try it here.](http://molarmanful.github.io/RETURN/)` Replace any `␆␃␄␇` with their unprintable counterparts. Anonymous lambda that leaves result on stack2. Usage: ``` ""{1 3 0 5-}""{0 2- 4 1}[{␆␃}\{␆}␄␅[¤¥][×␌]#}␁[¤][+]#]! ``` # Explanation ``` [ ] lambda {␆␃} sort and reverse first stack \{␆} sort second stack ␄␅ transpose and flatten [ ][ ]# while loop ¤¥ check if 2 items exist in stack × if so, multiply top 2 items ␌ and push to stack2 }␁ switch to stack2 [¤][+]# sum stack2 ``` [Answer] # J, 14 bytes ``` +/@(*|.)&(/:~) ``` Uses the same principle as the others. ## Explanation ``` +/@(*|.)&(/:~) Input: x on LHS and y on RHS &(/:~) Sort both x and y |. Reverse the sorted y * Multiply the sorted x and reversed sorted y elementwise +/@ Reduce the products using addition and return ``` ]
[Question] [ There is an existing "game" where pirates rationally divide gold coins according to certain rules. Quoting from [Wikipedia](https://en.wikipedia.org/wiki/Pirate_game): > > There are 5 rational pirates, A, B, C, D and E. They find 100 gold coins. They must decide how to distribute them. > > > The pirates have a strict order of seniority: A is superior to B, who is superior to C, who is superior to D, who is superior to E. > > > The pirate world's rules of distribution are thus: that the most senior pirate should propose a distribution of coins. The pirates, including the proposer, then vote on whether to accept this distribution. In case of a tie vote the proposer has the casting vote. If the distribution is accepted, the coins are disbursed and the game ends. If not, the proposer is thrown overboard from the pirate ship and dies, and the next most senior pirate makes a new proposal to begin the system again. > > > Pirates base their decisions on three factors. First of all, each pirate wants to survive. Second, given survival, each pirate wants to maximize the number of gold coins each receives. Third, each pirate would prefer to throw another overboard, if all other results would otherwise be equal. The pirates do not trust each other, and will neither make nor honor any promises between pirates apart from a proposed distribution plan that gives a whole number of gold coins to each pirate. > > > # Challenge Take as input an integer `n`, 1<=n<=99, where `n` is the number of pirates - and output the distribution of coins, starting with the first pirate. ## Test cases (first line is input; the second output): ``` 1 100 2 100 0 3 99 0 1 5 98 0 1 0 1 ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest solution in bytes wins. [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), ~~11~~ 10 [bytes](https://github.com/DennisMitchell/jelly/blob/master/docs/code-page.md) ``` R%2·∏䬵S»∑2_; ``` [Try it online!](http://jelly.tryitonline.net/#code=UiUy4biKwrVTyLcyXzs&input=&args=NQ) or [verify all test cases at once](http://jelly.tryitonline.net/#code=UiUy4biKwrVTyLcyXzsKw4figqw&input=&args=MSwgMiwgMywgNQ). ### How it works For input **n**, the task boils down to creating the list **x, 0, 1, 0, …** of length **n** whose sum is **100**. ``` R%2·∏䬵S»∑2_; Main link. Input: n R Yield [1, 2, ..., n]. %2 Replace each integer by its parity. Yields [1, 0, 1, 0, ...]. ·∏ä Dequeue; remove the first 1. This yields the list a = [0, 1, ...]. ¬µ Begin a new, monadic link. Argument: a S Compute the sum of a. »∑2_ Subtract the sum from 100. (»∑2 is 1e2 in Python syntax) ; Prepend the difference to a. ``` [Answer] ## Python, 33 bytes ``` lambda n:([-n/2+101]+[0,1]*n)[:n] ``` Computes the first value, appends some `0, 1, 0, 1...`, truncates to length `n`. Note that `-n/2+101` can't be shortened to `101-n/2` because unary and binary `-` have different precedence: the former is parsed as `(-n)/2` and the latter as `101-(n/2)`. Recursion was much longer (45): ``` f=lambda n,i=100:1/n*[i]or f(n-1,i-n%2)+[n%2] ``` [Answer] # [MATL](https://esolangs.org/wiki/MATL), 12 bytes ``` :2\ts_101+l( ``` This uses [current version (9.2.2)](https://github.com/lmendo/MATL/releases/tag/9.2.2) of the language/compiler, which is earlier than this challenge. ### Example ``` >> matl :2\ts_101+l( > 5 98 0 1 0 1 ``` ### Explanation ``` : % implicitly input number "n". Generate vector [1, 2, ..., n] 2\ % modulo 2. Gives [1, 0, 1, ...] ts % duplicate and compute sum _101+ % negate and add 101 l( % assign that to first entry of [1, 0, 1, ...] vector. Implicitly display ``` [Answer] ## Pyth, 13 bytes ``` +-100sJ%R2tQJ ``` [Test suite](https://pyth.herokuapp.com/?code=%2B-100sJ%25R2tQJ&input=3&test_suite=1&test_suite_input=1%0A2%0A3%0A4%0A5%0A99&debug=0). [Answer] # Python, ~~62~~ 58 bytes EDIT: Glad I made it a one-liner. But I lose for Python. Therefore, this is just for reference. Thanks @Zgarb ``` def x(i):n=[~j%2for j in range(i)];n[0]=101-sum(n);print n ``` It takes the input, creates a list pf parity of all numbers from 1 to i. Then sets the first element in i to 101-sum(n) and prints. [Try it here](http://ideone.com/rH9PDw) [Answer] # Javascript ES6, 45 bytes ``` a=>[...Array(a)].map((x,y)=>y?--y%2:202-a>>1) ``` Thanks to @Neil for 1 byte saved! [Answer] # ùîºùïäùïÑùïöùïü, 14 chars / 26 bytes ``` ‚©•√Ø‚í®?‚İ$%2:·ªâ-√جª1 ``` `[Try it here (Firefox only).](http://molarmanful.github.io/ESMin/interpreter2.html?eval=false&input=5&code=%E2%A9%A5%C3%AF%E2%92%A8%3F%E2%80%A1%24%252%3A%CB%9C%E1%B9%A5-%C3%AF%2F2)` Not bad, but not good either... # Explanation ``` ‚©•√Ø‚í®?‚İ$%2:·ªâ-√جª1 // implicit: √Ø=input, ·π•=101 ‚©•√Ø‚í® // map over a range [0,√Ø) and return: ?‚İ$%2 // (if mapitem>0) then ($-1) mod 2 :·ªâ-√جª1 // (else) 202-√Ø>>1 // implicit output ``` [Answer] # Seriously, ~~23~~ 17 bytes **EDIT**: Thanks @quintopia ``` ,R`2@%`M;Œ£2‚ï§u-0(T ``` Uses the same approach as my Python answer, but I do the modulo 2 using mapping, and several times, I rotate my stack. **Explanation**: This code pushes input (I will call it `i`). Next pushes `range(1,i+1)` and makes a function. Then pushes 2, rotates stack, and finally takes modulo. Next, map this function onto the range iterable. This gives the parity of each element in the list. Finally, duplicates the stack, sums the parity list, push 2, 10^2, and 100+1, and subtracts the sum (let me call this value `n`). Next the code pushes 0, rotates the stack by 1, and sets the list's index 0 element to n. The resulting list is implicitly printed. [Answer] # Japt, 14 bytes Yet another challenge where I find myself wishing for a built-in I had just considered adding... ``` 1oU mv u#√ä-U√Å1 ``` [Try it online!](http://ethproductions.github.io/japt?v=master&code=MW9VIG12IHUjyi1VwTE=&input=NQ==) ``` 1oU mv u#√ä-U√Å1 // Implicit: U = input integer 1oU // Create the range [1, U). mv // Map each item to 1 if even, 0 otherwise. u // Unshift (add to the beginning of the array) #√ä-U√Å1 // the char code of √ä (202), minus U >>> 1 (floor of U / 2). ``` [Answer] ## Actionscript 3, 87 bytes `function x(n){var l=[],i=1;for (l[0]=int(101-n/2);i<n;){l[i]=++i%2;}return l.join(" ")}` It's not the best golfing language, but I enjoy posting as3 answers. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 12 bytes (Non-comp) ``` <L√àDOTns-s)Àú ``` [Try it online!](https://tio.run/nexus/05ab1e#@2/jc7jDxT8kr1i3WPP0nP//LU0B "05AB1E ‚Äì TIO Nexus") [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-S`](https://codegolf.meta.stackexchange.com/a/14339/), 8 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` ov hL-Uz ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVM&code=b3YgaEwtVXo&input=NQ) [Answer] ## Perl ~~51~~ ~~49~~ 44 bytes ``` $,=$";@"=map{$i++%2}2..<>;say 100-(@">>1),@" ``` Need the following perlrun options `-E` ``` $ perl -E'$,=$";@"=map{$i++%2}2..<>;say 100-(@">>1),@"'<<<5 98 0 1 0 1 ``` [Answer] ## [QBIC](https://drive.google.com/drive/folders/0B0R1Jgqp8Gg4cVJCZkRkdEthZDQ), ~~28~~ 25 bytes ``` :?100-(a-1)'\`2[2,a|?b%2 ``` Explanation ``` : Get command line parameter, assign to 'a' Determine the part of the treasure for the crew: (a-1) \ 2 Integer Divide 'a'-1 by 2. The -1 compensates for even cases. ' ` Make \ a direct command for QBasic instead of substituting it for ELSE. ?100- Print 100 coins, minus the crew-share --> Captain's booty. [2,a| FOR b=2; b <= a; b++; ie for every other crew member ?b%2 Give every odd crewman a coin. [FOR loop implicitly closed by QBIC] ``` [Answer] # [Arn](https://github.com/ZippyMagician/Arn), [13 bytes](https://github.com/ZippyMagician/Arn/wiki/Carn) ``` ¬æ*‚Ć^‚Ķwu¬Ω‚ñ∫‚ô¶≈æ]# ``` [Try it!](https://zippymagician.github.io/Arn?code=WzEwMS06XjotX3shfS0+&input=MQoyCjMKNAo1CjYKNwo4CjkKMTA=) # Explained Unpacked: `[101-:^:-_{!}->` ``` [ Begin sequence --First entry-- 101 Literal `101` - Subtract :^ Ceiling :- Halve _ A variable ‚â° STDIN --Other entries-- { Block ! Boolean NOT _ Implied; last entry } End block -> To final length of _ Implied ] End sequence; implied ``` I am pretty sure this can be golfed further, but I'm leaving it here for now. [Answer] # [Husk](https://github.com/barbuz/Husk), 13 bytes ``` ·π†:o`-100Œ£t‚Üëƒ∞¬¨ ``` [Try it online!](https://tio.run/##AR4A4f9odXNr///huaA6b2AtMTAwzqN04oaRxLDCrP///zU "Husk ‚Äì Try It Online") ]
[Question] [ I recently saw this Javascript code on StackOverflow for [merging two arrays](https://stackoverflow.com/questions/1584370/how-to-merge-two-arrays-in-javascript), and removing duplicates: ``` Array.prototype.unique = function() { var a = this.concat(); for(var i=0; i<a.length; ++i) { for(var j=i+1; j<a.length; ++j) { if(a[i] === a[j]) a.splice(j--, 1); } } return a; }; var array1 = ["Vijendra","Singh"]; var array2 = ["Singh", "Shakya"]; var array3 = array1.concat(array2).unique(); ``` While this code works, it is horribly inefficient (`O(n^2)`). Your challenge is to make an algorithm with less complexity. The winning criteria is the solution with the least [complexity](http://web.mit.edu/16.070/www/lecture/big_o.pdf), but ties will be broken by shortest length in characters. **Requirements**: Package all your code together in a function that meets the following requirements for "correctness:" * Input: Two arrays * Output: One array * Merges elements of both arrays together- Any element in either input array must be in the outputted array. * **The outputted array should have no duplicates.** * Order doesn't matter (unlike the original) * Any language counts * **Don't use the standard library's array functions for detecting uniqueness or merging sets/arrays** (although other things from the standard library is okay). Let me make the distinction that array concatenation is fine, but functions that already do all of the above are not. [Answer] # JavaScript O(N) 131 124 116 92 (86?) Golfed version: ``` function m(i,x){h={};n=[];for(a=2;a--;i=x)i.map(function(b){h[b]=h[b]||n.push(b)});return n} ``` Human readable golfed version: ``` function m(i,x) { h = {} n = [] for (a = 2; a--; i=x) i.map(function(b){ h[b] = h[b] || n.push(b) }) return n } ``` I could use `concat` like so and do it in 86 characters: ``` function m(i,x){h={};n=[];i.concat(x).map(function(b){h[b]=h[b]||n.push(b)});return n} ``` But I am not sure if it is still O(N) based on this JsPerf: <http://jsperf.com/unique-array-merging-concat-vs-looping> as the concat version is marginally faster with smaller arrays but slower with larger arrays (Chrome 31 OSX). In practice do this (golf is full of bad practices): ``` function merge(a1, a2) { var hash = {}; var arr = []; for (var i = 0; i < a1.length; i++) { if (hash[a1[i]] !== true) { hash[a1[i]] = true; arr[arr.length] = a1[i]; } } for (var i = 0; i < a2.length; i++) { if (hash[a2[i]] !== true) { hash[a2[i]] = true; arr[arr.length] = a2[i]; } } return arr; } console.log(merge([1,2,3,4,5],[1,2,3,4,5,6])); ``` I'm not great at computing complexity but I believe this is `O(N)`. Would love if someone could clarify. **Edit:** Here is a version that takes any number of arrays and merges them. ``` function merge() { var args = arguments; var hash = {}; var arr = []; for (var i = 0; i < args.length; i++) { for (var j = 0; j < args[i].length; j++) { if (hash[args[i][j]] !== true) { arr[arr.length] = args[i][j]; hash[args[i][j]] = true; } } } return arr; } console.log(merge([1,2,3,4,5],[1,2,3,4,5,6],[1,2,3,4,5,6,7],[1,2,3,4,5,6,7,8])); ``` [Answer] # Perl ## 27 Characters Simple Perl Hack ``` my @vals = (); push @vals, @arr1, @arr2; my %out; map { $out{$_}++ } @vals; my @unique = keys %out; ``` I'm sure someone could one-liner this.. and thus (Thanks Dom Hastings) ``` sub x{$_{$_}++for@_;keys%_} ``` [Answer] ## Python 2.7, 38 chars ``` F=lambda x,y:{c:1 for c in x+y}.keys() ``` Should be O(N) assuming a good hash function. Wasi's 8 character `set` implementation is better, if you don't think it violates the rules. [Answer] **PHP, 69/42 68/41 chars** Including the function declaration is 68 characters: ``` function m($a,$b){return array_keys(array_flip($a)+array_flip($b));} ``` Not including the function declaration is 41 characters: ``` array_keys(array_flip($a)+array_flip($b)) ``` [Answer] ### One way in Ruby To keep within the rules outlined above, I would use a similar strategy as the JavaScript solution and use a hash as an intermediary. ``` merged_arr = {}.tap { |hash| (arr1 + arr2).each { |el| hash[el] ||= el } }.keys ``` Essentially, these are the steps I'm going through in the line above. 1. Define a variable `merged_arr` that will contain the result 2. Initialize an empty, unnamed hash as an intermediary to put unique elements in 3. Use `Object#tap` to populate the hash (referenced as `hash` in the `tap` block) and return it for subsequent method chaining 4. Concatenate `arr1` and `arr2` into a single, unprocessed array 5. For each element `el` in the concatenated array, put the value `el` in `hash[el]` if no value of `hash[el]` currently exists. The memoization here (`hash[el] ||= el`) is what ensures the uniqueness of elements. 6. Fetch the keys (or values, as they are the same) for the now populated hash This should run in `O(n)` time. Please let me know if I've made any inaccurate statements or if I can improve the above answer either for efficiency or readability. ### Possible improvements Using memoization is probably unnecessary given that the keys to the hash are going to be unique and the values are irrelevant, so this is sufficient: ``` merged_arr = {}.tap { |hash| (arr1 + arr2).each { |el| hash[el] = 1 } }.keys ``` I really love `Object#tap`, but we can accomplish the same result using `Enumerable#reduce`: ``` merged_arr = (arr1 + arr2).reduce({}) { |arr, val| arr[val] = 1; arr }.keys ``` You could even use `Enumberable#map`: ``` merged_arr = Hash[(arr1 + arr2).map { |val| [val, 1] }].keys ``` ### How I would do it in practice Having said all that, if I were asked to merge two arrays `arr1` and `arr2` such that the result `merged_arr` has unique elements and could use any Ruby method at my disposal, I would simply use the set union operator which is intended for solving this exact problem: ``` merged_arr = arr1 | arr2 ``` A quick peek at the source of [`Array#|`](http://www.ruby-doc.org/core-2.1.0/Array.html#method-i-7C), though, seems to confirm that using a hash as an intermediary seems to be the acceptable solution to performing a unique merge between 2 arrays. [Answer] ``` Array.prototype.unique = function() { var o = {},i = this.length while(i--)o[this[i]]=true return Object.keys(o) } ``` A function that would take n arrays could be the following: ``` function m() { var o={},a=arguments,c=a.length,i; while(c--){i=a[c].length;while(i--)o[a[c][i]] = true} return Object.keys(o); } ``` Golfed, I think this should work ( 117 chars ) ``` function m(){var o={},a=arguments,c=a.length,i;while(c--){i=a[c].length;while(i--)o[a[c][i]]=1}return Object.keys(o)} ``` **Update** If you want to keep the original type, you could ``` function m() { var o={},a=arguments,c=a.length,f=[],g=[]; while(c--)g.concat(a[c]) c = g.length while(c--){if(!o[g[c]]){o[g[c]]=1;f.push(g[c])}} return f } ``` or golfed 149: ``` function m(){var o={},a=arguments,c=a.length,f=[],g=[];while(c--)g.concat(a[c]);c= g.length;while(c--){if(!o[g[c]]){o[g[c]]=1;f.push(g[c])}}return f} ``` This still can cast some doubts, if you want to distinguish `123` and `'123'`, then this would not work.. [Answer] ## python,46 ``` def A(a,b):print[i for i in b if i not in a]+a ``` Or, using set operation simply ## python, 8 ``` set(a+b) ``` [Answer] # Perl 23 bytes, if we only count the code block inside subroutine. Could be 21, if overwriting global values is allowed (it would remove `my` from the code). It returns elements in random order, because order doesn't matter. As for complexity, on average it's O(N) (depends on number of hash collisions, but they are rather rare - in worst case it can be O(N2) (but this shouldn't happen, because [Perl can detect pathological hashes](http://perldoc.perl.org/perlsec.html#Algorithmic-Complexity-Attacks), and changes the hash function seed when it detects such behavior)). ``` use 5.010; sub unique{ my%a=map{$_,1}@_;keys%a } my @a1 = (1, 2, 3, 4); my @a2 = (3, 4, 5, 6); say join " ", unique @a1, @a2; ``` Output (also showing randomness): ``` /tmp $ perl unique.pl 2 3 4 6 1 5 /tmp $ perl unique.pl 5 4 6 2 1 3 ``` [Answer] ## Fortran: 282 252 233 213 Golfed version: ``` function f(a,b,m,n) result(d);integer::m,n,a(m),b(n),c(m+n);integer,allocatable::d(:);j=m+1;c(1:m)=a(1:m);do i=1,n;if(.not.any(b(i)==c(1:m)))then;c(j)=b(i);j=j+1;endif;enddo;allocate(d(j-1));d=c(1:j-1);endfunction ``` Which not only looks infinitely better but will actually compile (too long a line in its golfed form) with the human-readable form: ``` function f(a,b,m,n) result(d) integer::m,n,a(m),b(n),c(m+n) integer,allocatable::d(:) j=m+1;c(1:m)=a(1:m) do i=1,n if(.not.any(b(i)==c(1:m)))then c(j)=b(i);j=j+1 endif enddo allocate(d(j-1)) d=c(1:j-1) end function ``` This should be `O(n)` as I copy `a` into `c` and then check each `b` against all of `c`. The last step is to eliminate the garbage that `c` will contain since it is uninitialized. [Answer] ## Mathematica 10 Chars ``` Union[a,b] ``` Example: ``` a={1,2,3,4,5}; b={1,2,3,4,5,6}; Union[a,b] ``` > > {1, 2, 3, 4, 5, 6} > > > ## Mathematica2 43 Chars ``` Sort@Join[a, b] //. {a___, b_, b_, c___} :> {a, b, c} ``` [Answer] **Javascript 86** Golfed version: ``` function m(a,b){var h={};return a.concat(b).filter(function(v){return h[v]?0:h[v]=1})} ``` Readable version: ``` function merge(a, b) { var hash = {}; return a.concat(b).filter(function (val) { return hash[val] ? 0 : hash[val] = 1; }); } ``` [Answer] ## JavaScript 60 I'm using ES6 generator. The following is testable using [Google's Traceur REPL](http://google.github.io/traceur-compiler/demo/repl.html). ``` m=(i,j)=>{h={};return[for(x of i.concat(j))if(!h[x])h[x]=x]} ``` [Answer] If you're looking for a JavaScript-based implementation that relies on the underlying Objects behind the framework to be efficient, I would've just used Set. Usually in an implementation, the Set object inherently handles unique objects during insertion with some sort of binary search indexing. I know in Java it's a `log(n)` search, using binary search based on the fact that no set can contain a single object more than once. --- While I have no idea if this is also true for Javascript, something as simple as the following snippet may suffice for an `n*log(n)` implementation: # [JavaScript](https://babeljs.io/), 61 bytes ``` var s = new Set(a); // Complexity O(a.length) b.forEach(function(e) { // Complexity O(b.length) * O(s.add()) s.add(e); }); ``` [Try it online!](https://tio.run/##bYw7DsIwEER7n2JLR9o4hD@yKDkBJUqx/gSCLDuyTSgQZw8JHRLlvHkzdxoo6dj1uVSkrCt9MHYcKALBES41LnGFa9w0ks1Q/UDc4g73eMB60cjvKE29t08428ypkMCUaEM8kb7x9uF17oLntoAXA0iCjJmCZO9JHKsK@tj5nODfPdPBp@CscOHK0@x/AA "JavaScript – Try It Online") --- If the above snippet uses `a = [1,2,3]` and `b = [1,2,3,4,5,6]` then `s=[1,2,3,4,5,6]`. If you know the complexity of the `Set.add(Object)` function in JavaScript let me know, the complexity of this is `n + n * f(O)` where `f(O)` is the complexity of `s.add(O)`. [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), O(N), 28 bytes Anonymous tacit infix function. ``` (⊢(/⍨)⍳∘≢=⍳⍨), ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///X@NR1yIN/Ue9KzQf9W5@1DHjUeciWxALKKDzP@1R24RHvX2P@qZ6@j/qaj603vhR20QgLzjIGUiGeHgG/1cPy8xKzUspSlRXUA/OzEvPUFdIg7PUgzMSsysT1QE "APL (Dyalog Unicode) – Try It Online") `,` concatenate the arguments; O(N) `(`…`)` apply the following anonymous tacit function on that; O(1)    `⍳⍨` indices selfie (indices of first occurrence of each element in the entire array); O(N)   `=` compare element by element to; O(N):    `⍳∘≢` indices of the length of the array; O(N)  `(/⍨)` use that to filter; O(N):   `⊢` the unmodified argument; O(1) O(N + 1 + N + N + N + N + 1) = O(N) ]
[Question] [ Part of [**Code Golf Advent Calendar 2022**](https://codegolf.meta.stackexchange.com/questions/25251/announcing-code-golf-advent-calendar-2022-event-challenge-sandbox) event. See the linked meta post for details. --- It's Hanukkah! Unfortunately, it appears some of the candles in your menorah have been blown out. You've got a lighter on hand, but it doesn't work quite right. Whenever you use your lighter at position k, the candles at positions k-1, k, and k+1 all toggle. Let's see an example. We'll represent our candles as a binary sequence with 1 being the "lit" state. ``` [1, 1, 1, 1, 0, 1, 1, 1, 1] initial [1, 1, 1, 0, 1, 0, 1, 1, 1] light 4 [1, 1, 0, 1, 0, 0, 1, 1, 1] light 3 [0, 0, 1, 1, 0, 0, 1, 1, 1] light 1 [1, 1, 1, 1, 0, 0, 1, 1, 1] light 0 [1, 1, 1, 1, 1, 1, 0, 1, 1] light 5 [1, 1, 1, 1, 1, 1, 1, 0, 0] light 7 [1, 1, 1, 1, 1, 1, 1, 1, 1] light 8 ``` ## The challenge To cover our candelabra bases, we'll be working with any n>0 candles. Given the initial state of the candles as input, you must output a lighter usage sequence which will result in all of the candles being lit. Input and output can be taken in any reasonable form for a sequence. Output can be 0 or 1 indexed, but all numbers must fall within the range of the length (ie. no using the lighter at -1). You may assume that the input is always solvable, and you need only output one valid solution. ## Test cases These examples are zero indexed. ``` [1, 1, 1, 1, 0, 1, 1, 1, 1] -> [4, 3, 1, 0, 5, 7, 8] [0, 1, 1, 1, 1, 1, 1, 1, 1] -> [1, 2, 4, 5, 7, 8] [1, 0, 1, 1, 1, 1, 1, 1, 1] -> [0, 1, 2, 4, 5, 7, 8] [0, 0, 0, 0, 0, 0, 0, 0, 0] -> [1, 4, 7] [1, 1, 1, 1, 1, 1, 1, 1, 1] -> [] [1, 1, 1, 0, 1, 1, 1] -> [0, 1, 3, 5, 6] [0, 1, 1, 1, 1, 1, 1] -> [0, 2, 3, 5, 6] [1, 1, 1, 1, 1, 1, 1] -> [] [0, 0] -> [0] [0] -> [0] [1] -> [] ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 19 or 18 bytes ``` ’1;Ø1ị^ḊƲƬṖḢ€ṪỊ‘&ƲT ``` [Try it online!](https://tio.run/##y0rNyan8//9Rw0xD68MzDB/u7o57uKPr2KZjax7unPZwx6JHTUDGqoe7ux41zFA7tink/@F2oBBQufv//9HRhjoKcGSAxDaM1eFSiEYRwZBF14KhFzuC6cVvMrqTcLkHl2kQ9RBZqBo4rWOgA@MZQHkGcB5YPjYWAA "Jelly – Try It Online") (note: this solution produces 1-based output but the footer which tries all test cases converts the output format to 0-based to make it easier to compare to the given examples) This works as either a function or full program. Input is taken from a function argument or command-line argument as an array of 0 (unlit) / 1 (lit). Output is an array of the 1-based indexes of the candles that should be lit, and the order will be a suitable order in which you could light them. The `T` at the end is what specifies the output format as the indexes of all the candles that should be lit. If you remove it, you instead get an array which specifies, for each candle, whether to light it or not (via the truthiness or falsiness of the element), although the truthy values could be either 1 or 2. I'm not sure whether that's a valid output format; if it is, that saves a byte. ## Algorithm Most of the other answers here are brute-forcing, and the others are solving equations in order to solve the problem semi-efficiently. However, it's actually possible to solve the problem in linear time using an algorithm customised for the problem, and the linear-time algorithm comes out shorter than all the other answers so far. The first observation is that the order in which the candles are lit doesn't matter; additionally, lighting the same candle twice cancels itself out. So all that we need to do is to identify the set of candles that need to be lit, and we can assume without loss of generality that the candles are lit from left to right. Now imagine an algorithm that moves from candle to candle, from left to right, deciding whether or not to light each candle as it goes. If it's currently at the second candle or later, there actually isn't a decision to be made here; if the candle to the left of the current candle is unlit, it'd better light the current candle, because otherwise there's no way the candle to the left will ever be lit; and if the candle to the left of the current candle is lit, it can't light the current candle because then the candle to the left would be permanently extinguished. This means that the only decision that has to be made is whether or not to light the first candle; after that all decisions are forced. In turn, that means that it's possible to "brute-force" the solution by only checking two possibilities, with the first candle lit and with the first candle unlit. As it happens, if the number of candles is equal to 2 modulo 3, either both of these possibilities will work or neither will; if the number of candles is unequal to 2 modulo 3, exactly one will work. My conversion of this algorithm to Jelly works by storing the row of candles as integers for which only the bottom two bits are relevant; the 1s bit specifies the current state of the candle in the scenario where the first candle was lit, and the 2s bit specifies the current state of the candle in the scenario where the first candle wasn't lit. Using XOR operations to do the toggles means that we're processing both of the scenarios in parallel, by focusing on different bits – in other words, this is SIMD Jelly that actually vectorises on the processsor! All that then needs to be implemented is to simulate the two possible starting states in parallel, then see which of them worked. (Because the challenge says "You may assume that the input is always solvable, and you need only output one valid solution.", this solution picks one of the two scenarios arbitrarily if both of them work or if neither of them work; the latter situation shouldn't occur and the former situation allows either solution.) One thing that makes the answer a little more confusing: because only the bottom two bits of the integers matter, the obvious choice would be to use 0, 1, 2, 3, but I actually used -2, -1, 0, 1 because it was slightly golfier. Additionally, a bit being clear means that the candle is *lit*, and a bit being set means that the candle is *unlit*, the other way round from the intuitive meaning; again, this was just because it was slightly golfier. Thus, 0 means that a candle is lit in both scenarios; -1 means that a candle is unlit in both scenarios; 1 means that the candle is lit if and only if the first candle was left unlit; -2 means that the candle is lit if and only if the first candle was lit. ## Explanation ``` ’1;Ø1ị^ḊƲƬṖḢ€ṪỊ‘&ƲT ’ decrement each: maps a lit candle (1) to 0 maps an unlit candle (0) to -1 1; prepend 1; this inserts a "zeroth candle" that determines whether to light the first candle Ƭ loop until a previously seen output is observed: Ʋ (the loop body contains four commands) ị take the following elements from {the loop variable}: Ø1 the first element, and the first element again ^ bitwise XOR {corresponding elements of that list} with Ḋ {the loop variable} minus its first element Ṗ take all but the last element of {the history of the loop variable's values} € replace each element of {that curtailed history} Ḣ with its first element {this is the value Ʋ refers to later} Ṫ take its last element Ị 0 if {the last element} is <-1 or >1, 1 otherwise ‘ increment this & bitwise AND with Ʋ the value as of four commands ago {except its last element, due to Ṫ} T take the 1-based indexes of all truthy elements ``` The main loop that simulates the behaviour of all the candles is `Ø1ị^ḊƲƬ` (here, `Ƭ` specifies that there is a loop and what type of loop it is, `Ʋ` is what specifies how many commands to loop over, and the rest of it is the loop body). The idea is that the loop variable stores the current state of all the relevant candles (i.e. the candle that we're considering whether to light, plus one candle to its left and all candles to its right); the first element of the loop variable determines whether the first three candles should have their lighting status toggled (i.e. the second candle is lit), but because the first element will become irrelevant after this point, the required functionality is to delete the first element of the array and XOR it with the second and third (which can be expressed tersely in Jelly by forming a list of two copies of the first element, and XORing corresponding elements with the tail of the loop variable – elements beyond the first two remain untouched). Things get a bit weird at the end of the loop, but this solution just allows the weirdness to happen and fixes it up later. This sort of loop iterates until it sees an output it's previously seen. The last iteration that actually represents candles is the iteration where the algorithm is considering whether to light the last candle; at this point, the array is two elements long, consisting of the states of the penultimate and last candles (let's call these *x* and *y*, so the array is `[*x*, *y*]`). For a possibility to be valid, *x* and *y* must be in the same state as each other at this point, either both lit or both unlit (otherwise, either the first candle was wrong or the problem is unsolvable). The next loop iteration should conceptually be on a 1-element list, but the algorithm always toggles two elements of the list, so the loop variable will now be `[*x*^*y*, *x*]`. Continuing to calculate, on the iteration after that, the loop variable will be `[*y*, *x*^*y*]`, and on the iteration after that, it will be `[*x*, *y*]`, i.e. a repeat. So the loop must end after at most three 2-element loop variables. As it happens, these last three variables must always be distinct from each other. To prove this, consider the two scenarios (first candle lit, and first candle unlit), and consider which candles have differing actions in both scenarios (i.e. candles on which the algorithm uses the lighter in one scenario, but not in the other). It's fairly easy to see that the positions of these differing candles follow a regular repeating pattern (of two differing candles followed by one non-differing candle), regardless of which candles were initially lit; this implies that on any three consecutive iterations of the loop, their internal states must be different from each other (otherwise, the information needed to maintain this regular repeating pattern would be lost). This in turn means that the history of loop iterations will contain the useful iterations that specify the history of what happened to the candles, plus two more: `[*x*^*y*, *x*]` and `[*y*, *x*^*y*]`. The latter is useless, and gets discarded by `Ṗ`. However, the former starts with the value `*x*^*y*`, which is useful because a scenario is valid if and only if *x* and *y* are equal in that scenario. The value of `*x*^*y*` therefore specifies which scenarios are valid: 0 means that they're both valid, 1 means that only the scenario where the first candle was unlit is valid, -2 means that only the scenario where the first candle was lit is valid, and -1 means that they are both invalid. This value is then used to select a scenario: I chose the first-candle-lit scenario only when the value is -2, and the first-candle-unlit scenario otherwise, because this makes it possible to map the `*x*^*y*` value onto an integer with the relevant bit set in only two commands (`Ị` that checks whether the value is in the range `-1..1` inclusive, and an increment). Once the algorithm has chosen a scenario, it then needs to work out which candles were lit in that scenario; this can be done simply by looking at the first element of the loop variable as of each loop iteration (which is why `µ` was used to save the history of the loop), and using a bitwise AND to extract the relevant bit. The loop iteration history is therefore being used for two different purposes, but both of them only care about the first element of the loop variable. This makes it possible to rewrite the history to remove all but the first element of each element, which saves a byte later because it means that the "keep only the first element" command `Ḣ` doesn't need to be written twice. Thanks to @Jonathan Allan for saving a byte – normally I use `µ` to mark values that need to be reused later in the code, but `Ʋ` also works in this context. Although this doesn't save any bytes directly, its positioning to the right of the `&` means that it separates the `&` from the `T`, preventing them accidentally (and incorrectly) parsing as a group, thus meaning that no extra bytes need be wasted to make the `T` parse correctly. [Answer] # [PARI/GP](https://pari.math.u-bordeaux.fr), 54 bytes ``` a->matsolvemod(matrix(#a,,i,j,(i-j)^2<2),2,[!t|t<-a]~) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMHiNAXbpaUlaboWN80Sde1yE0uK83PKUnPzUzSA7KLMCg3lRB2dTJ0sHY1M3SzNOCMbI00dI51oxZKaEhvdxNg6TYjuW4xCiQUFOZUaiQq6dgoFRZl5JUCmEoijpJCmkaipqaMQHW2oowBHBkhsw1igLIoAuiS6BnSd2BFUJ15j0V2Dwyk4jIJZD5MG88Gc2Fho0CxYAKEB) Returns a binary array of which candle get lighted. --- # [PARI/GP](https://pari.math.u-bordeaux.fr), 72 bytes ``` a->k=0;[k|t<-a,matsolvemod(matrix(#a,,i,j,(i-j)^2<2),2,[!t|t<-a]~)[k++]] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMHiNAXbpaUlaboWNz0Sde2ybQ2so7NrSmx0E3VyE0uK83PKUnPzUzSA7KLMCg3lRB2dTJ0sHY1M3SzNOCMbI00dI51oxRKwhtg6zehsbe3YWIh5txiFEgsKcio1EhV07RQKijLzSoBMJRBHSSFNI1FTU0chOtpQRwGODJDYhrFAWRQBdEl0Deg6sSOoTrzGorsGh1NwGAWzHiYN5oM5sbGakKBZsABCAwA) \$1\$-indexed. This is solving linear equations \$AX=B\$ over the field \$\mathbb{F}\_2\$. The vector \$B\$ is the element-wise negation of out input. The matrix is \$A = (a\_{ij})\$, where \$a\_{ij} = 1\$ whenever \$|i-j|<2\$, and \$0\$ otherwise. After that we just take the indices of \$1\$'s in the solution \$X\$. The matrix \$A\$ is singular when the length of the input satisfies \$n\equiv2\pmod 3\$. So I have to use the built-in `matsolvemod` instead of simply multiplying the inverse matrix. [Answer] # [Python](https://www.python.org) NumPy, 71 bytes ``` lambda N:where(~N*mat(tril(triu(N==N,-1),1)).I%2)[1] from numpy import* ``` [Attempt This Online!](https://ato.pxeger.com/run?1=fZBNasMwEIXp1qcYAgUpyEFy0iQEnG3bjS_geqESiwj0hyK3eNOLdBMo7Z3a09SJE-O6ITCIGc333oz0_uXqsLVm_yHSp88qiHj5fa-4ft5wyFav29KX6C0bax5Q8FIdjgplaZqRmGHCMJ483iY4Z0UkvNVgKu1qkNpZH8YnuwdhPSiQBqwrDaJ4FYEkFlLQ3KHyhSuiJjunZECjeD3COALnpQmogYhA3HteI4kxbv32PzebnBHogvZyVkC8hnxGYHru3RFYEFgWUf4H_C9qsoTArK8Yug8UQ5we8QvRDWjwRet7bZM-QQe9tp4ex84vP6oDkz54bdppQXrAzpftb_8C) Port of @alephalpha's PARI/GP answer (but 0-indexed). [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 22 bytes ``` TS¹gã.ΔЦ0ª^s0š^^P}∞sÏ ``` [Try it online!](https://tio.run/##yy9OTMpM/f8/JPjQzvTDi/XOTTk84dAyg0Or4ooNji6MiwuofdQxr/hw////0YY6CnBkgMQ2jAUA "05AB1E – Try It Online") \$O(n2^n)\$ brute force. -1 byte: append only one 0 ``` TS¹gã.ΔЦ0ª^s0š^^P}∞sÏ TS # digits of 10 (pushes ["1", "0"]) ¹g # length of input ã # cartesian power .Δ } # first where the following is true: Ð # triplicate ¦ # tail 0ª # append 0 ^ # xor s # swap 0š # prepend 0 ^ # xor ^ # xor with implicit input P # product ∞sÏ # truthy indicies ``` # [05AB1E](https://github.com/Adriandmen/05AB1E), 33 bytes ``` ¦1ª^ΔDNo3*.$0Þ«^}ćiR5bÞ^R1ë0}ª∞sÏ ``` [Try it online!](https://tio.run/##yy9OTMpM/f//0DLDQ6vizk1x8cs31tJTMTg879DquNoj7ZlBpkmH58UFGR5ebVB7aNWjjnnFh/v//4821FGAIwMktmEsAA "05AB1E – Try It Online") \$O(n log(n))\$. Uses the same idea as alephalpha's answer but it implements the algorithm for solving \$A{\bf x} = {\bf b}\$. Unfortunately it's longer than just brute force. ``` ¦1ª^ΔDNo3*.$0Þ«^} ``` transforms \${\bf b}\$ into \${\bf d}\$ such that \$ A{\bf x} = {\bf b} \Leftrightarrow C{\bf x} = {\bf d} \$ where \$C = (c\_{ij})\$, \$c\_{ij}=1\$ if \$i=j+1\$ or \$j=n\$ and \$n-i\not\equiv 1\pmod{3}\$ and \$c\_{ij}=0\$ otherwise. This is a matrix where all numbers just below the diagonal are 1 and the last column from bottom up is 1, 0, 1, 1, 0, 1 ... ``` ćiR5bÞ^R1ë0}ª ``` uses substitution to finally solve the equation. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 29 bytes ``` IΦEX²Lθ⌕A⮌⍘ι²1⬤θ﹪⁺λΣE³№ι⊖⁺μν² ``` [Try it online!](https://tio.run/##ZY29CoNAEIRfZbFaYQPRlKkSg1UEiaVYHLqocN7F@zGPfzlNmWFhtvhmpp@E6bWQIdRmVg4LYR2Ws3RssBJvrPUnfjnBk9XoJlzTlKCc1XCTEl@8sbGMd2G5cTE/4kyQ70iSJbvt1EpQ6cFLjbX0FiVB45ej/EJQaB9XY@rBveGFlePhxy0EKj10VEZdQ2jbjOBMkP1f14XTJr8 "Charcoal – Try It Online") Link is to verbose version of code. Outputs all solutions (e.g. `[1, 1, 0, 1, 1] -> [0, 1] or [3, 4]`; solutions are double-spaced from each other). Explanation: Generates all `2ⁿ` sets of lighter usage and filters out those that don't result in the desired candle state. ``` ² Literal integer `2` X Raised to power θ Input array L Length E Map over implicit range ι Current value ⍘ Converted to base ² Literal integer `2` ⮌ Reversed ⌕A Find all occurrences of 1 Literal string `1` Φ Filter sets where θ Input array ⬤ All elements satisfy ³ Literal integer `3` E Map over implicit range № Count of μ Inner index ⁺ Plus ν Innermost value ⊖ Decremented ι In current set Σ Take the sum ⁺ Plus λ Inner value ﹪ ² Is odd I Cast to string Implicitly print ``` [Answer] # [JavaScript (V8)](https://v8.dev/), 86 bytes ``` f=(x,e=[],i=0)=>1+x[j=i]?f(x.map(v=>j*j--<2^v),[...e,i],++i)||f(x,e,i):/0/.test(x)?0:e ``` [Try it online!](https://tio.run/##jU5LCoMwEN33FF1m6iTGroo0epCQgpQEJtAiGkIW3j1tN1KlYuEtZnhf38VuvA/UBx4vOTvFElqlDZKSoJqqSNorMq1jSTy6nkXV@JPn/Hq@RUAthLBIBouCYJrcx4wEdSlLEewYWIJW1jb3Az0Dc0xXeJwhv@7KABxm1YLZVK0jNrN@Y531X@N6@t7uvZalf6l@f/kF "JavaScript (V8) – Try It Online") -1 from Arnauld [Answer] # JavaScript (ES6), 48 bytes *This is based on [ais523's insight](https://codegolf.stackexchange.com/a/255675/58563)* *-3 thanks to [@l4m2](https://codegolf.stackexchange.com/users/76323/l4m2)* Returns an array of binary values telling which candles were lit. ``` f=(a,p,b=a.map(q=v=>q^=(p^=v^!q)^v))=>p?b:f(a,1) ``` [Try it online!](https://tio.run/##jZBNDoIwEIX3nqLu2qQCBRRjUjwIKUlBMRqkRUyvXwmCIuXHySwmM/3ee@mNK16lj6t8bgpxOmudUcixxAnl1p1LWFJFwzKmUMZUxesSxQohGspjcsjqhwTpVBSVyM9WLi4wgxHB4NNObyYMIWDbIPIx8LrrFoMAgz1bDUR@wDGRenYx8KcVhu6GwjzuNPhI9wLUeDDmO598mvjmZaCplnjvvSbs7p@vMnB3GidLuGnY3s3qDE2TJYTpFw "JavaScript (Node.js) – Try It Online") (raw output) [Try it online!](https://tio.run/##hZLPjoIwEMbvPMXsrZPMIn9cNZriyaNPQEpSERSDtqjp62OBrCvI7jZzmMx8v286aU/SyFt6LfT986L2WV3nnEnStOPSPUvNKm54VCWc6YSb5KPCxCDySK93y9wKfaxXsQMQ@wTP8F5yXxBMJhBPCcLv5hfBnGAhGq6nHeFsGhBM@9BwxhB6J7yWGImfMZaYi@EqY@59kffa7k4j6sphe4vZb5sOiaBP@P8Qne2z9H5a285KwJ8q4QjHzdV1I9Mjk8AjSNXlpsrMLdWB2ZdGNy/lfWt/BDMEBTYSA2soYGlpRKwf "JavaScript (Node.js) – Try It Online") (with postprocessing to print a list of indices) ### Commented ``` f = ( // f is a recursive function taking: a, // a[] = input array p, // p = value of the previous candle, // initially set to either undefined or 1 b = // b[] = output array, built as follows: a.map(q = // initialize q to a zero'ish value v => // for each value v in a[]: q ^= ( // the value of the current candle is v XOR q p ^= // the value of the previous candle is p v ^ !q // if p is not set, we toggle the current // candle, implicitly toggle the previous one ) ^ v // and set q = 1 to toggle the next one ) // end of map() ) => // p ? // if the last candle is lit: b // success: return b[] : // else: f(a, 1) // try again with p initially set to 1 ``` [Answer] # [Pip](https://github.com/dloscutoff/pip), ~~75~~ 66 bytes ``` @({$+($BX((^1X3WR0Xk)@(k-_+1,2*k-_+1)Ma)BX\a)=k}FI,(k:#a)CB_MF\,k) ``` [Try It Online!](https://dso.surge.sh/#@WyJwaXAiLCIiLCJAKHskKygkQlgoKF4xWDNXUjBYaylAKGstXysxLDIqay1fKzEpTWEpQlhcXGEpPWt9RkksKGs6I2EpQ0JfTUZcXCxrKSIsIiIsIlsxOzE7MTsxOzA7MTsxOzE7MV0gIiwiLXAgLXgiXQ==) -9 bytes thanks to @DLosc 0 indexed. Verify all test cases [here](https://dso.surge.sh/#@WyJwaXAiLCIiLCJ7QCh7JCsoJEJYKChfTShKWzBYazsxWDM7MFhrXSkpQChrLV8rMSwyKmstXysxKU1hKUJYaCk9a31GSSwoazojKGg6YSkpQ0JfTUZcXCxrKX1NZyIsIiIsIlsxOzE7MTsxOzA7MTsxOzE7MV0gWzA7MTsxOzE7MTsxOzE7MTsxXSBbMTswOzE7MTsxOzE7MTsxOzFdIFswOzA7MDswOzA7MDswOzA7MF0gWzE7MTsxOzE7MTsxOzE7MTsxXSBbMTsxOzE7MDsxOzE7MV0gWzA7MTsxOzE7MTsxOzFdIFsxOzE7MTsxOzE7MTsxXSBbMF0gWzFdIFswOzBdIiwiLXAgLXgiXQ==) (it's slow) [Answer] # Python3, 214 bytes: ``` def f(m): q,s=[(m,[])],[m] while q: m,M=q.pop(0) if all(m):return M for i in range(len(m)): U=[*m] for j in[-1,0,1]: if 0<=i+j<len(m): U[i+j]=not U[i+j] if U not in s:q+=[(U,M+[i])];s+=[U] ``` [Try it online!](https://tio.run/##jY7BDoIwDIbvPEWPm0wD8WKUPQLHnZYdTNx0BsYYGOPTYyfGCNFo0kP79@vf39/6U@PWGx@G4aANGFLTbQIt67gkNZOKKiZrlcD1ZCsNLe6gZiVvV77xJKM4WgP7qop3QfeX4KBE0TQBLFgHYe@OmlTaIRCdAQSXi@g4QmeE5DJnGcvVYx39soLb9FyMV6MKQqKkuGv6Z5uMrIAo4adu26YYWrAylRZz7zochRp8sK4nhsicwauytz5XlCYvarL5Ss0tvnp9rrnXfx/n0X/l/vVlej@lcRru) [Answer] # [Python](https://www.python.org), 133 bytes ``` lambda t:max((w:=[j,*(u:=t+[0,0])[:2]])and[i for i in range(len(u)-2)if(w:=[w[1]^(s:=w[0]^1),w[2]^s,u[i+2]])and s]*w[0]for j in[0,1]) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=jZDRCoIwFIbptqfY5ZYL1KsY-AA9w2nCIlcTm6IT6wF6im6EqHeqp0kzIkdicOCccf7z_T8737Kj2aW6vshgdS2NnC_up0Ts1xuBDNuLA8YVCyCmM1yywDjgUpcTYD7nROgNKCTTHCmkNMqF3kY4iTQuydwnSr4uK_B4iAsWVODy0CO0Ap-HBS1BOW8IKvis3bakuCE1Hh4nXZjHZJnlShssMXgUfcr9mhsxmX5Uvc2gykYMsn6XzfrP0Y4-lnvMxbrvp7IyNq_uR-u6608) An alternative Python answer based on [@ais523's insight](https://codegolf.stackexchange.com/a/255675/110555). Not a competitive method compared to [@loopywalt's numpy answer](https://codegolf.stackexchange.com/a/255642/110555), but I thought it was interesting enough to warrant posting. Interstingly, a [recursive solution was the same length](https://ato.pxeger.com/run?1=jZFLCsIwEEBx6ymyTDSFpCsJ5ACeYUihUqMpmpY2IXgCD-GmG72Tnsb6RYOiMIQMM_PmkewO9cYtK9t1e-90MjlutVzl61mRI0dLyQQOQkJJR9gL6cbAKFMERKoUyW0BBumqQQYZi5rcLuZ4NbfYkyQlRl8nA3CV4VbIAExlnNAAqcpa6sGM7xDUqtGl2oNK1B8aO8rJTec0mNaNsQ5rDJyiZ7CXO1eEDJ9db5WvXTHiK-tzxKz_Nsbqv7x_bYnm360ixz67vejjo88), but as it required the inclusion of `f=` in the byte count, it was technically longer. ]
[Question] [ **This is the cops' challenge. To post a robber, go [here](https://codegolf.stackexchange.com/questions/241948/inject-arbitrary-code-into-a-compiler-robbers).** In this challenge, cops will invent a (likely simple) programming language, and write an interpreter, transpiler, or compiler that allows you to run it. Robbers will write a program in this language that manages to inject arbitrary code into the interpreter, transpiler, or compiler. ## Cops Cops should design a language. This language should be "pure"; its programs can take input and/or produce output, but cannot affect files, make network requests, behave non-deterministically (based on something like randomness or the system time), or otherwise impact or be impacted by the outside world (within reason). Cops must then implement this language, with one of: * **An interpreter:** This will take the code and input as arguments/input, and produce the programs's output as output. * **A transpiler:** This will take the code and input, and produce code in some other language which does the same task. When run using that language's interpreter/compiler with input, the correct output is produced. * **A compiler:** Similar to a transpiler, but with machine code instead of another language. There must be an intended "crack", or way to inject arbitrary code. ## Robbers Robbers should find a way to do one of the following: * Write a program that, when interpreted, transpiled, or compiled, can run arbitrary code as the interpreter/transpiler/compiler (e.g., if written in Python, you could run arbitrary Python, manipulate files, and so on) * Write a program that, when transpiled or compiled, injects arbitrary code into the resulting program/machine code (e.g., if your transpiler converts the language to Node.js, you could inject arbitrary JS into the transpiler output) ## Cop Posts Cops should include the interpreter/transpiler/compiler code, and some documentation for the language. For example: > > # Print1Lang > > > > ``` > function transpile(code) { > return code.replace(/^.+/g, "print(1)"); > } > > ``` > > Print1Lang takes code as input, and returns a Python program that prints `1`. > > > Cops should be designed with some exploit in mind that allows injecting **any** code, in some language or situation that allows performing arbitrary computations and interacting with the computer's files, running shell commands, system calls, non-deterministic code, or anything like that. Simply printing a nondeterministic value does not count, as it does not give you unrestricted access to the environment the code or transpilation/compilation output is being run or transpiled/compiled in. For an interpreter, this is likely going to be running code in the language the interpreter is written in. For a transpiler or compiler, the vulnerability can occur at either compile time or run time, and for the latter, the vulnerability would most likely consist of being able to inject arbitrary code or machine code into the compiled code. ## Other All the boring stuff. Nothing malicious, no crypto stuff. Winner for cops is the user with the most safe cops, winner for robbers is the user who cracks the most cops. **Note:** This challenge is intended for languages to be designed for the challenge specifically, but using existing languages is allowed. In this case, you can define a subset of the language such that it follows the rules about non-deterministic commands. [Answer] # Exceptionally ([cracked by emanresu A](https://codegolf.stackexchange.com/a/242116/16766)) Exceptionally is a toy language I invented for this challenge. It is inspired by, implemented in, and transpiled to [Whython](https://github.com/pxeger/whython) ([pxeger](https://codegolf.stackexchange.com/users/97857/pxeger)'s modified version of Python 3 with [an added exception-handling operator](https://www.pxeger.com/2021-09-19-hacking-on-cpython/)). ## The language A program in Exceptionally contains of a series of *lines*, each consisting of a *command* (or multiple commands connected with the Rescue operator; see below under Exceptions). The lines are executed one by one. When the instruction pointer reaches the end of the program, it wraps around to the beginning. The program thus forms an infinite loop; the only way to break out of the loop is by causing an error. Every Exceptionally program either does not terminate or terminates with an exception. Each command consists of a symbol, optionally followed by an *argument*. The argument can be an integer literal, a string literal, or a variable name. Most commands modify the value of a *register*, initially set to 0. A command without an explicit argument uses the value of the register as its argument. For example, the command `*3` multiplies the register by 3, while the command `*` multiplies the register by itself. ### Commands Here is the full list of commands: * `{`: Load (copy value into register) * `}`: Store (copy register into variable) * `+`: Add (value to register) * `-`: Subtract (value from register) * `*`: Multiply (register by value) * `/`: Divide (register by value--floating point division) * `%`: Mod (register by value) * `^`: Pow (take register to the power of value--result may be floating point) * `:`: Item (at given index in register) * `[`: Slice From (given index to end of register) * `]`: Slice To (given index from beginning of register) * `@`: Find (value's index in register) * `#`: Count (occurrences of value in register) * `|`: Split (register by value) * `$`: Join (register on value) * `<`: Print (value) * `>`: Input (line of stdin into variable) * `=`: Equal (assert that register is equal to value) * `!`: Skip (skip execution of the given number of lines) * `\`: Func (apply the given function to the register) The Skip command `!` provides simple control flow. Think of it as a goto, relative to the current line. The Func command `\` takes a string as its argument and does one of several things: * `\"int"`: Cast the register to an integer * `\"str"`: Cast the register to a string * `\"ord"`: Convert a single-character register value to its character code * `\"chr"`: Convert an integer register value to the corresponding character * `\"elems"`: Convert a string or list register value to a list of its elements * `\"len"`: Get the length of the register * `\"sum"`: Sum/concatenate the register * `\"range"`: Get the range from 0 to the register's value (exclusive) * `\"wrap"`: Wrap the register's value in a singleton list * `\"inv"`: Reverse the register's value, or negate it if it's a number ### Exceptions Most commands are capable of triggering an exception in some way. For example, dividing by 0 will cause an exception, as will an out-of-bounds index, as will trying to add a string and a number. These exceptions are the only way to end the program, but they don't have to end the program. They can be caught using the Rescue operator `?`, borrowed from Whython. A command may be followed by `?` and an additional command. If the first command succeeds, execution continues to the next line. If the first command causes an exception, the second command is executed instead. A line can contain any number of commands chained with `?`. If the last command is reached and it also causes an exception, then the program halts. For example, consider the line `/x ? <"Division by zero"`. The command `/x` attempts to divide the register by the value of `x`. If `x` is zero, this operation will trigger an exception, in which case the second command `<"Division by zero"` is executed, printing an error message (and leaving the value of the register unchanged). The `?` operator is the only conditional construct in Exceptionally. Different commands can be used to trigger exceptions under specific circumstances, and `!` can be used to jump to different points in the program depending on the results. For example, in `=5 ? !4`, the `=` command raises an exception if the register does not equal 5; in this case the `!` command is executed, skipping the next four lines. Or again, the following two lines: ``` -5 / ? !4 ``` will skip four lines if the register equals 5: `-5` subtracts 5 from the register, and `/` divides it by itself, resulting in 1 if it is nonzero or an exception if it is zero. ### Miscellaneous Exceptionally has comments that start with `'` and go until the next newline. Whitespace is generally unimportant in Exceptionally. This program to square an input number and halt: ``` > \"int" * < /0 ``` could also be written as `>\"int"*</0`. Newlines that end comments, and whitespace in strings, are the only significant whitespace. ## The transpiler Here is the Exceptionally transpiler, written in Whython: ``` import re import sys COMMANDS = { "{": "reg := %s", # Load "}": "%s := reg", # Store "+": "reg := reg + %s", # Add "-": "reg := reg - %s", # Sub "*": "reg := reg * %s", # Mul "/": "reg := reg / %s", # Div "%": "reg := reg %% %s", # Mod "^": "reg := reg ** %s", # Pow ":": "reg := reg[%s]", # Item "[": "reg := reg[%s:]", # SliceFrom "]": "reg := reg[:%s]", # SliceTo "@": "reg := reg.index(%s)", # Find "#": "reg := reg.count(%s)", # Count "|": "reg := reg.split(%s)", # Split "$": "reg := %s.join(reg)", # Join "<": "print(%s)", # Print ">": "%s := input()", # Input "=": "1 / (reg == %s)", # Equal "!": "ip := ip + %s", # Skip "\\": "reg := FUNCS[%s](reg)", # Func } PROGRAM_TEMPLATE = """program = %s FUNCS = { "int": int, "str": str, "chr": chr, "ord": ord, "elems": list, "len": len, "sum": lambda x: sum(x) ? sum(x, []) ? "".join(x), "range": lambda x: list(range(x)), "wrap": lambda x: [x], "inv": lambda x: x[::-1] ? -x, } ip = 0 reg = 0 while True: eval(program[ip]) ip = (ip + 1) %% len(program)""" def transpile(code): transpiled_lines = [] code = code.lstrip() if code[0] == "?": raise SyntaxError(f"Program cannot begin with {code[0]}") while code: if m := re.match("'.*", code): code = code[m.end():].lstrip() continue if code[0] == "?": # Continuing a previous line operator = code[0] transpiled_lines[-1] += f" {operator} " code = code[1:].lstrip() if not code: raise SyntaxError(f"Program cannot end with {operator}") else: # Start of a new line transpiled_lines.append("") if code[0] in COMMANDS: command = code[0] code = code[1:].lstrip() # Parse the command's argument if m := re.match(r"\w+", code): # Name or integer literal argument = m.group() argument = (argument.lstrip("0") if int(argument) else "0") ? f"'{argument}'" code = code[m.end():].lstrip() elif m := re.match(r'"[^"]*"', code): # String literal argument = repr(m.group()) code = code[m.end():].lstrip() else: # No argument, defaults to register argument = "'reg'" argument = eval(argument) ? f"eval({argument})" translation = "(" + COMMANDS[command] % argument + ")" transpiled_lines[-1] += translation else: raise SyntaxError(f"Expected command, found: {code[0]}") return PROGRAM_TEMPLATE % transpiled_lines ``` ### Attempt This Online! You can run the transpiler for yourself at [Attempt This Online](https://ato.pxeger.com/run?1=lZbNbuM2EMfv7EswTA1L_lr7VhjrpkE2KVok2WCdnhTtgrFom61EaikqduD6SXrJpegztU_ToSjFEu0EGx0kivxxOPOfIaW__lktH_VSiqenv3M97__w33ePPEml0lgxVLayxwyhs49XV6fXH6Z4gjcIw0U2ZIyJYgs8nuBWRnq4eR3jS0kji24N2soMCRMOoFMtYb2C7dbMmke3afwYn0al1b5D9l1ymt9bsuOQHZe8ymNLvnPIdy75gT9YsuWQrVYDBZuy9POzu3rHIW_kypLjJhm0srAu1jH-RbPEosEeOg6bwcd8xi6ULPnQ4cdN2yV_Ky39U5MecBGxtdfKfDvlGF9Aj0WPHXQmc6Hr6JnpsOyfDpulMW-wU9Nh2e8b5TX4XXLhwWuJAvsr9Fj0vUFTxevrNsrrxoxZ9sddKXKR5tpr8iCx6bXsxLAjqAGzMJ4YP_yGZudfc1oWzpFheVrYTd2iLUL7g6cWvburhXbx2_XZ1CT6OTgQNxezAt0idPPp48-fTq--3J5f3Vye3p7D_iMEgpULRRNsXEKFiWJfEggTbMO9h0imFbThDu3Z0rThDm2pImjDHdosZkkGbzHPzJSYCfPChJmeJ6ZNk_uI4jUYyhNv7eMT2-jhIDQvhNjMrH2YoqhYsMYkY9cruoEwyErRtEEE67Bn_H5o9K6D8bg_CmGB_rqHtggkneAhKtIAz9WSxwzfqpyNC53YA429UpOAp6Ff9BaTvCIbI9_sTwisonwQEaGIzbEG97IU7HkzGTHfGnzujL7EXLAMDAVhMWIgeDOPQQzi8tQrV5sXncEwNJVCToi1ZC5Fecbw9FFouj5XSipvTm7KDM6oEFLje7bgAq-4XuJNaWZLrGEbrOncWYTFEruJBgnVs6VH2oMOFE8thOqqORwkAyYizx-HTdd3qNBc5Ky-zEsxVXu7mMHFAlOcKvbAZZ5hI1kDlClTFI74yo9h2Bh21Q5M6rsTPCd4U03dYvJiWKOXAgL_jbhN7d6QFVCrzMmzG2S3Aosz5goy1RS-mHIOcgi22lfCDXVA09TkhNTs1lSHmqg-vG5Wk4SCd4cF_SZx4FikChTQS1aZa2eYqkWesPK0rHnULDdF7lbdw_VmTV_ThMEZY44itmAKhNAgYLxHVsuBt8lgoWTueulAXtWuYiJD4hv_zOFfjflFanAxdAJV1N5UI9s22bP-hg3C4n0l2iT4TMIOab-ixhRswRb5BhEUS5X3rMS-FG9y1i3PMjXyecEehhOQ5rHOsJbmiwzHNVOv-UfaQDki1oaLg3iXBiN-0bVLgE_290NMNZfCWPcIHNZVxQdlVYa4tVuji8khEwdOj5rpV7bsoVPgfJ2ymWZRtS16eA7_MNF472hWTOdK4L1vdGvPKYTs_8nuawN_1YNMR1wMFKOQRt-3f-Dlj_jTv2QzGqL3qD9CW44mQxDzaIQ25JLPtZzPjwg6Gln0fw). Put your Exceptionally code in the Input box and click Execute; the program will output the transpiled Whython code. Here is a version that immediately executes the transpiled code: [Attempt This Online](https://ato.pxeger.com/run?1=lZbdUuM2FMfv1ZcQopnY-YLATcdDljIs7LSzsMyGXhnvjoiVRK0tubJMQtM8SW-2F52-RF-kfZoeWTaxncAsvnBk6aejc_7nSMoffy_mj3ouxZf_vmE8TqTSWDFUtNLHFKHzD1dXZ9dvx3iEVwjDQ1bEw0SxGfZGuJWSHq4_-_i9pKFF1wZtpYaECTvQsZawXs52K2bNT7dufB-fhYXVfoPsN8lxdm_JToPsNMmrLLLkQYM8aJJv-YMlWw2y1aqhYFMWfn5qrt5pkDdyYUmvTvqtNKiKtY9_0Cy2qL-FekE9-IhP2KWSBR80eK9uu-BvpaW_r9MDLkK2dFqpa6fs40voseh-A53ITOgqem46LPt7g02TiNfYsemw7Le18hr8LLlw4LNAgf0Reix6YtBE8eq6tfK6MWOWfbMpRS6STDt1HiQ2vZYdGXYINWAWxiPjh1vT7OLXjBaFs2dYnuR2k2bR5qH9whOL3t1VQrv86fp8bBL9FByIm4lJjq4Ruvn44d3Hs6vPtxdXN-_Pbi9g_xECwcqZojE2LqHcRL4vCYQJtuHdQyTVCtrwhvZkbtrwhrZUIbThDW0WsTiFr4inZkrEhPlgwkzPYtOm8X1I8RIMZbGzdPGpbfSwH5gPQmxmli5MUVTMWG2Ssevk3UAYZKFoUiP8ZdAzfj_Uepe-5_WHASzQX_bQGoGkI3yI8jTA72LOI4ZvVca8XCf2QCOn0MTnSeDmvfkkJ8_G0DX7EwIrKRdERChkU6zBvTQBe85Ehsy1Bp86w88RFywFQ36QjxgIvszPIAJxeeIUq03zTv8wMJVCTom1ZB5Fecrw-FFourxQSipnSm6KDE6oEFLjezbjAi-4nuNVYWZNrGEbrOncWITFYruJBjHVk7lD2oMOFE8lhPKpOOzHAyZCx_WCuusbVGguMlZd5rmYyr2dz-BihilOFHvgMkuxkawGyoQpCkd86cdhUBtuqu2b1HdHeErwqpy6xuTZsIbPBQT-G3Hr2r0iK6BWkZMnN8hmBRalrCnIWFO4MeUU5BBssa1EM9QBTRKTE1KxW1EdaqK8eJtZjWMK3u0W9KvEgWORKlBAz1lprp1iqmZZzIrTsuJRvdwUuVt0d9ebNX1NYwZnjDmK2IwpEEKDgNEWWS4H3saDmZJZ08sG5JTtMiZySFzjnzn8yzE3Tw3Oh06hitqrcmTdJlvWX7FBWLStRJv4n0jQIe0X1BiDLdgiXyGCYolynpTYluJVzjbLs0iNfFqwh-EEpFmkU6yluZHhuGbqJf9IG6iGiJXh_CDepMGIn3dtEuCS7f0QUc2lMNYdAod1WfF-UZUBbm3W6GKyy8SO06Ni-oUtu-sUuFgmbKJZWG6LHp7Cf5jQ2zqaFdOZEnjrjm5tOYXQ5spWcPf8lelp_7t_352QcxmBk7_BZrnn2iPoDbrLr3G0FugE9YfoAK0Eah2h0SHouXdsvg6OkG10jlF3iPaOrLl_zKXGlmzibC618r5zLfLlz2Pb-B8). ## Example program Here is a commented program that outputs the orbit of an input number under the [Collatz function](https://en.wikipedia.org/wiki/Collatz_conjecture). (This is the program used in the second ATO link above.) ``` ' Read initial number from stdin > ' Convert to an integer \"int" ' Store a copy in n }n ' Output < ' Minus 1 -1 ' Divide by itself; if n is 1, (n-1)/(n-1) is division by zero and the program halts / ' Otherwise, keep going; load n back into the register {n ' Mod 2 %2 ' Is this equal to 0? If not, skip the next three lines =0 ? !3 ' Load n {n ' Divide by 2 /2 ' Skip the next three lines !3 ' Load n {n ' Multiply by 3 *3 ' Add 1 +1 ' Skip the next line (that is, skip the first line when the program loops) !1 ``` [Answer] # [Vyxal 2.7](https://github.com/Vyxal/Vyxal/releases/tag/v2.7.0) (safe) Yes, I found [another](https://codegolf.stackexchange.com/a/231059/101522) [another](https://codegolf.stackexchange.com/a/237727/101522) one. No, I'm not JoKing. As the rules call for deterministic languages, commands involving randomness are not allowed. Also, the `Eˆ` commands are not allowed, since those are designed to execute arbitrary code. Code and documentation can be found at [the repo](https://github.com/Vyxal/Vyxal). Solution: > > If you look at the recent releases and commits in the GitHub repo, you may notice that we don't like SymPy anymore. There's a reason for that. It turns out that it doesn't play nicely with strings. More specifically, a lot of the time, when you pass a string to it, you can make it do unintended stuff. For example, if you do `sympy.nsimplify("f'{print(69)}'")`, it will evaluate the f-string contained within the string, resulting in it printing 69. The ACE was originally found using `øḋ`, but there were actually a lot of commands that used it. This has now been fixed. > > > [Answer] # Exceptionally v0.3 (safe) Exceptionally is a toy language I invented for this challenge. It is inspired by, implemented in, and transpiled to [Whython](https://github.com/pxeger/whython) ([pxeger](https://codegolf.stackexchange.com/users/97857/pxeger)'s modified version of Python 3 with [an added exception-handling operator](https://www.pxeger.com/2021-09-19-hacking-on-cpython/)). This is the third (and ~~hopefully~~ final) version of the language, but the only difference is in the implementation; the language spec is the same as before. See [the original post](https://codegolf.stackexchange.com/a/242066/100664) for a full description. ## New transpiler Here is the Exceptionally v0.3 transpiler, written in Whython: ``` import re import sys COMMANDS = { "{": "reg := %s", # Load "}": "%s := reg", # Store "+": "reg := reg + %s", # Add "-": "reg := reg - %s", # Sub "*": "reg := reg * %s", # Mul "/": "reg := reg / %s", # Div "%": "reg := reg %% %s", # Mod "^": "reg := reg ** %s", # Pow ":": "reg := reg[%s]", # Item "[": "reg := reg[%s:]", # SliceFrom "]": "reg := reg[:%s]", # SliceTo "@": "reg := reg.index(%s)", # Find "#": "reg := reg.count(%s)", # Count "|": "reg := reg.split(%s)", # Split "$": "reg := %s.join(reg)", # Join "<": "print(%s)", # Print ">": "%s := input()", # Input "=": "1 / (reg == %s)", # Equal "!": "ip := ip + %s", # Skip "\\": "reg := program.FUNCS[%s](reg)", # Func } PROGRAM_TEMPLATE = """class Program: pass program = Program() program.LINES = %s program.FUNCS = { "int": int, "str": str, "chr": chr, "ord": ord, "elems": list, "len": len, "sum": lambda x: sum(x) ? sum(x, []) ? "".join(x), "range": lambda x: list(range(x)), "wrap": lambda x: [x], "inv": lambda x: x[::-1] ? -x, } ip = 0 reg = 0 while True: eval(program.LINES[ip]) ip = (ip + 1) %% len(program.LINES)""" BUILTIN_NAMES = dir(__builtins__) def transpile(code): transpiled_lines = [] code = code.lstrip() if code[0] == "?": raise SyntaxError(f"Program cannot begin with {code[0]}") while code: if m := re.match("'.*", code): code = code[m.end():].lstrip() continue if code[0] == "?": # Continuing a previous line operator = code[0] transpiled_lines[-1] += f" {operator} " code = code[1:].lstrip() if not code: raise SyntaxError(f"Program cannot end with {operator}") else: # Start of a new line transpiled_lines.append("") if code[0] in COMMANDS: command = code[0] code = code[1:].lstrip() # Parse the command's argument if m := re.match(r"\w+", code): # Name or integer literal argument = m.group() if argument in BUILTIN_NAMES and command == "}": raise SyntaxError(f"Cannot overwrite built-in name {argument}") argument = (argument.lstrip("0") if int(argument) else "0") ? f"'{argument}'" code = code[m.end():].lstrip() elif m := re.match(r'"[^"\\]*"', code): # String literal argument = repr(m.group()) code = code[m.end():].lstrip() else: # No argument, defaults to register argument = "'reg'" argument = eval(argument) ? f"eval({argument})" translation = "(" + COMMANDS[command] % argument + ")" transpiled_lines[-1] += translation else: raise SyntaxError(f"Expected command, found: {code[0]}") return PROGRAM_TEMPLATE % transpiled_lines ``` ### Changelog The second version was cracked thanks to unescaped backslashes in string literals. To close this loophole, backslashes are no longer allowed in string literals. A string can contain any character that is not `\` or `"`. I've also closed another unintended loophole: previously, you could overwrite `range` with `exec` and then do `\"range"` to execute an arbitrary string. Now you can no longer use a Whython builtin as the argument for the `}` command. ### Attempt This Online! You can run the transpiler for yourself at [Attempt This Online](https://ato.pxeger.com/run?1=lZfRcuI2FIbvPX0IRSmDnYAX7jrM0jTNkk46gc0s2SvHyyhYgFrbcmU5kKE8SW9y0-kztU_TI8sGyyaZXV8YWf50ztF_jiTz1z_r1bNc8fjl5e9MLro__PfdjkUJFxIJahWt9Dm1rKuP4_Hl5MMUDdHWQnDhLR4gLOgSDYaoleIOMq9TdMtJoNGdQlupImHAEXQqOfjL2fOKWfVzbho_RZdBYbVbI7t1cpo9avKsRp7VyXEWavJdjXxXJz-wJ022amSrZaBgkxdxfql7P6uRd3ytyYFJeq3Ur4p1im4kjTTqNdCBb04-ZHN6LXjB-zV-YNou-Huu6Z9M2mVxQDd2K3X0kFN0DT0aPa2hc57FsopeqQ7N_llj0yRkBjtVHZr93igv9zfOYhseCxTYX6FHo-8VmghW9WuU1516p9kfD6XI4iSTtsmDxKpXs0PF9qEGlGM0VHE4hmajPzJSFM6JYlmS203qRZtP7XeWaPThoTK1RPClIJF7_XlyNVUJ308SRM7ieT5kZ1l3nz7-8ulyPLsfje9uL-9HsA4xxvOQpClML7cxQAk8WYVFAIp-2yn73NubyUgt4dYe047zVY1BJIgM7h0Lp1JAG-7Qnq9UG-7Q5iKANtyhTUMapfAUslQNCWmsHmishmeRapPoMSBoA4ayyN446EI3Osjz1QPGOq8bB4YIEi-pMUjZtfNuIBSyFiQxCG_jd1TcT0bvxhsMun0fHHQ3HWtnQUKGqGflSYTf9YqFFN2LjA5ydekTCW1DIY8lvpO_y4faeUb7jlrjMD2TdSANlvXz55vb-5vJbHI5zgUOmLBns8eMhZLF6WzmWFZAF0jCbNIE3NtzHlBH-993BrOQxTSF4Z6fv1EQPKkfN4RcsMQuwlrknV7PV2WJL7C2pC5BWErR9DmWZDMSggt7gYtCQHMSx1yiR7pkMVozuULbwswOa8NaG9V5sAjOIr1i3YjI-crGbfcMKrQyhfKqBOxFLo0D2xn4ZugHNAZpMlp189qcyo0kH8HiJSKwbugT41mKlGQGyBMqCJwnZRw933hdV9tTlXI-RAuMtuXQHcKvTqv_2oQgfiWuqd03ZAXUKnKyDwMfPNAwpXVBppLA8cwXIEdM100l6lN1SZKonOCK3YrqUBPlKV_PahQRiO64oF8lDuzBRIACckVLc-0UEbHMIlpszZWIzHIT-GF9frzetOkJiShsSWrnoksqQAgJAoYNsnQH0UbuUvCsHmXhfs-BIubCVirs1RjmHzYNA-o6lu4rnWb-RMVaQIQo3x264CNW8W9Lr9WsH4ncLtul0LiHHRW1Ov7Kd05eLyh_dQGl3T5Yb-OG9W9YtTRspqeNvS9wqPlnuP1GkqZgDVbuV-RG0ETY-wQ1xfimcOurRgcz4XuHHQQbM8lCmSLJ1VcJHDpUvBUfbgNVk7HyOj9ODolQ8uddhxQ4uLlMQyIZj5V1G8NhUy5Er6g2H7UOPs4RPmbiyKZWMf3GTnKsWkebhM4l3Zd7By3gOy4YNE4MQWUmYtT4Pmk1grIs_Y12OAThn4WbyoDFrqAE0ug4-l9I8Wfk5V-87fes91a3b-2YNeyBmCd9a4tv2ULyxeIEWyd9jf4P). Put your Exceptionally code in the Input box and click Execute; the program will output the transpiled Whython code. Here is a version that immediately executes the transpiled code: [Attempt This Online](https://ato.pxeger.com/run?1=lZbNcts2EMfvmD4EDFcj0vqwZV86HCup68gZdyzFEzknmtHQEiShJQEGJC25qp6kl_TQ6Uv0Rdqn6YIgJYKSPTEPJAj-sLv47wLgH38v5k_JXPCv_33HWBgJmWBJUd6Kn2KELj_0-xeDd0PcxSuE4SIr4mAi6Qw7XVyLSROb1yG-Ef5Eo2uF1mJFwoA96DAR4C9jGyWz6tEwjR_ii0lutVUhW1VymD5o8qhCHlXJfhpo8rhCHlfJd-xRk7UKWasZKNgUeZyfq96PKuStWGjSMUm3FntlsQ7xdUJDjbo7qOOZkw_YmF5JkfNehXdM2zl_JzT9o0m3GZ_QpVWLbT3kEF9Bj0YPK-hYpDwpo5eqQ7O_V9g4CpjBDlWHZr83yqv9i2DcgtccBfZn6NHouUIjycp-jfK6Vd80-2ZbioxHaWKZPEisejXbVWwHakA5xl0Vh21o1vuS-nnhHCiWRZndqFq02dR-ZZFG7-9LU4ukmEk_bF99GlwOVcI3kwSRUz7OhqwRuv344f3Hi_7orte_vbm468E6JISMAz-OYXqZDQdH8IZyiwDk_ZZd9LVvrgc9tYRrG0w7zlY1AZEgMrg3EYkTCW24Q3s8V224Q1vICbThDm0a0DCGt4DFakhAuXqhXA1PQ9X2w4eJj5dgKA2tpY3f6kYTu556IUTndWnDEOnzGTUGKbtW1g2EQhbSjwzCXXpNFfej0bt0HafV8cBBa9lEawQJ6eITlCURnos5Cyi-kyl1MnXpox9YhkIuizw7-5YNtbKMdmy1xmF6JmtDGhD66dP1zd31YDS46GcCT5i0RqOHlAUJ4_FoZCM0oVOcwGziCNxbYzGhtva_6ZyMAsZpDMNdL_uiIHhTj3YAuWCRlYc1zTrdE0-VJXlLtCV1SZ_FFA-feOIve1IKaU1JXgh47HMuEvxAZ4zjBUvmeJWbWRNtWGujOrcWwVmoV2w79JPx3CL19hFUaGkKxVUK2A3blE8s2_HM0LcoB2lSWnbz3JyKjSQbwfgM-7Bu6CMTaYyVZAYoIip9OE-KOE4843NVbVdVSqOLpwSviqFrTJ6dVue5CUH8SlxTu1dkBdTKc7IJg2w90CCmVUGGiQ_Hs5iCHJwudpWoTrXtR5HKCSnZLakONVGc8tWshqEP0e0X9JvEgT3Yl6BAMqeFuXqMfTlLQ5pvzaWIzHKT5H7R2F9v2vTADylsSWrnojMqQYgEBAx2yMIdRBu2Z1Kk1Shz9xsOFDEXtlJho0Y3-7HZMaCufem-1GkWj1QuJESIs92hBT64in9VeC1nfU_kVtEuhCYnxFZRq-Ov-GZn9YKzT2-htOtb63WyY_0Vq5YGu-mpE_czHGreEam_kKQhWIOV-w25kTSS1iZBu2K8KtzqqtHBDMTGYRPDxuynQRLjRKi_Ejh0qHwpPlIHqiJj6XN2nGwToeTPurYpsMnuMg38hAmurFsEDptiIbp5tXm4tvXRwGSfiT2bWsn0CzvJvmrtLSM6Tuim3Jt4Cv9xE2fnxJA0SSXHO_8ntZ2gUOnXRMKp-VeaTFs__Pv-nFyKAIL8DdbwA0scgt6g--xnBK05OketDjpGK45qp6h7AnoenKm341OkG0dnqNFBB6fa3D_qOKZLOra2Z23u1rY18vXPM934Hw). ### Solution There are two suspiciously convoluted lines in the transpiler. First, > > `argument = (argument.lstrip("0") if int(argument) else "0") ? f"'{argument}'"` > > > which does this: > > Try to cast `argument` to an integer. If that works and the integer is nonzero, remove any leading 0s from `argument`; if the integer is zero, use `"0"`; if `argument` cannot be converted to an integer, wrap it in single quotes. (Note also that literal strings are `repr`'d, and the register as an argument is `'reg'` rather than just `reg`.) > > > Then, > > `argument = eval(argument) ? f"eval({argument})"` > > > > > If the argument was a name, it should be wrapped in quotes at this point, so `eval` gives just the name as a string. If the argument was a number, `eval` gives the number as a Python int. If the argument was a string, `eval` reverses the `repr` we did earlier. If `eval` fails (???), then we substitute `argument` into a string that has the effect of `eval`'ing it at post-transpilation runtime (???). > > > What kind of input will trigger this case? > > We need an argument matching the regex `\w+` that does not error when you pass it to `int`, but does error when you strip leading zeros and pass it to `eval`. Solution: Python 3 (and therefore Whython) allows underscores as digit-group separators in numeric literals. Thus, `0_1` is a legal int literal (with a value of 1); but when we strip the leading zero, `_1` is no longer a legal int literal, but rather a name. When we try to `eval` it, it errors because `_1` is not defined. So instead of `1` or `_1` being placed in the transpiled code, we get `eval(_1)`. > > > So the exploit is: > > If we set the variable `_1` to some string value, any reference to `0_1` will cause it to be `eval`'d. Here's a simple example: > > > ``` > {"exec('import os; print(os.getcwd()); exit(0)')" > }_1 > <0_1 > ``` > > > > Transpiled, this becomes (in essence): > > > ``` > reg := "exec('import os; print(os.getcwd()); exit(0)')" > _1 := reg > print(eval(_1)) > ``` > > [Attempt This Online!](https://ato.pxeger.com/run?1=lZfRcuI2FIbvPX0IVSmDnQALdx3v0m2aJZ10AptZsleOl1FAgFrbcmU5kKE8SW9y0-lL9EXap-mRZINlSGbjCyPLn845-s-RZP78e7V8lEuePP33DWNxyoVEgjpFK3vMHOfi43B4PvowRn20cRBceIN9hAVdIL-PGhluIfs6QdeczAy6VWgjUyQMOIKOJQd_mj2rmFU_Z7bxE3Q-K6y2a2S7To7ze0Oe1sjTOjnMI0O-qZFv6uQH9mDIRo1sNCwUbPIizi9176c18oavDOnbZNDIwqpYJ-hK0tigwQHqh_bkIzall4IXfFjjfdt2wd9yQ_9o0x2WzOjabWSeGXKCLqHHoCc1dMrzRFbRC9Vh2D9qbJZGzGLHqsOw31nl1fmVs8SFxwIF9hfoMeg7haaCVf1a5XWj3hn2h30psiTNpWvzILHqNWxfsT2oAeUY9VUcnqXZ4PecFIXzrWJZqu2m9aLVU_uNpQa9u6tMLRV8IUjcufw8uhirhO8mCSLnyVQP2TrOzaePP386H05uB8Ob6_PbAaxDjPE0IlkG09M2fJTCk1NYBKDod72yr3N9NRqoJdzYYcaxXtUYRILI4N5ycCYFtOEO7elSteEObS5m0IY7tGlE4wyeIpapIRFN1ANN1PA8Vm0S388IWoOhPHbXHnpvGi0UhOoBY5PXtQdDBEkW1Bqk7Lq6GwiFrARJLSJYhy0V94PVuw58v90LwUF73XK2DiSkj7qOTiL8rpYsouhW5NTX6tIHErmWQgFLQ0-_00NdndGep9Y4TM9mPUiD4_z0-er69mo0GZ0PtcAzJtzJ5D5nkWRJNpl4jjOjcyRhNlkK7t0pn1HP-N91ziYRS2gGw4NQv1EQPKmfTgS5YKlbhDXXnUE3VGWJ32NjSV2CsIyi8WMiyXogBBfuHBeFgKYkSbhE93TBErRicok2hZktNoaNNqpzbxGcxWbFdmIip0sXNzunUKGVKZRXJeAg7tBk5np-aIe-RxOQJqdVN8_NqdxI9AiWLBCBdUMfGM8zpCSzQJ5SQeA8KePohtbrutqBqpSzPppjtCmHbhF-dlq95yYE8Stxbe1ekRVQq8jJLgy890CjjNYFGUsCxzOfgxwJXR0qUZ9qh6Spygmu2K2oDjVRnvL1rMYxgeiOC_pV4sAeTAQoIJe0NNfMEBGLPKbF1lyJyC43ge9WZ8frzZgekZjClqR2LrqgAoSQIGB0QJbuINq4sxA8r0dZuN9xoIi9sJUKOzX6-sPmwIC6jqX7wqSZP1CxEhAh0rtDG3wkKv5N6bWa9SORu2W7FBp3saeiVsdf-c7T9YL0q_dQ2s299SY-sP6KVUujw_Q0cfAFDrXwFDdfSNIYrMHK_YrcCJoKd5egQzFeFW591ZhgRnznsIVgYyZ5JDMkufoqgUOHipfiw02gajJWXuvjZJ8IJb_u2qfAw4fLNCKS8URZdzEcNuVCDIpqC1Fj7-MM4WMmjmxqFdMv7CTHqnWwTulU0l25t9AcvuNm_sGJIajMRYIOvk8aB0E5lU8TAafmX7mct7__199guqZTt1n83eDZW2Q-5njWWVA5XUGCvbeIruFbses1YerbSc951530jIV_1AmsTeyP18KT5xnk6cn8_g8) > > > [Answer] # [Javastack](https://github.com/chunkybanana/javastack), [Cracked by tsh](https://codegolf.stackexchange.com/questions/241948/inject-arbitrary-code-into-a-compiler-robbers/241959#241959) Not much of a language but it should be enough. Crappy programming for the win! Code + docs is in the repo. Since this must be deterministic, random builtins are banned. As tsh pointed out, there's a small chance loop variables may coincide, but that chance is so small that you may simply consider it to not happen. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), since v2.6 (safe) Why does Vyxal have so many ACEs? Commands with randomness aren’t allowed, and neither are `Eˆ`. Info is in the [repo](https://github.com/Vyxal/Vyxal). [Answer] # [Jyxal](https://github.com/chunkybanana/jyxal), [Cracked by redwolf](https://codegolf.stackexchange.com/questions/241948/inject-arbitrary-code-into-a-compiler-robbers/241995#241995) Jyxal is a half-baked JS implementation of [Vyxal](https://github.com/vyxal/vyxal). While it has most core features (loops, functions, lambdas etc), it has almost no elements, but it's still possible to ACE it. Vyxal docs should apply for most of it, but for some parts you may have to read the code. Intended solution: ``` @=1,console.log("ACE"),process.exit(),'+',d|; ``` Quite similar to Redwolf's, this gets compiled into ``` var arity = '=1,console.log("ACE"),process.exit(),d';FUNC_=1,console.log("ACE"),process.exit(),d = <meaningless junk> ``` Just like [this Vyxal ACE](https://codegolf.stackexchange.com/a/237727/100664), this exploits how arbitrary code can be inserted into functions. [Answer] # Exceptionally v0.2 ([cracked by emanresu A](https://codegolf.stackexchange.com/a/242254/100664)) Exceptionally is a toy language I invented for this challenge. It is inspired by, implemented in, and transpiled to [Whython](https://github.com/pxeger/whython) ([pxeger](https://codegolf.stackexchange.com/users/97857/pxeger)'s modified version of Python 3 with [an added exception-handling operator](https://www.pxeger.com/2021-09-19-hacking-on-cpython/)). This is the second version of the language, but the only difference is in the implementation; the language spec is the same as before. See [the original post](https://codegolf.stackexchange.com/a/242066/100664) for a full description. ## New transpiler Here is the Exceptionally v0.2 transpiler, written in Whython: ``` import re import sys COMMANDS = { "{": "reg := %s", # Load "}": "%s := reg", # Store "+": "reg := reg + %s", # Add "-": "reg := reg - %s", # Sub "*": "reg := reg * %s", # Mul "/": "reg := reg / %s", # Div "%": "reg := reg %% %s", # Mod "^": "reg := reg ** %s", # Pow ":": "reg := reg[%s]", # Item "[": "reg := reg[%s:]", # SliceFrom "]": "reg := reg[:%s]", # SliceTo "@": "reg := reg.index(%s)", # Find "#": "reg := reg.count(%s)", # Count "|": "reg := reg.split(%s)", # Split "$": "reg := %s.join(reg)", # Join "<": "print(%s)", # Print ">": "%s := input()", # Input "=": "1 / (reg == %s)", # Equal "!": "ip := ip + %s", # Skip "\\": "reg := program.FUNCS[%s](reg)", # Func } PROGRAM_TEMPLATE = """class Program: pass program = Program() program.LINES = %s program.FUNCS = { "int": int, "str": str, "chr": chr, "ord": ord, "elems": list, "len": len, "sum": lambda x: sum(x) ? sum(x, []) ? "".join(x), "range": lambda x: list(range(x)), "wrap": lambda x: [x], "inv": lambda x: x[::-1] ? -x, } ip = 0 reg = 0 while True: eval(program.LINES[ip]) ip = (ip + 1) %% len(program.LINES)""" def transpile(code): transpiled_lines = [] code = code.lstrip() if code[0] == "?": raise SyntaxError(f"Program cannot begin with {code[0]}") while code: if m := re.match("'.*", code): code = code[m.end():].lstrip() continue if code[0] == "?": # Continuing a previous line operator = code[0] transpiled_lines[-1] += f" {operator} " code = code[1:].lstrip() if not code: raise SyntaxError(f"Program cannot end with {operator}") else: # Start of a new line transpiled_lines.append("") if code[0] in COMMANDS: command = code[0] code = code[1:].lstrip() # Parse the command's argument if m := re.match(r"\w+", code): # Name or integer literal argument = m.group() argument = (argument.lstrip("0") if int(argument) else "0") ? f"'{argument}'" code = code[m.end():].lstrip() elif m := re.match(r'"[^"]*"', code): # String literal argument = repr(m.group()) code = code[m.end():].lstrip() else: # No argument, defaults to register argument = "'reg'" argument = eval(argument) ? f"eval({argument})" translation = "(" + COMMANDS[command] % argument + ")" transpiled_lines[-1] += translation else: raise SyntaxError(f"Expected command, found: {code[0]}") return PROGRAM_TEMPLATE % transpiled_lines ``` ### Changelog The first version was cracked because too many parts of the interpreter were modifiable from within the code. To close this loophole, I've changed the `program` variable to `program.LINES` and the `FUNCS` variable to `program.FUNCS`. Since variable names in Exceptionally cannot contain dots, these changes should make the program contents hack-proof. ### Attempt This Online! You can run the transpiler for yourself at [Attempt This Online](https://ato.pxeger.com/run?1=lZbNcts2EMfv7EvAcDUibYmRbh1OVNfjKJ10bMcTuSeaycAiJKElAQYELXlUPUkvvnT6IH2K9mm6IEiJoGRPzAOJjx8Wi_8uAP7593LxqBaCPz39VahZ_4f_vvuHpZmQCknqVKX8MXeci49XV-fX7yZohNYOggevcYCwpHMUjFAnxz1kP8foUpDYoBuNdnJNwoAD6EQJmK9kTxtm9efUNn6MzuPKar9F9tvkpLg35EmLPGmTV0ViyDct8k2bfMceDNlpkZ2OhYJNUfn5uT37SYu8EUtDBjYZdvKoKdYx-qBoatBwDw0ie_EJm9L3UlR81OID23bF3wpD_2TTPuMxXbmd3DNDjtF7aDHocQudioKrJnqhGwz7R4vNs4RZ7EQ3GPZ7K7383wTjLlQrFNhfoMWgbzWaSdac10qvG91n2B93qch4VijX5kFi3WrYkWaHkAN6YjTSfniWZuOvBakS50izLCvtZu2kLZf2O8sMenfXWFomxVyS1H__6_XFRAd8u0gQueDTcsjGcW4-ffz50_nVl9vx1c3l-e0Y9iHGeJqQPIfllTYClEHNqSwCULW7Xt3mX364Hust3NliZuJyV2MQCTyDd8_BuZJQhjeUpwtdhjeUhYyhDG8o04SmOdQSlushCeW6QrkeXqS6TNL7mKAVGCpSd-WhM1PooTDSFYxNXFceDJGEz6k1SNt1y2YgNLKUJLOIcBX1tN8PVusqDIL-MIIJ-ques3EgICM0cMogwne5YAlFt7KgQakufSCJaykUsizyyr5yqFtGdOjpPQ7Ls1kPwuA4MZ0hBa7mGdh2pyKmnjG-bYy_JIzTHMyFUdmjIajpj5-A0CxzqzlnZWM4iHTO4TNsLOlHEpZTNHnkiqzGUgrpznAVZTQlnAuF7umccbRkaoHWlZkNNobNwnXjziJMlprt6KdETRcu7vonkH6NJdRPw-Ew9SmPXS-IbNd3KFeMF7Q5zXNrqk-JcgTjc0RgU9AHJoocacksUGRUErgsaj8GkdXdVjvUaXA6QjOM1vXQDcLPLmv43ILAfy2urd0rogJqVTHZuoF3M9Akp21BJorA3StmIAeny30l2kv1SZbpmOCG3YbqkBP1Fd6OapoS8O6woN8kDhywRIICakFrc90cETkvUlqduw2P7HST-G55ejjfjOlrklI4b_SxROdUghAKBEz2yHo68Db151IUbS9bkFuX6zXhAfa0f_oaqfu8MjSo7DqDLOqu655NF-9Zf8UGocm-El0cfsbRCe6-oMYEbMEW-QYRJM2ku1ViX4pXOdtOzyo0YjthD8EJSIpE5UgJfbfD0U3lS_7hLlAtERvd5aG8C4MWv2zaBcDD-_shIYoJrq27GI7sOuPDKisj1NnNcYrwIRMHTo-G6Re27KFTYLzK6FTRuN4WPTSDv6E42DuaJVWF5Gjvlu_sOeU45k9nd9vA_7mfq5hxX1ICYfQ88y9f_dI__YvXw4Hz1ukPnQ1zRgMQ82jorPElmykxmx1h52ho0P8B). Put your Exceptionally code in the Input box and click Execute; the program will output the transpiled Whython code. Here is a version that immediately executes the transpiled code: [Attempt This Online](https://ato.pxeger.com/run?1=lZbRcuI2FIbv1ZdQlDLYQEhIbjqesGkmS3a2k2QzS3rleHcUEKDWllxZDqSUJ-nN9qLTy75AX6R9mh5ZNtiGZDa-MLL06Zyj_xxJ_P7XfPakZ1J8-e-bv3kUS6WxYihvJU8JQhcfrq_Pb94OcR8vEYaHLImHiWJT7PVxIyEdXH328ZWkY4uuDNpIDAkTdqBDLcFfxrZLZs1Pu2p8H5-Pc6sHNfKgTg7TB0u2amSrTl6noSUPa-RhnXzLHy3ZqJGNRgUFmzKP81Pde6tG3sq5Jb0q6TeSoCzWPn6vWWRRfwv1guriQz5il0rmfFDjvartnL-Tlv6-Sne5GLOF00hcO2UfX0KPRfdr6EimQpfRC9Nh2d9qbBKHvMIOTYdlv62UV_cnyYUDnzkK7A_QY9FTg8aKl_1WyuvWjFn2zaYUuYhT7VR5kNj0WrZv2B7UgHGM-yYOt6LZ4JeU5oWzZ1geZ3bjetFmS_uZxxa9vy8tLVZyqmjUvfzx5mJoEr5eJIicilE2ZYXQ7ccP7z6eX3--G1zfXp3fDWAfEkJGIU0SWF5mw8MxfKHcIgB5v-MWfd2r9zcDs4Uba8w6znY1AZEgMnh3EEm0gja8oT2amTa8oS3VGNrwhjYLWZTAV8gTMyVkwnwwYaankWnT6GFM8QIMpZGzcPGZbXSwH5gPQmxeFy5MUVRMWWWSsetk3UAYZK5oXCH8RdAxcT9Wehe-5x30AnBwsOigFYKE9PERypIIv_MZDxm-UynzMnXZIw2dikI-jwM3G8umOllGe67Z47C8KutCGhAaswnWEGoSg21nJMfMtcbXnePPIRcsAXN-kI0YCL7MTzcEoXns5D4nWad_FJiaI2fEWjKPojxhePgkNF0MlJLKmZA8y3hEhZAaP7ApF3jO9QwvczMrYg3bhZvOjUVwFtnt2I2oHs0c0uy2oPxKSyieUsB-1GVi7LheUA19gwrNRcrKbp5bU3FKZDO4mGIKm4I9cpkm2EhWAWXMFIXLoojjKKgM19X2TRm0-3hC8LKYusLk2WX1nlsQxG_ErWr3iqyAWnlO1mGQjQcWJqwuyFBTuHvlBOQQbL6tRH2pXRrHJiekZLekOtREcYXXsxpFFKLbLehXiQMHLFWggJ6xwlwzwVRN04jl524pomq5KXI_b--uN2v6hkYMzhtzLLEpUyCEBgHDLbJwB9FG3amSaT3KGuQU7WJN5Ii4Jj5zjRRjbpYanA2dQRU1l8XIqkm2rL9ig7BwW4km8T-RoEWaL6gxBFuwRb5CBMVi5ayV2JbiVcHWyzNPjVw77GA4AWka6gRrae52OLqZeik-0gSqJmJpODuUN2kw4mddmwS4ZHs_hFRzKYx1h8CRXVS8n1dlgBsbH21MdpnYcXqUTL-wZXedAoNFzEaajYtt0cET-Dc09raOZsV0qgTeuuUbW0Gh0gWv4O75M9WTg-_-fXdKLmQIQf4Km-WBa4-gN-g-u9LRSqBTdNBDh2gpUOMY9Y9Az70T83V4jGyjdYLaPbR3bM39Yy41tmAjZ3Op5W5d1yJf_jixjf8B). [Answer] # [Vyxal 2.10](https://github.com/Vyxal/Vyxal/tree/v2.10.0), [cracked](https://codegolf.stackexchange.com/a/246355/107299) Yep, [another](https://codegolf.stackexchange.com/a/231059/101522) [another](https://codegolf.stackexchange.com/a/237727/101522) [another](https://codegolf.stackexchange.com/a/241951/101522) one. Again, commands with randomness aren’t allowed, and neither are `Eˆ`. Info is in the [repo](https://github.com/Vyxal/Vyxal). [Answer] # Vyxal 2.7.2 to 2.11.1 (safe, patched in v2.11.2) Yet another ACE in Vyxal. Commands with randomness aren’t allowed, and neither are `Eˆ`. Info is in the [repo](https://github.com/Vyxal/Vyxal). Explanation: > > The vulnerability is in `∆K` (Stationary Points) and `∆¢` (Local Maxima). These both use sympy directly on a string, meaning you can just inject an f-string, like this: > > > > ``f"{open('look, an ACE!', 'w').write('!')}"` ∆K` > > > > or: > > > > ``f"{open('look, an ACE!', 'w').write('!')}"` ∆¢` > > > ]
[Question] [ The [Corpus](https://warframe.fandom.com/wiki/Corpus) are a fictional faction from the popular video game [Warframe](https://www.warframe.com/) who have a somewhat interesting language. Whilst other factions in the game such as the Grineer have some logic behind their language, the Corpus is simply a lossy substitution of the English language. All Corpus words are the same as their English counterparts, except with the following alphabetical mappings: [![English to Corpus mapping](https://i.stack.imgur.com/Uobtj.png)](https://i.stack.imgur.com/Uobtj.png) This causes some problems with pronunciation as: `yes` becomes `yey` `say` becomes `yay` `yay` becomes `yay` `sassy` becomes `yayyy` `case` becomes `yaye` Here's a text version of the mappings: ``` a -> a b -> t c -> y d -> p e -> e f -> t g -> j h -> k i -> i j -> t k -> k l -> p m -> s n -> t o -> o p -> k q -> r r -> t s -> y t -> p u -> u v -> t w -> j x -> k y -> y z -> b ``` # The challenge Given text using the English alphabet, output its Corpus translation. For example, the text `Hello, World!` becomes `Keppo, Jotpp!` in Corpus ### The Rules * Input will only consist of ASCII printable characters * Input text may contain whitespace and punctuation, these must be preserved * Capitalization of letters must be preserved * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so naturally, fewest bytes wins! ## The Testcases Test cases are separated with `<===========>`, with a blank line between input and expected output ``` Hello, World! Keppo, Jotpp! <===========> Yes Yey <===========> TestcaSe PeypyaYe <===========> Programming Puzzles and Code Golf Ktojtassitj Kubbpey atp Yope Jopt <===========> This text has a newline in it Pkiy pekp kay a tejpite it ip <===========> Corpus language best language Yotkuy patjuaje teyp patjuaje <===========> Strip the flesh! Salt the wounds! Yptik pke tpeyk! Yapp pke joutpy! <===========> "Install Warframe" they said, "It'll be fun" they said "Itypapp Jatttase" pkey yaip, "Ip'pp te tut" pkey yaip <===========> What the **** did you just ****ing say about me, you little *****? I'll have you know I graduated top of my class in the Navy Seals, and I've been involved in numerous secret raids on Al-Quaeda, and I have over 300 confirmed kills. Jkap pke **** pip you tuyp ****itj yay atoup se, you pipppe *****? I'pp kate you ktoj I jtapuapep pok ot sy ypayy it pke Taty Yeapy, atp I'te teet ittoptep it tusetouy yeytep taipy ot Ap-Ruaepa, atp I kate otet 300 yottitsep kippy. ``` ### The Bonus If you also include an audio recording (or video with audio) of you pronouncing each of the testcase's Corpus translations, you may multiply your bytecount by `1` as a reward. [Answer] # [Bash](https://www.gnu.org/software/bash/) + coreutils, 46 ``` tr b-zB-Z ${a=typetjkitkpstokrtyputjkyb}${a^^} ``` [Try it online!](https://tio.run/##TZDBahtBDIbv8xSyySnYIZBzKG0OiS8hwQHTHgJaj9Y7We1omdGssy6BvkZfry/iau1SMrd/PumX9FeYm@NRE1TLw7flD7j4ibc69qRvbdC2zyptMl1Mj9WH0dfXj@PxgZhlARtJ7GfuO2X3Qlm3uCb3lGSXsOtC3MFTORyYMmD0cCee4F64di9NyKD0rtCgMRdpzyEShAhB3Z2kvmRgjLuCO4LKjP8rt9YUetCGoDbjZgZrZD3pvZTo88zNVzErMsMGU22L0HzCI2QMfgHzlf759dtoZQ4lfmJu0@DZ6dIe@OBhlAJvxcZPP9M9GUfASopCR4sT5qDK55bLL2519m5woBNto@xhBZaHL6jkQaUHqaEbYcuY83TyNPERhxHWhJwXbspq8hmm08kiiYPwYL1WG0tHSSydTNtECsn2ziARvvLyuSB5/Nd/XkEGSnBzfQ1biXVInZm0gTlf/QU "Bash – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 24 bytes ``` ži.•ÜÁ©;«ìñä°ÔG·ÖYΘ•Du«‡ ``` Explanation: ``` ‡ transliterate ži a-zA-Z with .•ÜÁ©;«ìñä°ÔG·ÖYΘ• atypetjkitkpstokrtyputjkyb Du« concatenated with itself, uppercased ``` [Try it online!](https://tio.run/##AUMAvP9vc2FiaWX//8W@aS7igKLDnMOBwqk7wqvDrMOxw6TCsMOUR8K3w5ZZzpjigKJEdcKr4oCh//9IZWxsbywgV29ybGQh "05AB1E – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 42 bytes ``` ≔”$⌊∧T-¶I^F⁷ü@n⁹γ›7η”η⭆θ⎇№β↧ι§⎇№βι↧ηη⌕β↧ιι ``` [Try it online!](https://tio.run/##ZY1NDsIgGET3PQV2xZfgCbpCo7FWI7EY0yUCaUkIKMW/0yPdmXQ1eZmXGTmIIL2wKdFxNL3DJeUd2/B9U/OGtfzUnDNfMnerkqABqoIF4yJuY47@KO74QRDXwYnwxWv/zNWNoIN/6yDFqLEBIIjG2in9wTPPwL87wPRA0NY4NVuByQaoUtppaz1BVx@sWhRp@bI/ "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ≔ Assign ”$⌊∧T-¶I^F⁷ü@n⁹γ›7η” Compressed string `ATYPETJKITKPSTOKRTYPUTJKYB` η To variable θ Input string ⭆ Map over characters and join ⎇ If β Lowercase alphabet № Contains ι Current character ↧ Lowercased (Then) ⎇ If β Lowercase alphabet № Contains ι Current character (Then) η Variable ↧ Lowercased (Else) η Variable § Indexed by ⌕ Index of ι Current character ↧ Lowercased β In lowercase alphabet (Else) ι Current character Implicitly print ``` [Answer] # T-SQL, 107 Bytes ``` SELECT TRANSLATE(v,'bcdfghjlmnpqrstvwxzBCDFGHJLMNPQRSTVWXZ', 'typtjktpstkrtyptjkbTYPTJKTPSTKRTYPTJKB')FROM t ``` Line break and indent are for readability only. Uses the SQL 2017 function [`TRANSLATE`](https://docs.microsoft.com/en-us/sql/t-sql/functions/translate-transact-sql?view=sql-server-2017) for character replacement. Unfortunately had to put (almost) the entire alphabet in there *twice* to maintain casing. There are probably better ways, maybe something that handles the **t**'s as a group, but this worked for me. Input is via a pre-existing table **t** with varchar column **v**, [per our IO rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/5341#5341). In this case the table must be created using a *case-sensitive collation*, either by running on a case-sensitive server, or by using the `COLLATE` keyword (not counted toward character total): ``` CREATE TABLE t(v varchar(999) COLLATE Latin1_General_CS_AS) ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 100 bytes ``` s=>s.replace(/[a-z]/gi,c=>(C='_atypetjkitkpstokrtyputjkyb'[Buffer(c)[0]&31],c>{}?C:C.toUpperCase())) ``` [Try it online!](https://tio.run/##bZPBbhMxEIbvPMW0B5JUSVrUG1JSlRwgHFAhRVXVVGiyO5s469iWPd7iVki8Bq/Hi4RxliJAu7fxzPzzz2fvFhsMhVeOR8aWtK8m@zCZhrEnp7Gg/ukdjh7vT9dqWEym/dmk9wU5OeJtrbh2gW3tJY4Sp1Xv7k2sKvL9YnB3dv/y/NX9sJg@fbuYvZ6N2X52jvwMA/UHg8G@sCZYTWNt1/2q33tHWtsh3Fivy6PeYPDiv/wthY7Tawpc4II6Ulferj3udsqs4So@PmoKgKaEmSwJb62uuuQ2KgDTV4YNSvXSGHrQyhAoA4o7GmbWuxhAo1lHXBOsxM@fqKN@wQIaeENQiZ/NESxQ8yF@sNGUoWvz47kJjFrDDfpKNqLj3JAgoCqHcDznn99/SHYlmtH8leuQutlgO@1EPihVCclG2EYxnU8yqoAJcGUjw46Gh7RWzLptOblYmnk7boMNHdK1sQ8wB2FdRmQqga0DW8EuQaExhMwuj/yATYIFoQ7DpckXkYWajIwErmmsbqRZik3ckbdCNVDhicHLLgGsgUs9@hiRSnwWaE3Yhjycn52BLFspvxOVWmkdxh0A3tfowNW/ATi5i7wCx@RaALyFlAGwjU7mtwCkTF7uPwCcg1qWbQGw3YqXLaOL6Ej0bQ2WISRIDlOSl3MYeS3/DdwSupT9szsAEA0mWVIYW8fSLMUcA4kBaaeUjxiVS1nx0o0@CQCHzwKtCcsikAEky6w4SEstllMGsP8F "JavaScript (Node.js) – Try It Online") ``` s => // s = input string s.replace( // replace in s ... /[a-z]/gi, // ... all letters, no matter the case c => ( // for each letter c: C = // pick a replacement letter C '_atypetjkitkpstokrtyputjkyb' // from a 1-indexed lookup string [Buffer(c)[0] & 31], // using the 5 lowest bits of the ASCII code of c c > {} ? // if the original letter was in lower case: C // use the replacement letter as-is : // else: C.toUpperCase() // convert it to upper case ) // ) // end of replace() ``` [Answer] # [R](https://www.r-project.org/), 79 bytes ``` function(x)chartr("b-zB-Z",paste0(y<-"typetjkitkpstokrtyputjkyb",toupper(y)),x) ``` [Try it online!](https://tio.run/##TVBBbtswELzrFRtdJAVSYaDXAEWbQ@NLkMIFjBa5rMSVxYjiCuRStnzqN/q9fsQl7aAoL@RydmZnx136h@bSB9uJZlueqm5AJ67M2@b8pfmZ1zN6oU25PjS5rDPJ26hlnL3w6GIdYr22eS0c5plcuVZVfaouPbtSQFvoyqx4ImO4hj07o@6KOit@kE/Xd/LS4Y7S@8XxweE0aXuAl3A@G/KAVsEjK4KvbPorYdAehE4CA0Y4s3Q02lKaoyU1PLKbgweD9hDwQNDGCf@q1LATp2eQgaCPE4Y72KGRa33kYJW/2su31gsaA3t0fTRFeepYwaNWNeRb@fPrd0TbKBLsf1ji7ge86d3HA0orWDnAW4g@0k9az@MK2HIQmKi@wkaLmBvl/lO2vckPuNAVHS0fYQsxHhVQSIHwDNzDtEJn0Pu0fpr4jMsKO0Lj6yxFl3SWlAHFeOzCZonc2GvDRI5jTJ46RwIuWvfAFj6b5ltAUvjOv1nghRx83GygY9trN0WRURvjPxRZVXUoZV9KVRev9tUW1eUv "R – Try It Online") Only 3 bytes shorter than literally typing both lower- and uppercase replacement strings together... # [R](https://www.r-project.org/), 79 bytes ``` function(x,`[`=chartr)"B-Z"[toupper(y),"b-z"[y<-"typetjkitkpstokrtyputjkyb",x]] ``` [Try it online!](https://tio.run/##TVDBjtMwEL3nK2ZzSbJK0EpcFyHYA/SCFhWpgu5KO0kmjTeOJ7LHadMTv8Hv8SPFThHCF3v85r158@ylu68unTeNKDb5qXzZv7xrerRii/Rj9SPdC/tpIpsvRZnW1TndL/dVKstE8jooGSYnPNhQ@1AvdVqenp8vHdtcQBlo8iT7TFpzCTu2ur3JyiT7Ti5e38hJg1uK70fLB4vjqMwBHv35rMkBmhYeuCX4xLpbCb1yIHQS6DHAiaGjVobiHCWx4YHt5B1oNAePB4I6TPhXxYatWDWB9ARdmNDfwBa1rPWRvWndai/dGCeoNezQdsEUpbFjAYeqLSHdyO@fvwJaBxFv/sMid9fjVe82HGhVCwt7ePXBR/yJ6zlcAGv2AiOVK6yViL5Sbt8nm6t8jzOt6GD4CBsI8bQehVoQnoA7GBdoNDoX148Tv@C8wJZQuzKJ0UWdOWZAIR4zs54DN/QaP5LlEJOjxpKADdYdsIEPuvrqkVr8y79a4JksvL27g4ZNp@wYRAaltXuTJUXRoORdLkWZPZknkxWXPw "R – Try It Online") Fancier code, same byte count. [Answer] # [Perl 5](https://www.perl.org/) `-p`, 54 bytes ``` eval"y/B-Zb-z/".uc($a=typetjkitkpstokrtyputjkyb)."$a/" ``` [Try it online!](https://tio.run/##K0gtyjH9/z@1LDFHqVLfSTcqSbdKX0mvNFlDJdG2pLIgtSQrO7Mku6C4JD@7CMgvBfIrkzT1lFQS9ZX@//dIzcnJ11EIzy/KSVH8l19QkpmfV/xftwAA "Perl 5 – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), 55 bytes ``` $_.tr!"b-zB-Z",(x="typetjkitkpstokrtyputjkyb")+x.upcase ``` [Try it online!](https://tio.run/##TZDBbtswDIbvegrG6GHrnKDAzsOw9bDlMrRIgWC7DLRFx6pp0ZAoJ85pr7HX24PMk5OhqG6/fvIj@YdUTfN883OjYVVU6/Pn9Y@ifHP6UOg0kD53TrshqnQh65T1VBVv3502aagx0jx/JWYpYS@B7cp8p2ieKGqNOzIPQQ4B@975Azyk85kpAnoL92IJvgg35ql1EZROCi1mz3g6svMEzoNTcy9hSBEY/SHhgaDK4BdldhrcANoSNBncrmCHrBd9lORtXJli66MiM@wxNHkRKhZ7gojOllBs9c@v39mtMiH5V57Zt3gl3eYH1lmYJMFzyuOXn@WeiBNgJUmhp/Jis1Pla8vtR7O9slsc6eJ2Xo6whZyHTahkQWUAaaCfoGaMcTl5mfgNxwl2hBxLs2S1cMbldMqR@FF4zL251qeeguR0ItWBFELeO4J4@MTrx4Rk8X//dQUZKcD7uzuoxTcu9BnSOea4@SuDOvFxXg//AA "Ruby – Try It Online") [Answer] # [J](http://jsoftware.com/), 78 61 bytes -17 bytes thanks to FrownyFrog! ``` rplc(u:,98 66+/i.25);"0(,toupper)@'typetjkitkpstokrtyputjkyb' ``` [Try it online!](https://tio.run/##TcoxCsIwGMXxvad4ZonFUougaEUQXPQEzql@0drYhOTL0EHwGl7Pi9RO6vh7/3frddjkKFCi6L0zp3Ess9USi8VkWuezeboWxThjG50jn24ld4741tTcuMC28YPj4K6SfZqIHFJvcokMjxI6JAmdrhYack/GWBytN@eR/K47610MMKq9RHUhVBT4q99NHNrAyhgcldde3UmAr9QhqPqcQRz4/XwNtSLo2P412X8A "J – Try It Online") [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), ~~151~~ 83 bytes ``` n=>n.Select(a=>char.IsLetter(a)?(char)(" ATYPETJKITKPSTOKRTYPUTJKYB"[a%32]|a&32):a) ``` [Try it online!](https://tio.run/##jVDNTsJAEL77FEMTzTbBHuCmUKMEFSGR2BpCrIehHegmyyzZ3UYwHnwNX88Xwa0aNenFPe33M99@s7k9zq3cX1ac9ybSul5eoonboyFXazK4UPTFxNv@nvsxRwkpyp3Aflzz0chOyDkyAsMzUTOhCOA8nU@H6c14lI6nSXo7vvP43uP5RfCAh93O4wsedTvhCYb704OBZqsVRTMjHU0kk7DOSF5FXsjRia0Irkkp3YaZNqpoBVGqB/6hc2NwJ0KP6t4irG/fXBj@K3aOu4x7/d8TZ5ySdTkm1BCmRq8Mrtc@AqbV87MiC8gFDHRBcKXVshlVSguOtg5K9N6MmZ6ULwKSQbqGfaDNprKgkFcVrggWvskPargTv8wGXEmw9E3KFiSo3Cd@0hUXttWYyIIRW4dKwQzN0q9CWVAP7MCiLNrgdff@@ub1hQ@t@K/6vz/ffwA "C# (Visual C# Interactive Compiler) – Try It Online") Saved a whopping 68 bytes thanks to Pietu1998! [Answer] # [K (ngn/k)](https://gitlab.com/n9n/k), ~~87~~ ~~63~~ ~~61~~ ~~60~~ 59 bytes ``` f:{`c$x-a-@[!128;98+!25;:;0+"typetjkitkpstokrtyputjkyb"]a:_x} ``` [Try it online!](https://tio.run/##bVPRblMxDH3nK9wrpG2wwgAhjfYB0B6gm4QGmzRV28TcXrdNkybWjdM1Q/Drw7l3mjpB3mzHx/Y5tu37ub@/nw1@3Uyfb/rY/3TZe/P2cPjh8GXv7fvhYHjwspLMJEtrxHKUYBu1k9p5Ul3j4Ofm970Mfj2/zH@awQw2w5tgh7s3MzRuuBnmYbN3/fuZXFZfybmwDxehcXWvegZQnRCzeo6DMPeq6/JpTLENjSl3jnOKMsUzar2nlDnjmLrQaRPmDa5Wxs/hNN3dOYqAvoajUBN8CW7WFZGwFIzRyBJO0mTClAGFYRyYtDRLB3blq9e71fnCRBDaCCxQwQpA9ypPt854AuPBSLVXkLuUU2syMFkGi/lJitCSjWiKgOFqry1zFBpOERz6ecI5wUTHe7S6yYPYpIgoy4RL0m4yP1pdr2fSGAZZEMx05kUPztBJa9@G5OvYsTtmMRbYKoTObHswRubWXoYknB8Yv6pGPgo6BxfYzJRPuqoKVoaIpt4HjcuORidaLfntWFulhDMX5GMUUaJLuhbJkNFwm847GlUeJMl2bJv3iwV2A7zQB7WpIYcEy6TkFE9ROBZ2J9o5rGi/DTsj4rqUFx@3eB@Vdhe4pvaX9eEWRqCbUicUqkECQ5jBKsPU6V4URUvlb7jOcEbo4v4WVtmn0c66CEWqvF8Ht1YMzfFpRU1QLSNNGxJolJEIwcNn1/@ekGr8B6drKqypgXcHBzANfmaalcJZ41x8tb1VxxY7rVpCWOUus0jSXWgJ0WXOhRAJibWDjhD9xvxfQrhspzwQogehvehRcEImLRMsBIGosjDmXPa1VD5HyTAm5PxkED2d0U5Rk3RoVUAvSDE0R1IkbUdRKBeXqMa5AH/m/g8lhPEfnK6pIIpUCMlBxEjUXKuTZCXk@v4v "K (ngn/k) – Try It Online") `{` `}` function with argument `x` `_` to lowercase `a:` assign to `a` `!128` the list `0 1 2 ... 127` `@[!128;` *indices* `;:;` *values* `]` amend it by replacing the elements at *indices* with the given *values* `98+!25` the list `98 99 100 ... 122` which are the ascii codes for `"bcd`...`z"` juxtaposition is indexing, so we use `a` (implicitly converted to integers) as indices in the amended list `x-a-` subtract from `a`, then subtract form `x`; this restores upper/lowercase as in the original string ``c$` convert to characters [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 59 bytes ``` [a-z] $& T`l`L T`L`ATYP\ETJKITKPST\OKRTYPUTJKYB T`L `l_` . ``` [Try it online!](https://tio.run/##XVDLbhNBELzvV3QsxCFyokhceShECBZHYNhFlpUgtu3p9Q7pnbHmsWZ94je4@Vv8KfyI02MjQNuHkaa6urq6HAVt8HC4w4vt12y/e/I0KyuubuW9ra7L@fT@Tfl@kpeTaVHef5x8FuSLAPPXibDfVfyt2u8uD4d3xGzHMLOO1Vn2/MW/epnNyQ@QknxYYkEDeOrsymHbarOCadxumTygUXBjFcFby/VQptEeAv0I0KAwM0Mb1oZAG9BhwL2xbh09MJpVxBXBQiz8/Q24RXB6DaEhqMVCcwYFcjj@NzYa5YcHjnLjAzLDDF0tB9AokXvwqNUYRnn4/fOXdBeiF81/vYHMrMHTlnMpUFpBbyN8j2I0ISkVjz3gwsYALY2PbdYh8Gnk/FWWnzY12NGx@2DsBnKQVFXEQAqCXYOtoe1hyeh9iipt/IBdDwUh@3GWEk86XQqJJErTWe5kVrgmtuSs5Ohp6SiAkys8WAPXfPEpIin8M3@yYDty8OzqCpbW1Nq1IvKgmf3lIw "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: ``` [a-z] $& ``` Prefix a non-ASCII character to each letter. (I tried to use a non-breaking space but Firefox might have changed it back to a regular space after copying and pasting.) ``` T`l`L ``` Uppercase all of the letters. ``` T`L`ATYP\ETJKITKPST\OKRTYPUTJKYB ``` Convert the letters to Corpus. ``` T`L `l_` . ``` Lowercase the letters after the non-ASCII character and delete the non-ASCII character. Naïve solution is 63 bytes: ``` T`lL`aty\petjkitk\pst\okrty\putjkybATYP\ETJKITKPST\OKRTYPUTJKYB ``` [Try it online!](https://tio.run/##XVBNj9NADL3nV3h7XBW0Elc@tKwQhCIoJKiqlMO6HaeZjTOOZjwp2RN/g7@3f6RMWgQovvm952f7eVLr8HQq7/nTPepY9aQPrdW26oNW0voJigkad7fldl29Kz@u8nK1Lsrqy@pbQr4nYPv2dPpAzLKEjXg2V9nLV//qdbalMENKCrrHgmbw2svBY9dZd4B1fHxkCoDOwJ0YgvfC9dymsQGUfig0mJSZoyNbR2AdWJ1p78T3MQCjO0Q8EOzSCX@7mbZQb3vQhqBOJzRXUCDruT9KdCbMH1zkLigywwZ9nR6gxSQeIaA1S1jk@vTzV2J3yS@6/7iZzabBy5brVGCsgVEiPMR06IRMqQQcAXcSFTpanmm2qnwZuX6T5ZdNDQ50ZlsnR8ghpWoiKhlQ6UFq6EbYM4YwRTVt/IzDCAUhh2U2JT75DFNIlKJ0g/CQZpPWxY68pBwD7T0p@PRFAHFwy8@@RiSDf@YvJ8hAHl7c3MBeXG19l0xayxye/wY "Retina 0.8.2 – Try It Online") Link includes test cases. [Answer] # [Python 2](https://docs.python.org/2/), 115 bytes ``` lambda i:i.translate(''.join(a)) a=map(chr,range(256)) b='typetjkitkpstokrtyputjkyb' a[66:91]=b.upper();a[98:123]=b ``` [Try it online!](https://tio.run/##jVJNb9pAEL37V0x8sUkpSoiKGlpaVTm0XKpUREJV6GHMjvHCetfanTV1/jwdQ5XkRvY28@bjzXvbdFw5Oz6Us9XBYF0oBD3VI/Zog0GmPMtGW6dtjoNBgrMam3xd@aHAG8rHHyaSLWYZdw3xdqd51wR2Oy9xlLgrsgQfJ5Pp7fWfWTGKTUM@H3zCx9uP0@vxjeQOjdeWoczTH2SMg6XzRl2kA3gH6cp@nr28LyubJs/VvymcL3qgwGtc0PnKe@82Huta2w3cx6cnQwHQKrhziuC7M@XZEVmWPVQ6ANNfhgqlPbG0N9oSaAuaBT/LYsFeN8AVQSkEqgtYoOFjvHfRqvAGXe6cb2IAI/ZE3BAUIsFzdP6IdG4DozGwRF@KIJT26zsIqNUQ0jmvMgELIRjtKyh7gzrLCk@3XMoDpRV0LsI2Cr8@0ysfsAMsXGSoaXiEjWY2p5bLr8n8uL3Clo7gzro9zEGMU1F@qgJ2DbgS6g7WBkPohe8X/sS2gwWhCcOkN1XGtL0yJL7Y1plWWqXUxpq8E/ECrT0xeDksgLPwzbz/FZEU/m8/MXAtebi5uoK1s6X2tQzZaWPCqHf68A8 "Python 2 – Try It Online") Adapted from @ElPedro's answer. This generates the replacement for every ascii character in the array `a` and then uses `str.translate`. Can be brought to **113 bytes** if returning an array of chars is acceptable: ``` lambda i:[a[ord(x)]for x in i] a=map(chr,range(256)) b='typetjkitkpstokrtyputjkyb' a[66:91]=b.upper();a[98:123]=b ``` [Try it online!](https://tio.run/##lVJNb9pAEL37V0x8sZ1SlBAVNbS0qnJouVSpiIQq4DBmx3hhvWPth8H583RtorRSL2Fvs2/e7Jv3tm5dyXp0Kqark8IqFwhyssQlG5Ees3XBBo4gNch1hNMK63RTmoFBvaV09GGcZVE@TVxbk9vtpdvX1vHehNqHus2TCJfj8eT@dj3Nh76uyaTZJ1zef5zcju7C3ak2UjtIkuGOpU6LNP5BSjEs2ChxFWcZvIN4pT9P/54vKx1H/9F@k72g@4ms2@CcLqA8Gt4arCqpt/Don58VWUAt4IEFwXdWxdtnJUnyVEoLjo4OSgxzIk0HJTX1PruAv13X3BlZgysJiiCpvII5KtfXB/Za2EtMfGBTewsqhOtxS5AHm16rC/aLZ9o6VAoWaIpgGsWdoBYsSjGAeOZWSQDzINnrf6DkEgcXJZ7XvA4HhBTQsoedD4q7my4miy1gzt5BRYMeVtI5daZcf41mvYwSG@rBveYDzCCkLDw6EuC4Bi6gamGj0NounO7Bn9i0MCdUdhB1PyCMaTqvKGSnG1ZNoIZW7SsyHOy0tDHkwIQNLbCGb@r9L48k8IV@VsANGbi7uYEN60KaKgzZS6XssP8Npz8 "Python 2 – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 29 bytes ``` “qḍỊYl4ḃ©ƭṄxḳ½Dy’ṃⱮØA,Øa¤⁺żẎy ``` [Try it online!](https://tio.run/##LY69TsNAEIT7PMXWkUGRoEeRaNIgIQpEufFt4kvWd3A/BndBoUKCOkiUNBQgIZokQOMI3uP8IuZw2HJnvpmZEHPZNPXs8SIs78LH7Rnvh@W8ev55Caubq7B8r74Oy3r2EFbz@u11s@gnmwVWT/X1@vszrO8j25xm6MBlBN14IKSAUnuYeOvaj1RjsFgCDrV3kFPSyiyd4y3SPegMYgMzZFhQq06VvoQBjA0Kj44EOH0OegR5CSmjtSBV23iERQknhGyTDioBfzkxYkikoqXQXEQ2epXPyWhvwVJqyIFBKSxoBX3eOfZIAv/57QRdkIG9Xg9SrUbS5DFkKpnt7i8 "Jelly – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt), 37 bytes ``` ;®i`…ypetjkŠkp¡okrtyp©jkyb`pu)gCpu bZ ``` [Try it online!](https://ethproductions.github.io/japt/?v=1.4.6&code=O65pYIV5cGV0amuKa3Chb2tydHlwqWpreWJgcHUpZ0NwdSBiWg==&input=WyJIZWxsbywgV29ybGQhIgoiWWVzIgoiVGVzdGNhU2UiCiJQcm9ncmFtbWluZyBQdXp6bGVzIGFuZCBDb2RlIEdvbGYiCiJUaGlzIHRleHQgaGFzIGEKbmV3bGluZSBpbiBpdCIKIkNvcnB1cyBsYW5ndWFnZSBiZXN0IGxhbmd1YWdlIgoiU3RyaXAgdGhlIGZsZXNoISBTYWx0IHRoZSB3b3VuZHMhIgoiV2hhdCB0aGUgKioqKiBkaWQgeW91IGp1c3QgKioqKmluZyBzYXkgYWJvdXQgbWUsIHlvdSBsaXR0bGUgKioqKio/CkknbGwgaGF2ZSB5b3Uga25vdyBJIGdyYWR1YXRlZCB0b3Agb2YgbXkgY2xhc3MgaW4gdGhlIE5hdnkgU2VhbHMsCmFuZCBJJ3ZlIGJlZW4gaW52b2x2ZWQgaW4gbnVtZXJvdXMgc2VjcmV0IHJhaWRzIG9uIEFsLVF1YWVkYSwKYW5kIEkgaGF2ZSBvdmVyIDMwMCBjb25maXJtZWQga2lsbHMuIl0KLW1S) The above link includes most test cases, but I haven't been able to input the second to last one as a string because it contains both single and double quotes. [Here](https://ethproductions.github.io/japt/?v=1.4.6&code=O65pYIV5cGV0amuKa3Chb2tydHlwqWpreWJgcHUpZ0NwdSBiWg==&input=WyciJywnSScsJ24nLCdzJywndCcsJ2EnLCdsJywnbCcsJyAnLCdXJywnYScsJ3InLCdmJywncicsJ2EnLCdtJywnZScsJyInLCcgJywndCcsJ2gnLCdlJywneScsJyAnLCdzJywnYScsJ2knLCdkJywnLCcsJyAnLCciJywnSScsJ3QnLCInIiwnbCcsJ2wnLCcgJywnYicsJ2UnLCcgJywnZicsJ3UnLCduJywnIicsJyAnLCd0JywnaCcsJ2UnLCd5JywnICcsJ3MnLCdhJywnaScsJ2QnXQotUA==) is that test case, input as an array of characters instead. Explanation: ``` ; #Set C to the lowercase alphabet ® #For each character Z of the input: bZ # Find its index in: C # The lowercase alphabet pu # Plus the uppercase alphabet # (-1 if it is not a letter) g # And get the character at that index in: `…ypetjkŠkp¡okrtyp©jkyb` # Get the lowercase Corpus alphabet pu) # Plus the uppercase Corpus alphabet i # Add Z at the end (index -1) ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~138~~ 132 bytes ``` def f(i,a='bcdfghjlmnpqrstvwxz',b='typtjktpstkrtyptjkb'):a+=a.upper();b+=b.upper();return''.join((x,b[a.find(x)])[x in a]for x in i) ``` [Try it online!](https://tio.run/##jVJNb9swDL3nV7C@OG68oNhu67Jh6GHLZeiQAsHQ9EBHdKxEpjyJcuL8@VR2hqy3lCdSjx@Pj2o6qSx/PJ0UlVCOdY6ztFirclNtTc3NX@el3R@OaV7MUuka2e6k8bJzZ79Is884meE0NA25cXZfTGbFJXAkwXGaTrdW83h8yItnnJaa1fiQvWTPB9AM@FJaB4Ors1PjNEukkfwkYywsrTPqJslgAsmKv8z@29cVJ6NL9h/y15OeyMsaF3Q989HZjcO61ryBx3A8GvKArODBKoIf1pRXW6Rp@lRpD0IHgQpj@YhpbzTTsKhE/CqLhTjdgFQEZSRQ3cACjQzx3gZW/h26PFjXBA8GeRNwQ1BECS7R9SWSOXtBY2CJroyCUNKP78CjVjkkc1mlESwiwcBvoPQd6iwrPO9yGw2UVtDZANsQ@fUvvfIeO8DCBoGa8gE2WsScS26/jebD9ApbGsAd2z3MIR5OBRRSILYBW0Ldwdqg973w/cBf2HawIDQ@H/VHjW3aXhmKd@HWmjaWxlQONTkbxfO0jv8YXFzMg2X4bj78DkgK/5WfGdiWHHy6u4O15VK7OjbZaWP8tL/06RU "Python 2 – Try It Online") Actually shorter with a named function than with a lambda! lambda version, **138** bytes ``` lambda i,a='bcdfghjlmnpqrstvwxzBCDFGHJLMNPQRSTVWXZ',b='typtjktpstkrtyptjkbTYPTJKTPSTKRTYPTJKB':''.join((x,b[a.find(x)])[x in a]for x in i) ``` [Try it online!](https://tio.run/##jVFNc9owEL3zKza@CFKXybS3TkmnodOEpMmQ2BOahhzWSMYCWXKllcH8eSqbTtob2dNKbz/ee1s1VBj9YZ@P5nuFZcYRZIwjli14vixWqtTVb@uo3mx3F@Nv3y@vrn/c3k3vH5L0cfbzF4uzEaOmotWaKkdre8iz9GmaXt@k0yS9eTjkF@wTY8OVkbrf38bZMw5zqXl/O3gZPG9BasCX3FjoUjnYV1ZqgrwfXQmlDMyMVfwkGsA7iOb68@hfnM911HutfhLueFEqHC0wEccrp9YsLZal1EuY@t1OCQeoOYwNF3BpVH50BGMsLaQDEluCAkN7T4uNklp0QingR1kkZGUFVAjIA4HiBBJU1L03xmvu3uDL2NjKO1Colx6XArJgwevruIhooh2hUjBDmwdDRNSub8Ch5DFEE5qzAGaBoNf/QewN7swKPGg5DQFccmiMh5UP/Nqf1nmHDWBmPEEp4g5WkkgdWk6/9Cbd9gJr0YFrbTYwgXA47pEEBzIVmBzKBhYKnWuNbxfeYd1AIlC5uNceNYypW2dEuIuujapDayjVvhTWBPOcWFhBYIMwB0bDV/X@3qPg@Lf9wMDUwsLHszNYGJ1LW4Yha6mUG7aX3v8B "Python 2 – Try It Online") **~~131~~ 125** if we are allowed to return an array of characters and have the `join` outside the function. ``` def f(i,a='bcdfghjlmnpqrstvwxz',b='typtjktpstkrtyptjkb'):a+=a.upper();b+=b.upper();return[(x,b[a.find(x)])[x in a]for x in i] ``` [Try it online!](https://tio.run/##lVNNj9MwEL33V8zm4mQbqhXcgILQHqAXtKgrVajtYVJPGrfOOPgjbfrni5OiBYnLxqcZP7/xmzd20/nK8NvrVVIJZapynItiJ8t9ddA1N7@s8@3pfBF5MRe@a/zh6Bvnj/YWFyJ7j9M5zkLTkE2zD8V0XrwklnywvE7PebHGWalYpudsm63PoBhwWxoLQ6i218Yq9iDE7GAUp2WafCOtDayM1fIuyTKYQrLhj/O/69OGk8l/tJ/kRpx@Jud3uKQRlCdr9hbrWvEensLloskBsoRHIwm@Gl2@vpYQ4rlSDjydPVQY60yYTloxDab4iL9e19Jb1YCvCMooqbqDJWo/5CcTWLoxJj4a2wQHGnkfcE9QRJteshH9JQt2HrWGFdoymkZJL6gDh0rmkCz8RkSwiJID/wOJMQ6uKry1eR8XSCWhMwEOISrud/oxOewACxM81JQPsFbe6xvl/vNkMciosKUBPLI5wQLilGVATxK8acCUUHew0@hcP5z@wu/YdrAk1C6f9C8glml7ryjOjluj20iNRznUZE2009EufgiwsUMHhuGLfvMjIEn8Q78pMC1ZePfwADvDpbJ1LHJUWrvZ8BquvwE "Python 2 – Try It Online") [Answer] # [PHP](https://php.net/), 100 bytes **Code** ``` <?=strtr($argv[0],($u=bcdfghjklmnpqrstvwxyz).($f=strtoupper)($u),($v=typtjktkpstkrtyptjkyb).$f($v)); ``` [Try it online!](https://tio.run/##NcuxDoIwFIXhnadoSAeaGOKOlcGBld04FKFFCvR6e6nCy2OjcTw53w897KcSeki4QhOuxxuTLK3RGVTT9JgNq5dtGzvP1Nyyi2s7VrlRp0VSnmMoPSFh9m8PGV9kc2@16Qc7TjM80VN4vddN5BnXX@0WgA5FlCLyIGkFGixZ8GTxN9ZG5FzHU4hi3z8 "PHP – Try It Online") **Explanation** ``` # using the provided character mapping given on the question, as an array strtr($argv[0], # strtr for the string replacement ($u=bcdfghjklmnpqrstvwxyz).($f=strtoupper)($u), # Taking onthe the keys for the first string ($v=typtjktkpstkrtyptjkyb).$f($v)); # Using the values for second string # In both Strings appending the upper version of each string. ``` [Answer] # Pyth, 35 Bytes ``` XQ.*m+r1dd[tG."byàHuH¯¹e?rJyfh ``` [Try it!](https://pyth.herokuapp.com/?code=XQ.%2am%2Br1dd%5BtG.%22by%04%C3%A0Hu%05H%C2%AF%C2%B9e%3FrJyfh%22&input=%22Hello%2C+World%21%22&debug=0) Could probably use Left map or something to get rid of the two d's, but I couldn't figure out how. [Answer] # Java, 211 Bytes ``` a->{String b="BCDFGHJLMNPQRSTVWXZbcdfghjlmnpqrstvwxz",c="TYPTJKTPSTKRTYPTJKBtyptjktpstkrtyptjkb";a.chars().map(x->{int z;return(z=b.indexOf(x))>-1?c.toCharArray()[z]:x;}).forEach(x->System.out.print((char)x));}; ``` [Try it online!](https://tio.run/##VZHfb4IwEMef51/R8VQSIdnrCFum@2F0bk7IdDM@lFIUhMLakyGGf32sINnivfRyvX7ve59GJCdG5O/qOtt7cUgRjYmUaEpCjo49pCLkwERAKEPLrtJEnoY@4tgBEfINIrrV3lS99pBAQEktUYFsRIybY9fm2dpgeP/4NBo/T19mb3PHfV8sPz3qB5ttFCc8@xIS8u@i1PrU1tyPmTueuDPHncxP@QAOGUQ7yCTsxCn3NIuYdEuExLqZkAwXapyyjEpLMNgLjkvbM0Pus@I1wIWu3xhXt9SEdKje3AlBDlhflevrwqp0M0jFA6HbRsM5SGCJme7BzJR3wLgZoisBq7JOW3bAumVbIInC1jFZrRERG6krZhesYHQPzGUSlM0zVEo8J8DOVM7b27Z/8KgwOdZGLI7TPlqkIvYvtT/Jqq7rnzSDMOWyNhipm3/8BQ "Java (JDK) – Try It Online") [Answer] # Pyth, 34 chars ``` J."byàHuH¯¹e?rJyfh"XXztGJrtG1rJ1 ``` [Try it online!](http://pyth.herokuapp.com/?code=J.%22by%04%C3%A0Hu%05H%C2%AF%C2%B9e%3FrJyfh%22XXztGJrtG1rJ1&input=Hello+World%21&test_suite_input=Yey%0A%3C%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3E%0ATestcaSe%0A%0APeypyaYe%0A%3C%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3E%0AProgramming+Puzzles+and+Code+Golf%0A%0AKtojtassitj+Kubbpey+atp+Yope+Jopt%0A%3C%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3E%0AThis+text+has+a%0Anewline+in+it%0A%0APkiy+pekp+kay+a%0Atejpite+it+ip%0A%3C%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3E%0ACorpus+language+best+language%0A%0AYotkuy+patjuaje+teyp+patjuaje%0A%3C%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3E%0AStrip+the+flesh%21+Salt+the+wounds%21%0A%0AYptik+pke+tpeyk%21+Yapp+pke+joutpy%21%0A%3C%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3E%0A%22Install+Warframe%22+they+said%2C+%22It%27ll+be+fun%22+they+said%0A%0A%22Itypapp+Jatttase%22+pkey+yaip%2C+%22Ip%27pp+te+tut%22+pkey+yaip%0A%3C%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3E%0AWhat+the+%2a%2a%2a%2a+did+you+just+%2a%2a%2a%2aing+say+about+me%2C+you+little+%2a%2a%2a%2a%2a%3F%0AI%27ll+have+you+know+I+graduated+top+of+my+class+in+the+Navy+Seals%2C%0Aand+I%27ve+been+involved+in+numerous+secret+raids+on+Al-Quaeda%2C%0Aand+I+have+over+300+confirmed+kills.%0A%0AJkap+pke+%2a%2a%2a%2a+pip+you+tuyp+%2a%2a%2a%2aitj+yay+atoup+se%2C+you+pipppe+%2a%2a%2a%2a%2a%3F%0AI%27pp+kate+you+ktoj+I+jtapuapep+pok+ot+sy+ypayy+it+pke+Taty+Yeapy%2C%0Aatp+I%27te+teet+ittoptep+it+tusetouy+yeytep+taipy+ot+Ap-Ruaepa%2C%0Aatp+I+kate+otet+300+yottitsep+kippy.&debug=0&input_size=20) The string is a compressed version of *"typetjkitkpstokrtyputjkyb"*. For some reason I cannot get Pyth to compress *"atypetjkitkpstokrtyputjkyb"* with the function ``` +++\.N++hSzeSzCi-RChSzCMz-hCeSzChSzN ``` even though it would probably save a byte or two as the two t's could be eliminated. [Answer] # [Tcl](http://tcl.tk/), 114 bytes ``` proc C s {string map [split {btcydpftgjhkjtlpmsntpkqrrtsytpvtwjxkzbBTCYDPFTGJHKJTLPMSNTPKQRRTSYTPVTWJXKZB} ""] $s} ``` [Try it online!](https://tio.run/##TVHRbtswDHz3V7DGgAJFNhTYBwxrhrVJtsKtjWVZ0QfZpmMnsqSJlFMnyLdnVDIM04Mg6cjj3YkrfTo5byuYAsGB2HdmDb1y8EJOdwyHkquxdg2vN@12w9r1ZNhtf3vPNLIbeLd52@7Lu2K6@pJ9Le7nD4t58S37nj8W2eLp@bnIV0X2o1jOfy5@3R0hTV/hHR1POo6QgUn6gFrbCSyt1/VVmqQrJNkLJK5UjnLMvF171fdRWBb2e40EytQwtTXCvdVNLG87AsY3hlYJmhjc6c4gdAY6FnxqvQsEWpl1UGuEUuj/3QTPxbcDbhEaoW@vIFeaz/edDaYmEXZIZ4ZYaQ1L5RsRhGksGIFUV08gnfG1YKUwBPMfckzSZasuXDeyoO5qGG2ATRAJ8SX6IjWCKm1g6HFyhiV71peWm0/JLHK3asAztjV2BzOQVOqgGGtg68A20I9QaUUUbcd5j2oYIUelaZLExGbXQ7SOEooZrB6kUypN6NFbSYew8sjgRTWBNfBZv38KCmv1t/siwA7o4ePtLVTWNJ3vhWTbaU0f0uQIBxeY4GUqf/x6PP0B "Tcl – Try It Online") [Answer] # [Lua](https://www.lua.org), 153 bytes ``` t="atypetjkitkpstokrtyputjkyb"for c in(...):gmatch"."do i=c:lower():byte()-96n=t:sub(i,i)io.write((i<0or i>26)and c or(c==c:upper()and n:upper()or n))end ``` [Try it online!](https://tio.run/##NU9Nb4MwDL33V1hcClWLqk2qNDQ27djLpGmHHaoeDDElJcQocaj49Sylm2/P78s2AWfDqLw4bS@n0yxlgjINJNdOSzd44c5FHCKeqqRhBzVom@Z5nhWXHqVukzxRDLqsC8M3cmlWVJNQmu1eDraUwocq1Vudac5vTkci1a/7GKPfng4ZWhXz2KV1Gf1hGO7@@9L@g6i0WUZWzefz0jrPPy0KSEuwiQNKK5g4wDV4WTbxD/A4AVYcBHraLrTRIuZh2byvjmtjoMWRFq6zfIMjXByqgEIKhAfgBvoJaoPex4eXvk8cJ/gmNH67uh95XMeAishGwchmjM6otKEnx8GDp9qRgEOtPLCFD7P7CkgK/9yPA3gkB8/7PdRsG@36GNJpY3z@Cw "Lua – Try It Online") ]
[Question] [ Swapping two elements in a vector/matrix is very simple in Octave: ``` x='abcde'; x([4,1])=x([1,4]) x = dbcae ``` Unfortunately, I have yet to find a way to do this inside an anonymous function. While the function below is syntactically correct, it only gives back the two elements that are swapped, not the entire `x` vector: ``` f=@(x)(x([4,1])=x([1,4])) f(x) ans = ad ``` Is there a way to achieve the desired behavior using anonymous functions in a golfy way? Can several elements be swapped this way using an anonymous function? I *could* create an indexing vector: `f=@(x)x([4,2,3,1,5])`, but creating such a vector dynamically will likely take a lot of bytes too. [Answer] # Argument List ``` f=@(x,y=x([4 1])=x([1 4]))x; ``` [Try it online!](https://tio.run/##y08uSSxL/f/fQaNCp9K2QiPaRMEwVhPEMFQwidXUrLD@n5hXrKGUmJScoqT5HwA "Octave – Try It Online") [Answer] # Be `eval` ``` f=@(x)eval"x([4 1])=x([1 4])" ``` [Try it online!](https://tio.run/##y08uSSxL/Z9mq6en999Bo0IztSwxR6lCI9pEwTBW0xbIMFQwidVU@l9hq56YlJySqm7NlQZU9h8A) --- In Matlab the parentheses cannot be omitted: ``` f=@(x)eval('x([4 1])=x([1 4])') ``` [Answer] ## Cell array One option is to use a cell array, like this: ``` f=@(x){x([1,4])=x([4,1]);x}{2} ``` [Try it online!](https://tio.run/##y08uSSxL/Z9mq6en999Bo0KzukIj2lDHJFbTFsgw0TGM1bSuqK02qv2fpqGemJSckqqu@R8A "Octave – Try It Online") ]
[Question] [ Write a function or program that takes in a list and produces a list of the local extremes. In a list `[x_0, x_1, x_2...]` a local extreme is an `x_i` such that `x_(i-1) < x_i` and `x_(i+1) < x_i` or `x_(i-1) > x_i` and `x_(i+1) > x_i`. Notice that the first and last elements of the list can never be local extremes. So for some examples ``` local_extremes([1, 2, 1]) = [2] local_extremes([0, 1, 0, 1, 0]) = [1, 0, 1] local_extremems([]) = [] ``` This is code golf so the shortest code wins! [Answer] # J - 19 char Couldn't help it ;) ``` (}:#~0,0>2*/\2-/\]) ``` Explanation follows: * `2-/\]` - Over each pair of elements in the argument (each 2-item long infix), take the difference. * `2*/\` - Now over each pair of the new list, take the product. * `0>` - Test whether each result is less than 0. This only happens if the multiplicands had alternating signs, i.e. it doesn't happen if they had the same sign or either was zero. * `0,` - Declare that the first element isn't an extreme element. * `}:` - Cut off the last element, because that can't possibly be an extreme either. * `#~` - Use the true values on the right side to pick items from the list on the left side. Usage: ``` (}:#~0,0>2*/\2-/\]) 1 2 1 2 (}:#~0,0>2*/\2-/\]) 0 1 0 1 0 1 0 1 (}:#~0,0>2*/\2-/\]) i.0 NB. i.0 is the empty list (empty result also) (}:#~0,0>2*/\2-/\]) 3 4 4 4 2 5 2 ``` [Answer] # Mathematica ~~66 58~~ 51 ## Current Solution Shortened thanks to a contribution by Calle. ``` Cases[Partition[#,3,1],{a_,b_,c_}/;(a-b) (b-c)<0⧴b]& ``` `Partition[#,3,1]` finds the triples. `(a-b) (b-c)<0` is true if and only if `b` is below `a`, `c`, or above `a`,`c`. and looks at takes the signs of the differences. A local extreme will return either `{-1,1}` or `{1,-1}`. --- **Examples** ``` Cases[Partition[#, 3, 1], {a_, b_, c_} /; (a - b) (b - c) < 0 :> b] &[{1, 2, 1}] Cases[Partition[#, 3, 1], {a_, b_, c_} /; (a - b) (b - c) < 0 :> b] &[{0, 1, 0, 1, 0}] Cases[Partition[#, 3, 1], {a_, b_, c_} /; (a - b) (b - c) < 0 :> b] &[{}] Cases[Partition[#, 3, 1], {a_, b_, c_} /; (a - b) (b - c) < 0 :> b] &[{9, 10, 7, 6, 9, 0, 3, 3, 1, 10}] ``` > > {2} > > {1, 0, 1} > > {} > > {10, 6, 9, 0, 1} > > > --- ## Earlier Solution This looks examples all triples (generated by `Partition`) and determines whether the middle element is less than both extremes or greater than the extremes. ``` Cases[Partition[#,3,1],{a_,b_,c_}/;(b<a∧b<c)∨(b>a∧b>c)⧴b]& ; ``` --- ## First Solution This finds the triples, and looks at takes the signs of the differences. A local extreme will return either `{-1,1}` or `{1,-1}`. ``` Cases[Partition[#,3,1],x_/;Sort@Sign@Differences@x=={-1,1}⧴x[[2]]]& ``` **Example** ``` Cases[Partition[#,3,1],x_/;Sort@Sign@Differences@x=={-1,1}:>x[[2]]]&[{9, 10, 7, 6, 9, 0, 3, 3, 1, 10}] ``` > > {10, 6, 9, 0, 1} > > > --- **Analysis**: ``` Partition[{9, 10, 7, 6, 9, 0, 3, 3, 1, 10}] ``` > > {{9, 10, 7}, {10, 7, 6}, {7, 6, 9}, {6, 9, 0}, {9, 0, 3}, {0, 3, > 3}, {3, 3, 1}, {3, 1, 10}} > > > `%` refers to the result from the respective preceding line. ``` Differences/@ % ``` > > {{1, -3}, {-3, -1}, {-1, 3}, {3, -9}, {-9, 3}, {3, 0}, {0, -2}, {-2, 9}} > > > `Sort@Sign@Differences@x=={-1,1}` identifies the triples from {{9, 10, 7}, {10, 7, 6}, {7, 6, 9}, {6, 9, 0}, {9, 0, 3}, {0, 3, 3}, {3, 3, 1}, {3, 1, 10}} such that the sign (-, 0, +) of the differences consists of a `-1` and a `1`. In the present case those are: > > {{9, 10, 7}, {7, 6, 9}, {6, 9, 0}, {9, 0, 3}, {3, 1, 10}} > > > For each of these cases, x, `x[[2]]` refers to the second term. Those will be all of the local maxima and minima. > > {10, 6, 9, 0, 1} > > > [Answer] # Javascript - ~~62~~ 45 Characters ``` f=a=>a.filter((x,i)=>i&&i<a.length-1&&(a[i-1]-x)*(a[i+1]-x)>0) ``` **Edit** ``` f=a=>a.filter((x,i)=>(a[i-1]-x)*(a[i+1]-x)>0) ``` [Answer] # Ruby, ~~83~~ ~~70~~ ~~60~~ ~~55~~ 49 characters ``` f=->a{a.each_cons(3){|x,y,z|p y if(x-y)*(z-y)>0}} ``` Prints all local extremes to STDOUT. ~~Uses the `<=>` "spaceship" operator, which I really like. (It returns 1 if the first thing is greater than the second, -1 if it's less, and 0 if equal. Therefore, if they add to -2 or 2, that means the middle is an extreme.)~~ ~~Not anymore, as @daniero pointed out that the "obvious" way is actually shorter!~~ Changed yet again! Now it uses the awesome algorithm found in [MT0's answer](https://codegolf.stackexchange.com/a/22274/3808) (+1 to him!). Also, I like `each_cons` which selects each `n` groups of consecutive elements in an array. And trailing `if` is interesting too. Overall, I just like how elegant it looks. Some sample runs: ``` irb(main):044:0> f[[1,2,1]] 2 => nil irb(main):045:0> f[[1,0,1,0,1]] 0 1 0 => nil irb(main):046:0> f[[]] => nil irb(main):047:0> f[[1,2,3,4,5,4,3,2,1]] 5 => nil irb(main):048:0> f[[1,1,1,1,1]] => nil irb(main):049:0> f[[10,0,999,-45,3,4]] 0 999 -45 => nil ``` [Answer] # C++ - 208 chars Longest solution again: ``` #include<iostream> #include<deque> using namespace std; int main(){deque<int>v;int i;while(cin){cin>>i;v.push_back(i);}for(i=0;i<v.size()-2;)if(v[++i]>v[i-1]&v[i]>v[i+1]|v[i]<v[i-1]&v[i]<v[i+1])cout<<v[i]<<' ';} ``` To use, enter your integers, then any character that will crash the input stream - any non-number characters should work. Input: `0 1 0 x` Output: `1` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes ``` IṠIỊ¬T‘ị ``` [Try it online!](https://tio.run/##JZC9UYQxDERbcQEO8L9dwuVkDCEJcw2QEd81cOEVQAPMZXTy0Yh5bwg0K69WWsnvb@fzx96n4/t@Oh6Xn6/n38/b8bjuvV/GjKGWGHqLYdYYSoohz/@YI4ZEFBG@d7gY1hPlDEqTV7AbjFm2wxXy4kh005zWDGbqY8FRS8Si3n0b2sJltAtt4w1UWpykqwvqjAJ2Cg6neVBuYPceMLmrZrQ0p2jEBPZsDoRW7VUqMKiu7TnIOjjkiKEh2EFTDBKtdA2Ug4HDo6Ea5eYefgx5qX4QRFLs79jnVf6iHE/d@@sf "Jelly – Try It Online") ## Explanation ``` IṠIỊ¬T‘ị I Differences between adjacent elements {of the input} Ṡ Take the sign of each difference I Differences between adjacent difference signs Ị Mark the elements that are in the range -1..1 inclusive ¬ not T Take the indexes of the marked elements ‘ with an offset of 1 ị Index back into the original list ``` An element is only a local extreme if its difference with its left neighbour has an opposite sign to its difference with its right neighbour, i.e. the signs of the differences differ by 2 or -2. Jelly has a number of useful primitives for dealing with "find elements with certain properties" (in particular, we can find elements with certain properties in one list and use that to extract elements from a different list), meaning that we can translate back to the original list more or less directly (we just need to offset by 1 because the first and last elements of the original list got lost in the difference-taking). [Answer] # Matlab - 45 bytes ``` x=input('');y=diff(x);x(find([0 y].*[y 0]<0)) ``` [Answer] # Python 2.7 - 73 bytes ``` e=lambda l:[l[i]for i in range(1,len(l)-1)if(l[i]-l[i-1])*(l[i]-l[i+1])] ``` Not too impressive (Look at every element of the list except the first and last, see if it's larger or smaller than its neighbours). I'm mostly only posting it because not everyone knows you can do `x<y>z` and have it work. I think that's kind of neat. Yes, `x<y>z` is a cool feature of python, but it's not actually optimal in this case. Thanks to V-X for the multiplication trick, that didn't occur to me at all. Wrzlprmft reminded me that declaring an anonymous function is less keystrokes than `def x(y):`. [Answer] **Haskell 50** ``` f a=[x|(p,x,n)<-zip3 a(tail a)(drop 2 a),x>p&&x>n] ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~11~~ 10 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ¥.±¥Ä2Q0šÏ ``` [Try it online](https://tio.run/##yy9OTMpM/f//0FK9QxsPLT3cYhRocHTh4f7//6MtdQwNdMx1zHQsdQx0jIHQECgQCwA) or [verify a few more test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaXL/0NL9Q5tPLT0cItRoMHRhYf7/x9er/M/OtpQx0jHMFYn2kDHUAeMgWwgMtYxAUMjHVMgz1LH0EDHXMdMxxKoxhgIDYECQHGQZpBKUyA2hhpkqAOGIJYBULWlpaWOrokpSBlQCKgEqsUYQsfGAgA). **Explanation:** ``` ¥ # Get the forward differences (deltas) of the (implicit) input-list # i.e. [9,10,7,6,9,0,3,3,1,10] → [1,-3,-1,3,-9,3,0,-2,9] .± # Get the signum of each delta (-1 if neg.; 0 if 0; 1 if pos.) # → [1,-1,-1,1,-1,1,0,-1,1] ¥ # Get the forward differences of that list again # → [-2,0,2,-2,2,-1,-1,2] Ä # Convert each integer to its absolute value # → [2,0,2,2,2,1,1,2] 2Q # And now check which ones are equal to 2 (1 if truthy; 0 if falsey) # → [1,0,1,1,1,0,0,1] 0š # Prepend a 0 # → [0,1,0,1,1,1,0,0,1] Ï # And only leave the values in the (implicit) input-list at the truthy indices # → [10,6,9,0,1] # (after which the result is output implicitly) ``` [Answer] # Python with Numpy – ~~81 74~~ 67 bytes (~~61~~ 54 without the `import` line) ``` import numpy e=lambda a:a[1:-1][(a[2:]-a[1:-1])*(a[1:-1]-a[:-2])<0] ``` The input needs to be a Numpy array. [Answer] # C, 83 ``` x,y,z;main(){y=z=0;while(scanf("%d",&x)){(y-z)*(y-x)>0?printf("%d ",y):1;z=y,y=x;}} ``` [Answer] # awk - 32 chars ``` {c=b;b=a;a=$0;$0=b}(b-c)*(a-b)<0 ``` No hope of beating a language like J or APL on brevity, but I thought I'd throw my hat into the ring anyway. Explanation: * At any given time, `a`, `b`, and `c` hold `x_i`, `x_(i-1)`, and `x_(i-2)` * `b-c` and `a-b` approximate the derivative before and after `x_(i-1)` * If their product is negative, then one is negative and the other is positive, therfore `x_(i-1)` is a local extreme, so print [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 17 bytes ``` s₃{b≠h.&k≠&{⌉|⌋}} ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/6htw6OmpofbFjzc1Vn7cOuE/8WPmpqrkx51LsjQU8sGUmrVj3o6ax71dNfW/v8frRBtqGOkYxirE22gY6gDxkA2EFnqGBromOuY6VgCRY2B0BAoEKsQCwA "Brachylog – Try It Online") Takes input through the input variable and [generates](https://codegolf.meta.stackexchange.com/a/10753/85334) the output through the output variable. ``` s₃{ } For a length-3 substring of the input: {b its last two elements ≠ are distinct, h and the first of those elements is . the output variable; &k its first two elements ≠ are also distinct; &{⌉| } either its largest element &{ |⌋} or its smallest element } is also the output variable. ``` If runs of values could be guaranteed to be absent, `s₃{{⌉|⌋}.&bh}` would save four bytes. [Answer] # [Perl 5](https://www.perl.org/) `-p`, 49 bytes ``` s/\d+ (?=(\d+) (\d+))/say$1if($1-$&)*($1-$2)>0/ge ``` [Try it online!](https://tio.run/##K0gtyjH9/79YPyZFW0HD3lYDSGsqgElN/eLEShXDzDQNFUNdFTVNLTBtpGlnoJ@e@v@/gYKhAhj/yy8oyczPK/6v62uqZ2Bo8F83DwA "Perl 5 – Try It Online") [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~43~~ ~~42~~ 41 bytes ``` BlockMap[#2&@@#/.Median@#->Set@$&,#,3,1]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73yknPznbN7EgWtlIzcFBWV/PNzUlMzHPQVnXLji1xEFFTUdZx1jHMFbtf0BRZl5JNFA8zUE5Vk3foZqr2lDHSMewVoer2kDHUAeMQZxartr/AA "Wolfram Language (Mathematica) – Try It Online") ``` BlockMap[ &,#,3,1]& (* for every consecutive triple of elements *) #2&@@# (* take the second (middle) element, *) /.Median@#->Set@$ (* discarding it if it is not a local extreme *) ``` [Answer] ## PHP, ~~116 114~~ 113 ``` function _($a){for(;$a[++$i+1];)if(($b=$a[$i])<($c=$a[$i-1])&$b<($d=$a[$i+1])or$b>$c&$b>$d)$r[]=$a[$i];return$r;} ``` Example usage: ``` print_r(_(array(2, 1, 2, 3, 4, 3, 2, 3, 4))); Array ( [0] => 1 [1] => 4 [2] => 2 ) ``` [Answer] # Haskell, 70C Golfed version ``` e(a:b:c:r) |a<b&&b>c||a>b&&b<c=b:s |True=s where s=e(b:c:r) e _=[] ``` Ungolfed version ``` -- if it's possible to get three elements from the list, take this one extrema (a:b:c:rest) | a<b && b>c = b:rec | a>b && b<c = b:rec | otherwise = rec where rec = extrema (b:c:rest) -- if there are fewer than three elements in the list, there are no extrema extrema _ = [] ``` [Answer] # Javascript: 102 characters ``` function h(a){for(u=i=[];++i<a.length-1;)if(x=a[i-1],y=a[i],z=a[i+1],(x-y)*(y-z)<0)u.push(y);return u} ``` [Answer] # APL, 19 bytes ``` {⍵/⍨0,⍨0,0>2×/2-/⍵} ``` I converted the 20 char J version to APL. But I add a zero to the beginning and the end instead of removing the first and last digit. Otherwise it works just like the J version. `⍵` - formal parameter omega. This is the input to the function. [Answer] # [Python 2](https://docs.python.org/2/), 59 bytes ``` f=lambda l=0,c=0,*r:r and(c,)*(l<c>r[0]or l>c<r[0])+f(c,*r) ``` [Try it online!](https://tio.run/##TYnBCoAgEETvfcUeXduDeQzzR6KDGVJgJkuXvt4MCjrMMO9Nvs71SLqUMES3z4uDOCjyNZJ7BpcW4QmliMZbHtV0METrzTOxDfWTjCXzlk4RREegCTrE5jOqIsHbP49Ybg "Python 2 – Try It Online") This function mostly avoids the costly business of indexing, by taking the elements of the list as arguments, instead of the list itself. While there is more than one element left in the list, we recursively build up the list, checking for a maximum at each step. ]
[Question] [ Given a ragged list of positive integers return a full cycle of recursive rotations starting with the unchanged input and ending with the state immediately before revisiting the initial state. #### Examples: ``` [[2,3],4,5,5] -> [[2,3],4,5,5] , [4,5,5,[3,2]] , [5,5,[2,3],4] , [5,[3,2],4,5] [1,10,[2,2,4],6,[[5,6],7],1] -> [1,10,[2,2,4],6,[[5,6],7],1] , [10,[2,4,2],6,[7,[6,5]],1,1] , [[4,2,2],6,[[5,6],7],1,1,10] , [6,[7,[6,5]],1,1,10,[2,2,4]] , [[[5,6],7],1,1,10,[2,4,2],6] , [1,1,10,[4,2,2],6,[7,[6,5]]] [[5,6],[6,5]] -> [[5,6],[6,5]] [1,[2,3,4,5,6],[7,8]] -> [1,[2,3,4,5,6],[7,8]] , [[3,4,5,6,2],[8,7],1] , [[7,8],1,[4,5,6,2,3]] , [1,[5,6,2,3,4],[8,7]] , [[6,2,3,4,5],[7,8],1] , [[8,7],1,[2,3,4,5,6]] , [1,[3,4,5,6,2],[7,8]] , [[4,5,6,2,3],[8,7],1] , [[7,8],1,[5,6,2,3,4]] , [1,[6,2,3,4,5],[8,7]] , [[2,3,4,5,6],[7,8],1] , [[8,7],1,[3,4,5,6,2]] , [1,[4,5,6,2,3],[7,8]] , [[5,6,2,3,4],[8,7],1] , [[7,8],1,[6,2,3,4,5]] , [1,[2,3,4,5,6],[8,7]] , [[3,4,5,6,2],[7,8],1] , [[8,7],1,[4,5,6,2,3]] , [1,[5,6,2,3,4],[7,8]] , [[6,2,3,4,5],[8,7],1] , [[7,8],1,[2,3,4,5,6]] , [1,[3,4,5,6,2],[8,7]] , [[4,5,6,2,3],[7,8],1] , [[8,7],1,[5,6,2,3,4]] , [1,[6,2,3,4,5],[7,8]] , [[2,3,4,5,6],[8,7],1] , [[7,8],1,[3,4,5,6,2]] , [1,[4,5,6,2,3],[8,7]] , [[5,6,2,3,4],[7,8],1] , [[8,7],1,[6,2,3,4,5]] ``` #### Rules: Direction of rotation is your choice but must be consistent across layers. You must start with the initial state and stop immediately before it reappears. States are completely determined by their values, cf. example 3 to see what I mean by that. Destroying the input is ok but different iterations cannot be the same object (if that makes any sense in your language - me only speak Python). Other than the above standard code golf loopholes and I/O apply. #### Promises: Lists and sublists will be nonempty and finite as will be the nesting. #### Scoring: Code golf: shortest in bytes per language wins. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 52 bytes ``` If[#!=##2,#0[Map[RotateLeft,#,{0,-2}],##2,#],{##2}]& ``` [Try it online!](https://tio.run/##JYqxCsIwFEX3/IUEOl0xjU2cCl0cBAXRMWQIpaEd2opke7z@eow6Xc45dw5pHOaQpj7k2OZLdHLXSqkhlbuFl3usKaThOsQECVLYa/b4dQ8qy77K9/e0pEMXu3M/rp2stmcflo0EkcaR0cDAMATVqBWK02gYFkQGlnFi1N/6J7Lly4LzBw "Wolfram Language (Mathematica) – Try It Online") Uses an approach from [this answer](https://codegolf.stackexchange.com/a/186798/81203) to `RotateLeft` on every level. --- If the initial state can be last instead, **48 bytes**: ``` If[#!=##2,Map[RotateLeft,#,{0,-2}]~#0~##,{##2}]& ``` [Try it online!](https://tio.run/##JYq7CsIwFIb3voUc6PSLbWzqVMjiICiIjqVDCA3t0AuS7XDy6jHi@F0WG6ZxsWF2Nvku3XxPh45I4WH3/rUFG8b76AMIXOGoZIhURcqUHxnK9PzMazgZb65u2gyV8e3sGrlgVjgLGmhoQcE16grZKTSCFswareAiqH/1T9zmVwpJXw "Wolfram Language (Mathematica) – Try It Online") [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), 23 bytes ``` {(`i>@x)(o',/|0 1_)/x}\ ``` [Try it online!](https://ngn.bitbucket.io/k#eJxLs6rWSMi0c6jQ1MhX19GvMVAwjNfUr6iN4eJKU9AwUjC2NrE2tTbVBPEMrQ0NrI0UjBRMrM2sNUwVzKzNNa0NwVIgjpkCUBkXAB9dEXY=) ``` {(`i>@x)(o',/|0 1_)/x}\ Iterate and collect until it returns to the input... (`i>@x)( )/x Apply once if x is not an integer atom... o',/|0 1_ Rotate once and apply recursively to each item ``` Not quite sure if I can circumvent the explicit type checking. [Answer] # [Ruby](https://www.ruby-lang.org/), 69 bytes ``` r=->l{l*0==0?l:l.rotate.map(&r)} f=->l,x=l{l!=r[x]?[x]+f[l,r[x]]:[x]} ``` [Try it online!](https://tio.run/##hc7PCoJAEAbwu09RHkLrS9T8E8Lmg0xzsEgIJpPFwAiffdu1U5c6zMAwv/kY/Tg9jdFqe5CXrGOl4loqifR9aIZLdGv6YKXDyWsdwKgsWipNI9e2Ni0J3MCVbZPp9bUbFm10bkQCohQ7RoYcOYfevPOP3bHzvW@XIIlhcYqMUYAoR8EoGcnPsw@jwqb/iXePzH84X2JvvXkD "Ruby – Try It Online") *r* => rotate ragged list *l\*0==0?l* If input is a value return it. Else is an array, so rotate and map by *r*. *f* => recursively build an array of the steps. [Answer] # [R](https://www.r-project.org), ~~124~~ ~~115~~ ~~112~~ 101 bytes ``` r=\(l)"if"(is.list(l),Map(r,c(l[-1],l[1])),l) `+`=list f=\(l,a=+l,b=r(l))"if"(+b%in%a,a,f(b,c(a,+b))) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=TY9NCsIwEIX3PUahMENeharVbrJ25QlqoYkYCIQiaT2Nm7rwUN7GxFhxM_D43g9zf_h5ft4mUzavi5cncpxbk5MdV86OU5A4qit5nMm1ZdXBtVXHDMdZL3oZPZmJMSgpHLT0IZIqhC7sUCgoGNIhryA0M3_HDuPkyVAaiWeNDWOLGnUwZX-0wsI_eMdJ79Hwr2754Q0) -12 bytes thanks to Dominic van Essen. -11 bytes thanks to pajonk. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), ~~16~~ ~~15~~ 10 bytes ``` ≬Iȧ[vxǓ]İǔ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLiiaxJyKdbdnjHk13EsMeUIiwiIiwiWzEsMTAsWzIsMiw0XSw2LFtbNSw2XSw3XSwxXSJd) ~~All because there's a bug with `ǔ` and nested lists.~~ Gotta love bug fixes. ## Explained ``` ≬Iȧ[vxǓ]İǔ ≬ İ # Apply the following on the input while the result is unique, collecting iterations: Iȧ # Either push lambda arugment spaces or split a list into two halves. Then remove all whitespace. [ ] # If that's truthy (that is, the item is a list): vx # Apply this lambda to each item recursively Ǔ # And rotate the result of that left once ǔ # Rotate the resulting list right ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 25 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` [="ИÊi®δ.V}DdiëÀ"©.VDIQ# ``` Outputs the states each on a separated newline. [Try it online](https://tio.run/##yy9OTMpM/f8/2lbp8ITTcw53ZR5ad26LXlitS0rm4dWHG5QOrdQLc/EMVAYqMdQxNNCJNtIx0jGJ1THTiY421TGL1TGP1TGM/a@rm5evm5NYVQkA) or [verify all test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpipaBkX6nDpeRfWgLh6VT@j7ZVOjzh9JzDXZmH1p3bohdW65KSeXj14QalQyv1wlwqA5X/1x7aZv8/OjraSMc4VsdEx1THNFZHIdpQx9BAByhmpGMSq2OmEx1tqmMWq2Meq2MIkoXwos2AaiGKQbrBmkHC5joWsbGx/3V18/J1cxKrKgE). **Explanation:** Yet another 05AB1E [ragged-list](/questions/tagged/ragged-list "show questions tagged 'ragged-list'") monstrosity.. ``` [ # Loop indefinitely: = # Print the current list with trailing newline (without popping) # (which will be the implicit input-list in the first iteration) "..." # Create the recursive-string explained below © # Store it in variable `®` (without popping) .V # Evaluate and execute it as 05AB1E code DIQ # If it's now equal to the input: # # Stop the infinite loop # Ð # Triplicate the current list/item ˜ # Flatten the top copy Êi # If the top two lists are NOT equal (so there is an inner list): δ # Map over each inner item: ® .V # Do a recursive call } # After the if-statement, whether we've executed it or not Ddië # If the current item is NOT an integer (so it's a list): # (necessary to prevent rotation on multi-digit integers) À # Rotate this list once towards the left ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 42 bytes ``` ⊞υθFυFΦι⁺κ⟦⟧⊞υκW¬⁼θω«≔∨ω×¹θω⟦⭆¹θ⟧FυUMκ§κ⊕μ ``` [Try it online!](https://tio.run/##NY7NasMwEITP8VPscQVbqEOaHnwKpYEc2hjam9BB2GosIsmxfuJA6bOrVktOs@zM8E03SN@N0uTcpjBgIphYU32NHjAx@NO9NlF51AStSQHPBFwwxuBeOC@FedBGAb6PEV@nJE3AiWAuqe9qtQtBnxwePc4En9qqgHXhsBJpqlXrtYvIP@Kipzd5@XdFse5Dlu/LaK10feHv4sH16lbOg@u8sspF1aNdeE31kzPnNdWPxNe0po2gLXH@RFtBz4JqIfLD1fwC "Charcoal – Try It Online") Link is to verbose version of code. Would save 1 byte if the initial state could be last instead. Explanation: ``` ⊞υθFυFΦι⁺κ⟦⟧⊞υκ ``` Collect the list and all of the sublists. ``` W¬⁼θω« ``` Repeat until the current value equals the original value. ``` ≔∨ω×¹θω ``` Actually save a clone of the original value the first time through the loop, so that the above comparison fails to start with and then succeeds when the original value returns. ``` ⟦⭆¹θ⟧ ``` Pretty-print the list, since Charcoal's default list output format doesn't suit ragged lists. ``` FυUMκ§κ⊕μ ``` Rotate the list and all of its sublists. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ṙ1ßI¡€ ÇƬ ``` A monadic Link that accepts a ragged list of numbers and yields the recursivesly rotated states in a list. **[Try it online!](https://tio.run/##AT4Awf9qZWxsef//4bmZMcOfScKh4oKsCsOHxqz/w4fFkuG5mP//WzEsMTAsWzIsMiw0XSw2LFtbNSw2XSw3XSwxXQ "Jelly – Try It Online")** Note that this still works if ragged lists and their sublists may be empty. ### How ``` ṙ1ßI¡€ - Helper Link, one recursive rotation: ragged list of numbers A ṙ1 - rotate A left by one € - for each element: ¡ - repeat... (utilised as an if statement, as described below) I - ...number of times: forward differences given either a number or a list containing up to one number and nothing else we get an empty list which is falsey, so we don't do the "action" given any other list get a non-empty list which is truthy, so we do the "action" once ß - ...action: call this Link (with the element) ÇƬ - Main Link: ragged list of numbers, R Ƭ - start with R and collect inputs up while distinct applying: Ç - call the last Link (our helper) as a monad - f(current) ``` [Answer] # [PARI/GP](https://pari.math.u-bordeaux.fr), 73 bytes ``` a->b=a;until(a==b=t(b),print(b)) t(a)=if(#a',[t(a[i%#a+1])|i<-[1..#a]],a) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=LY5BasMwEEX3PYWwKZXod4jS2AlJlX1WPcBkKOOFiyAIEeRFIIvcIxtDKT1TbxO5zmrm__n_MbffKCf_-RWH7065nz511fpvL9WudbLtQ_JHLc61LunWIJ58GBfzlLQY5ztdygsoC_LPpbxaNhf_XpGdzUphhpgH8CoxHs9aVLVTE6TYh80hFEpUcQgffdoUZqu6TIUiogXeGEvUqDlrCztH9hZYMhoQ1WgYK4Ydr5OiJmen8Nj-L4_2CmtmfvwxDNO8Aw) [Answer] # Javascript, 110 Bytes # Solution ``` j=JSON.stringify f=x=>-x+x?[...x.slice(1),x[0]].map(f):x g=(x,y=[])=>y.includes(j(x))?y+"":g(f(x),[...y,j(x)]) ``` # Explanation ``` j=JSON.stringify f=x=> -x+x // If x is a number, then -x+x is 0 (i.e. // falsey), but if x is an array, then -x+x is // a non-empty string (i.e. truthy) ? [...x.slice(1),x[0]].map(f) // Rotate array and recurse if x is an // array :x // return as is otherwise g=(x,y=[])=> y.includes(j(x)) // Stop when y includes current array ? y+"" // Equivalent to y.join(",") : g(f(x),[...y,j(x)]) // Recurse ``` # Tests ``` // 110 Bytes, solution in g(x) j=JSON.stringify f=x=>-x+x?[...x.slice(1),x[0]].map(f):x g=(x,y=[])=>y.includes(j(x))?y+"":g(f(x),[...y,j(x)]) // Test Cases input1 = [[2,3],4,5,5] input2 = [1,10,[2,2,4],6,[[5,6],7],1] input3 = [[5,6],[6,5]] input4 = [1,[2,3,4,5,6],[7,8]] console.log(g(input1)) console.log(g(input2)) console.log(g(input3)) console.log(g(input4)) ``` [Answer] # [Factor](https://factorcode.org/) + `math.unicode`, 80 bytes ``` [ dup '[ dup . [ dup array? [ 1 rotate ] when ] deep-map dup _ ≠ ] loop drop ] ``` [Try it online!](https://tio.run/##TY1NCsJADIX3nuLtXFms@AO6cClu3IgrKTJMU1psZ8Z0ipbSA3gLz@ZFamwRJCRf8njkJUp7y93puD/s1rgSG8qRcA3H5H3tODMeilnVJUq6VWQ0lQE9PKt/ISZyKJRPg8pk2sb0e7UZjRqECKdoMJOao8VS9gYLYYuVdIi2OyOuHMYDAgzsc7dyhGDrlSdEuKdkBN/ASaFc77vg/XyJmFsrAsuIOq3yvPsA "Factor – Try It Online") The key to this is the `deep-map` combinator which is like `map` except instead of acting on the surface elements of a sequence, it uses a depth-first search algorithm to perform the mapping. We need to check if the element is a list and only perform the rotation if so (since rotating an atom causes an error). [Answer] # Python3, 124 bytes: ``` f=lambda x:x if int==type(x)else(j:=[f(i)for i in x])[1:]+j[:1] g=lambda x,c=0:[x]+([]if(y:=f(x))==(c or x)else g(y,c or x)) ``` [Try it online!](https://tio.run/##fVRdTvMwEHwmp1j1BUcsqGmhrSKZI3ABf9YnF5JilLZRYqH09GX9kzpYKOpLdmd3Znakur2Yz/NpvWu767XmjTruPxQM5QC6Bn0ynJtLW7Ehr5q@Yl8lFzXTeX3uQBMMg8xFUcqHL1EWMjvc9vGdL0sxyAcmpK7ZpeQ1ceScs3egXU8HB3bBUOdXfWzPnQHVm6zni8VCiBWuJT7jC75IeHwF8buDINwXijWupKtd5WdC7TC7IWUmCiyWFl8RjBsUhG8kbiUWgX9ugOg8@GwZCdyi2FheLAJMdlYBi4v2t3RwsjKR8tvJTpTy2qEZNUYye5nf9XWIatJxp9tcXHS2vcWdvN38B2L9hJ5VE7sYgpsgMyKglHYwKEJtw3Mbfj70yAiGXd/3nFP1kWeqHP1Evb/9RPWRZ6oc/aTXpn6i@sgzVY5@0mtTP1F95JkqRz/ptamf@Zyjn/Ta1M98ztFPem3qZz7n6Ce9NvUzn3P0k16b@pnkLOnZyG5vU60bU3Xs7XyqEPqnvm20Yff/Tvd5XmZ3CmEPHI6qZfTkPBFWdar5X32rBkGP0/Y/QvM03vcVvU7MlPzAFCr7lu0RTHb9AQ) [Answer] # [Python 3](https://docs.python.org/3/), 81 bytes *Your OP's reference implementation* ``` f=lambda L,*t:t*(L in t)or f(g(L),*t,L) g=lambda L:L*-1*-1or[*map(g,L[1:]+L[:1])] ``` [Try it online!](https://tio.run/##fVDLboMwELzzFVZONt1EgTyFRL@AP7B8oEpILRFAYFXK19P1g9q1IoADu7M7MzvDS3333WGem7Ktn1@3mlSQqkKltCKyI4r1I2nog1YM21Cx5PE3V1TpNsOvH3n6rAf6gIpnhfioeJEJJmb5HPpRkek1JQ2ytJoPi92kbrLbjff61sruPlFWJIQQ2ZAWoVEOrqEfCT0piSa//9Qt4MDQSkU3ZPtJNowtY8MoO0UlNFSysuwJqlH9Dz1jM@c5HAQc4QQnoRf/N4Bw8wf8ALkwtansjKsNpjdEkvAMsr3Gc4ThDBzxs4CLgMzSr@HIZsGjJkTwAvyMtAg6GN3kDvOL@t0bOFoJpOx2tOOlrLZreo2FTB9md21tgwobYE7XuZjoNHCBq1hufgNoP66n1fjVh2Am0Ax3KIbtDHJX6/DMhp13PXQCbtf2LWeovvCEyt6P13vvx6svPKGy9xNfG/vx6gtPqOz9xNfGfrz6whMqez/xtbGf9Zy9n/ja2M96zt5PfG3sZz1n7ye@NvaznrP3E18b@wlyTn4B "Python 3 – Try It Online") ]
[Question] [ *(yes, "generating generating" in the title is correct :) )* # Context In middle (?) school we are taught about sequences and, in particular, we are taught about linear sequences where the `n`th term is generated with an expression of the form `an + b`, where `a` and `b` are some coefficients. In this challenge, we will deal with sequences generated by polynomials of arbitrary degree. # Task Given the first `m` terms of a sequence, find the coefficients of the polynomial of ***lowest*** degree that could have generated such a sequence. A polynomial, and thus the generating expression you are looking for, is to be seen as a function \$p(n)\$ that takes `n` as an argument and returns $$a\_0 + a\_1 n + a\_2 n^2 + a\_3 n^3 + \cdots + a\_k n^k$$ where \$k \geq 0\$ and \$a\_i, 0 \leq i \leq k\$ have to be found by you. You will assume that the `m` terms you were given correspond to taking `n = 0`, `n = 1`, ..., `n = m-1` in the generating polynomial above. ## Examples If I am given the sequence `[2, 2, 2]` then I realize this is a constant sequence and can be generated by a polynomial of degree `0`: `p(n) = 2`. If I am given the sequence `[1, 2, 3]` then I realize this cannot come from a constant polynomial but it could come from a linear polynomial `p(n) = n + 1`, so that is what my output should be. Notice how ``` p(0) = 1 p(1) = 2 p(2) = 3 # and NOT p(1) = 1, p(2) = 2, p(3) = 3 ``` # Input Your input will be the first terms of a sequence, which you can take in any reasonable format/data type. A standard list is the most obvious choice. You may assume the input sequence is composed of integers (positive, 0 and negative). # Output The coefficients of the polynomial of ***lowest*** degree that could have generated the input sequence. The output format can be in any sensible way, as long as the coefficients can be retrieved unambiguously from the output. For this, both the value of each coefficient and the degree of each coefficient are important. (e.g. if using a list, `[1, 0, 2]` is different from `[0, 1, 2]`). You can assume the polynomial you are looking for has integer coefficients. # Test cases For these test cases, the input is a list with the first terms; the output is a list of coefficients where (0-based) indices represent the coefficients, so `[1, 2, 3]` represents `1 + 2x + 3x^2`. ``` [-2] -> [-2] [0, 0] -> [0] [2, 2, 2] -> [2] [4, 4] -> [4] [-3, 0] -> [-3, 3] [0, 2, 4, 6] -> [0, 2] [2, 6] -> [2, 4] [3, 7] -> [3, 4] [4, 8, 12, 16] -> [4, 4] [-3, -1, 5, 15, 29] -> [-3, 0, 2] [0, 1, 4, 9] -> [0, 0, 1] [3, 2, 3, 6, 11] -> [3, -2, 1] [3, 4, 13, 30, 55] -> [3, -3, 4] [4, 12, 28, 52, 84] -> [4, 4, 4] [2, 4, 12, 32, 70] -> [2, 1, 0, 1] [3, 6, 21, 54] -> [3, -1, 3, 1] [4, 2, 12, 52, 140] -> [4, -2, -3, 3] [10, 20, 90, 280] -> [10, 0, 0, 10] [-2, 8, 82, 352, 1022, 2368, 4738] -> [-2, 4, -1, 4, 3] [4, 5, 32, 133, 380] -> [4, -2, 0, 2, 1] [1, 0, 71, 646, 2877, 8996, 22675] -> [1, -1, 0, -3, 0, 3] [4, 2, 60, 556, 2540, 8094, 20692] -> [4, -2, -1, 0, -2, 3] [1, 2, -17, 100, 1517, 7966, 28027, 78128, 186265] -> [1, 3, -2, 4, -3, -2, 1] [4, 5, 62, 733, 4160, 15869, 47290, 118997] -> [4, 3, -1, -3, 1, 0, 1] ``` Test cases generated with [this code](https://tio.run/##XVLRboMwDHzPV1h9StYwQanUbVL3IyhCqJgOqQ0sSTtNVb@d2QHK1AdIcr6zz0763/DV2XwYGtedwVW2pqU9950L4BFrHbHWBsEnucuVEDU2cESLrgooDx02Xn0IgBqPDhH2cEI7wZBARhGP3wQXhrZN56CF1nLaI8pJs56ryEznKmYDuJImjTsWEVMDZ2Ux2sv5ufwoWe8j6aXvfmSrWaVijCy8Vn2PtpZXRhyGi7MMDwF9KA@VR88mKSZTDQV9qeHVKD1jycaM/xHajLRMw1bDu5lEBEzxnJCMz8TI3jTkOzMhE49yCyMEt2eXmWzS2I/D6lSSfzI1D4c0OzYfm2azcyChUlv1PNw5gzI04GKZ8FaZx6U83SPhyzjmgT0SadKMl@AVvYN/TE/vRaqxlVLDwmM3C4/76h27aFY3It0h@YRbJN5XavgD) --- This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest submission in bytes, wins! If you liked this challenge, consider upvoting it! If you dislike this challenge, please give me your feedback. Happy golfing! [Answer] # JavaScript (ES7), ~~193 ... 154~~ 145 bytes *Saved 9 bytes thanks to @Bubbler* Returns \$(a\_0,a\_1,...,a\_k)\$ with some possible trailing zeros. ``` v=>v.map((_,i)=>(g=(i,m=v.map((n,y)=>v.map((_,x)=>x==i?n:y**x)))=>+m||m.reduce((s,[v],i)=>v*g(0,m.map(([,...r])=>r).filter(_=>i--))-s,0))(i)/g()) ``` [Try it online!](https://tio.run/##nZXfbpswFMbv@xS@tFND/A8Dm8iu@hQRqlBKMqYQKtKhVOq7Z@fYuKXTqkGiEMDi@/yd3zHOr2qozru@eX6JTt1Tfd0X16HYDHFbPVP6yBtWbOihoA1vi3HwxF/Z5IkL3FyKovlx@va6Wl0Yg/v79u2tjfv66feupvTMt0PpnIbVgQreeumWx3HclzDcs3jfHF/qnj4WmyaKGIvOXDBGG7Y@UMau37d3hGwjVXKy7LNeOxmqBSdioR7VwokVJ/hdokexn9lwYm6Y2ThxpBfndkWDTIe6ITpksLNdXN1Y7li6vSE9zun0ECS9Qa@DHpJnnEjwk3NzOHpBjyQiyUkCBnCo/P8mAeA7A7iQjmG@lCEqAwYoAX4tjMhZNiOGSE08IIPE1oJvksxwCR5TnMhSAdMEzpmZh8O4qU1YEaOLhiMVM2MoB3EKBFAo7IxZ0NexmzrYGMcVw2A50ojZ9SDXj9dEYrPhyPGczXrj0Ef6HmNVfqdAV2CbIR2XSCjErS0MmlRn/zD2m5SDGvllpkNpiWcsNeackWpSmn/vPSTPPYWTNQg9S1OImOd4rWyafBFK@kDCcxKTXLgpuCWIDomBy0zkOC5srr5wC8hHR/W5TItLCcs0Ep1lktkciSlsiJQQNi3/thvXAoZ7X1nlXbzv@odq95NWpNiQXXc6d8c6PnYHuqcV/D1d/wA "JavaScript (Node.js) – Try It Online") (removed the penultimate test case, which requires more precision than IEEE-754 provides) ### How? We use [Cramer's rule](https://en.wikipedia.org/wiki/Cramer%27s_rule) to solve a system of linear equations based on a square [Vandermonde matrix](https://en.wikipedia.org/wiki/Vandermonde_matrix): 1. Given an input vector of length \$n\$, we build a Vandermonde matrix \$V\_n\$ of size \$n\times n\$ with coefficients \$\alpha\_i=i,0\le i <n\$: $$Vn=\begin{pmatrix} 1&0&0&...&0\\ 1&1&1&...&1\\ 1&2&4&...&2^{n-1}\\ \vdots&\vdots&\vdots&\ddots&\vdots\\ 1&n-1&(n-1)^2&...&(n-1)^{n-1} \end{pmatrix}$$ 2. Using Cramer's rule, the coefficient \$a\_i\$ of the polynomial is computed by taking the determinant of the matrix obtained by replacing the \$i\$-th column of \$V\_n\$ with the input vector, and dividing by the determinant of \$V\_n\$. ### Example for \$(4,2,12,52,140)\$ The constant coefficient \$a\_0\$ is given by: $$a\_0=\begin{vmatrix} \color{blue}4&0&0&0&0\\ \color{blue}2&1&1&1&1\\ \color{blue}{12}&2&4&8&16\\ \color{blue}{52}&3&9&27&81\\ \color{blue}{140}&4&16&64&256 \end{vmatrix}/|V\_5|=\frac{1152}{288}=4$$ The coefficient \$a\_1\$ is given by: $$a\_1=\begin{vmatrix} 1&\color{blue}4&0&0&0\\ 1&\color{blue}2&1&1&1\\ 1&\color{blue}{12}&4&8&16\\ 1&\color{blue}{52}&9&27&81\\ 1&\color{blue}{140}&16&64&256 \end{vmatrix}/|V\_5|=\frac{-576}{288}=-2$$ And so on. [Answer] # [R](https://www.r-project.org/), ~~55~~ 52 bytes -3 bytes thanks to Giuseppe. ``` round(solve(outer(n<-seq(a=u<-scan())-1,n,"^"))%*%u) ``` [Try it online!](https://tio.run/##DchBCoAgEADAryxCsBsKJioJ9ZVAylsoadv3zdswtfdaOF/Yyv0lLPyminlTLT0Ydx44Y0YitcgsxSGIpnli6hYMeA3OeTDOalh1GKV9MP0H "R – Try It Online") Outputs \$(a\_0, a\_1,\ldots,)\$ with possible trailing zeros. Let \$u\$ be the output sequence, and \$X\$ be the \$m\times m\$ matrix such that \$X\_{i,j}=i^j\$ (0-indexed), i.e. \$ X=\begin{pmatrix} 1&0&0&\ldots&0\\ 1&1&1&\ldots&1\\ 1&2&4&\ldots&2^{m-1}\\ 1&3&9&\ldots&3^{m-1}\\ \vdots&\vdots&\vdots&\ddots&\vdots\\ 1&m-1&(m-1)^2&\ldots&(m-1)^{m-1} \end{pmatrix}. \$ Then in matrix notation, \$u=Xa\$, hence \$a=X^{-1}u\$. The code implements this: `n` is the vector `(0, 1, ..., m-1)` where `m` is the length of `u`; this is used to construct `X = outer(n, n, "^")`. The function `solve` performs matrix inversion, and the `round` is there to avoid numerical errors. [Answer] # APL+WIN, 16 bytes Index origin = 0 Prompts for input as a vector and outputs coefficients from a0 to an-1 where n is the length of the vector. The order of the polynomial can be obtained by summing the number of coefficients up to the last none zero coefficient: ``` 0⍕n⌹m∘.*m←⍳⍴n←,⎕ ``` [Try it online! Courtesy of Dyalog Classic](https://tio.run/##LU9LTgMxDN3PKbxGFNlO4iRHQAJxhqpoENK0IHXVC0AXFLGpxC26gA3bHiUXGV6saiTPi/0@9vJ1WjzultPL02I1Lbfb59XcPo/3d@3tKwxAtw9APLT9@zhzOxw37eNv3fbfN1drDNrhpx1@N0DX4M5gzeNwPukwDkyMqoQP/0hx6JPgXUY3kvm810DZOYVESezCPJ@EEkkira4RaKqzlQIZifgjkgQKTCm5Bxy0UFIq0f29E5QyO9tI4Rqdqn0EpsQ@E2zFVFEL@wawoAJtZ7DCNlihmENxceqmEhDtdCGmLGQRASVnKrUCqeV0ibK@IVopMhWuaLFVdaX2UzNCcGMCyNW6CytgEVwjxdTSJdZwC2KjWKcXq9hJsbYIMvM/ "APL (Dyalog Classic) – Try It Online") [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~50~~ ~~49~~ 37 bytes Returns a polynomial. Mathematica is so awesome `x+1` can be used as a variable in this context. `Apart` is a weird built-in that, quoting from the docs, seems to attempt to rewrite an expression as a sum of terms with minimal denominators, and also happens to expand polynomials (that are returned in a weird collapsed form by default) into something more sane. ``` Apart@InterpolatingPolynomial[#,x+1]& ``` [Try it online!](https://tio.run/##PYwxC8IwFIR3f0VAcPEJfWn7kgxCXQpu3WuHIEUDaVJCBkX622Pi4HLcd8fdouNzXnQ0d5368y1dVh1id3VxDqu3OXePwdu384vRdtzD64jTIQ3BuNj14weBcWAnFMCwqrK0xQpFlAtZ8QISucyNJE7tNu3@2wZYC4zyXtQ1sAbpdyBJZRBcFUKplNim9AU "Wolfram Language (Mathematica) – Try It Online") # [Sledgehammer](https://github.com/tkwa/Sledgehammer), 8 bytes (it will try to deceive you into thinking it's actually 7.5, but it's actually not) ``` ⣕⢤⣏⠛⡪⣊⠵⢼ ``` Explanation: It's `Apart@InterpolatingPolynomial[Input[], x+1]`, but compressed via an awesome Mathematica compressor (it is so awesome that, as far as I understand, it translates Mathematica to an intermediate stack-based language). Unfortunately, running this is fairly painful. [Answer] # [J](http://jsoftware.com/), 10 bytes ``` %.^/~@i.@# ``` [Try it online!](https://tio.run/##y/qvpKegnqZga6WgrqNgoGAFxLp6Cs5BPm7/VfXi9OscMvUclP9r/k9TMKhQMKxQMKrgSlPQiQdTRhUQBGSaVCiYViiYAbnmxsYVCiaGZiDlphZmlkCOuZEliGdoYWlpXgEA "J – Try It Online") Obligatory J answer on a matrix-related challenge. Takes input as a vector of extended integers (otherwise the answer may have small floating-point errors), and gives the polynomial's coefficients in lowest-first order, possibly with some extra zeroes at the end. ### How it works ``` %.^/~@i.@# NB. Input: a vector V of extended integers. # NB. Length of V i.@ NB. Generate 0..(len(V)-1) ^/~@ NB. Self outer product by ^(exponentiation) %. NB. Matrix-divide V by the matrix above, NB. i.e. solve a linear system of equations ``` [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 38 bytes ``` a->Vecrev(polinterpolate([0..#a-1],a)) ``` [Try it online!](https://tio.run/##RVDRasMwDPwV072kYBdLsWX7Yf2MvZQ8mJGOQllDKIN9fXZyPApxTj6dTpKXut7c17JdzbvZqjt/zJ/r/DMsj/vt@zmvwPqch4s/nd6qo8nW43Gry3L/HapxZ7OskCE86OVgrgPy1lwujieAt8YrsjX6aRisCYpu7DnfcqClKxsim7o8W0OgSf7LHFkTQeBw6RbULEovhRx/AU2dQZIAI6QxdmN1ZbhHYA69e@dHnOR7MYxYe4ZeyLtG6yg0EekWOEUxN8pxGz2rWVN61n6jgAxpzN0r7r1o1On2SrSCTQJI0NY5JfiUojFLiq8ppK2jfAwIsy/KeyncfVhfK2lzfaOoYSrSTD3rJZO@AGVhia@JRLfXiQJJK8xSdGrW/YgwS5qm4/YH "Pari/GP – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/) + Numpy, 69 bytes ``` lambda x:polyfit(range(len(x)),x,len(x)-1).round() from numpy import* ``` [Try it online!](https://tio.run/##VVLRbqMwEHxuvsJvgRNEtjHGVOr9SNuH3MXpIRGDgFSJon57uuMlcJXirL2e3Znx0l@nf10o7seXt3u7P/057MXlue/a67GZkmEfPnzS@pBc0jS7ZLzLVbobunM4JOnmOHQnEc6n/iqaU98N0687RzFex83kx2kUL9jvxunQhN3g97GsG0TbBC@aICJoN/YtEW7fwjZ93jw1oT9PmejOE0VqAOwDIvLfYptunvqhCVNy3N4i@Avp2zHxn/s2iZk0/cqEv/T@7@QP4tY2Ixnyn34Y/YFh3D4l4Da9v@b6HT0QN68yE5KPkk46E/hxAtcmE4ZPhk55saCxLbieKghm5y4oj43mBG4pQfCKEwUnqMRlQtG1mpGGL9A5V5ko6YaWrlfCuTkFFTnrhRMpZqGG9G/prBa@XC/XVKUgnQrKcgWsoqBIk7KSojOrMgawV2AKWpVcPKr/NRC7hgOzEqgoSzGH5hagUEYuHJD5eFcFr7RqRDdjFDsFEaYFPCl1UBN7SQ3xhaWkqQr3GHPUnPOTFaygZAOqAJ37KYFHCqlsqqJgDTy5qiK6usZe22p@P8XNJYuXCwe@gfjMgJeGtk7WyEtb65@m53I9e4@1uapgCWZLbKvaRg1S4@AUhqSc1XaVMY/asJLH1Nmuxbxg1ygbezpb45k0XlgpclUtmuaBocljrt8 "Python 3 – Try It Online") May have leading zeros. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~68~~ 62 bytes ``` ≔⟦¹⟧ηFLθ«⊞υ⁰≔÷⁻§θιΣEυ×κXιλ∨ΠEι⊕κ¹ζUMυ⁺κ×ζ§ηλ⊞η⁰≔Eη⁻§η⊖λ×κιη»Iυ ``` [Try it online!](https://tio.run/##VVBbS8MwGH1ef0Uev0CETQUf@lQ2hILFwnwrfahtXD6ai8tljom/vSa1Kgskge@cnEt60dnedHKaCufwoKHZtIwImmdvxhJ44vrgBRwpJZ/Zqg5OQGBkHeHVwi@13@EJBw4V6uCg8KUe@BmOjCBlZB8UVN17evWCijsYGanNB7eAjEiaFiPPFmprhtD7mRuRUveWK649H2CcOZt0XJJxpGyNUp0ekmotwyz6o35h5DeAWPTzJbe4zp2M4ug6dBzs@L@zTJ5/sXHOkb7mK6stag/bznl4ROljnRil6s6oYt/i1RkZPIe9xJ4nZJyL0nyamuaWkftYJ153cT@s23a6Oclv "Charcoal – Try It Online") Link is to verbose version of previous version of code that excludes trailing zeros, but apparently it isn't necessary to do that, thus saving 6 bytes. Outputs the terms in power order i.e. the constant term is printed first. Explanation: ``` ≔⟦¹⟧η ``` Start by creating a helper polynomial \$ h(x) = 1 \$. ``` FLθ« ``` Loop over the \$ m \$ terms. ``` ⊞υ⁰ ``` Add a \$ 0x^i \$ term to the result polynomial \$ u(x) \$. ``` ≔÷⁻§θιΣEυ×κXιλ∨ΠEι⊕κ¹ζ ``` Subtract the value of \$ u(i) \$ from the input term and divide that by \$ i! \$. ``` UMυ⁺κ×ζ§ηλ ``` Multiply \$ h \$ by that value and add the result to \$ u \$. This doesn't change the values of \$ u(0) ... u(i-1) \$ but the value of \$ u(i) \$ is now the input term. ``` ⊞η⁰≔Eη⁻§η⊖λ×κιη ``` Multiply \$ h \$ by \$ x - i \$. ``` »Iυ ``` Print the coefficients of \$ u \$, which may include trailing zeros. [Answer] # [Haskell](https://www.haskell.org/), 77 bytes ``` h%(a:t)=h-a:a%t h%_=[h] f(h:t)=h:foldr(%)[](f$zipWith((/).(-h+))t[1..]) f e=e ``` [Try it online!](https://tio.run/##TVJNb5wwEL3zK@aQlaDBFBt/sQq595BzDxStnC0sq7AELVYVRf3toTNeR6mEmeHNe2/GNqNbX/pp2rZxl7q9z5qRub3b@WTcHZp27JIhHQO8H16n39d0l7VdOty9n5efZz@m6fesSNl4n2W@5UXRZckAfdNv/R83HZyHt@Ym@@XgmT26@@dvb1mZYHGFBRpoP3npcH29/Jh9f7q6CeYMlr8zPDBoy6KY@vnkR1i6Lkl8v/rD0a39SuqWiS5HTg4lRZEDPZTKHCRFVsVaGWoI68gMEasm0m0OHGGuP2WM56AQwCXqaMGDRR2lSMe3RphHBIscQ4VUpaIxuQp0VxitjN0jXuEyZRSjkaCeMgrFjUM6LgOJ0y5w1RRtgJgIo1syC8xSUL9KIyhNZaOXuvXiFU13U2IrtDEYtKTW1hj0qWvKhTbqawodtkO4kpjasia81LWIPoJOy1BzOiNFqal1MC0FfVhOJ8CtFlp9TaRp9zSR5DoIra5pakH74xxnMXTnF3ee8bYvbnmC5XqePdzRBwzw39@wfRyHyZ3WjR2X5R8 "Haskell – Try It Online") [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 10 bytesSBCS ``` ⊢⌹∘.*⍨∘⍳∘≢ ``` [Try it online!](https://tio.run/##JYy9CsJQDEZ3nyKzqNzktvdndrGTYH2BgtSloKuzULTYooPg3Mmtg5NrHyUvck3t8n0n4STZsZjvTllx2Adunsmay7sKXLV8@/LltZhy/Zbm@jPktQ25CFw3o1ud@05z@ZAp3Swlt6skDTlEEIMhsFpDhEYBxs54iCx5YXTe28koaQIUSTv1XzhAWRjhGUkQDInSfYcWUA2fBKw3BsgpEnRIcuUMmfgH "APL (Dyalog Unicode) – Try It Online") A port of [Graham's APL+WIN solution](https://codegolf.stackexchange.com/a/202828/78410) into a modern APL, which happens to work exactly the same (and have the same byte count) as [my own J solution](https://codegolf.stackexchange.com/a/202838/78410). ### How it works ``` ⊢⌹∘.*⍨∘⍳∘≢ ⍝ Input: V, result of a polynomial evaluated at 0..m-1 ⍳∘≢ ⍝ Generate 0..m-1 ∘.*⍨∘ ⍝ Self outer product by * (exponentiation) ⊢⌹ ⍝ Matrix divide V by above (solve linear system of equations) ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~48~~ 47 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` g≠iā<DδmUεXøINǝ}Xšεā<sUœε©2.ÆíÆ.±Xε®Nèè}«P}O}ć÷ ``` Sometimes 05AB1E's lack of almost all matrix builtins is pretty annoying.. ;) Inspired by [@Arnauld's JavaScript answer](https://codegolf.stackexchange.com/a/202829/52210). [Try it online](https://tio.run/##yy9OTMpM/f8//VHngswjjTYu57bkhp7bGnF4h6ff8bm1EUcXntsKFC4OPTr53NZDK430DrcdXnu4Te/Qxgggf53f4RWHV9QeWh1Q6197pP3w9v//o010jHQMjXRMgaSJQex/Xd28fN2cxKpKAA) or [verify almost all test cases](https://tio.run/##NY69SkNBEIVfJaQ@G3Zn/0FIYx1tIpGQQkEkoKYICBFuYROxE60F7SKiIBi0zibY3YfIi1zn3lUWdnbOfufMTKZHx@OT6nLWbbe28/tWuztLdwfV6fb2aby@3tktP8/75XKQvg97P4/FYPNcLlme9jcP5XL1Qp00T29p3ll9DLh/76VFWhSr1/1ir1jfpK@qQDUcChqhNZSQdSHwqR8Gpi5CZ12ybuAy0hQNn7kARVDujxYKFsqCYrYptsXMEzQclMqdgdLQEtbmGA6hAEsIJk9pJE3wMhsciLNNpqn@ZFiZ5lfxfhKR79D0gmMQ2F4jkjhauwDjdch2WwcrzQtkXkHCKzjDQ4L3CDHyi5y3/@NcvSlr1kgEGVmSLtJoVAlxMRFnR1ezXw) (removed the last two largest ones, since they time out on TIO). **Explanation:** First handle the edge case of a single-element input-list (would cause issues with the `«` later on in the code): ``` g # Get the length of the (implicit) input-list ≠i # And if it is NOT 1, continue with: # ... (see below) # (implicit else:) # (output the implicit input-list as implicit output) ``` Next we'll get the exponentiation matrix of the list `[0, input-length)`: ``` ā # Push a list in the range [1, (implicit) input-length] (without popping) < # Decrease each value by 1 to make the range [0, input-length) Dδ # Apply double-vectorized on itself by first duplicating: m # Take the power of the two values U # Pop and store this exponentiation matrix in variable `X` ``` Next we'll create a list of this matrix, with every column one by one replaced with the input-list: ``` ε } # Map over the input-list that was still on the stack X # Push the exponentiation matrix from variable `X` ø # Zip/transpose it; swapping rows/columns ǝ # Replace the transposed row of the exponentiation matrix N # at the current map-index I # with the input-list ``` We'll prepend the original exponentiation matrix to this list: ``` Xš # Prepend the matrix `X` in front of this list ``` And we'll [calculate the determinant of each inner matrix](https://codegolf.stackexchange.com/a/202866/52210) in this list: ``` ε } # Map over the list of matrices: ā # Push a list in the range [1, matrix-length] (without popping) < # Decrease it by 1 to make the range [0, matrix-length) sU # Swap to get the matrix again, and pop and store it in variable `X` œ # Get all permutations of the [0, matrix-length) list ε # Inner map over each permutation: © # Store the current permutation in variable `®` (without popping) 2.Æ # Get all 2-element combinations of this permutation í # Reverse each inner pair Æ # Reduce it by subtracting .± # And get it's signum (-1 if a<0; 0 if a==0; 1 if a>0) X # Push the matrix from variable `X` ε # Map over each of its rows: ® # Push the current permutation of variable `®` Nè # Get the value in the permutation at the current map-index è # And use that to index into the current matrix-row }« # After the map of rows: merge it together with the signum list P # And take the product of this entire list }O # After the map of permutations: sum all values ``` Now that we have all determinants of the matrices, we get the default one again to divide all others by it: ``` ć # Extract head: pop and push remainder-list and first item separated ÷ # Integer-divide each value in the remainder-list by this head # (after which the result is output implicitly) ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 12 bytes ``` n:qGyz3$ZQYo ``` The result is given with higher-order coefficients first, and may contain leading zeros. [Try it online!](https://tio.run/##y00syfn/P8@q0L2yylglKjAy////aF1jHQVdQx0FUx0FQyA2sowFAA) Or [verify all test cases](https://tio.run/##PVC7TgQxDOz5ihSUWSl2EsehPokaiYY7nQQ9DyFRwP38MhOfTtqsnbFnPM7H28/7/rp/Pnw//l3q/fHp5Ws/HH@f99Om57tTyakgaE78kLWcGsJWo1BWAaBFFwNKIzo9JwEodmVsklPHHUdnsGWxZ9DQi78BlQBQEoSKxt5Dk4IK4Y7oLaZe4YozSjAhopzWgqXRQZI0tgid40xGJ7LpMuwUWn1FOaoawDaqh1CPMVJpa/EwBRoDwRqn@hhQmZO52ug3A7a2INwbUi@TeLGpoaJ8oMHBfJfOdExbkkV5ceHi4qbWb26MS9NNE1s8t0nDys1EYGSc/wE) ### Explanation Consider input `[-3, -1, 5, 15, 29]` as an example. ``` n:q % Implicit input. Number of elements. Range. Subtract 1, element-wise % STACK: [0, 1, 2, 3, 4] G % Push input again % STACK: [0, 1, 2, 3, 4], [-3, -1, 5, 15, 29] yz % Duplicate from below. Number of non-zero elements % STACK: [0, 1, 2, 3, 4], [-3, -1, 5, 15, 29], 4 3$ZQ % Fit polynomial with inputs x, y, degree % STACK: [3.7536e-16, -3.1637e-15, 2.0000, -8.8363e-15, -3] Yo % Round, element-wise. Implicit display % STACK: [0, 0, 2, 0, -3] ``` [Answer] # [SageMath](http://www.sagemath.org/), ~~63~~ 48 bytes ``` lambda v:QQ[x].lagrange_polynomial(enumerate(v)) ``` [Try it online!](https://sagecell.sagemath.org/?z=eJxdUNtqwzAMfe9XGPaSQDMsX2R7sI_ocwnDY2kpJGkJXdn-fkd2Ry9gLOlIOjrSTr2rMU-fX1ld3jab7U__Oub9kuf98HE6jr_zcTrksRnm72lY8nloLm27Wp2Ww3xuds22M2sV8WCsx0fa4DeWAbpgY9-26kWVMrdWHRVj-xsBQg9EWq2FE_W1RcqBarAhd9dBBQww7BjZGAIEpCS-4eCv_VTHobSzxTxNBSsD9V76vIMbdRJcczKPGv55zCMJFZKOgqyNPHlxQ-KiShsJIhlcgiIbvhNmK5mr2rqnBetJGGiQkzjiQh45yU1NkoiwcLiptFWksFWt1P8BFfhozA==&lang=sage&interacts=eJyLjgUAARUAuQ==) Outputs the polynomial as $$a\_k n^k + \cdots + a\_3 n^3 + a\_2 n^2 + a\_1 n + a\_0 $$ [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 14 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` J’*þ`æ*-⁸æ×ær0 ``` A monadic Link accepting a list of integers which yields a list of the exponents (floats and/or integers) with the lowest degree on the left of the same length as the input (with trailing zeros if need be). **[Try it online!](https://tio.run/##y0rNyan8/9/rUcNMrcP7Eg4v09J91Ljj8LLD0w8vKzL4//9/tKGOgoGOgjmQMjMx01EwsjA311GwsLQEsY3MzE1jAQ "Jelly – Try It Online")** ### How? ``` J’*þ`æ*-⁸æ×ær0 - Link: list of integers, V J - range of length (V) ’ - decrement (vectorises) ` - use as both arguments of: þ - outer-product using: * - exponentiation - - minus one æ* - matrix-exponentiation (i.e. inverse) ⁸ - chain's left argument, V æ× - matrix-multiplication ær0 - round to zero decimal places (vectorises) ``` ]
[Question] [ Taking some output from xxd and turning it into usable shellcode by hand is no fun, so your job is to automate the process. **Rules** Your submission can be a function, lambda, script, or any reasonable equivalent of those. You may print the result, or if your submission is a function/lambda then you may also return it. You program must take three arguments, the first being a string containing the output of xxd, ran with no arguments other than a filename, like this: `xxd some_file`. Here's an example of what the the first argument will look like: ``` 00000000: 31c0 b046 31db 31c9 cd80 eb16 5b31 c088 1..F1.1.....[1.. 00000010: 4307 895b 0889 430c b00b 8d4b 088d 530c C..[..C....K..S. 00000020: cd80 e8e5 ffff ff2f 6269 6e2f 7368 4e58 ......./bin/shNX 00000030: 5858 5859 5959 59 XXXYYYY ``` Your need to take that middle section containing the bytes (the first 8 columns after the `:`) and turn it into shellcode by removing any whitespace, then putting a `\x` before each byte. Here's what the output should be for the input above (ignoring any other arguments): `\x31\xc0\xb0\x46\x31\xdb\x31\xc9\xcd\x80\xeb\x16\x5b\x31\xc0\x88\x43\x07\x89\x5b\x08\x89\x43\x0c\xb0\x0b\x8d\x4b\x08\x8d\x53\x0c\xcd\x80\xe8\xe5\xff\xff\xff\x2f\x62\x69\x6e\x2f\x73\x68\x4e\x58\x58\x58\x58\x59\x59\x59\x59` You can assume the first argument will always be a valid xxd output, ran with no arguments other than the filename. Your output should also be a string where the backslashes are literal backslashes, not used as escape characters. So when I say "\x65", I'm not talking about the byte 0x65, or even the letter "A". In code, it would be the string "\x65". The second argument specifies where in the xxd output the shellcode should start, and the third specifies where it should end. If the third argument is `-1`, it will end at the end of xxd output. The second and third argument will also always be non negative, except for when the third is `-1` Here are some test cases: Argument 1: ``` 00000000: 31c0 b046 31db 31c9 cd80 eb16 5b31 c088 1..F1.1.....[1.. 00000010: 4307 895b 0889 430c b00b 8d4b 088d 530c C..[..C....K..S. 00000020: cd80 e8e5 ffff ff2f 6269 6e2f 7368 4e58 ......./bin/shNX 00000030: 5858 5859 5959 59 XXXYYYY ``` Argument 2: `7`, Argument 3: `e` (these are both strings representing hexadecimal numbers) Output: `\xc9\xcd\x80\xeb\x16\x5b\x31\xc0` Argument 1: ``` 00000000: 31c0 b046 31db 31c9 cd80 eb16 5b31 c088 1..F1.1.....[1.. 00000010: 4307 895b 0889 430c b00b 8d4b 088d 530c C..[..C....K..S. 00000020: cd80 e8e5 ffff ff2f 6269 6e2f 7368 4e58 ......./bin/shNX 00000030: 5858 5859 5959 59 XXXYYYY ``` Argument 2: `0`, Argument 3: `2e` Output: `\x31\xc0\xb0\x46\x31\xdb\x31\xc9\xcd\x80\xeb\x16\x5b\x31\xc0\x88\x43\x07\x89\x5b\x08\x89\x43\x0c\xb0\x0b\x8d\x4b\x08\x8d\x53\x0c\xcd\x80\xe8\xe5\xff\xff\xff\x2f\x62\x69\x6e\x2f\x73\x68\x4e` Argument 1: ``` 00000000: 31c0 b046 31db 31c9 cd80 eb16 5b31 c088 1..F1.1.....[1.. 00000010: 4307 895b 0889 430c b00b 8d4b 088d 530c C..[..C....K..S. 00000020: cd80 e8e5 ffff ff2f 6269 6e2f 7368 4e58 ......./bin/shNX 00000030: 5858 5859 5959 59 XXXYYYY ``` Argument 2: `a`, Argument 3: `-1` Output: `\xeb\x16\x5b\x31\xc0\x88\x43\x07\x89\x5b\x08\x89\x43\x0c\xb0\x0b\x8d\x4b\x08\x8d\x53\x0c\xcd\x80\xe8\xe5\xff\xff\xff\x2f\x62\x69\x6e\x2f\x73\x68\x4e\x58\x58\x58\x58\x59\x59\x59\x59` The code with the least bytes wins. The winner will be announced in seven days, on August 15, 2016 (but submissions after then are still appreciated). **Update** Congrats to [@Adnan](https://codegolf.stackexchange.com/users/34388/adnan) to winning the challenge! [Answer] # Bash + coreutils + xxd, ~~73~~ ~~71~~ 69 bytes ``` printf \\x%s `xxd -r|xxd -p -s0x$1 -l$[(e=1+0x$2)?e-0x$1:-1]|fold -2` ``` Expects the hexdump on STDIN and start/end as command-line arguments. This prints some warnings to STDERR, which is allowed by default. [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), ~~39~~ 38 bytes Input in the form: ``` arg2 arg3 arg1 ``` Code: ``` ²\|vy9F¦}40£ðK}J2ô„\xì²H>²®Qi²}£¹HF¦}J ``` Explanation: ``` ²\ # Get the first two inputs and discard them. | # Take the rest of the input as an array. vy } # For each line... 9F¦} # Ten times, remove the first character. 40£ # Only remain the substring [0:40]. ðK # Remove spaces. J # Join the string. 2ô # Split into pieces of 2. „\xì # Prepend a "\x" at each string. ²H # Convert the second line from hex to int. > # Increment by one. ² # Push the second input again. ®Qi } # If equal to -1... ² # Push the second input again. £ # Take the substring [0:(² + 1)]. ¹H # Convert the first input from hex to int. F¦} # Remove that many characters at the beginning. J # Join the array and implicitly output. ``` Uses the **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=wrJcfHZ5OUbCpn00MMKjw7BLfUoyw7TigJ5ceMOswrJIPsKywq5RacKyfcKjwrlIRsKmfUo&input=YQotMQowMDAwMDAwMDogMzFjMCBiMDQ2IDMxZGIgMzFjOSBjZDgwIGViMTYgNWIzMSBjMDg4ICAxLi5GMS4xLi4uLi5bMS4uCjAwMDAwMDEwOiA0MzA3IDg5NWIgMDg4OSA0MzBjIGIwMGIgOGQ0YiAwODhkIDUzMGMgIEMuLlsuLkMuLi4uSy4uUy4KMDAwMDAwMjA6IGNkODAgZThlNSBmZmZmIGZmMmYgNjI2OSA2ZTJmIDczNjggNGU1OCAgLi4uLi4uLi9iaW4vc2hOWAowMDAwMDAzMDogNTg1OCA1ODU5IDU5NTkgNTkgICAgICAgICAgICAgICAgICAgICAgICBYWFhZWVlZ). [Answer] ## JavaScript, 84 bytes ``` (s,f,t,u)=>s.replace(/.*:| .*\n?| /g,'').replace(/../g,'\\x$&').slice(f*4,++t*4||u) ``` Explanation: Removes all the unwanted parts of the dump, prepends `\x` to each hex pair, then extracts the desired portion of the result. `||u` is used to convert the zero obtained by incrementing the `-1` parameter into `undefined` which is a magic value that causes `slice` to slice to the end of the string. 101 bytes if `f` and `t` are strings of hex digits: ``` (s,f,t,u)=>s.replace(/.*:| .*\n?| /g,``).replace(/../g,`\\x$&`).slice(`0x${f}`*4,t<0?u:`0x${t}`*4+4) ``` [Answer] # Ruby: ~~90~~ ~~89~~ ~~87~~ ~~79~~ 63 bytes -2 bytes thanks to @addison -8 bytes thanks to @PiersMainwaring ``` ->s,x,y{'\x'+s.scan(/(?<=.{9})\w\w(?=.* )/)[x.hex..y.hex]*'\x'} ``` See the tests on repl.it: <https://repl.it/Cknc/5> [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~48~~ 44 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ØhiЀɠ’ḅ¥®L’¤Ạ?⁴‘ ṣ⁷ṫ€⁵ḣ€40Fḟ⁶s©2ḣ¢ṫ¢[“\x”]p ``` This expects the hexdump as sole command-line argument, and the end and start points on STDIN, in that order, separated by a linefeed. [Try it online!](http://jelly.tryitonline.net/#code=w5hoacOQ4oKsyaDigJnhuIXCpcKuTOKAmcKk4bqgP-KBtOKAmArhuaPigbfhuavigqzigbXhuKPigqw0MEbhuJ_igbZzwqky4bijwqLhuavColvigJxceOKAnV1w&input=LTEKYQ&args=MDAwMDAwMDA6IDMxYzAgYjA0NiAzMWRiIDMxYzkgY2Q4MCBlYjE2IDViMzEgYzA4OCAgMS4uRjEuMS4uLi4uWzEuLgowMDAwMDAxMDogNDMwNyA4OTViIDA4ODkgNDMwYyBiMDBiIDhkNGIgMDg4ZCA1MzBjICBDLi5bLi5DLi4uLksuLlMuCjAwMDAwMDIwOiBjZDgwIGU4ZTUgZmZmZiBmZjJmIDYyNjkgNmUyZiA3MzY4IDRlNTggIC4uLi4uLi4vYmluL3NoTlgKMDAwMDAwMzA6IDU4NTggNTg1OSA1OTU5IDU5ICAgICAgICAgICAgICAgICAgICAgICAgWFhYWVlZWQ) [Answer] ## PowerShell v2+, ~~175~~ ~~157~~ ~~142~~ ~~133~~ 129 bytes ``` param($a,$b,$c)'\x'+(($z=$a-split"`n"|%{$_[10..48]-ne32-join''-split'(..)'-ne''})["0x$b"..(("0x$c",$z.count)[$c-eq-1])]-join'\x') ``` Takes input `$a`, `$b`, `$c`, with `$a` as either a literal newline-separated string, or with the PowerShell ``n` character separating the lines. We set helper string `$z` as the heavily processed `$a` as follows -- First we `-split` on newlines, then, for each line `|%{...}`, we slice the middle section `[10..48]`, use the `-ne32` to remove spaces, `-join` it back together into one long string, `-split` it on every two characters (keeping the two characters), and `-ne''` to remove the empty elements. This results in an array of two-element strings, like `('31','c0','b0'...)`. We then slice into that array based on `$b` cast with the hexadecimal operator up to the value of `$c`. We need to use a pseudo-ternary here that accounts for whether `$c` is `-1` or not. If it is, we choose the `.count` (i.e., the end element) of `$z`. Otherwise, we just prepend the `0x` hexadecimal operator with `$c` in a string. Note that this is zero-indexed. That array slice has its elements `-join`ed together with a literal `\x` to form one string. That's prepended with another literal `\x` and the result is left on the pipeline. Printing is implicit. ### Example ``` PS C:\Tools\Scripts\golfing> .\xxd-output.ps1 "00000000: 31c0 b046 31db 31c9 cd80 eb16 5b31 c088 1..F1.1.....[1.. 00000010: 4307 895b 0889 430c b00b 8d4b 088d 530c C..[..C....K..S. 00000020: cd80 e8e5 ffff ff2f 6269 6e2f 7368 4e58 ......./bin/shNX 00000030: 5858 5859 5959 59 XXXYYYY" a -1 \xeb\x16\x5b\x31\xc0\x88\x43\x07\x89\x5b\x08\x89\x43\x0c\xb0\x0b\x8d\x4b\x08\x8d\x53\x0c\xcd\x80\xe8\xe5\xff\xff\xff\x2f\x62\x69\x6e\x2f\x73\x68\x4e\x58\x58\x58\x58\x59\x59\x59\x59 ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~39~~ ~~38~~ 37 bytes ``` ØhiⱮɠ’ḅ¥ȷ9Ṃ?⁴‘ Ỵṫ€⁵ḣ€40Fḟ⁶s2ṭ€⁾\xḣ¢ṫ¢ ``` [Try it online!](https://tio.run/##dY69TsMwFIX3PMV9AVw7jl2bpUOlLkgsLEGw4MRVW1UsXWBrKvEOZQIVMfEjIRVIhMQQFngM@0XMTVJGznB8f44/e2bn88sQvtaTqX95/rn1y2tXXtX33@/aVauBL7Z@uY7cx9ZVD3716ItXV95hkdCRK2988baIXfXUbj5PL3BXbzBZb0LYY9FZoDvtA2cZBUMTiVVumlZDlisK1jAJwnAGGVUKgBEyYgQddYJH1BEYMhJO@6C0MIBJ3bQZIqkBlSftLAfRzGCIVwkZNogDQo7@GDEyujeVFTBGocVjkLHUIC1WfS4VJFbgP0innpme9xaTw3TH4MgQCgNoGoRuDf5RmqbHqF8 "Jelly – Try It Online") Now beats 05AB1E! (despite the lack of "convert from hexadecimal" builtin) Same input format as [Dennis' solution](https://codegolf.stackexchange.com/a/89204). Use `Ɱ`, which is a new feature (short for `Ѐ`). Without it, this would take 38 bytes. [Answer] ## Perl, 114 bytes ``` ($_,$a,$b)=@ARGV;s/^.*:|\S*$|\s//gm;@_=(m/../g);for(@_){s/^/\\x/}$"='';say substr"@_",4*$a,$b!=-1?4*($a+$b):2<<20; ``` Arguments given on the command line as a quoted string followed by two numbers. The numbers are taken in decimal (I know hex was used in the examples but it wasn't specified in the post) Technically only works on inputs with up to 2^21 bytes since perl's substring method is silly [Answer] ## Python, 140 bytes ``` lambda O,a,b:''.join(sum([['\\x'+x[:2],('','\\x')[len(x)>2]+x[2:]]for x in O.split()if len(x)<5],[])[int(a,16):(int(b,16)+1,None)[b=='-1']]) ``` <https://repl.it/ClB3> Splits the original string and dumps the elements if they're less than five characters, prepends `\x`, and slices by the second and third arguments. 162 byte version if we need to handle other types of output not specified by the question: ``` import re J=''.join def f(x,a,b):r=J(J(re.findall(':(.*?) ',x)).split());print J(['\\x'+i+j for i,j in zip(r,r[1:])][::2][int(a,16):(int(b,16)+1,None)[b=='-1']]) ``` [Answer] # Python 2 and 3 - ~~164 162 150 146 134~~ 150 bytes Now accepts hex strings for second and third arguments. ``` j=''.join def f(a,b,c):s=j(x[10:49].replace(' ','')for x in a.split('\n'));print(j('\\x'+s[i:i+2]for i in range(int(b,16)*2,1+2*int(c,16)%len(s),2)) ``` [Answer] Python 3.5, 125 bytes ``` import re lambda s,b,e:re.sub(r'(\w\w)',r'\\x\1',re.sub(r'^.*?:| .*$|\s','',s,0,8)[2*int(b,16):[2*int(e,16)+2,None][e<'0']]) ``` Ungolfed: ``` def f(s,b,e): b = 2*int(b,16) e = [2*int(e,16)+2,None][e<'0'] x = re.sub(r'''(?v) # verbose (not in golfed version) ^.*?: # match begining of line to the ':' | .*$ # or match ' ' to end of line |\s # or match whitespace ''', '', # replacement s, 0, # replace all matches re.M # multiline mode ) y = re.sub(r'(\w\w)', # match pairs of 'word' characters r'\\x\1', # insert \x x[b:e]) return y ``` ]
[Question] [ ### Objective Given a 2D array of any size, write a program or function to shift alternatively the columns and rows ### Example ``` a b c d e f g h i j k l m n o ``` All elements in the **first** column shift **down** one row, the **second** column shift **up** one row, the **third** shift **down** one row and so on, wrapping when they reach the edge. ``` k g m i o a l c n e f b h d j ``` All elements in the **first** row shift to the **right**, the **second** to to the **left**, the **third** to the **right** etc., wrapping when they reach the edge. ``` o k g m i l c n e a j f b h d ``` I will follow the tradition of selecting the shortest working code as the best answer [Answer] # [MATL](https://github.com/lmendo/MATL), 13 bytes ``` ,!tZy:oEq2&YS ``` [**Try it online!**](https://tio.run/##y00syfn/X0exJKrSKt@10EgtMvj//2j1xKTklFR1a/W09IzMLCCdnZObl68eCwA "MATL – Try It Online") ### Explanation ``` , % Do twice ! % Transpose. Takes input implicitly the first time t % Duplicate Zy % Size. Gives a vector with numbers of rows and of columns : % Range from 1 to the first entry of the vector (number of rows) o % Parity: gives 0 or 1 for eacn entry Eq % Times 2, minus 1: transforms 0 into -1 2 % Push 2 &YS % Circularly shift along the second dimension. This shifts the % first row by 1 (that is, to the right), the second by -1 (to % the left), etc. % End (implicit). Display (implicit) ``` [Answer] # [J](http://jsoftware.com/), 26, 21 19 bytes -5 bytes thanks to miles ``` (|."_1~_1^#\)@|:^:2 ``` ## Explanation: `^:2` - repeate twice the following: `@|:` - transpose and `#\` - find the length ot the prefixes (1, 2, 3 ... rows) `_1^` - raise -1 to the above powers, creating a list of alternating -1 1 -1 1... `|."_1~` - rotate each row of the input array with offset from the above list [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/NWr0lOIN6@IN45RjNB1qrOKsjP5rcilwpSZn5CukKRgrmKqoJyYlp6SmpWdkZmXn5Oblq/8HAA "J – Try It Online") ## Original version: ``` (($_1 1"0)@#|."0 1])@|:^:2 ``` ## How it works `^:2` - repeate twice the following: `|:` - transpose and `|."0 1]` - rotate each row of the input array, offsets in the list: `@#` - the number of rows in the array `($_1 1"0)` - alternate \_1 1 (3 -> \_1 1 \_1) [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/NTRU4g0VDJUMNB2Ua/SUDBQMYzUdaqzirIz@a3IpcKUmZ@QrpCkYK5iqqCcmJaekpqVnZGZl5@Tm5av/BwA "J – Try It Online") [Answer] # [Husk](https://github.com/barbuz/Husk), 7 bytes ``` ‼ozṙİ_T ``` [Try it online!](https://tio.run/##yygtzv7//1HDnvyqhztnHtkQH/L///9opcSk5JRUJR2ltPSMzCwgnZ2Tm5evFAsA "Husk – Try It Online") ## Explanation ``` ‼ozṙİ_T Implicit input: a list of lists. ‼ Do this twice: T Transpose, oz then zip with İ_ the infinite list [-1,1,-1,1,-1,1,.. ṙ using rotation. This rotates the rows in alternating directions. ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 55 bytes ``` Nest[MapIndexed[RotateLeft[#,(-1)^#2]&,Thread@#]&,#,2]& ``` [Try it online!](https://tio.run/##DcixCsIwFAXQXxEConAddBdcBRURt5DCs3k1sSaV5g2FkG@P2Q4nkDgOJL6nmlbHeuMk@kq/c7S8sNWPSUj4woNohc1uv@3UwazxdDOTPalGhRb1PvsoOumcCS/0sOCCPOANB49P84gvAiKmUoypfw "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 83 bytes ``` x=input() exec'x=[l[i%2*2-1:]+l[:i%2*2-1]for i,l in enumerate(zip(*x))];'*2 print x ``` [Try it online!](https://tio.run/##LclBDsIgEIXhfU/Bxgy0uJBlTU9CWNQ6taMUCKEJennMRDdf/peX3mWLwbRWJwrpKFJ1WHGBOllv6WR6c76MbvB2/A@3xixIe0FBYDh2zHNB@aEk@6qUu0JvupQpFFFbsxZm0AJuzMLcGQSnhYWV@8FsDDHP3/Xi9szOBCaCc18 "Python 2 – Try It Online") [Answer] # APL+WIN, 30 bytes Prompts for screen input of a 2d array ``` ((↑⍴m)⍴¯1 1)⌽((1↓⍴m)⍴¯1 1)⊖m←⎕ ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 26 bytes ``` {(¯1 1⍴⍨≢⍵)⌽(¯1 1⍴⍨≢⍉⍵)⊖⍵} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24RqjUPrDRUMH/VuedS74lHnoke9WzUf9ezFEO0ES3RNA1K1QJ0KxgqmINm@qY4A "APL (Dyalog Unicode) – Try It Online") Prefix Dfn. ### How? ``` {(¯1 1⍴⍨≢⍵)⌽(¯1 1⍴⍨≢⍉⍵)⊖⍵}⍝ Main function, prefix. Input matrix is ⍵. ⊖⍵}⍝ Rotate the columns of ⍵ according to the left arg: ( ⍉⍵) ⍝ Transpose ⍵ (makes a 3x5 matrix become 5x3) ≢ ⍝ Tally (yields the number of rows of the matrix) ⍨ ⍝ Swap arguments of the following fn/op ⍴ ⍝ Shape ¯1 1 ⍝ This vector. This yields a vector of ¯1 1 with size = number of columns of ⍵. ⌽ ⍝ Rotate the rows of ⍵ according to the left arg: {(¯1 1⍴⍨≢⍵) ⍝ Does the same as the preceding expression, without transposing ⍵. ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 15 bytes (SBCS) ``` {⍵⌽⍨¯1*⍳≢⍵}∘⍉⍣2 ``` [Try it online!](https://tio.run/##lZK7jtQwFIb7eYpf02yClhGe2VmW7UE0QDMv4JmcIYbEjmxHIUK0K3ZFEBRINDRsQ0eBKGl4FL/IcOwss0CDtohin8v3n4tlU90uelmZp7vdyzB8D29@hOHLz6/iVhi@hfPPbHoVXn8Mw3kYLue7XRg@4fGT1f1TPDQdvEEtnxN601qYTsOT89hIR27CkfHDqiSQdCp6Otnvc3xJNZSLd0eNtNITdFuvyTp0ypdwjdyQg9QFOisbhmzKRLSsrLRTBYHzSDOJBZGpGc2QsTfPD9G0PkrEYMfRMLYgm2BbpWVV9WgsNaSLhJyGs/fh4mw6wwNjQS9k3VR0yAAuUFor@9N9PxDAHFgAR8ByNB0Dd4ET4B7EnWQSAmIOsYA4gljuk11p2qrAmrgl5T1pVCrNQrlrhbGWTLDMgkWWeXbM@JMEz7O/yfmfc9Z41vKUrxrDNG5jGgec1hKn8U8v0X4ztZT2SPJAt63eeGU0Mteua@Ucn9m/5fLf4f9PaSStuABey2/WZJIqHQlvP/D/4CBcXI7HbQRcp109s8mNe/gF "APL (Dyalog Unicode) – Try It Online") [Answer] ## JavaScript (ES6), ~~94~~ 91 bytes ``` a=>(g=a=>a[0].map((_,i)=>(b=a.map(a=>a[i]),i%2?[...b.slice(1),b[0]]:[b.pop(),...b])))(g(a)) ``` There's probably a golfier way to do the rotation... [Answer] # Pyth, 15 bytes ``` L.e.>b^_1k.Tbyy ``` [Try it online](https://pyth.herokuapp.com/?code=L.e.%3Eb%5E_1k.Tbyy&input=%5B%5B%27a%27%2C%20%27b%27%2C%20%27c%27%2C%20%27d%27%2C%20%27e%27%5D%2C%20%5B%27f%27%2C%20%27g%27%2C%20%27h%27%2C%20%27i%27%2C%20%27j%27%5D%2C%20%5B%27k%27%2C%20%27l%27%2C%20%27m%27%2C%20%27n%27%2C%20%27o%27%5D%5D&debug=0) ### Explanation ``` L.e.>b^_1k.Tbyy L b Define a function on a list... .T ... which transposes it... .e.>b^_1k ... and rotates each row alternating left and right. yyQ Apply twice to the (implicit) input array. ``` [Answer] # [q/kdb+](http://kx.com/download/), 32 bytes **Solution:** ``` {rotate'[#:[x+:]#-1 1](+)x}/[2;] ``` **Example:** ``` q)3 5#.Q.a / reshape "a..o" into 3 row, 5 column grid "abcde" "fghij" "klmno" q){rotate'[#:[(+)x]#-1 1](+)x}/[2;]3 5#.Q.a "okgmi" "lcnea" "jfbhd" ``` **Explanation:** Flip the grid in order to apply rotation to **columns**, the second iteration flips once again thus the rotation is applied to the **rows** on the second pass. Rotation is based a the list `-1 1 -1 1..` of the length of the row/column being rotated. A healthy **9 bytes** have been golfed off from this *easier-to-read* version ``` {rotate'[count[flip x]#-1 1;flip x]}/[2;] / ungolfed solution { }/[2;] / perform lambda 2 times rotate'[ ; ] / perform rotate on each-both flip x / flip x<->y of grid #-1 1 / take from list -1 1 count[flip x] / the length of the flipped grid ``` [Answer] # JavaScript (ES6), ~~116~~ 76 bytes ``` m=>(g=m=>m[0].map((_,x)=>m.map(_=>m[y++%h][x],h=m.length,y=x&1||h-1)))(g(m)) ``` [Try it online!](https://tio.run/##NcxLCoMwFIXhuatw0ibBKHUB6UZCkFRjos1DVIqCe7enQgffhZ8Dd9QfvbTzMK1lTJ05e3EG8aRW4Ab5UFXQE6UN3xj6iuY37EVxc0puijsRKm@iXR3fxXavj8OVNWOMWhoYO9sUl@RN5ZOlPZVZnkuiCScvaKEDQxS/hh5hwcEA4394IzwEiJCIyhS@fwE "JavaScript (Node.js) – Try It Online") ### Commented ``` m => ( // m[] = input matrix g = m => // g is the main helper function taking a matrix m[] m[0].map((_, x) => // for each column at position x in m[]: m.map(_ => // for each row of m[]: m[y++ % h][x], // yield the x-th value of the row (y mod h) and increment y h = m.length, // h = number of rows y = x & 1 // start with y = 1 if x is odd, || h - 1 // or h - 1 if x is even ) // end of inner map() ) // end of outer map() )(g(m)) // invoke g twice on the input matrix ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes ``` ZJ-*ṙ"@Zµ⁺ ``` [Try it online!](https://tio.run/##y0rNyan8/z/KS1fr4c6ZSg5Rh7Y@atz1/3D70UkPd874/z86WsFQR0HBCIiNgdgEiE1jdbgUohXMgExzILYAYksdBUMDsLAhULUhULUhULUhULWhaWwsAA "Jelly – Try It Online") [Answer] # [Clean](https://clean.cs.ru.nl), 93 bytes ``` import StdEnv,StdLib k=[0,1:k] ^l=[[[last a:init a],tl a++[hd a]]!!b\\a<-transpose l&b<-k] ``` # ``` ^o^ ``` As a partial function literal, that happens to look like a face. [Try it online!](https://tio.run/##RY49C4MwGIR3f0WkUAcV2lV0a4eCm2OM8Bq/UpM3EmPBP9806NDpuTuO47jsAZ3S3SZ7okCgE2rRxpLKdk/8JB6laIO5oLfkns0saGRBKZWwWgKZQOHBEisJxDGdOm9YGLZ1DXlqDeC66LUn8trm6cxcZcHY4ELAGNhJQSiNoOVdH7GERsM4ifehZqlQR4z55rAht0KjLze6CYp/cGy4Lx8kjKtLX6V77AhK8NOcv38 "Clean – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 14 bytes ``` 2FøvyNÉiÀëÁ}}) ``` [Try it online!](https://tio.run/##MzBNTDJM/f/fyO3wjrJKv8OdmYcbDq8@3Fhbq/n/f3S0eqK6joJ6EohIBhEpICJVPVZHIVo9DcROBxEZICITRGRBpLJB7BwQkQsi8kBEvnpsLAA "05AB1E – Try It Online") **Explanation** ``` 2F # 2 times do: ø # zip vy # for each row(y), index(N) do: NÉiÀ # if N is odd, rotate left ëÁ # else rotate right }} # end if and inner loop ) # wrap in list ``` [Answer] # APL NARS, 36 bytes, 18 chars ``` c←b∘b←{⍵⌽⍨-×-\⍳≢⍵}∘⍉ ``` This {⍵⌽⍨-×-\⍳≢⍵} would rotate each row of the matrix argument follow the vector -1 1 -1 1 etc(that has its vector length the length of the argument matrix rows). Test: ``` ⎕←a←3 5⍴⎕A ABCDE FGHIJ KLMNO ⎕←c a OKGMI LCNEA JFBHD ``` [Answer] ## bash et al, 84 Non-competing shell solution. This is based around a function that alternates the direction of the rotation of the rows. The same procedure done on the transposed array will rotate the columns. For example `transpose | rotate | transpose | rotate`. The alternating rotation can be done on single character arrays with `sed` like this: ``` sed -E 's/(.*) (.)$/\2 \1/; n; s/^(.) (.*)/\2 \1/' ``` The transposition can be done with `rs` or `datamash`: ``` rs -g1 -T datamash -t' ' transpose ``` Taken together: ``` r() { sed -E 's/(.*) (.)$/\2 \1/; n; s/^(.) (.*)/\2 \1/'; } t() { rs -g1 -T; } <f t | r | t | r ``` Output: ``` o k g m i l c n e a j f b h d ``` ]
[Question] [ Lets define a class of functions. These functions will map from the positive integers to the positive integers and must satisfy the following requirements: * The function must be Bijective, meaning that every value maps to and is mapped to by exactly one value. * You must be able to get from any positive integer to any other positive integer by repeated applications of the function or its inverse. Now, write some code that will perform any one function in this class on its input. This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") question so answers will be scored in bytes, with less bytes being better. [Answer] # [Python 3](https://docs.python.org/3/), 24 bytes ``` lambda n:n-(-1)**n*2or 1 ``` [Try it online!](https://tio.run/##DcUxCoQwEAXQWk/xG3EmmCKxE/Qk20TcqKBfCdnC02dt3rufvF3sS8SITznCOS8BHGjFOjWGxl8JrsRXYidS4PoV18E7HerqTjuztI3/wU54a9FA2CEKVbX8AQ "Python 3 – Try It Online") [Answer] # Python, 22 bytes ``` lambda n:n+n%2*4-2or 1 ``` The even numbers go down to the previous even number, odd numbers go up to the next odd number, and the mapping 2 -> 1 connects those two. [Answer] ## JavaScript (ES6), 20 bytes ``` n=>n>1?n%2?n-2:n+2:2 ``` Maps `... -> 5 -> 3 -> 1 -> 2 -> 4 -> ...`, which I *think* is valid. Correct me if I'm wrong... [Answer] ## Haskell, 20 bytes ``` f 1=2 f x=x+2*(-1)^x ``` The example function from the OP's comment in Haskell. [Try it online!](https://tio.run/##y0gszk7Nyfn/P03B0NaIK02hwrZC20hLQ9dQM67if25iZp6CrUJKPpeCQkFRZl6JgopCmoIpCs8YhWeIwjNC4Zlw/QcA "Haskell – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes ``` -*Ḥạo1 ``` [Try it online!](https://tio.run/##ASAA3/9qZWxsef//LSrhuKThuqFvMf8yMFLCtcW8w4figqxH/w "Jelly – Try It Online") ### How it works ``` -*Ḥạo1 Main link. Argument: n -* Compute (-1)**n, yielding 1 for even n and -1 for odd n. Ḥ Unhalve; multipliy the result by 2. ạ Compute the absolute difference of the result and n. o1 If the difference is 0, yield 1. ``` [Answer] # Python 3, 43 bytes ``` lambda n,a=(1,3,-3,-1):n+a[n%4]if n-2else 1 ``` [Try it online!](https://tio.run/##DcqxDsIgGEXhuT7FXUghwgB1alJfRB1@IyhJvSVYB58eSU5ylq/89tfGqSUsuLZV3veHgFYW7e1kXc@bmUe5UJ1uOYEuxPUT4VvaKohMVOEzdo7Q6WEoNXPXowpfuDP6RihoWiRNY0z7Aw "Python 3 – Try It Online") And the inverse, also 43 bytes: ``` lambda n,a=(-3,-1,1,3):n+a[n%4]if n-1else 2 ``` [Try it online!](https://tio.run/##DcWxDsIgFAXQWb/iLqSP@BgApyb1R9QBIyhJvW2wDn49epazfrfnwtgLJlz6nF63ewI1TeKiOq9eox15SGea47UW0Pk8vzNCL0sDUYmW@MjiFcHbcb9bW@UmgwkfuBP@DTAQKorQWtt/ "Python 3 – Try It Online") TIO links use Dennis's test footer code. Since everyone is using one way of doing, I decided I'd be different, so I created by own (although I'm probably not the first person to discover it) function. This functions maps like `... 10 -> 7 -> 6 -> 3 -> 2 -> 1 -> 4 -> 5 -> 8 -> 9 -> ...`, I can show you the hand drawing I made to test this if you would like. My golfed algorithm ~~may be~~ probably is golfable - tips would be appreciated. Ungolfed versions: [Try it online!](https://tio.run/##jY9BCsMgEEXX9RR/E6I0gapdFexdCtXURSZBzKKntyZQGi2Frhx8n5n352d8TKRTulsHx0lcGLwDwRioPCPYuASCZBhh8n@D85YY18RplyAc19QbyQrpD1IF6vdIV0iy1Wsovfar1R9exQX5deGHV9FG122Sm0KePCHcaLBcdlAySx7m4CnytlEL@ivy02Y1Tt1WQoj0Ag "Python 3 – Try It Online") [Answer] # x86 32-bit machine code, 10 bytes ``` 48 83 F0 01 74 01 40 34 01 C3 ``` [Try it online!](https://tio.run/##XVHLboMwEDzjr9hSRbEDifKQekhCLjn30lOlpkKOMeDWGGSgdRrl10ttElS1Pqy9s@Od8ZpV1TRjrOvuhWKyTThs6yYR5SzfoT@QFMf/mBYqcxjipuFagb/34RzHtLGVY9vwOMZY86yiusALQggI1UCKXaRkc0G0LgDDk4/RLJPlkUpIUbpGXsIZcGqQZ0rtDiEskPf2BfW7qJBnDfRVl62vHCp7iuYNIj6QDUJOo6BCXcV0xkJgOdUwmdjkg6AzArtc0UAE8xBObtv06GcuJAccBAa2ESweSI@6VdkXNyn2RwKmOxiJg/JDsPZSbAi5Xh4oB/VIWS4UB1YmfO3fyuZXJinhPLBhNF8@216nCONW1SJTPOkNT0hKXkwQvNp5DcZOcGebmP1qkGwbR8XjgxrfIDuJ1n6IVbqgrvtmqaRZ3U2L1dIGO/bIynL5Aw "C++ (gcc) – Try It Online") Uses the regparm(1) calling convention – argument in EAX, result in EAX. Assembly: ``` .global f f: dec eax xor eax, 1 jz skip inc eax skip: xor al, 1 ret ``` [![Graph of how this affects numbers](https://i.stack.imgur.com/hwL8I.png)](https://i.stack.imgur.com/hwL8I.png) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 8 bytes ``` ®¹m·αD_+ ``` [Try it online!](https://tio.run/##MzBNTDJM/f//0LpDO3MPbT@30SVe@/9/QwMA "05AB1E – Try It Online") Exactly what Dennis's stuff does. ``` É4*+ÍD_+ ``` [Try it online!](https://tio.run/##MzBNTDJM/f//cKeJlvbhXpd47f//DQ0A "05AB1E – Try It Online") orlp's stuff. [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), 22 bytes ``` r->r%2>0?r<2?2:r-2:r+2 ``` [Try it online!](https://tio.run/##XY49T8NADIbnu1/hBSkVzalkg4R0Q2Jg6ogYruklckh8J8epVKH@9mAgXRgsv3798bj3Z5/HFKg/fS44psgCvXpuFhxcO1MjGMm9rKK0Ns3HARtoBj9N8OaR7Jc1qzmJF03niCcYtZUdhJG69w/w3E0ba3TUtJEhQxJAeIbHUlMFD7vytzxiHxrJcKOzxhwuk4TRxVlc0jsykHZKa67W/Ef@3Lstq6SVdfu7eiUJXeAtrKKGVnEL5zXfFfVuz1WxL54417gvFmUYDjIzQet8SsMloz/w1S7f "Java (OpenJDK 8) – Try It Online") I wish Java had a `**` exponentiation operator. Oh well! [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal) `r`, 6 bytes ``` uedε1⟇ ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=r&code=ued%CE%B51%E2%9F%87&inputs=&header=%40chain%3A1%7C&footer=%3B%0A1%3A%E2%82%B4%20%60%5Ct-%3E%5Ct%60%E2%82%B4%20%40chain%3B%2C%0A2%3A%E2%82%B4%20%60%5Ct-%3E%5Ct%60%E2%82%B4%20%40chain%3B%2C%0A3%3A%E2%82%B4%20%60%5Ct-%3E%5Ct%60%E2%82%B4%20%40chain%3B%2C%0A4%3A%E2%82%B4%20%60%5Ct-%3E%5Ct%60%E2%82%B4%20%40chain%3B%2C%0A5%3A%E2%82%B4%20%60%5Ct-%3E%5Ct%60%E2%82%B4%20%40chain%3B%2C%0A6%3A%E2%82%B4%20%60%5Ct-%3E%5Ct%60%E2%82%B4%20%40chain%3B%2C%0A7%3A%E2%82%B4%20%60%5Ct-%3E%5Ct%60%E2%82%B4%20%40chain%3B%2C%0A8%3A%E2%82%B4%20%60%5Ct-%3E%5Ct%60%E2%82%B4%20%40chain%3B%2C%0A9%3A%E2%82%B4%20%60%5Ct-%3E%5Ct%60%E2%82%B4%20%40chain%3B%2C%0A10%3A%E2%82%B4%20%60%5Ct-%3E%5Ct%60%E2%82%B4%20%40chain%3B%2C%0A11%3A%E2%82%B4%20%60%5Ct-%3E%5Ct%60%E2%82%B4%20%40chain%3B%2C%0A12%3A%E2%82%B4%20%60%5Ct-%3E%5Ct%60%E2%82%B4%20%40chain%3B%2C%0A13%3A%E2%82%B4%20%60%5Ct-%3E%5Ct%60%E2%82%B4%20%40chain%3B%2C%0A14%3A%E2%82%B4%20%60%5Ct-%3E%5Ct%60%E2%82%B4%20%40chain%3B%2C%0A15%3A%E2%82%B4%20%60%5Ct-%3E%5Ct%60%E2%82%B4%20%40chain%3B%2C%0A16%3A%E2%82%B4%20%60%5Ct-%3E%5Ct%60%E2%82%B4%20%40chain%3B%2C%0A17%3A%E2%82%B4%20%60%5Ct-%3E%5Ct%60%E2%82%B4%20%40chain%3B%2C%0A18%3A%E2%82%B4%20%60%5Ct-%3E%5Ct%60%E2%82%B4%20%40chain%3B%2C%0A19%3A%E2%82%B4%20%60%5Ct-%3E%5Ct%60%E2%82%B4%20%40chain%3B%2C%0A20%3A%E2%82%B4%20%60%5Ct-%3E%5Ct%60%E2%82%B4%20%40chain%3B%2C) @Dennis' answer, ported directly to Vyxal. Requires the `r` flag to reverse the arguments, e.g. `ab+` evaluates to `b+a` instead of `a+b`. Explanation taken from Dennis: ``` # Implicit input -> n ue # Compute (-1)**n, yielding 1 for even n and -1 for odd n. d # Unhalve; multipliy the result by 2. ε # Compute the absolute difference of the result and n. 1⟇ # If the difference is 0, yield 1. # Implicit output ``` [Answer] # Mathematica, 21 bytes ``` a@1=2;a@b_:=b+2(-1)^b ``` Move along, nothing to see here... ]
[Question] [ Based on [this](https://codegolf.stackexchange.com/questions/119361/easier-communication-means-faster-coding-means-fewer-coders-means/119406), but I was asked[[​1​]](https://codegolf.stackexchange.com/questions/119361/easier-communication-means-faster-coding-means-fewer-coders-means#comment292359_119361),[[​2​]](https://codegolf.stackexchange.com/questions/119361/easier-communication-means-faster-coding-means-fewer-coders-means#comment292548_119406) to do a graphical edition. [![EASIER COMMUNICATION MEANS FASTER CODING MEANS FEWER CODERS MEANS…](https://i.stack.imgur.com/pEzT8.png)](https://i.stack.imgur.com/pEzT8.png) # Task **Generate a circular display of the text `EASIER COMMUNICATION MEANS FASTER CODING MEANS FEWER CODERS MEANS` .** Any uppercase font goes. The letter tops must face out of the circle. Either the space before `FEWER` must be at the bottom (6 o'clock) or (for brownie points) your text must rotate. [Answer] # Octave, 168 bytes ``` for i=1:(n=nnz(s='CATION MEANS FASTER CODING MEANS FEWER CODERS MEANS EASIER COMMUNI')),text(sin(i/n*2*pi),cos(i/n*2*pi),s(i),'rotation',-i/n*360);axis([-2,2,-2,2]);end ``` **[Try it here](http://octave-online.net/#cmd=for%20i%3D1%3A(n%3Dnnz(s%3D%27CATION%20MEANS%20FASTER%20CODING%20MEANS%20FEWER%20CODERS%20MEANS%20EASIER%20COMMUNI%27))%2Ctext(sin(i%2Fn*2*pi)%2Ccos(i%2Fn*2*pi)%2Cs(i)%2C%27rotation%27%2C-i%2Fn*360)%3Baxis(%5B-2%2C2%2C-2%2C2%5D)%3Bend)** [Answer] ## Mathematica, 153 Bytes ``` x=Pi/33;Graphics@Map[StringSplit["CATION MEANS FASTER CODING MEANS FEWER CODERS MEANS EASIER COMMUNI",""][[#/x]]~Text~{Sin@#,Cos@#}~Rotate~-#&,Range@66x] ``` [![enter image description here](https://i.stack.imgur.com/LJPH3.png)](https://i.stack.imgur.com/LJPH3.png) Increasing it to 178 bytes lets it rotate: ``` x=Pi/33;Graphics@Map[StringSplit["CATION MEANS FASTER CODING MEANS FEWER CODERS MEANS EASIER COMMUNI",""][[#/x-a]]~Text~{Sin@#,Cos@#}~Rotate~-#&,(a+Range@66)x]~Animate~{a,1,66,1} ``` [![enter image description here](https://i.stack.imgur.com/1zZUC.gif)](https://i.stack.imgur.com/1zZUC.gif) [Answer] # HTML and JS, 13 + 170 = ~~284~~ ~~227~~ ~~192~~ ~~186~~ 183 bytes *41 bytes saved thanks to @Shaggy* ``` (x=c.getContext("2d")).translate(r=c.height/2,r) for(i in t="CATION MEANS FASTER CODING MEANS FEWER CODERS MEANS EASIER COMMUNI"){x.rotate(2/21);x.fillText(t[i],0,-r*.8)} ``` ``` <canvas id=c height=250 width=250> ``` The width and height set to 250 to allow better visibility were not included in the bytes count. [Answer] # Bash + ImageMagick, 168 bytes ``` convert -font $(convert -list font|grep Font:|head -n1|cut -d" " -f4) label:"FEWER CODERS MEANS EASIER COMMUNICATION MEANS FASTER CODING MEANS " -distort Arc 360 i.png ``` **Example output:** [![Example output](https://i.stack.imgur.com/awCTX.png)](https://i.stack.imgur.com/awCTX.png) [Answer] # BBC BASIC, 248 Download interpreter at <http://www.bbcbasic.co.uk/bbcwin/download.html> ``` F.i=6TO767a=i DIV6*.024-.3r=(80+i MOD6)MOD83*9-369IFASC(M."?[O@Wo}@b}O@O|O@y?l@xHH@GGE@zmo@yo|@}oU@o?m@?L|@phh@GEE@?u?@?{o@Wk?@?I?@g|O@EGE@?]M@z}o@|_|@}?m@?MO@GDG@xhh@?k?@?oU@z}o@?LO@a?L",i DIV6))>>i MOD6A.1CIRCLEFILL500-r*COS(a),500+r*SIN(a),9 N. ``` **Ungolfed** ``` FORi=6TO767 a=i DIV 6 * .024 - .3 r=(80 + i MOD 6) MOD 83 * 9 - 369 :REM iterate through ({80,81,82,0,1,2} - 41 = {39,40,41,-41,-40,-39}) * 9 IF ASC(MID$("?[O@Wo}@b}O@O|O@y?l@xHH@GGE@zmo@yo|@}oU@o?m@?L|@phh@GEE@?u?@?{o@Wk?@?I?@g|O@EGE@?]M@z}o@|_|@}?m@?MO@GDG@xhh@?k?@?oU@z}o@?LO@a?L",i DIV6))>>i MOD6AND1 THEN CIRCLEFILL 500-r*COS(a), 500+r*SIN(a), 9 :REM dots are circle radius 9 according to documentation (but BBC BASIC actually draws them smaller.) ENDIF NEXT ``` Doing this in a language that doesn't support rotated text - for fun. Each character is a 3x3 dot matrix array. There are a total of 66 characters but there are 2 diametrically opposite spaces that we do not print (after CODERS and before FASTER.) Each byte of the magic string encodes for a single vertical row of one letter and a single vertical row of the opposite letter. In this way we only have to sweep through 180 degrees. [![enter image description here](https://i.stack.imgur.com/VD6hE.png)](https://i.stack.imgur.com/VD6hE.png) [Answer] ## SVG(HTML5), 212 bytes ``` <svg width=500 height=500><defs><path id=p d=M250,451a201,201,0,0,1,0,-402a201,201,0,0,1,0,402></defs><text font-size="32"><textPath xlink:href=#p>FEWER CODERS MEANS EASIER COMMUNICATION MEANS FASTER CODING MEANS ``` Static version of my answer to [Easier communication means faster coding means fewer coders means …](https://codegolf.stackexchange.com/questions/119361) tweaked so that `FEWER` is at the bottom. Adjustable version in case your font doesn't match mine: ``` <p><input type=number value=0 min=0 max=9 oninput=p.setAttribute('d','M250,250m0,20_a20_,20_,0,1,1,20_,-20_a20_,20_,0,1,1,-20_,-20_a20_,20_,0,1,1,-20_,20_a20_,20_,0,1,1,20_,20_'.replace(/_/g,this.value))></p> <svg width=500 height=500><defs><path id=p d=M250,250m0,200a200,200,0,1,1,200,-200a200,200,0,1,1,-200,-200a200,200,0,1,1,-200,200a200,200,0,1,1,200,200></defs><text font-size="32"><textPath xlink:href=#p>FEWER CODERS MEANS EASIER COMMUNICATION MEANS FASTER CODING MEANS ``` [Answer] # Postscript (127 bytes) Hex dump: ``` 00000000: 2f53 2031 92a5 9233 2f4d 6f6e 6f20 3992 /S 1...3/Mono 9. 00000010: 8e88 6432 3030 926b 3292 9a28 4943 4154 ..d200.k2..(ICAT 00000020: 494f 4e20 4d45 414e 5320 4641 5354 4552 ION MEANS FASTER 00000030: 2043 4f44 494e 4720 4d45 414e 5320 4645 CODING MEANS FE 00000040: 5745 5220 434f 4445 5253 204d 4541 4e53 WER CODERS MEANS 00000050: 2045 4153 4945 5220 434f 4d4d 554e 297b EASIER COMMUN){ 00000060: 5388 0033 2032 9287 9278 5320 6661 6c73 S..3 2...xS fals 00000070: 6592 112d 352e 3435 9288 7d92 4992 a7 e..-5.45..}.I.. ``` Ungolfed (text) version: ``` /S 1 string def /Mono 9 selectfont 100 200 moveto 2 setlinejoin (ICATION MEANS FASTER CODING MEANS FEWER CODERS MEANS EASIER COMMUN) {S 0 3 2 roll put S false charpath -5.45 rotate} forall stroke ``` Sample output: [![enter image description here](https://i.stack.imgur.com/30Tzx.png)](https://i.stack.imgur.com/30Tzx.png) [Answer] # Java 8, 1,087 bytes ``` import javafx.animation.*;import javafx.application.*;import javafx.scene.*;import javafx.scene.layout.*;import javafx.scene.shape.*;import javafx.scene.text.*;import javafx.stage.*;import javafx.util.*;import java.util.*;import static javafx.animation.PathTransition.*;public class P extends Application{@Override public void start(Stage stage)throws Error{char[] t="EASIER COMMUNICATION MEANS FASTER CODING MEANS FEWER CODERS MEANS".toCharArray();Shape q=new Circle(400,400,120);List<Text>h=new ArrayList<>();List<Transition>z=new ArrayList<>();for(char c:t){Text o=new Text(c+"");h.add(o);z.add(x(q, o));}Pane p=new Pane();p.getChildren().addAll(h);int s=h.size();for(int i=0;i<s;i++){Transition w=z.get(i);w.jumpTo(Duration.seconds(10).multiply((i+.5)*1/s));w.play();}stage.setScene(new Scene(p,800,800));stage.show();}Transition x(Shape e,Text t){PathTransition v=new PathTransition(Duration.seconds(10),e,t);v.setCycleCount(INDEFINITE);v.setOrientation(OrientationType.ORTHOGONAL_TO_TANGENT);v.setInterpolator(Interpolator.LINEAR);return v;}static void main(String[]a){launch(a);}} ``` [![Screenshot](https://i.stack.imgur.com/SB9Bf.png)](https://i.stack.imgur.com/SB9Bf.png) [Answer] # LaTeX + TikZ, 380 bytes ``` \documentclass[tikz,border=20pt]{standalone}\usetikzlibrary{decorations,decorations.text,}\begin{document}\begin{tikzpicture}\draw[color=white,rotate=-90,postaction={decorate,decoration={text along path,raise=4pt,text align={align=center},text={FEWER CODERS MEANS EASIER COMMUNICATION MEANS FASTER CODING MEANS },reverse path}}](0,0)circle(2.425cm);\end{tikzpicture}\end{document} ``` Example output [![enter image description here](https://i.stack.imgur.com/MJLLI.png)](https://i.stack.imgur.com/MJLLI.png) [Answer] # Tcl/Tk, 222 ``` grid [canvas .c] set i 90;lmap c [split "FEWER CODERS MEANS EASIER COMMUNICATION MEANS FASTER CODING MEANS" ""] {.c cr t [expr {93*cos([set i [expr $i+5.5]]/57.3)+99}] [expr {93*sin($i/57.3)+99}] -te $c -ang [expr -$i-90]} ``` [![enter image description here](https://i.stack.imgur.com/JeNUx.png)](https://i.stack.imgur.com/JeNUx.png) Will golf it more later! [Answer] # Java 10, 690 bytes ``` import java.awt.*;v->new Frame(){{add(new Panel(){RenderingHints R;Math M;public void paint(Graphics g){Graphics2D G=(Graphics2D)g;G.setRenderingHint(R.KEY_ANTIALIASING,R.VALUE_ANTIALIAS_ON);var v=new Font("Hei",0,8).createGlyphVector(G.getFontRenderContext(),"ICATION MEANS FASTER CODING MEANS FEWER CODERS MEANS EASIER COMMUN");int n=99,i=0;for(G.translate(n,0);i<66;){double p=M.PI/2,t=-6/1.1*i*p/90+p;v.setGlyphPosition(i,new Point(0,0));var a=java.awt.geom.AffineTransform.getTranslateInstance((int)(n*M.cos(t)+n),(int)(-n*M.sin(t)+n));a.rotate(t=4*p*i/66);a.translate(n*M.cos(p-t),n*M.sin(p-t));a.translate(-4,0);G.fill(a.createTransformedShape(v.getGlyphOutline(i++)));}}});show();}} ``` Result: [![enter image description here](https://i.stack.imgur.com/WPMtW.png)](https://i.stack.imgur.com/WPMtW.png) **Explanation:** ``` import java.awt.*; // Required import for almost everything v-> // Method with empty unused parameter and Frame return-type new Frame(){ // Create the Frame { // In an inner code-block: add(new Panel(){ // Add a Panel we can draw on: RenderingHints R; // RenderingHints null-instance on class-level, for static calls Math M; // Math null-instance on class-level, for static calls public void paint(Graphics g){ // Overwrite its paint method: Graphics2D G=(Graphics2D)g; // Cast Graphics to Graphics2D, to open up more methods G.setRenderingHint(R.KEY_ANTIALIASING,R.VALUE_ANTIALIAS_ON); // Apply a focus rendering, otherwise the text would be too vague var v=new Font("Hei",0,// Create a "Hei"-Font (could alternatively be Kai) // (note that a centered monospace font would look a lot better // for letters like the 'I's) 8) // of font-size 8 .createGlyphVector(G.getFontRenderContext(), // Create a GlyphVector using that Font "ICATION MEANS FASTER CODING MEANS FEWER CODERS MEANS EASIER COMMUN"); // With this String as text (first character will be at the top) int n=99, // Integer we'll use a bunch of times, radius of the circle 99 i=0; // Index integer, starting at 0 for(G.translate(n,0); // Set the starting coordinate at 99,0, otherwise the circle // would be partially outside of the Frame boundaries i<66;){ // Loop `i` in the range [0, 66): // (66 is the amount of characters of the text) double p=M.PI/2, // Temp-double `p`, set to PI/2 t= // Temp-double, which will start at: -6/1.1 // -360 / 66 *i // multiplied by the current `i` *p/90 // multiplied by PI/180 +p; // And add PI/2 to that v.setGlyphPosition(i,new Point(0,0)); // Start the `i`'th Glyph position at 0,0 var a=java.awt.geom.AffineTransform.getTranslateInstance( // Create an AffineTransform Translation instance, starting at: (int)( // x-coordinate as casted integer: n // 99 *M.cos(t) // multiplied by the cosine of `t` +n), // Add 99 to that (int)( // y-coordinate as casted integer: -n // -99 *M.sin(t) // multiplied by the sinus of `t` +n)); // Add 99 to that a.rotate( // Then rotate the current letter by, t= // and set `t` to it at the same time: 4*p // 2*PI *i // multiplied by the current `i` /66); // divided by the length 66 a.translate( // Then move the letter to the correct position: // x-coordinate: n // 99 *M.cos(p-t), // multiplied by the cosine of PI/2 - the new `t` // y-coordinate: n // 99 *M.sin(p-t)); // multiplied by the sinus of PI/2 - the new `t` a.translate(-4,0); // Slightly adjust based on the font-size G.fill( // Then add to the Panel through the Graphics2D: a.createTransformedShape( // The shape of: v.getGlyphOutline(i++)));}}}); // The current `i`'th Glyph we just created show();}} // And afterwards show the Frame ``` ]
[Question] [ A [heap](https://en.wikipedia.org/wiki/Heap_(data_structure)), also known as a priority-queue, is an abstract data type. Conceptually, it's a binary tree where the children of every node are smaller than or equal to the node itself. (Assuming it's a max-heap.) When an element is pushed or popped, the heap rearranges itself so the the biggest element is the next to be popped. It can easily be implemented as a tree or as an array. Your challenge, should you choose to accept it, is to determine if an array is a valid heap. An array is in heap form if every element's children are smaller than or equal to the element itself. Take the following array as an example: ``` [90, 15, 10, 7, 12, 2] ``` Really, this is a binary tree arranged in the form of an array. This is because every element has children. 90 has two children, 15 and 10. ``` 15, 10, [(90), 7, 12, 2] ``` 15 also has children, 7 and 12: ``` 7, 12, [90, (15), 10, 2] ``` 10 has children: ``` 2 [90, 15, (10), 7, 12, ] ``` and the next element would also be a child of 10, except that there isn't room. 7, 12 and 2 would all also have children if the array was long enough. Here is another example of a heap: ``` [16, 14, 10, 8, 7, 9, 3, 2, 4, 1] ``` And here is a visualization of the tree the previous array makes: [![enter image description here](https://i.stack.imgur.com/12r92.jpg)](https://i.stack.imgur.com/12r92.jpg) Just in case this isn't clear enough, here is the explicit formula to get the children of the i'th element ``` //0-indexing: child1 = (i * 2) + 1 child2 = (i * 2) + 2 //1-indexing: child1 = (i * 2) child2 = (i * 2) + 1 ``` You must take an non-empty array as input and output a truthy value if the array is in heap order, and a falsy value otherwise. This can be a 0-indexed heap, or a 1-indexed heap as long as you specify which format your program/function expects. You may assume that all arrays will only contain positive integers. You may *not* use any heap-builtins. This includes, but is not limited to * Functions that determine if an array is in heap-form * Functions that convert an array into a heap or into heap-form * Functions that take an array as input and return a heap data-structure You can use this python script to verify if an array is in heap-form or not (0 indexed): ``` def is_heap(l): for head in range(0, len(l)): c1, c2 = head * 2 + 1, head * 2 + 2 if c1 < len(l) and l[head] < l[c1]: return False if c2 < len(l) and l[head] < l[c2]: return False return True ``` # Test IO: All of these inputs should return True: ``` [90, 15, 10, 7, 12, 2] [93, 15, 87, 7, 15, 5] [16, 14, 10, 8, 7, 9, 3, 2, 4, 1] [10, 9, 8, 7, 6, 5, 4, 3, 2, 1] [100, 19, 36, 17, 3, 25, 1, 2, 7] [5, 5, 5, 5, 5, 5, 5, 5] ``` And all of these inputs should return False: ``` [4, 5, 5, 5, 5, 5, 5, 5] [90, 15, 10, 7, 12, 11] [1, 2, 3, 4, 5] [4, 8, 15, 16, 23, 42] [2, 1, 3] ``` As usual, this is code-golf, so standard loopholes apply and the shortest answer in bytes wins! [Answer] ## JavaScript (ES6), ~~34~~ 30 bytes ``` a=>!a.some((e,i)=>e>a[i-1>>1]) ``` Edit: Fixing my code for the spec clarification cost 1 byte, so thanks to @edc65 for saving 4 bytes. [Answer] # Jelly, ~~11~~ ~~9~~ 5 bytes ``` x2:ḊṂ ``` 4 bytes removed thanks to Dennis! [Try it here.](http://jelly.tryitonline.net/#code=eDI64biK4bmC&input=&args=WzkwLCAxNSwgMTAsIDcsIDEyLCAyXQ) ### Explanation ``` x2 Duplicate each element. :Ḋ Each element divided by the input with the first element removed, as integer, so there is a 0 only if some element in the duplicated list is less than the corresponding element in the other. There are also elements left unchanged, but it doesn't matter as the input is all positive. Ṃ Minimum in the list. ``` [Answer] # Haskell, 33 bytes ``` f(a:b)=and$zipWith(<=)b$a:b<*"xx" ``` or ``` and.(zipWith(<=).tail<*>(<*"xx")) ``` [Answer] # J, 24 bytes ``` */@:<:]{~0}:@,<.@-:@i.@# ``` ## Explanation ``` */@:<:]{~0}:@,<.@-:@i.@# Input: s # Count of s i.@ Create range [0, 1, ..., len(s)-1] -:@ Halve each <.@ Floor each 0 , Prepend a zero to it }:@ Remove the last value to get the parent indices of each ] Identity function to get s {~ Take the values from s at the parent indices <: For each, 1 if it is less than or equal to its parent else 0 */@: Reduce using multiplication and return ``` [Answer] # [MATL](https://github.com/lmendo/MATL), ~~13~~ 12 bytes ``` ttf2/k)>~4L) ``` [Try it online!](https://tio.run/##y00syfn/v6QkzUg/W9OuzsRH8///aEMzHQVDEyA20FGw0FEw11Gw1FEw1lEw0lEAicYCAA) Or [verify all test cases](https://tio.run/##dY@xDsMgDER3voI1ElKDgQJLpowZs0WR0qVL2425v07PdqaqlUBYd88@/Lq1Z@@Hae1Ol8cwveMymHntfaujsz7h4s14yFnazVaDyiWrjDJB9lfUUekiTnUWKLpYZWIUTU3QSRxF1OdA7uJRWS3OFyKDSNL0fWDEf8aPHbxkycwgPzgHlJNEOLHBu5Kkh/0D). An array is truthy if it is non-empty and all its entries are nonzero. Otherwise it's falsy. Here are [some examples](http://matl.tryitonline.net/#code=YCAgICAgICAgICAgICUgaW5maW5pdGUgbG9vcCB0byB0YWtlIGFsbCBpbnB1dHMKPyd0cnV0aHknICAgICUgaWY6IHRydXRoeQp9J2ZhbHN5JyAgICAgJSBlbHNlOiBmYWxzeQpdICAgICAgICAgICAgJSBlbmQgaWYKRFQgICAgICAgICAgICUgZGlzcGxheSBhbmQgZW5kIGxvb3A&input=W10KWzAgMSAyXQpbMyA0IC01XQpbMSAxOyAxIDFd). ### Explanation ``` t % Take input implicitly. Duplicate tf % Duplicate and push indices of nonzero entries. This gives [1 2 ... n] where n % is input size 2/k % Divide by 2 and round down ) % Index into input. Gives array of parents, except for the first entry >~ % True for entries of the input that don't exceed those in the array of parents 4L) % Discard first entry ``` [Answer] ## Python 2, 45 bytes ``` f=lambda l:l==[]or l[len(l)/2-1]/l.pop()*f(l) ``` Outputs 0 for Falsy, nonzero for Truthy. Checks that the last element is less than or equal to its parent at index `len(l)/2-1`. Then, recurses to check that the same is True with the last element of the list removed, and so on until the list is empty. --- **48 bytes:** ``` f=lambda l,i=1:l==l[:i]or l[~-i/2]/l[i]*f(l,i+1) ``` Checks that at each index `i`, the element is at most its parent at index `(i-1)/2`. The floor-division produces 0 if this is not the case. Doing the base case as `i/len(l)or` gives the same length. I had tried zipping at first, but got longer code (57 bytes). ``` lambda l:all(map(lambda a,b,c:b<=a>=c,l,l[1::2],l[2::2])) ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `r`, 5 bytes ``` hJY≥A ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJyIiwi4pahxpsiLCJoSlniiaVBIiwiIiwiWzkwLCAxNSwgMTAsIDcsIDEyLCAyXVxuWzkzLCAxNSwgODcsIDcsIDE1LCA1XVxuWzE2LCAxNCwgMTAsIDgsIDcsIDksIDMsIDIsIDQsIDFdXG5bMTAsIDksIDgsIDcsIDYsIDUsIDQsIDMsIDIsIDFdXG5bMTAwLCAxOSwgMzYsIDE3LCAzLCAyNSwgMSwgMiwgN11cbls1LCA1LCA1LCA1LCA1LCA1LCA1LCA1XVxuWzQsIDUsIDUsIDUsIDUsIDUsIDUsIDVdXG5bOTAsIDE1LCAxMCwgNywgMTIsIDExXVxuWzEsIDIsIDMsIDQsIDVdXG5bNCwgOCwgMTUsIDE2LCAyMywgNDJdXG5bMiwgMSwgM10iXQ==) [Answer] # R, ~~97 88~~ 82 bytes Hopefully I've understood this correctly. Now to see if I can get rid of some more bytes. Ditched the rbind and put in an sapply and deal with 1-based vector properly. Implemented as an unnamed function ``` function(Y)all(sapply(1:length(Y),function(X)Y[X]>=Y[X*2]&Y[X]>=Y[X*2+1]),na.rm=T) ``` With a few of the test cases ``` > f= + function(Y)all(sapply(1:length(Y),function(X)Y[X]>=Y[X*2]&Y[X]>=Y[X*2+1]),na.rm=T) > f(c(90, 15, 10, 7, 12, 2)) [1] TRUE > f(c(93, 15, 87, 7, 15, 5)) [1] TRUE > f(c(10, 9, 8, 7, 6, 5, 4, 3, 2, 1)) [1] TRUE > f(c(5, 5, 5, 5, 5, 5, 5, 5)) [1] TRUE > f(c(4, 5, 5, 5, 5, 5, 5, 5)) [1] FALSE > f(c(90, 15, 10, 7, 12, 11)) [1] FALSE > f(c(4, 8, 15, 16, 23, 42)) [1] FALSE ``` [Answer] # CJam, ~~19~~ ~~16~~ ~~13~~ 12 bytes ``` q~_:_\(;./:* ``` Golfed off 3 bytes thanks to Dennis. [Try it here.](http://cjam.aditsu.net/#code=q%7E_%3A_%5C%28%3B.%2F%3A*&input=%5B90%2015%2010%207%2012%202%5D) [Answer] # Pyth, 8 bytes ``` .AgV.i+h hQ first element of input + Q plus input .i Q interleaved with input gV Q vectorized greater-than-or-equal comparison with input .A check if all results are true ``` [Try it online](https://pyth.herokuapp.com/?code=.AgV.i%2Bh&input=%5B90%2C+15%2C+10%2C+7%2C+12%2C+2%5D%0A%5B93%2C+15%2C+87%2C+7%2C+15%2C+5%5D%0A%5B16%2C+14%2C+10%2C+8%2C+7%2C+9%2C+3%2C+2%2C+4%2C+1%5D%0A%5B10%2C+9%2C+8%2C+7%2C+6%2C+5%2C+4%2C+3%2C+2%2C+1%5D%0A%5B100%2C+19%2C+36%2C+17%2C+3%2C+25%2C+1%2C+2%2C+7%5D%0A%5B5%2C+5%2C+5%2C+5%2C+5%2C+5%2C+5%2C+5%5D%0A&test_suite=1&test_suite_input=%5B90%2C+15%2C+10%2C+7%2C+12%2C+2%5D%0A%5B93%2C+15%2C+87%2C+7%2C+15%2C+5%5D%0A%5B16%2C+14%2C+10%2C+8%2C+7%2C+9%2C+3%2C+2%2C+4%2C+1%5D%0A%5B10%2C+9%2C+8%2C+7%2C+6%2C+5%2C+4%2C+3%2C+2%2C+1%5D%0A%5B100%2C+19%2C+36%2C+17%2C+3%2C+25%2C+1%2C+2%2C+7%5D%0A%5B5%2C+5%2C+5%2C+5%2C+5%2C+5%2C+5%2C+5%5D%0A%5B4%2C+5%2C+5%2C+5%2C+5%2C+5%2C+5%2C+5%5D%0A%5B90%2C+15%2C+10%2C+7%2C+12%2C+11%5D%0A%5B1%2C+2%2C+3%2C+4%2C+5%5D%0A%5B4%2C+8%2C+15%2C+16%2C+23%2C+42%5D%0A%5B2%2C+1%2C+3%5D) [Answer] # [Retina](https://github.com/m-ender/retina), 51 bytes ``` \d+ $* ^(?!(1+ )*(1+) 1* ?(?<-1>1+ )*(?(1)(?!))1\2) ``` [Try it online!](https://tio.run/##XY7BCgIxDETv@YoRFNpdhE1rt1sQe/QnFlHQgxcP4v/XyXpRCQTmzWTI8/a6Py5t447nNl97WXdycnXltIfvuD20Q3V1v9XDh1WnngnvdQ6@tTJAE3RAhgYEKdH0lE0nJNERujN/IimICKAUgrKgEYnAsEGWMcOTbIi95FnY8z2y@9O/PyiLeBZZa9Fp8UYEgiC0Ed8 "Retina – Try It Online") --- Takes a space-separated list of numbers as input. Outputs `1`/`0` for truthy/false [Answer] # [C (GCC)](https://gcc.gnu.org), ~~63~~ 60 bytes *-3 bytes thanks to [@Juan Ignacio Díaz](https://codegolf.stackexchange.com/users/112488/juan-ignacio-d%c3%adaz)* ``` f(v,n,b,j)int*v;{for(b=j=0;n+~j;)b|=v[j/2]<v[++j];return!b;} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=rdPRaoMwFAbgi121T3FWGOjMmNGmKqkPMpyM6WqpsGyI9cZlL7Kb3vShtqfZSdLBkNiBTJSIkC-_5yQfx_JhW5aHw3HfVjfx57pyOiJIQWp3J9rrjvfVS-MUaZ36XHjvNXeLt7TL6tsgX3eZ59U5bzbtvhGXBZfG-Lq4e37cCcft57MeUIEuyyGFPvEJUIYPjhEOAYFAwu-Lw2uDEypncfV0LxYEVBpYuS4HOcRCg8WRwfCVTcboCoWlSRZrLyGAC2BC9VWOYNS3Yr6ebhyEmUaMRuVosjFMFU2lUREj46gaai4aSwaJDWM6zPCWf9YstmHL_8QsW4NSObWbujahLvtgT5zF2Mhvxqds2IFAqdM3baAbF1ozncNCjc3mpxP2c1q_AQ) Original note of the 63 bytes version: > > I know 2 bytes can be saved by inverting the meaning of the values `0` > and `1`, but I prefer to keep it this way. > > > [Answer] # C++14, ~~134~~ 105 bytes ``` #define M(d) (2*i+d<c.size()&&(c[i]<c[2*i+d]||f(c,2*i+d)==0)) int f(auto&c,int i=0){return!(M(1)||M(2));} ``` Requires `c` to be a container supporting `.operator[](int)` and `.size()`, like `std::vector<int>`. Ungolfed: ``` int f(auto& c, int i=0) { if (2*i+1<c.size() && c[i] < c[2*i+1]) return 0; if (2*i+2<c.size() && c[i] < c[2*i+2]) return 0; if (2*i+1<c.size() && (f(c,2*i+1) == 0)) return 0; if (2*i+2<c.size() && (f(c,2*i+2) == 0)) return 0; return 1; } ``` Could be smaller if truthy=`0` and falsy=`1` would be allowed. [Answer] # R, 72 bytes A slightly different approach from [the other R answer](https://codegolf.stackexchange.com/a/85082/59052). ``` x=scan();all(diff(x[c(a<-1:(N<-sum(1|x)),a,a*2,a*2+1)],l=N*2)<1,na.rm=T) ``` Reads input from stdin, creates a vector of all of the comparison pairs, subtracts them from each other, and checks that the result is a negative number or zero. ### Explanation Read input from stdin: ``` x=scan(); ``` Create our pairs. We create indices of `1...N` (where `N` is the length of `x`) for the parent nodes. We take this twice as each parent has (maximally) two children. We also take the children, `(1...N)*2` and `(1...N)*2+1`. For indices beyond the length of `x`, R returns `NA`, 'not available'. For input `90 15 10 7 12 2`, this code gives us `90 15 10 7 12 2 90 15 10 7 12 2 15 7 2 NA NA NA 10 12 NA NA NA NA`. ``` x[c(a<-1:(N<-sum(1|x)),a,a*2,a*2+1)] ``` In this vector of pairs, each element has its partner at a distance of `N*2` away. For example, item 1's partner is located at position 12 (6\*2). We use `diff` to calculate the difference between these pairs, specifying `lag=N*2` to compare the items to their correct partners. Any operations on `NA` elements simply return `NA`. ``` diff(x[c(a<-1:(N<-sum(1|x)),a,a*2,a*2+1)],l=N*2) ``` Finally, we check that all of these returned values are less than `1` (i.e. that the first number, the parent, was bigger than the second number, the child), excluding `NA` values from consideration. ``` all(diff(x[c(a<-1:(N<-sum(1|x)),a,a*2,a*2+1)],l=N*2)<1,na.rm=T) ``` [Answer] # [Actually](http://github.com/Mego/Seriously), 16 bytes This answer is largely based on [jimmy23013's Jelly answer](https://codegolf.stackexchange.com/a/85087/47581). Golfing suggestions welcome! [Try it online!](http://actually.tryitonline.net/#code=Ozsy4pWf4pSszqMxKHRaYGk8YE1t&input=WzkwLCAxNSwgMTAsIDcsIDEyLCAyXQ) ``` ;;2╟┬Σ1(tZ`i<`Mm ``` **Ungolfing** ``` Implicit input a. ;; Duplicate a twice. 2╟ Wrap two of the duplicates into a list. ┬ Transpose the duplicates. Σ Sum all of the columns to get a flat list like this: [a_0, a_0, a_1, a_1, ..., a_n, a_n] This gets the parent nodes of the heap. 1(t Get a[1:] using the remaining duplicate of a. This is a list of the child nodes of the heap. Z`i<`M Check if every child node is less than its parent node. m Get the minimum. This returns 1 if a is a max-heap, else 0. Implicit return. ``` ]
[Question] [ The SUDSI sequence (**su**m, **d**ifference, **s**wap, **i**ncrement) is a curious integer sequence that appears to exhibit rather chaotic behavior. It can be generated as follows: Let *S* be an infinite list of the natural numbers: `1 2 3 4 5 6 ...`. Let *Si* denote the one-indexed *i*th element of *S*. So initially, *S1* is 1, *S2* is 2, etc. (there is no *S0*). Starting with *S1* and *S2* ... * Compute their sum: `*sum* = *S1* + *S2*` * Compute their absolute difference (the larger one minus the smaller one): `*diff* = |*S1* - *S2*|` * Swap the two values in *S* at the indices of the sum and difference: `swap(*Ssum*, *Sdiff*)` * Increment the indices of *S* you are working with. So next time you will compute the sum and difference of *S2* and *S3*, and the time after that it will be *S3* and *S4*, etc. * Repeat this process indefinitely. Here are the first few stages of *S* as this process is applied. The brackets `[]` surround the two values that are about to be summed and differenced. Original *S*: ``` [1 2] 3 4 5 6 7 8 9 10 11 12 ... ``` After *S3* (`3 = 1 + 2`) and *S1* (`1 = |1 - 2|`) are swapped: ``` 3 [2 1] 4 5 6 7 8 9 10 11 12 ... ``` After *S3* and *S1* are swapped: ``` 1 2 [3 4] 5 6 7 8 9 10 11 12 ... ``` After *S7* and *S1* are swapped: ``` 7 2 3 [4 5] 6 1 8 9 10 11 12 ... ``` After *S9* and *S1* are swapped: ``` 9 2 3 4 [5 6] 1 8 7 10 11 12 ... ``` After *S11* and *S1* are swapped: ``` 11 2 3 4 5 [6 1] 8 7 10 9 12 ... ``` After *S7* and *S5* are swapped: ``` 11 2 3 4 1 6 [5 8] 7 10 9 12 ... ``` etc. **The SUDSI sequence is defined as the sequence of the first elements in each of these lists.** So the first few terms of the SUDSI sequence are `1 3 1 7 9 11 11`. Here are the first 200 terms of the SUDSI sequence (20 per line): ``` 1 3 1 7 9 11 11 11 15 15 19 19 19 19 19 19 19 19 19 19 19 19 19 19 19 19 19 19 57 59 59 59 59 59 59 59 59 59 77 79 81 83 85 87 89 91 91 91 91 91 91 91 91 91 91 91 91 91 115 115 121 123 125 127 127 127 127 127 137 139 141 143 145 147 147 147 147 147 147 147 147 147 147 147 167 167 167 167 167 167 167 167 167 167 167 167 167 167 167 167 167 167 167 167 209 211 211 211 211 211 221 223 223 223 223 223 223 223 223 223 223 223 243 243 243 243 243 243 257 259 261 263 263 263 263 263 263 263 263 263 263 263 263 263 263 263 263 263 263 263 263 263 263 263 263 263 263 263 263 263 263 263 325 327 329 331 331 331 331 331 331 331 331 331 349 351 351 351 351 351 361 363 363 363 363 363 363 363 363 363 363 363 363 363 363 363 363 363 363 363 ``` It is unclear (to me at least) how one might predict future terms. It only feels safe to say that that the terms are always odd, non-decreasing (after the second term), and that some numbers are repeated lots of times. # Challenge Write a program or function that takes in a positive integer *n* and prints or returns the *n*th term of the SUDSI sequence. For example, if *n* is 1, the output is `1`, if *n* is 2, the output is `3`, if *n* is 200, the output is `363`. Take input in any usual way (stdin/command line/function arg). **The shortest answer [in bytes](https://mothereff.in/byte-counter) wins.** (That site encodes things in UTF-8, but you may use any darn existing encoding you want.) Mathy bonus: (potentially eligible for bounty) * Tell me more about the SUDSI sequence. What's the underlying pattern to what numbers are part of it and how many of them there are (and stuff like that)? (I couldn't find SUDSI on [OEIS](http://oeis.org/search?q=1%2C3%2C1%2C7%2C9%2C11%2C11%2C11%2C15%2C15%2C19&language=english&go=Search) by the way.) [Answer] # Mathematica, 88 bytes ``` Last[f@n_:=n;(r=f@1;{f@a,f@b}={f[b=+##],f[a=Abs[#-#2]]};r)&@@f/@{#,#+1}&/@Range@Input[]] ``` This is a full program, reading the input from a prompt. It's a very direct implementation of the definition, where I'm keeping track of the current sequence in `f` (whose values `f[n]` default to `n`). Here is a slightly more readable version: ``` Last[ f@n_ := n; ( r = f@1; {f@a,f@b} = {f[b=+##],f[a=Abs[#-#2]]}; r ) & @@ f /@ {#,#+1} & /@ Range @ Input[] ] ``` ## Some analysis I've plotted the first 2000 elements of the sequence (it doesn't really get more interesting afterwards): ![enter image description here](https://i.stack.imgur.com/Trf2R.png) So the sequence is essentially linear with slope 2 and always has a few of those steps. It seems that the steps grow sublinearly (if they aren't even bounded), since they become barely noticeable as you increase the number of points you plot. We can justify the linear growth quite easily (this is a bit handwavy, but I think it would hold up to a rigorous proof by induction): initially, the maximum affected number of a permutation step at `n` is `n + (n+1) = 2n + 1`. Also note that these numbers will always be moved to `1`, since `|n - (n+1)| = 1`. So it's not surprising that we get numbers which are approximately `2n` in the sequence. However, we can also note that for steps up to *n*, *Sn+1* is always bounded by *n+1*, which means that no swapping step can swap two numbers which are both greater than *n*. Hence, numbers that still need to be processed will be less than or equal to their initial value. Hence, `2n + 1` is also the bound for the sequence itself. I think finding an argument for the length of the steps will be trickier. [Answer] # Pyth, ~~45~~ ~~41~~ ~~40~~ 38 bytes ``` MXGH_HhugGm@Gtd,s<>GH2.a-@GH@GhHtQr1yQ ``` I noticed (as did Martin Büttner), that the maximum affected number of a permutation step at `k` is `2k + 1`. But since we only have `n - 1`, steps, we only need a list of the numbers up to `2n - 1`. Try it online: [Demonstration](https://pyth.herokuapp.com/?code=MXGH_HhugGm%40Gtd%2Cs%3C%3EGH2.a-%40GH%40GhHtQr1yQ&input=5&debug=0) ``` M define a function g(G, H): return (G is the list of numbers, H is a tuple) XGH_H a translation of G (replaces the elements in H with the elements in reversed H) in this application it swaps two values in the list G implicit: Q = input() u tQr1yQ reduce, G = [1, 2, ..., 2*Q-1] for each H in [0, 1, ..., Q - 2]: G = gG... g(G, ...) h print the first element of the resulting list And the second argument ... of the function call g is: , create the tuple ( s<>GH2 sum(G[H:][:2]), .a-@GH@GhH abs(G[H],G[H+1]) ) m@Gtd and map each value d to G[d - 1] ``` [Answer] # CJam, ~~45 40~~ 39 bytes Just a naive approach. ~~Can be golfed further.~~ Missing a array swap function too much. ``` ri_K*,\{\:L>2<L1$:+:S@:-z:DL=tDSL=t}/1= ``` How it works: ``` ri_ "Read the input, convert to integer and copy it"; K*, "Multiply the copy by 20 and get 0 to 20*input-1 array"; \{ ... }/1= "Swap and put input on stack and run the loop that many"; "times. After the loop, take the second element as"; "we have a 0 based array while series is 1 based"; {\:L>2<L1$:+:S@:-z:DL=tDSL=t} \:L "Swap to put iteration index behind the array"; "and store array in L"; >2< "In each loop, the iteration index will be on stack"; "Get the two elements from the array starting at that"; L1$ "Put the array on stack and copy the tuple"; :+:S "Get the sum and store it in S"; @:-z:D "Get the absolute difference of the tuple and store in D"; L=t "Put the element at S diff at sum index"; DSL=t "Put the element at S sum at diff index"; ``` [Try it online here](http://cjam.aditsu.net/#code=ri_K*%2C%5C%7B%5C%3AL%3E2%3CL1%24%3A%2B%3AS%40%3A-z%3ADL%3DtDSL%3Dt%7D%2F1%3D&input=200) [Answer] # Haskell, 95 bytes ``` f#n=let b=f$n+1;l=f n+b;r=abs$f n-b;y x|x==l=f r|x==r=f l|1<2=f x in y p n=foldl(#)id[1..n-1]$1 ``` Usage example: `p 70` -> `139` I do not store the sequence in a list or array. I repeatedly update the identity function to a function with the two elements of the current step swapped. After `n` steps I call the resulting function with parameter `1`. [Answer] # J, 63 bytes ``` 3 :'{.>((1-~{(+,|@-)]{~1+[)|.@:{`[`]}])&.>/(<"*i.1-y),<>:i.3*y' ``` Usage and tests: ``` f=.3 :'{.>((1-~{(+,|@-)]{~1+[)|.@:{`[`]}])&.>/(<"*i.1-y),<>:i.3*y' f 5 9 f every 1+i.20 1 3 1 7 9 11 11 11 15 15 19 19 19 19 19 19 19 19 19 19 ``` [Try it online here.](http://tryj.tk/) [Answer] # Pyth, ~~55~~ ~~53~~ 51 Can probably be golfed further. ~~Might get really slow for large `n` as I was lazy to figure out how long of an array I'd need and just used a `n^n` one.~~ Thanks to [Volatility](https://codegolf.stackexchange.com/users/7911/volatility) and [Martin Büttner](https://codegolf.stackexchange.com/users/8478/martin-b%c3%bcttner) for pointing out that I can use a maximum of `3n`. ``` KU*3QFNr1QJ@KN=G@tKNAJG,+JG.a-JG=Y@KJ XXKJ@KGGY)@K1 ``` ## Explanation ``` Q = input (implicit) KU*3Q K = range(3 * Q) FNr1Q for N in range(1, Q): J@KN J = K[N] =G@tKN G = K[1:][N] AJG,+JG.a-JG J, G = J + G, abs(J - G) =Y@KJ Y = K[J] XXKJ@KGGY K[J], K[G] = K[G], Y ) @K1 print K[1] ``` [Answer] # Python 2, ~~117~~ ~~106~~ 101 ``` j=input();a=range(3*j) for i in range(1,j):b,c=a[i:i+2];d=abs(b-c);a[b+c],a[d]=a[d],a[b+c] print a[1] ``` ~~Uses a `dict` (map) to save the values to use arbitrary indices. `g(n)` is a function returning the `n`th item. Then just iterates `input-1` times and outputs the first item.~~ It turns out it's shorter using the methods from my Pyth answer. Thanks to [xnor](https://codegolf.stackexchange.com/users/20260/xnor) for saving 5 bytes. [Answer] # Go 150 ``` func f(j int){a:=make([]int,j*2);for i:=range a{a[i]=i};for i:=1;i<j;i++{b,c:=a[i],a[i+1];v:=b-c;if v<0{v*=-1};a[b+c],a[v]=a[v],a[b+c]};println(a[1])} ``` Ungolfed, nothing tricky, mostly stolen from @Pietu1998 ``` func f(j int) { a := make([]int, j*2) // Build the array we will be working on for i := range a { a[i] = i } for i := 1; i < j; i++ { b, c := a[i], a[i+1] v := b - c if v < 0 { v *= -1 } a[b+c], a[v] = a[v], a[b+c] } println(a[1]) } ``` <http://play.golang.org/p/IWkT0c4Ev5> [Answer] # Java, 162 ``` int f(int n){int a[]=new int[2*n],s,d,x,t;for(x=0;x<2*n;)a[x]=++x;for(x=0;++x<n;){s=a[x]+a[x-1]-1;d=Math.abs(a[x]-a[x-1])-1;t=a[s];a[s]=a[d];a[d]=t;}return a[0];} ``` ## Explanation ``` int f(int n) { int a[] = new int[2 * n], sum, diff, x, temp; for (x = 0; x < 2 * n;) { a[x] = ++x; // set initial array } for (x = 0; ++x < n;) { sum = a[x] + a[x - 1] - 1; diff = Math.abs(a[x] - a[x - 1]) - 1; temp = a[sum]; a[sum] = a[diff]; a[diff] = temp; } return a[0]; } ``` [Answer] # dc, ~~134~~ ~~132~~ 131 bytes ``` [_1*]sOdsn2*ddslsSsa[ladd:S1-dsa0<P]dsPx1d0rsN:N[la1+dsad;SdS@r1+;SdS@rL@L@r+Ss-d0>Od;SrLsdSsrLs;Sr:S:S1;SladsN:Nlaln>G]dsGxln1-;Nf ``` Use `echo $n $code | dc`, where `$n` is *n* and `$code` is...the code (*gasp*). Quote to taste. Edit: Unless you pester me for an explanation, I will never get around to it. [Answer] # Perl 5, 131 A naive solution (i.e. a direct implementation of the definition). A subroutine, it takes input as a list of `1`s of the desired length. ``` {map$a[$_]=$_,1..3*@_;($a[$a[$_-1]+$a[$_]],$a[abs($a[$_-1]-$a[$_])])=($a[abs($a[$_-1]-$a[$_])],$a[$a[$_-1]+$a[$_]])for 2..@_;$a[1]} ``` Visualize its output by e.g. `print sub...->(1,1,1,1,1)`. Explanation: `map$a[$_]=$_,1..3*@_` builds the array `@a`, indexing each integer by itself from 1 to 3 times the size of `@_` (the input). `($a[$a[$_-1]+$a[$_]],$a[abs($a[$_-1]-$a[$_])])=($a[abs($a[$_-1]-$a[$_])],$a[$a[$_-1]+$a[$_]])for 2..@_` repeats the switcheroo repeatedly (one fewer times than the size of `@_`), switching `$a[$a[$_-1]+$a[$_]]` with `$a[abs($a[$_-1]-$a[$_])]` as `$_` ranges from 2 to the size of `@_`. And then the subroutine returns `$a[1]`. [Answer] # [Perl 5](https://www.perl.org/), 90 + 1 (-p) = 91 bytes ``` @a=0..3*$_;$_=(map{@a[$d,$s]=@a[$s=$a[$_]+$a[$_-1],$d=abs$a[$_]-$a[$_-1]];$a[1]}1..$_)[-1] ``` [Try it online!](https://tio.run/##K0gtyjH9/98h0dZAT89YSyXeWiXeViM3saDaITFaJUVHpTjWFsQqtlUBkvGx2mBK1zBWRyXFNjGpGCKqCxONtQayDGNrDfX0VOI1o4Ei//8bchlxGXOZcJlyGRkY/MsvKMnMzyv@r1uQAwA "Perl 5 – Try It Online") ]
[Question] [ ## Background *Inspired by [this video](https://www.youtube.com/watch?v=s9-b-QJZdVA) by Matt Parker* A [Faro shuffle](https://en.wikipedia.org/wiki/Faro_shuffle) is a perfect riffle shuffle where the deck is exactly interleaved with its other half. This is how to perform one: * the deck of 52 cards is split into two piles of 26 cards each * the two piles are interleaved. In the case of an "in" shuffle, the bottom card of the top pile ends up on the bottom, and the top card of the bottom pile ends up on the top (the outer cards move inwards). In the case of an "out" shuffle, the top card of the top pile ends up on top and vice versa (the outer cards stay on the outside). For example, with a demonstration deck of only 6 cards, the steps are as follows: * Start: `[1, 2, 3, 4, 5, 6]` * Split: `[1, 2, 3] [4, 5, 6]` * For an "in" shuffle, interleave like this: `[4, 1, 5, 2, 6, 3]` (zip the second half with the first half) * For an "out" shuffle, interleave like this: `[1, 4, 2, 5, 3, 6]` (zip the first half with the second half) ## Challenge Given a list of values representing "in" and "out" Faro Shuffles, determine the minimum number of times that list needs to repeat such that a deck of 52 distinct cards will return to its starting arrangement. *Note that this is not the same value shown in Matt's video; it is divided by the length of the input*. If the deck returns to the starting arrangement part way through the list (for example, `[0, 0, 0, 0, 0, 0]` (6 out shuffles) would finish after 1 full set of 6 and then 2 more shuffles), it doesn't count as having finished the cycle because it wasn't completed at the end of the list (so the output for that example would be `LCM(6, 8) / 6 = 4`). ## Example Input: `[0, 1, 1, 0, 1, 1, 1]` (using `0` for "out" shuffles and `1` for "in" shuffles, and representing the starting deck is `[0, 1, 2, 3, ... 48, 49, 50, 51]`) * First, we perform the shuffles as they are specified in the input: out, in, in, out, in, in, in. This gives the output: ``` [0, 26, 1, 27, 2, 28, 3, 29, 4, 30, 5, 31, 6, 32, 7, 33, 8, 34, 9, 35, 10, 36, 11, 37, 12, 38, 13, 39, 14, 40, 15, 41, 16, 42, 17, 43, 18, 44, 19, 45, 20, 46, 21, 47, 22, 48, 23, 49, 24, 50, 25, 51] ``` * Now, we check if that has caused the list to return to its exact original arrangement * Repeat these steps, and output the number of times we've looped. In this case, it takes 1260 repetitions of `[0, 1, 1, 0, 1, 1, 1]`, so our output is 1260 ## Test cases Using `0` for "out" shuffles and `1` for "in" shuffles. ``` [0] 8 [1] 52 [0, 1] 252 [0, 0, 1] 20 [0, 1, 0] 20 [1, 0, 0] 20 [0, 1, 1, 0, 1, 1, 1] 1260 [0, 0, 0, 0, 0, 0, 0, 1] 2 [0, 0, 0, 0, 0, 0] 4 [0, 0, 0, 0, 0, 0, 0, 0, 0] 8 [0, 0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 0, 1] 144 [1, 0, 1, 1, 1, 0, 1, 1, 1] 60 [0, 1, 1, 0] 44 [1, 1, 1, 1, 0, 1, 0, 1, 0] 306 [1, 1, 0, 1, 1, 0, 0, 1, 1, 0] 210 [1, 0, 0, 0, 0, 0, 0, 1] 2 [0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1] 168 [1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 1] 228 [1, 0, 1, 0, 1] 60 [1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 0, 0, 0, 1, 1] 66 [0, 0, 0, 0, 1, 0] 252 ``` ## Rules * The values that represent "in" and "out" in the input list can be any two distinct values, within reason. For example, `0` and `1` is allowed, but `code_to_do_an_in_shuffle()` and `code_to_do_an_out_shuffle()` are not * [Standard loopholes](https://codegolf.meta.stackexchange.com/q/1061) are forbidden * You may use [any sensible I/O method](https://codegolf.meta.stackexchange.com/q/2447) * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins [Answer] # [Pyth](https://github.com/isaacg1/pyth), ~~63~~ 53 bytes ``` J26AcU*J2JW=Y?@Q%ZlQ.iHG.iGH=+Z1AcYJI&qYSY!%ZlQB;/ZlQ ``` [Try it online!](https://tio.run/##K6gsyfj/38vIzDE5VMvLyCvcNtLeIVA1KidQL9PDXS/T3cNWO8rQMTnSy1OtMDI4UhEk5WStDyT//4821FEw0FGAkJjIEIYMkJQZxgIA "Pyth – Try It Online") ``` J26 # Set J to 26. AcU*J2J # Assign G and H to range(0, 26) and range(26, 52) respectively. W # While ?@Q%ZlK # If the current element of Q (input list) .iHG # is 1, then interleave H and G .iGH # Otherwise, interleave G and H =Y # Assign that value to Y =+Z1 # Increment Z by 1 AcYJ # Now reassign G and H to the first and last 26 elements of Y respectively I&qYSY!%ZlQB # If Y is already sorted and we are at the end of input list, then break ;/ZlQ # Print Z divided by length of input list ``` [Answer] # [J](http://jsoftware.com/), 45 40 36 bytes ``` 3 :'*./#&>C.{/|.y{(,:&,&|:|.)i.2 26' ``` [Try it online!](https://tio.run/##lVLNDoIwDL7zFI0m/Jg51oELWYIXEk@efAUjUS@eDbw7QhikK3Aw6Q79@rVf2/Xd7WRUQ2khAgEKbP@OEqrb9dJlYKODTPfhuZJN2spvEwsbirC1rUxeUoM2UZcEj/vzAzWgGEwRmxEaQkYIxvwCyr6GsGp0T9r5OPraAfGQ5SS1mqF1dJBiqFN3KGrjsWm3cz0qwmziYJ4zFvo7QFreJRmvJdxsgNRGb6ZMmbkCS2fDo6LE5YdQrrenjXFNsVwKCn4BXGRS0AUbfH23a2ezuTsaM2zY/@4xWR6c96tJ9wM "J – Try It Online") -4 thanks to xash Rather than use a while loop, the solution constructs the permutation, changes it to cyclic form `C.`, and then takes the LCM `*./` of the cycle lengths. [Answer] # [Python 3.8](https://docs.python.org/3.8/), ~~88~~ 84 bytes ``` *r,=range(52) f=lambda k,s=r:[s:=s[x::2]+s[1-x::2]for x in k[::-1]]!=s==r or-~f(k,s) ``` [Try it online!](https://tio.run/##hVJBboMwEDyXV2w5mQYqmxCELLmv6M3ywTSmQaGADGnppV@nBhNKQqJKe5jdmR3vIOrv9lCV26TWff@kfaZl@a7QLvScjBXyI91LOPoN05Q3lDW8ozQUm4aTYERZpaGDvIQjpzQgQjyyhjENlQ5@MmQWvf7rkBcKXvVJUedB@pACMwv1qUXec1MXeYtcAa5nOEOoT1kgCRtwxTCy2halBtd6QMbADV5cHzIkPYNVV6u3Vu3NJPV6jgUkDicCdqHDsQ8GhROcOmznprcNGRk8M@sattaUgOiO3rLJgiULsCxrTqLofMYFY0tAPJ9sr57kV9o51BbHZx4vJEuHkPwF/y8rufS4YWkSxMkiwe2PuNqbXguvVqfAZGV1LxK@vCWOV/fj8Sf4BQ "Python 3.8 (pre-release) – Try It Online") Uses [@l4m2](https://codegolf.stackexchange.com/users/76323/l4m2)'s neat idea (on [@hyper-neutrino's answer](https://codegolf.stackexchange.com/a/224987/101474)) to reverse the shuffles instead of execute them forwards. -4 bytes thanks to [@dingledooper](https://codegolf.stackexchange.com/users/88546/dingledooper) [Answer] # [Python 2](https://docs.python.org/2/), 100 bytes ``` def f(k): s=t=range(52);q=1 while 1: for x in k[::-1]:s=s[x::2]+s[1-x::2] if s==t:return q q+=1 ``` [Try it online!](https://tio.run/##hVJBbsIwEDzjV6xySkSovC5EyJX7it4iqwrFKREoBMcU@vp0waE1BFTJh9md3fGM5ebbrba16LqlKaGM14lk0CqnbFF/mngmkpedQgaHVbUxgJKNyq2FI1Q1rHMpJ6hlq9r8KKXQ4zbHyRmxUVWSinLSGre3NezYaDdW2HmZN7s3pFSksAAFtji8V3Wzd3Hy1DabysWRhighnkjzVWziAsYQ6VPrNF/VLl4QbiwhIJFo8hql5L1ICJtjYz6cWVJn0eVcw5zlqGEmWM5TICR62Ffc96n2BZ4ZHjK@5QGtoMj4ReHmnASHlIbpg3nPzgMWAxAeL47T6cUh3rOWXXmme/34zexv3meeXfgwaagg8O9N/suK1xp3JClBNg8S3H/EwV5/m7hZ7QPjQOpRJH7tJcsG/vn5f/wA "Python 2 – Try It Online") -10 bytes thanks to pxeger -4 bytes thanks to Neil -11 bytes thanks to l4m2 -6 bytes thanks to dingledooper [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~47~~ 35 bytes ``` W¬⁼ω⁺αβ«⊞υωF⮌θ≔⭆²Φ∨ω⁺αβ﹪⁺κ⁺λξ²ω»ILυ ``` [Try it online!](https://tio.run/##XU49D4JAFJvhV7zxkTwTZWUyRidRoiNhOPEE4gsn9wEmxt9@HsbJDh3apm3dCl0rwd5PbccS8KAsbgcn2OBEULAzKAguSQC84qhwpkVHMCVZHN2UBjzJUWojcQiBtTFd0@PZ6q5vcvHAlGDXsZUaj/qvjyBXV8cKv9r95zHBc/bSmeaRd1yEMosbYSzuZd/YsB/OZN6X5ZJgRfDjqvKLkT8 "Charcoal – Try It Online") Link is to verbose version of code. Edit: Saved 12 bytes thanks to @l4m2 by performing in-sorts and out-sorts instead, but the input values are now `0` for an in-shuffle and `1` for an out-shuffle. Explanation: ``` W¬⁼ω⁺αβ« ``` Repeat until the shuffle reaches the initial pack, represented here by the concatenation of the upper and lower case letters. ``` ⊞υω ``` Keep track of the number of cycles. ``` F⮌θ ``` Loop over each type of shuffle in reverse, since we're performing inverse shuffles. ``` ≔⭆²Φ∨ω⁺αβ﹪⁺κ⁺λξ²ω ``` Take alternating cards from the pack (initialising it on the first pass). Whether odd or even cards are taken first depends on the type of shuffle. The remaining cards are then concatenated, completing the in-sort or out-sort. ``` »ILυ ``` Output the number of shuffles needed. [Answer] # [Ruby](https://www.ruby-lang.org/), ~~86 80~~ 77 bytes ``` ->s{r=k=[*0..51];1.step.find{s.map{|c|r=k.map{|v|r[(v/2+26*v+=c)%52]}};r==k}} ``` [Try it online!](https://tio.run/##bcxPC4IwHMbxe6/CS7A/tdzAXeTXi/A6djBTEMnGtEHNvfY1Cw9Btw88D1/7uDxjB/F4nryFARTJGSu4Ljmb5tawrh@vfmK32vilWdLjS7dYhdxJUCGJo9DgfSF0CKUFGEKIJuuUyrXefcA35IeVydVWQchhIiRNqTURfjdO/6yv3qCK2ftcz20mJE5VIXV8Aw "Ruby – Try It Online") [Answer] # [Husk](https://github.com/barbuz/Husk), 13 bytes ``` Γ€GFöΣT*½ḣ52∞ ``` [Try it online!](https://tio.run/##ASMA3P9odXNr///Ok@KCrEdGw7bOo1Qqwr3huKM1MuKInv///1sxXQ "Husk – Try It Online") or [Verify all tests](https://tio.run/##yygtzv4fkqsREqKuoAmkDy1PLdbQVlJ41DZJQan4UVOjpmZu0aFt/89NftS0xt3t8LZzi0O0Du19uGOxqdGjjnn///@PNozlitYFEYY6UArO0AWywbI6EAZYRBeiAIKg6hEQXQhDAbKYLpxCRlBDUOxBt1IX2XGoitBkEHJounC6WhdZC4Z2JJehm4GqFEOxLrKjUM1G04hsGRLfMBYA "Husk – Try It Online") [15 bytes](https://tio.run/##ASMA3P9odXNr//9Wzps8dEdGw7bOo1Qqwr3huKM1MuKInv///1sxXQ "Husk – Try It Online"), [16 bytes](https://tio.run/##ASMA3P9odXNr//9WUz1PdEdGw7bOo1Qqwr3huKM1MuKInv///1sxXQ "Husk – Try It Online"), [16 bytes](https://tio.run/##yygtzv7//1HTmkdNjSXuboe3nVsconVoL5D3qGMe18Mdi02N/v//H20YCwA "Husk – Try It Online") input taken as `1` instead of `0` and `-1` instead of `1`. -2 bytes from Leo. This could be another [15 bytes,](https://tio.run/##ASQA2/9odXNr//9T4oKsb3RHRsO2zqNUKsK94bijNTLiiJ7///9bMV0 "Husk – Try It Online") but times out. ## Explanation ``` Γ€GFöΣT*½ḣ52∞ ∞ infinite list of repetitions of the input G scan from left with: ḣ52 1..52 as the start value Fö fold the repeated list with the current value as start and do the following: ½ split in two halves * multiply by the list number T transpose Σ flatten Γ take first element and: € find its index in the remaining list ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~102~~ ~~99~~ ~~98~~ 95 bytes ``` f=s=>s.map(v=>L=L.map((_,i)=>L[i+52*(i%2^v)>>1]))|L+[]==G||1+f(s);L=G=[...Array(52)].map(Array) ``` [Try it online!](https://tio.run/##hVJBT4MwGL37K7gY2oFdWzdCXIrx4i7cPHbVdFAWDMKEjWRx/nbsKFM2tpj08L6@73vfe03fZS2rqEzXm7u8iFXTJKxiQYU@5BrULAhZ2ELw5qZQlzx1pnQE0lv6WsMgIALCfehwwdh8vydOAio4C9mccYTQU1nKHZhSKFqJtoRNVORVkSmUFStQqs9tWipgJ5UNUalk/Jxm6mWXRwC7XyqPijjNVw/2dpP49vehY53JSIExWHA0elwIaIFF7MDxytUGpbvUFoFkCVC1zICE0OWSseWB0UbhrOFYWP4NJ8Ka0huOXUsj2sGuwuZe16YgLYP7jLkyQI8Q6uGjwtk5CA4pYU2u9BvW77GkB/rHiJPJ5OiQXLLmnXjWe037We9v3nvsHfl@0r4CJX9v8l9WcqpxQVIn8PxegsuPOJjrttGz0S4wGUhdi4RPvXjewD9u/8cP "JavaScript (Node.js) – Try It Online") [Answer] # [Wolfram Language](https://www.wolfram.com/language/), 97 bytes ``` s|->Length@NestWhileList[Fold[Riffle@@#~TakeDrop~26~RotateLeft~#2&,#,s]&,Range[52],UnsameQ,All]-1 ``` [Try it online!](https://tio.run/##PYpBCsIwFET3nkIIdJWCKehOqSCuimhVXIQsPvWnDaapNH9XmkN4A0/oEWpRFGbevMXUQBXWQKaAQS8H/3o8M3QlVekOPV0qYzEznuS2sVeZG60tpikLJ7jhpm3uIVmEvCEgzFBTYEnEGfcq4jm4EuU8UfzsPNR44GtrVSyGYwFO7lvjSLJ4pSVT43vSdbOed2LsjH/526n45C@i79XwBg "Wolfram Language (Mathematica) – Try It Online") (uses [\[Function]](http://reference.wolfram.com/language/ref/character/Function.html) rather than `|->`, as TIO doesn't have the most recent version of the language) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 15 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ØẠŒHṚ⁹¡ż/Fʋƒ@ƬL ``` A monadic Link accepting a list of `1`s (in) and `0`s (outs) which yields a positive integer (number of repetitions of the described procedure required to reset the deck of 52 cards). **[Try it online!](https://tio.run/##y0rNyan8///wjIe7Fhyd5PFw56xHjTsPLTy6R9/tVPexSQ7H1vj8//8/2lBHAYgMkBBcBFnKEE1BLAA "Jelly – Try It Online")** ### How? Just repeatedly executes the instructions list until reset has occured... ``` ØẠŒHṚ⁹¡ż/Fʋƒ@ƬL - Link: list, shuffles ØẠ - "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" ...26*2=52 :) Ƭ - collect up starting with that "deck" until a repetition occurs using: @ - with reversed arguments - f(shuffles,deck) ƒ - reduce using (X) as the initial value with: ʋ - last four links as a dyad - f(current_deck, current_shuffle): ŒH - split (current_deck) into two halves ¡ - repeat... ⁹ - ...number of times: right argument = current_shuffle Ṛ - ...action: reverse / - reduce using: ż - zip together F - flatten L - length ``` [Answer] # [R](https://www.r-project.org/), 80 bytes ``` o=scan();e=d=0:51;while({for(s in o)d=t(matrix(d,26,3)[,1:2+s]);sd(d-e)})T=T+1;T ``` [Try it online!](https://tio.run/##rVRda8IwFH3Pr7jgS4Id5EYNYsm/KOxhjFHaZJZpIkllA/G3d7JWrF@YDmkoeTjn3HPvPcQ3jVOhyC1lqVal4osZpt/LaqXpzjhPA1QWHCtVTdd57asfWiZCJhP2luBCjMM7S0NJyxfN9ixT2RjTrOGAh6/9IyF@TTNGRuB1qU1lNeQBzNYWdeUs1A6KpS6@oNahhiIPOiyIyb37CMutMSutjCJHNHVsR57kkuwJCdvNxusQXnNvK/sZaL8wLShnjMEI5g@B2AJn4rFkAh1YxKF7BB6lfqBE4/FPnw/Ub1ntpfOGQvLIbi7OsbnB7JY3/V/Vk8A8XgB7l/45dYHTaeTM8d4k5ZAtdDOIKnpR8SwqEy4jJfoJuPQhMDpxT8gAnju5YazbiZzH7@R2RK@ke57FMPX4LeOVoXsb4NdNSzl0lvz0KjW/ "R – Try It Online") Implements riffle shuffle by re-arranging the deck into a matrix with 26 rows, and transposing. An 'in' shuffle first reverses the columns, which is achieved in [R](https://www.r-project.org/) by making a 3-column matrix (which gets filled by recycling elements), and then selecting columns 2,3. ``` e=d=0:51 # set e,d to the initial order of the deck while({ # while loop: for(s in o) # first cycle through the shuffle-types in o d= # reordering d each time t( # as the transpose of matrix(d,26, # a matrix with 26 rows 3) # and 3 columns (so the third column is the first one again) [,1:2+s]) # selecting columns 1:2 if o==0, # or columns 2:3 (same as 2:1) if o==1; sd(d-e)} # then repeat until standard deviation of d-e is non-zero # (d & e are both permutations of the deck, # so sum(d-e) must be zero, and sd(d-e) can only ) # be zero if d==e) T=T+1 # increment T (from initial value of 1) each loop T # and finally output the value of T ``` [Answer] # PowerShell 7, 87 84 bytes ``` for(;"$c"-ne0..51;$x++){$args|%{$s=$_ $c=$c ??0..51|%{(2*$_+($s,!$s)[$_/51])%52}}}$x ``` [Try it online!](https://tio.run/##hVHbaoNAEH33K@wyadx6qQqWgiwIoYW@tKXJWwhizKZJMDF1lQSs325310t9kSyKO@fMnDMzntMLzdiOJkkNW1LWEBPbsjxH2aQlRNk3@52UwAiECmcg5pHmPkCoa8CMO2B4CeGj56zwxHOrSoGrrleX3T6hGoIYmScqxTBca07mlOWziFGmEjXQFJWfoJQfcfanc5GLiyBt3OP0eqZxTjcSf27wyhgrdEYKPfdWpW2ojnz6y5iW4z7ZN/swbEO@Ixq9goIVWPDFMBJoeLAjsXcRvBfHNc2IUzVGIF0M6MT4n7FaKLQ6sMnMKCuSnLtp97BVA5mFByLzPBNkE3A7tAQNQvOQ7k/IUBFeoQrLSBVhU8iKOKaMEdSqI5P@oL6ZNkmOo5Pl53xWsDw9fqwPnF4F5VQwUzKYS9f9eSvZaftvoh/u0DWJ/C/p9W/qv3TTD7wrpWo3@fuaZscoNxfROqH1Hw "PowerShell – Try It Online") (Link is to a TIO-compatible version with 4 additional bytes; PowerShell 6 and below do not support the null-coalescing operator `??`) [Answer] # [Python 3](https://docs.python.org/3/), 136 bytes -5 thanks to OP Can definitely be golfed more, but I'm too tired. ``` def f(s): o=l=[*range(52)];c=0 while 1: for i in s:l=[(l[:26],l[26:])[j%2-i][j//2]for j in range(52)] c+=1 if l==o:return c ``` [Try it online!](https://tio.run/##RczNDsIgEATge59iLybgT9pi7AGzT0L2YBDsNgQaijE@PdKTpznMN7N@y5zitdan8@DFJnUHCQOaY37ElxM3JelucejgM3NwMLYefMrAwBE23aQIRquJzsGoSZM0y0FdmMzS94p2uezy/9b29oRjC/YQEJPOrrxzBFvXzLEIL8xAUtYf) [Answer] # [Haskell](https://www.haskell.org/), 91 bytes ``` f l=[r|r<-[1..],and[foldl(\x i->mod(2*x+mod(div x 26+i)2)52)y([1..r]>>l)==y|y<-[0..51]]]!!0 ``` [Try it online!](https://tio.run/##hVLtaoMwFP3vU9yWQs38WJK1oTDjE@wNXH4I2i0s1WJlKPTdXWx0i9UyCOTenHtOzgn5TC9fuVJddwTFk@paRUFCwlD4aZElx1Jlyn1vQAbxqcxc@tR4/Z7Jb2iAMk8iivYUtW7PqUQcK8R5e221CA7DPRFCrFa4O6Wy4FnpgCv9EkXB5ZwW7jPfii2KNvFHXr/JIndA5TU0vMrTbCM9by3Wr63p6lQq0PRzJYvaPeoh3vqN3yIHeukuwQIOTkIE7KmTYB90RYdy6LA5171pyA3BNmKOTKEphDI8KtytXnAOCdg9mDfowUKJVdjLiJPdbnRIlqyxiWd9rxm/m/3N@4LZiNtJbQVK/t7kv6xkqrEgqROwg5Vg@RFnvOE2ekcdApOZ1KNIeOqFsZl/fPsfPw "Haskell – Try It Online") `f` takes `l` as a list of `0`s and `1`s, with the format described in the statement. [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~194~~ \$\cdots\$ ~~180~~ 174 bytes Saved 6 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!! ``` w=52;n;c;i;j;a[156];f(s,l)int*s;{for(c=i=0;i<w*3;)a[n=i++]=i%w;for(;n;++c)for(j=0;j<l;++j)for(i=!wmemcpy(a+w,a,w);i<w;n=wmemcmp(a,a+2*w,w))a[i++]=a[w+(s[j]+i&1)*26+i/2];n=c;} ``` [Try it online!](https://tio.run/##hVZhk5owEP3ur0idsQPCzbFBUBtpP3T6KzymwyDexaLniC22jn@9dkmikpW7MpBN8nbfLo8AyR@e8/x8rpOIi43IhRQrkc0hilOxdCq/dOVmP6zEcfm6c/JEJoGQs3oYCjebbxLpeWkiB7VoUAz3vNxtuit0W81KHK/UWCYf6nWxzre/ncyr/cyv3YZGbBI1vd46mZ95fFgjgMSKNpvXnlPNV6knP4I75LEnH3mKIbk4nX@9ygXb7rA2p6kv87Flpds79hgemJI180yyhAUCzYyVgnmedBXeHCp46fQH1WDR95n8gk3/Ux9bzJ@6onfqNQzrTG6cC28zsS@qfTBPkfgYnIQ1DXoayDQ33j6jSHhFOsDRLQxxAkYmlYqkYNyO1C66Q1OM2/nJSX0n3b7Ea/oOY4c7BMQfWp322VEQQFsD@O/NAqeyUIfwSkjYup8BjNr@bbXfTmE/t/cVh/heTLCzdCSlJGOiUvfDvuPpqmdyT3XnMyWa3Nd5n@jN4nnQqUBL1aHyq7SbejV9XYc2XJtQm5E2kTaxNmNtJtpMTfiFxvCAIQLDBIYKDBcYMjBsYOjA8HG6EL6XuuRK/ilel46q3H00o6Ee@qyFgo2CjXIb5TYa2mhooyMbHdloZKORjcY2Gtvo2EbHNjqx0YmNTm10StQgYgFVi8pF9AIiGBDFgEgGRDMgogFRDYhsQHQDIhwQ5YBIB0Q7IOIBUQ@IfED040Q/HLcWaHHIt0W@LxZ6jeJajnD9c9UEtwt43PR8hi8D@sAIbTPT2DDAN4KDxiFGmPOJhuNYcZl8@Uu2G2Jb5D@KHeZjTcb@0@EbfzpMv@IVNf/l1jjsm8jbT36zKA7mR6@6s8utXm/kdre3KbUfaPxddrzuCtQnpXr5uVyWRYWc@uui3FLR9mKlQfFN7oJ3COP@yTD5uDcR9tbjDUzpj7G3Z0DZLxsX9vCZDRZsUD1tUKKdfxWxSJJdaihPvdP5b74ss@fq/FD/Aw "C (gcc) – Try It Online") Inputs a pointer to the shuffle array and its length (since pointers in C carry no length info). ### Explanation (before some golfs) ``` w=52;n;c;i;j; // declare needed vars f(s,l)int*s;{ // main function char a[w],b[w],e[w]; // declare arrays for shuffling for(c=i=0;i<w;)a[i++]=e[i]=i; // init a and e to 0..51 for(n=1;n;++c) // loop until array a is back // to its original order (n == 0) // c counts iterations for(j=0;j<l;++j) // loop over shuffle array for(i=!memcpy(b,a,w); // copy a over to b (returns !0) i<w; // loop over a and b n=memcmp(a,e,w)) // here's a good place to calc n a[i++]= // set each element in a to b[ ]// an element in b depending on ((s[j]+i)%2)*26+i/2 // our current shuffle and i n=c; // return count } ``` ]
[Question] [ You will be given a square matrix of integers **M** and another positive integer **n**, strictly smaller than the size of **M**. Your task is to generate all square sub-matrices of **M** of size **n**. For the purposes of this challenge, a *square sub-matrix* is a group of **adjacent** rows and columns contained in **M**. ## Input / Output Formats You are free to choose any other reasonable formats, these are just some examples. **Input** * A matrix in the native matrix type (if your language has one) * A 2D array (an array of 1D arrays, each corresponding to one row / one column) * A 1D array (since the matrix is always square) * A string (you chose the spacing, but please do not abuse this in any way), etc. **Output** * A matrix of matrices. * A 4D array, where each element (3D list) represents the sub-matrices on a row/column. * A 3D array, where each element (2D list) represents a sub-matrix. * A string representation of the resulting sub-matrices, etc. ## Specs * You may choose to take the *size* of **M** as input too. It is guaranteed to be at least **2**. * The orientation of the output is arbitrary: you may choose to output the sub-matrices as lists of columns or lists of rows, but your choice must be consistent. * You can compete in any [programming language](https://codegolf.meta.stackexchange.com/a/2073/59487) and can take input and provide output through any [standard method](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods), while taking note that [these loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden by default. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest submission (in bytes) for *every language* wins. ## Example Given **n = 3** and **M**: ``` 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 ``` The possible **3x3** submatrices are: ``` +-------+ +--------+ 1 2 3 4 1 2 3 4 |1 2 3| 4 1| 2 3 4 | +--------+ +--------+ |5 6 7| 8 5| 6 7 8 | |5 6 7|8 5| 6 7 8| |9 10 11|12 9|10 11 12| |9 10 11|12 9|10 11 12| +-------+ +--------+ |13 14 15|16 13|14 15 16| 13 14 15 16 13 14 15 16 +--------+ +--------+ ``` So the result would be: ``` [[[1, 2, 3], [5, 6, 7], [9, 10, 11]], [[2, 3, 4], [6, 7, 8], [10, 11, 12]], [[5, 6, 7], [9, 10, 11], [13, 14, 15]], [[6, 7, 8], [10, 11, 12], [14, 15, 16]]] ``` As noted above, an output of: ``` [[[1, 5, 9], [2, 6, 10], [3, 7, 11]], [[2, 6, 10], [3, 7, 11], [4, 8, 12]], [[5, 9, 13], [6, 10, 14], [7, 11, 15]], [[6, 10, 14], [7, 11, 15], [8, 12, 16]]] ``` would also be acceptable, if you choose to return the sub-matrices as lists of rows instead. ## Test cases The inputs **M, n**: ``` [[1,2,3],[5,6,7],[9,10,11]], 1 [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]], 3 [[100,-3,4,6],[12,11,14,8],[0,0,9,3],[34,289,-18,3]], 2 [[100,-3,4,6],[12,11,14,8],[9,10,11,12],[13,14,15,16]], 3 ``` And the corresponding outputs (sub-matrices given as lists of rows): ``` [[[1]],[[2]],[[3]],[[5]],[[6]],[[7]],[[9]],[[10]],[[11]]] [[[1,2,3],[5,6,7],[9,10,11]],[[2,3,4],[6,7,8],[10,11,12]],[[5,6,7],[9,10,11],[13,14,15]],[[6,7,8],[10,11,12],[14,15,16]]] [[[100,-3],[12,11]],[[-3,4],[11,14]],[[4,6],[14,8]],[[12,11],[0,0]],[[11,14],[0,9]],[[14,8],[9,3]],[[0,0],[34,289]],[[0,9],[289,-18]],[[9,3],[-18,3]]] [[[100,-3,4],[12,11,14],[9,10,11]],[[-3,4,6],[11,14,8],[10,11,12]],[[12,11,14],[9,10,11],[13,14,15]],[[11,14,8],[10,11,12],[14,15,16]]] ``` Or, as lists of columns: ``` [[[1]],[[2]],[[3]],[[5]],[[6]],[[7]],[[9]],[[10]],[[11]]] [[[1,5,9],[2,6,10],[3,7,11]],[[2,6,10],[3,7,11],[4,8,12]],[[5,9,13],[6,10,14],[7,11,15]],[[6,10,14],[7,11,15],[8,12,16]]] [[[100,12],[-3,11]],[[-3,11],[4,14]],[[4,14],[6,8]],[[12,0],[11,0]],[[11,0],[14,9]],[[14,9],[8,3]],[[0,34],[0,289]],[[0,289],[9,-18]],[[9,-18],[3,3]]] [[[100,12,9],[-3,11,10],[4,14,11]],[[-3,11,10],[4,14,11],[6,8,12]],[[12,9,13],[11,10,14],[14,11,15]],[[11,10,14],[14,11,15],[8,12,16]]]] ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 8 bytes ``` 2FεŒsù}ø ``` [Try it online!](https://tio.run/##Fcu7CcMwFEbh3rOcC/6vJD8WyBJChQ2ZIHWWyC4GpzZps5IslQe@M6Zt17NWf/yP3@d1fd/XWWvOwpxAJBXyhM0s2IrGlhJyTAFF1IFpQjNa0NrGjly446FlxFMpQ7gB "05AB1E – Try It Online") **Explanation** ``` 2F # 2 times do: ε } # apply to each element in the input matrix (initially rows) Œsù # get a list of sublists of size input_2 ø # transpose (handling columns on the second pass of the loop) ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 4 bytes ``` thYC ``` Inputs are `n`, then `M`. The output is a matrix, where each column contains all the columns of a submatrix. [Try it online!](https://tio.run/##BcGxDYAwDEXBnineCPw4DiCXTIGiFHQU0GV/c/fd882cz3Vm2tJFwaiB09jYgwOtSKgEMlSRozZ@) ### Explanation ``` thY % Address the compiler with a formal, slightly old-fashioned determiner C % Convert input to ouput ``` More seriously, `t` takes input **n** implictly and duplicates it on the stack. `h` concatenates both copies of **n**, producing the array **[n, n]**. `YC` takes input **M** implicitly, extracts all its **[n, n]**-size blocks, and arranges them as columns in column-major order. This means that the columns of each block are stacked vertically to form a single column. [Answer] # [R](https://www.r-project.org/), 75 bytes ``` function(M,N,S,W=1:N,g=N:S-N)for(i in g)for(j in g)print(M[i+W,j+W,drop=F]) ``` [Try it online!](https://tio.run/##VY3BCoJAGITvPYXHlUbwdzfTJa/d9GLgITqUsbJCqyxG9fTbWlDIMDAw3zDWqWAXBU7dTTvpwbASFWo0BckKXVHJOqpCNVimA22C7hP7bxytNhMrj3rdoPe@2mEs9qfQKXY7T1Y/GUlKIbwuLzs8ikMIDhGufn3rCY6N3CKXRHPL/yiBL9E4RuT3SEEJiEACGWKvfB4KJFmOiDI/W34m/tO9AQ "R – Try It Online") Takes `M`, `N`, and the `S`ize of the matrix. Prints the resultant matrices to stdout; `drop=F` is needed so the in the `N=1` case the indexing doesn't drop the `dim` attribute and yields a `matrix` rather than a `vector`. [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 26 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set") Anonymous infix lambda taking **n** as left argument and **M** as right argument. ``` {s↓(-s←2⍴⌈¯1+⍺÷2)↓⊢⌺⍺ ⍺⊢⍵} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24Tq4kdtkzV0geQEo0e9Wx71dBxab6j9qHfX4e1GmkCpR12LHvXsAvIVgBjE6d1a@98zr6C0BKjjUdvER31TvYL9/bj8S0ugYhCBRx0zQLqBCMz4D5FXMFRIUwDrVlCPjjbUMdIxjtWJNtEx1TED0uY6FjqWsbHqUMMUjDEU65gAlQEV6wCVAlmWOoYGOoaGOoZGQI6hsY6hiY6hqY6hGZIZRihmGBjo6AINAdtmaATWagI2yUDHQMcS7BhjEx0jC0sdXUMLIBeXW3Cag8dFAA "APL (Dyalog Unicode) – Try It Online") `{`…`}` anonymous lambda where `⍺` is the left argument and `⍵` is the right argument:  `⊢⍵` yield the right argument (`⊢` separates `⍺ ⍺` from `⍵`)  `⊢⌺⍺ ⍺` all `⍺`-by-`⍺` submatrices including those overlapping the edges (those are padded with zeros)  `(`…`)↓` drop the following number elements along the first two dimensions:   `⍺÷2` half of `⍺`   `¯1+` negative one plus that   `⌈` round up   `2⍴` cyclically **r**eshape to a list of two elements   `s←` store in `s` (for **s**hards)   `-` negate (i.e. drop from the rear)  `s↓` drop `s` elements along the first and second dimensions (from the front) [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 31 [bytes](https://github.com/abrudz/SBCS) ``` {(1↓2 1 3 4⍉⊖)⍣(4×⌊⍺÷2)⊢⌺⍺ ⍺⊢⍵} ``` [Try it online!](https://tio.run/##nY07CsJAFEX7rOKWM4Xgm3zUJVgIFoJ1jIkENBEmKURsA4YMKIJWNroGEdJmJ28jMdmCxYV7mnP8/XawPvjbdNO2R0Fc3BQINhw2Zy7vks1bOM2Dq5JN3XyV5PLFVd0BuvVgPqe2ZfPEzI8TRHkSZHGaQOh8tYu17r60rAhcXPB3wLL6wCLUGQJfhxpiOZ13Wjvi4ioIqhdK4cLDCGMpJqAhiEBKCrJBDsgFefIH "APL (Dyalog Unicode) – Try It Online") A different approach than Adám's. [Answer] # [J](http://jsoftware.com/), 11 8 bytes -3 bytes thanks to miles ``` <;._3~,~ ``` [Try it online!](https://tio.run/##jY4xDsIwEAT7vGKEIpmIxPL5THACVEhUVHwgBSICGn6QrxtHER0FJ213szuvtLJm5NhjqHH0OY3ldL2c02FvB53qKVUFxf32eMNa0VLwKFtadnSIQ6RiRJYf0/w8820IhFI2TyvtDOk/0MI4x6CEPCs@TyKBmG1ddshWAR87Bono3OvTBw "J – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), 67 bytes ``` m#n|r<-[0..length m-n]=[take n.drop x<$>take n(drop y m)|x<-r,y<-r] ``` [Try it online!](https://tio.run/##JcdLCsIwFEbhrfzQDhRugtZHFVI3Eu4gYLClybXEDFro3uNrcjhf716jD6GUWMmajLI7rYOXR@4RlXBnsxs9RN/Tc8Js6tvfm58XxO06G5Vo@YRLdIOgw5QGyahh7Z7QEA5MsEfCiXD@bku4EK7MqNCUNw "Haskell – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes ``` Z⁹Ƥ⁺€ ``` Uses the 4D output format. For 3D, append a `Ẏ` for **6 bytes**. [Try it online!](https://tio.run/##y0rNyan8/z/qUePOY0seNe561LTm////0dEKhjoKCkZAbAzEJrE6XArRCqZAphkQmwOxBUTIUkfB0ACIgaoNjcBChkANhiZADFRtaBYb@98YAA "Jelly – Try It Online") ### How it works ``` Z⁹Ƥ⁺€ Main link. Left argument: M (matrix). Right argument: n (integer) ⁹Ƥ Apply the link to the left to all infixes of length n. Z Zip the rows of the infix, transposing rows and columns. ⁺€ Map Z⁹Ƥ over all results. ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 13 bytes ``` {tN&s₎\;Ns₎}ᶠ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/v7rET634UVNfjLUfiKp9uG3B///R0dGGBgY68cY6JjpmsTrRhkY6hoY6hiY6FkCOgY6BjqWOMZBlbKJjZGGpE29oAeTG6hjF/o8CAA "Brachylog – Try It Online") This returns lists of columns. Technically, `tN&s₎\;Ns₎` is a generating predicate which unifies its output with any of those submatrices. We use `{…}ᶠ` only to expose all possibilities. ### Explanation ``` tN& Call the second argument of the input N { }ᶠ Find all: s₎ A substring of the matrix of size N \ Transpose that substring ;Ns₎ A substring of that transposed substring of size N ``` [Answer] # [APL (Dyalog Classic)](https://www.dyalog.com/), ~~24~~ 23 bytes ``` t∘↑¨(¯1-t←-2⍴⎕)↓,⍀⍪\⍪¨⎕ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob2pm/qO2CQZcjzra0/6XPOqY8aht4qEVGofWG@qWACV0jR71bgGq0nzUNlnnUW/Do95VMUB8aAVQ7D9Qz/80LqAGDUMDA4VD640VTBTMNDUMjRQMDRUMTRQsNDUsFQwNwDwjoLgxSNDQVMHQTJPLGAA "APL (Dyalog Classic) – Try It Online") the result is a matrix of matrices, though Dyalog's output formatting doesn't make that very obvious input the matrix (`⎕`), turn each element into a nested matrix of its own (`⍪¨`), take prefix concatenations by row (`,\`) and by column (`⍪⍀`), input n (`⎕`), drop the first n-1 rows and columns of nested matrices (`(¯1-t←-2⍴⎕)↓`), take the bottom right n-by-n corner from each matrix (`t∘↑¨`) ``` ┌─┬──┬───┐ │a│ab│abc│ ┼──┼───┤ ┼──┼───┤ n=2 ┌─┬─┬─┐ ┌─┬──┬───┐ ├─┼──┼───┤ │ab│abc│ │ab│ bc│ ┌───┐ │a│b│c│ │a│ab│bac│ │a│ab│abc│ │de│def│ │de│ ef│ │abc│ ⍪¨ ├─┼─┼─┤ ,\ ├─┼──┼───┤ ⍪⍀ │d│de│def│ 1 1↓ ┼──┼───┤¯2 ¯2∘↑¨┼──┼───┤ │def│ ---> │d│e│f│ ---> │d│de│edf│ ---> ├─┼──┼───┤ ---> │ab│abc│ ---> │ │ │ │ghi│ ├─┼─┼─┤ ├─┼──┼───┤ │a│ab│abc│ │de│def│ │de│ ef│ └───┘ │g│h│i│ │g│gh│hgi│ │d│de│def│ │gh│ghi│ │gh│ hi│ └─┴─┴─┘ └─┴──┴───┘ │g│gh│ghi│ ┴──┴───┘ ┴──┴───┘ └─┴──┴───┘ ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), 10 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` │Æ☼♂Mqß E╖ ``` [Run it](http://stax.tomtheisen.com/#c=%E2%94%82%C3%86%E2%98%BC%E2%99%82Mq%C3%9F+E%E2%95%96&i=%5B%5B1%2C2%2C3%2C4%5D%2C%5B5%2C6%2C7%2C8%5D%2C%5B9%2C10%2C11%2C12%5D%2C%5B13%2C14%2C15%2C16%5D%5D%2C+3&a=1) The ascii representation of the same program is ``` YBFMyBF|PMmJ ``` It works like this. ``` Y Store the number in the y register B Batch the grid into y rows each F Foreach batch, run the rest of the program M Transpose about the diagonal yB Batch the transposed slices into y rows each F Foreach batch, run the rest of the progoram |P Print a blank line M Transpose inner slice - restoring its original orientation mJ For each row in the inner grid, output joined by spaces ``` [Answer] # JavaScript (ES6), 91 bytes Takes input in currying syntax `(a)(n)`. Returns the results as lists of rows. ``` a=>n=>(g=x=>a[y+n-1]?[a.slice(y,y+n).map(r=>r.slice(x,x+n)),...g(a[x+n]?x+1:!++y)]:[])(y=0) ``` ### Test cases ``` let f = a=>n=>(g=x=>a[y+n-1]?[a.slice(y,y+n).map(r=>r.slice(x,x+n)),...g(a[x+n]?x+1:!++y)]:[])(y=0) ;[ [ [[1,2,3],[5,6,7],[9,10,11]], 1 ], [ [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]], 3 ], [ [[100,-3,4,6],[12,11,14,8],[0,0,9,3],[34,289,-18,3]], 2 ], [ [[100,-3,4,6],[12,11,14,8],[9,10,11,12],[13,14,15,16]], 3] ] .forEach(([m, a]) => console.log(JSON.stringify(f(m)(a)))) ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 8 bytes ``` TmoTmX¹X ``` [Try it online!](https://tio.run/##DccxDoAgEEXBC73CzwLqPShICL2JIRbGw9l6sZVu5nju072Mq4z6vdXdzVsTASN2WiKzsk3taEFCYUaGIkoo9/4D "Husk – Try It Online") This function takes **n** and **M** and returns a matrix of matrices. [Answer] # [Ruby](https://www.ruby-lang.org/), 63 bytes ``` ->c,g{n=c.size-g+1 (0...n*n).map{|i|c[i/n,g].map{|z|z[i%n,g]}}} ``` [Try it online!](https://tio.run/##Jcu9DsIgFIbhnatgMfHngJy2NjrgjRAGJZYwcNJoHKRw7Vh0fN4v3/N9/9RJV3F14BfSTr5Cegh/QLZVUkra007G27zkkJ0JRwJv/045mbBpLqXUyDU3BpUC0cMAowWDHSACDnBecQFUP3Zt6VvGE@BoLaP12rOZTyYC2foF "Ruby – Try It Online") This is a lambda taking a 2D array and an int, returning a 3D array. Ungolfed: ``` ->m,n{ a = m.size - n + 1 # The count of rows in m that can be a first row in a submatrix (0...a*a).map{ |b| # There will be a*a submatrices m[b/a,n].map{ |r| # Take each possible set of n rows r[b%a,n] # And each possible set of n columns } } } ``` [Answer] # [Python 2](https://docs.python.org/2/), 91 bytes ``` lambda a,n:(lambda R:[[r[i:i+n]for r in a[j:j+n]]for i in R for j in R])(range(len(a)+1-n)) ``` [Try it online!](https://tio.run/##hY9BbsMgEEXX7SlmF1C@JQY7jk2UHiJbyoKqcYuVkAhlk9O7gBJ1167483mPEdf77fsS9TLt35eTP398evKIRjzywVibbDBhHd10SZQoRPJ2NnMuahNKc6AS5xqdFMnHr6M4HaPwcs1NlHIp9/nhQlhhLUOjdbAb9NjmcwQrMDsHYgl6EuieDIZfCqzzwC24A2/AfdHah6YUmuyhL4iudFdlBYWxLm076GFEw0Mes6r/U//eS868vlxTiLfyQ6z2bytMIke5o1ovPw "Python 2 – Try It Online") [Answer] # [Uiua](https://uiua.org), 3 [bytes](https://codegolf.stackexchange.com/a/265917/97916) ``` ◫⊟. ``` [Try it!](https://uiua.org/pad?src=0_2_0__ZiDihpAg4per4oqfLgoKZiAxIFtbMSAyIDNdIFs1IDYgN10gWzkgMTAgMTFdXQpmIDMgW1sxIDIgMyA0XSBbNSA2IDcgOF0gWzkgMTAgMTEgMTJdIFsxMyAxNCAxNSAxNl1dCmYgMiBbWzEwMCDCrzMgNCA2XSBbMTIgMTEgMTQgOF0gWzAgMCA5IDNdIFszNCAyODkgwq8xOCAzXV0KZiAzIFtbMTAwIMKvMyA0IDZdIFsxMiAxMSAxNCA4XSBbOSAxMCAxMSAxMl0gWzEzIDE0IDE1IDE2XV0K) ``` ◫⊟. . # duplicate ⊟ # couple ◫ # windows ``` ]
[Question] [ A Hilbert Curve is a type of space-filling curve, and it basically maps a line to a plane. Each point in the line corresponds to just one point in the plane, and each point in the plane corresponds to just one point on the line. Shown are iterations 0 through 4 of the Hilbert Curve: Iterations 0 up to 4: ![](https://i.stack.imgur.com/5XqcV.png) ![](https://i.stack.imgur.com/4nXZn.png) ![](https://i.stack.imgur.com/BAsOF.png) The objective of this task: Write code that draws the fourth iteration of the Hilbert Curve, as defined above. Your code should be complete - in other words, if you create a function to draw the Hilbert Curve, your code must call that function. The output can either be displayed directly on the screen, or you can write the output to an image file. The curve may be rotated or flipped, but lines must intersect at right angles and the output cannot be stretched. ASCII art is appreciated but will not be accepted. Shortest code in bytes wins! [Answer] # [MATL](https://github.com/lmendo/MATL), ~~39~~ 38 bytes ``` O5:"tZjJ*JQ-wJq+t2+&y2j+_v2/]XG25Y01ZG ``` This takes the number of iterations as input. If you want to hard-code it, replace `i` by the number. The program is a port of the Matlab code by Jonas Lundgren shown [here](http://blogs.mathworks.com/steve/2012/01/25/generating-hilbert-curves/). The result is shown below. You can also try it at [MATL Online!](https://matl.io/?code=O5%3A%22tZjJ%2aJQ-wJq%2Bt2%2B%26y2j%2B_v2%2F%5DXG25Y01ZG&inputs=&version=19.4.0) It takes a couple of seconds to produce the output. This compiler is experimental; you may need to refresh the page and press "Run" again if it doesn't initially work. [![enter image description here](https://i.stack.imgur.com/DI3p1.png)](https://i.stack.imgur.com/DI3p1.png) ### Explanation ``` O % Push 0. This is the initial value of "z" in the original code 5:" % Do 5 times t % Duplicate Zj % Complex conjugate J* % Multiply by 1j (imaginary unit). This is "w" in the original code JQ- % Subtract 1+1j w % Swap: brings copy of "z" to top Jq+ % Add 1-1j t % Duplicate 2+ % Add 2 &y % Duplicate the third element from top 2j+_ % Add 2j and negate v % Concatenate the three matrices vertically 2/ % Divide by 2 ] % End XG % Plot (in complex plane). The numbers are joined by straight lines 25Y0 % Push string 'square' 1ZG % Make axis square ``` [Answer] ## R, 90 bytes ``` n=scan();a=1+1i;b=1-1i;z=0;for(k in 1:n)z=c((w<-1i*Conj(z))-a,z-b,z+a,b-w)/2;plot(z,t="s") ``` Shameless R-port of the the algorithm used in the link posted by @Luis Mendo. For `n=5` we get: [![enter image description here](https://i.stack.imgur.com/vvTmQ.png)](https://i.stack.imgur.com/vvTmQ.png) [Answer] # MATLAB, ~~264~~ ~~262~~ 161 bytes This works still very much the same, except that we basically calculate the "derivative" of the hilbert curve, that we then "integrate" via `cumsum`. This reduces the code size by quite a bunch of bytes. ``` function c;plot(cumsum([0,h(1,1+i,4)]));axis equal;end function v=h(f,d,l);v=d*[i*f,1,-i*f];if l;l=l-1;D=i*d*f;w=h(f,d,l);x=h(-f,D,l);v=[x,D,w,d,w,-D,-x];end;end ``` ### Old version This is just a plain recursive approach. I used complex numbers to store vectorial information for simplicity. You can change the curve at the part `h(0,1,1+i,4)`. The first argument `p=0` is the initial position, the second argument `f` is a flag for the orientation (`+1` or `-1`), the third argument `d` is the direction/rotation in which the curve should be drawn and the fourth one `l` is the recursion depth. ``` function c;hold on;h(0,1,1+i,4);axis equal;end function p=h(p,f,d,l);q=@plot;if l;l=l-1;d=i*d*f;p=h(p,-f,d,l);q(p+[0,d]);p=p+d;d=-i*d*f;p=h(p,f,d,l);q(p+[0,d]);p=p+d;p=h(p,f,d,l);d=-i*d*f;q(p+[0,d]);p=p+d;p=h(p,-f,d,l);else;q(p + d*[0,i*f,1+i*f,1]);p=p+d;end;end ``` This is what it looks like in older versions: ![](https://i.stack.imgur.com/A2LD1.jpg) This is what it looks like in 2015b: ![](https://i.stack.imgur.com/eZ8H7.png) --> [Answer] ## JavaScript (ES6), ~~266~~ ... ~~233~~ 232 bytes A SVG rendering of the Hilbert Curve. ``` document.write('<svg><path fill=none stroke=red d="M8 8'+(f=(i,s='2',d=x=y=8)=>i?f(i-1,s.replace(/./g,c=>[32410401423,,10432423401][+c]||c)):s.replace(/./g,c=>c-4?(d+=c&1&&c-2,''):`L${x+=4-'4840'[d&=3]} ${y+=4-'0484'[d]}`))(5)+'">') ``` *Saved 1 byte thanks to Neil* [Answer] # MATLAB/Octave, 202 bytes I noticed the [version @LuisMendo linked](http://blogs.mathworks.com/steve/2012/01/25/generating-hilbert-curves/) ~~is~~ was way shorter than previous ["handmade" solution](https://codegolf.stackexchange.com/a/100356/24877) but uses an entirely different approach. I'm posting a golfed version here now as a CW: This version is based on the Lindenmayer system approach: ``` A=zeros(0,2);B=A;C=A;D=A;n=[0,1];e=[1,0];for k=1:4;a=[B;n;A;e;A;-n;C];b=[A;e;B;n;B;-e;D];c=[D;-e;C;-n;C;e;A];D=[C;-n;D;-e;D;n;B];A=a;B=b;C=c;end;A=[0,0;cumsum(A)];plot(A(:,1),A(:,2));axis off;axis equal ``` [![enter image description here](https://i.stack.imgur.com/u8mrH.jpg)](https://i.stack.imgur.com/u8mrH.jpg) [Answer] # Python 3, ~~177~~ ~~175~~ 171 bytes A simple implementation of the Lindenmayer system for the Hilbert curve. Golfing suggestions welcome! **Edit:** -2 bytes thanks to Kade. -3 bytes from restructuring how the Hilbert curve is built. -1 byte with thanks to ETHproductions. ``` from turtle import*;s="a";exec('t=""\nfor c in s:t+=c>"F"and"+-abFF-+baFFba-+FFab+-"[c<"b"::2]or c\ns=t;'*5) for c in s: if"-">c:rt(90) elif"F">c:lt(90) elif"a">c:fd(9) ``` [![enter image description here](https://i.stack.imgur.com/DMHpW.png)](https://i.stack.imgur.com/DMHpW.png) **Ungolfing** ``` import turtle hilbert_seq = "a" for _ in range(5): new_seq = "" for char in hilbert_seq: if char == "a": new_seq += "-bF+aFa+Fb-" elif char == "b": new_seq += "+aF-bFb-Fa+" else: new_seq += char hilbert_seq = new_seq for char in hilbert_seq: if char == "F": turtle.forward(9) elif char == "+": turtle.right(90) elif char == "-": turtle.left(90) ``` [Answer] # Mathematica (Wolfram Language) 76 bytes After Mathematica 11.1, there is a [HilbertCurve](http://reference.wolfram.com/language/ref/HilbertCurve.html) function, but i don't want to use it ``` Region@Line@ReIm@Nest[Join[w=I Conjugate@#-1-I,t=#+I-1,t+2,-2I-w]/2&,{0},#]& ``` [![enter image description here](https://i.stack.imgur.com/vjeK7.png)](https://i.stack.imgur.com/vjeK7.png) [Answer] # MSWLogo (Version 6.5b), 136 bytes Based on the final Hilbert curve program [here](http://eurologo.web.elte.hu/lectures/batagel1.htm). ``` to h :n :a :l if :n=0[stop] rt :a h :n-1(-:a):l fd :l lt :a h :n-1 :a :l fd :l h :n-1 :a :l lt :a fd :l h :n-1(-:a):l rt :a end h 5 90 9 ``` A function `h` is defined, which takes number of iterations `:n` (1-based), angle `:a`, length `:l`. It is recursive, calling a lower iteration of itself with the angle `:a` negated in two instances to get the orientation correct. * `rt :a`, `lt :a` rotate the turtle (triangle thingy whose path is traced) right, left by `:a` degrees. * `fd :l` moves the turtle forward by `:l` steps. Finally, the function is called: `h 5 90 9`. The turtle can be hidden for an extra 2 bytes, `ht`. [![(5-1)-th iteration](https://i.stack.imgur.com/JWGks.png)](https://i.stack.imgur.com/JWGks.png) [Answer] ## Mathematica 128 Bytes ``` Graphics[Line@AnglePath[Total/@Split[Cases[Nest[#/.{-2->(s=##&@@#&)[l={-1,2,0,1,-2,0,-2,1,0,2,-1}],2->s@-l}&,{-2},4],-1|1|0],#!=0&][[;;-2,;;-2]]*Pi/2]] ``` Replace the 4 above with a different number of iterations if you like. Done as a Lindenmayer system with integer sequences rather than string sequences so the second production rule is just the negative of the first rule. This version is 151 bytes. The port of Jonas Lundgren's MATLAB code is only 128 bytes. ``` z=0;Graphics[Line[{Re[#],Im[#]}&/@Flatten[Table[w=I*Conjugate[z];z={w-(a=1+I),z-(b=1-I),z+a,b-w}/2,{k,5}][[5]]]],AspectRatio->1] ``` I see that in a future version of Mathematica, this may become really short, something like: ``` Graphics@HilbertCurve[n] ``` <http://mathworld.wolfram.com/HilbertCurve.html> [Answer] # [LindenMASM](https://github.com/kade-robertson/pylasma), 63 Bytes Another question with a LindenMASM answer? Awesome! ``` STT AXI A INC 5 SET F 0 RPL A -BF+AFA+FB- RPL B +AF-BFB-FA+ END ``` Once again, due to some drawing bugs with Python's `turtle`, sometimes when you run this the whole drawing isn't there. However you can see it does actually work: [![4th iteration](https://i.stack.imgur.com/UpfJi.png)](https://i.stack.imgur.com/UpfJi.png) ]
[Question] [ *Longest day of the year - here's something to waste the extra time...* --- ## Overview Note this is not a popularity contest and not a graphical output challenge - you are only required to output a string of 65,536 zeroes and ones. The Stack Snippet at the bottom of the question will display this as a 256 by 256 black and white image and calculate your official score. You can then save the image and upload it to your answer alongside your code (since the string output will not fit in a 30,000 character Stack Exchange answer). --- ## Scoring The score of an image is the sum of the scores of its individual pixels. The score of an individual pixel is the sum of the subscores for each of the ***non-orthogonal***, ***prime distance*** pixels that are of ***opposite colour*** to the pixel being scored. The subscore for each such pixel is `1/p` where `p` is the prime distance. In the context of this question, the terms have the following definitions: * ***Non-orthogonal:*** A pixel is non-orthogonal to the pixel being scored if it is not in the same row and is not in the same column. * ***Prime distance:*** A pixel is at a prime distance from the pixel being scored if they are separated by a Euclidean distance that is **exactly** a prime number. In particular, distance is the minimum distance measured toroidally - the top left pixel is a distance of `sqrt(2)` from the bottom right pixel (all 4 edges wrap). * ***Opposite colour:*** A pixel is of opposite colour to the pixel being scored if their values sum to 1. That is, the first is 0 and the second is 1, or the first is 1 and the second is 0. The Stack Snippet includes example code that shows how to score an image, but does not include any optimisations or an efficient approach, just correct code so scoring of final images can be done consistently. *If anything in the code is not correct, please let me know either in the comments or in [chat](http://chat.stackexchange.com/rooms/240/the-nineteenth-byte "The Nineteenth Byte").* JavaScript may not necessarily be the best language for *answering* this particular challenge. Note that the Snippet code deliberately gives no clues as to faster approaches. It will only have efficiencies introduced that have already been demonstrated in an existing answer. --- ## Visualisation ### The scoring pixels For an intuitive feel for the distribution of the scoring pixels, here (in purple) are the non-orthogonal prime distance pixels for pixel (128, 128) of a 256 by 256 image: ![image of non-orthogonal prime distance distribution](https://i.stack.imgur.com/Q2KT5.png "Scoring pixels for pixel (128, 128)") --- ### A random image This is the randomly generated image from the example Python 3 answer. It has a score of 138,267.64 and gives you something to beat. ![randomly generated image](https://i.stack.imgur.com/EAzDT.png "Python 3: Randomly generated image") --- ## Input The code does not require input. ## Output The code should output a string of 65,536 zeroes and ones, representing the pixels of a black and white 256 by 256 image. The digits should be a continuous string, with no separators. You may find copying and pasting easier if you output to a file, but this is up to you. Your code may also output other information that you find useful, as long as the string can be copied and pasted into the Stack Snippet. For example, you may wish to output the best yet string to a file and the best yet score to STDOUT at regular intervals, allowing the user to choose when to stop the search. --- ### Stack Snippet As pointed out by [Sp3000](https://codegolf.stackexchange.com/users/21487/sp3000 "profile on PPCG"), the snippet was taking 10 minutes to calculate a score, which is a little *too* slow, even for a deliberately inefficient reference implementation. I've edited in Sp3000's suggested improvement of precomputing the pixel offsets for the scoring, and it now takes a few seconds to calculate a score. ``` canvas = document.getElementById('canvas') ctx = canvas.getContext('2d') scoreArea = document.getElementById('scoreArea') pastedData = document.getElementById('pastedData') timeout = 0 primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499] primesSquared = [] for (i=0; i<primes.length; i++) { primesSquared.push(primes[i] * primes[i]) } width = canvas.width height = canvas.height area = width * height scoringFilter = calculateScoringFilter() function calculateScore() { var percentage = Math.floor(currentIndex / 65536 * 10000) / 100 scoreArea.value = 'Calculating:' + percentage + '%' for (var t=0; t<1000; t++) { if (currentIndex < 65536) { partialScore += pixelScore(currentIndex) currentIndex += 1 } else { scoreArea.value = 'Score: ' + partialScore return } } timeout = setTimeout(calculateScore, 10) } function pixelScore(i) { var score = 0 var x = i % width var y = Math.floor(i / width) var a, b, xd, yd, j, k, d, m for (k=0; k<scoringFilter.length; k++) { bundle = scoringFilter[k] m = bundle[0] a = m % width b = Math.floor(m / width) j = ((x+a) % width) + width * ((y+b) % height) d = bundle[1] score += Math.abs(pixels[i] - pixels[j]) / d } return score } function display(pixels) { for (var i=0; i<area; i++) { ctx.fillStyle = pixels[i] ? 'white' : 'black' ctx.fillRect(i % width, Math.floor(i / width), 1, 1) } } function stop() { clearTimeout(timeout) scoreArea.value = 'Calculation cancelled.' } function isPrimeSquared(n) { return primesSquared.indexOf(n) > -1 } function applyToImage() { var potentialPixels = [] var pastedString = pastedData.value if (pastedString.length !== 65536) { scoreArea.value = 'Incorrect length:' + pastedString.length return } var i, digit for (i=0; i<pastedString.length; i++) { digit = pastedString.substring(i, i + 1) if (digit === '0') { potentialPixels.push(0) } else if (digit === '1') { potentialPixels.push(1) } else { scoreArea.value = 'Invalid character ' + i + ':' + digit return } } pixels = potentialPixels display(pixels) scoreArea.value = 'Calculating score...' partialScore = 0 currentIndex = 0 timeout = setTimeout(calculateScore, 10) } function calculateScoringFilter() { var scoringFilter = [] var i, x, y, xd, yd for (i=0; i<area; i++) { x = i % width y = Math.floor(i / width) xd = Math.min(x,(-x+width)%width) yd = Math.min(y,(-y+height)%height) dSquared = xd*xd + yd*yd if (xd && yd && isPrimeSquared(dSquared)) { d = Math.sqrt(dSquared) scoringFilter.push([i, d]) } } return scoringFilter } ``` ``` <canvas id='canvas' width='256' height='256'></canvas> <br> <input id='scoreArea' rows='1' readonly></input> <br> <button onclick='applyToImage()'>Apply string to image</button> <button onclick='stop()'>Stop</button> <br> <br> Paste in string of 65,536 zeroes and ones here: <br> <input id='pastedData'></input> ``` --- If you use the output or the code of another answer as the starting point for your own code, please remember to give credit and link to the supporting answer. Answers to this question do not need to credit the example answer or the code in the question. [Credit to Randall Munroe for the term ***Nerd Sniping***](https://xkcd.com/356/ "Meta Nerd Sniping") [Answer] # CJam, score 276496.9062958626 ``` 2,128*_(]128* ``` ![](https://i.stack.imgur.com/r7YJS.png) It turns out to be optimal, because: There aren't any non-orthogonal pairs with distance 2. So the distance must be odd, and so is the distance squared. As p2=x2+y2, one of x and y (squared or not) must be odd, and the other must be even. Those points are always in the opposite color in this image. This and its negative are also the only optimal solutions. In an optimal solution, no non-orthogonal, prime distance pixels should have the same color. There are diagonally adjacent opposite pixels like (3,4) and (4,3). By filling pixels of the opposite of opposite color, etc, we can get a diagonal with the same color. Starting from each pixel in the diagonal, we can get all the anti-diagonals filled in the same way. Note that they wrap around. It is still optimal if they don't, though. [Answer] ## Python 3, score 138267.64 This is a minimal answer as an example of what is required, and as something to beat... It includes * The language name. * The score from the Stack Snippet in the question. * The image saved from the Stack Snippet. * The code used to produce the string of 65,536 zeroes and ones. ### Output ![randomly generated image](https://i.stack.imgur.com/EAzDT.png "Python 3: Randomly generated image") ### Code ``` from random import random output_string = '' filename = '65536digits.txt' for t in range(65536): digit = int(random() * 2) output_string += str(digit) with open(filename, 'w') as output_file: output_file.write(output_string) ``` This is just an example. Python may not necessarily be the best language for competitive answers to this particular challenge. ]
[Question] [ # Introduction Finding the *closest* power to a number is a common enough problem. But what if you need both the next-highest and next-lowest power? In this challenge you must find the closest powers to a given number - the 'power sandwich' if you will, where the given number is the filling and the powers are the bread. Mmm, tasty. # Challenge Given a power **P >0** and a number **N >0**, output the largest integer **x^P** that is smaller or equal to **N**, and the smallest integer **y^P** that is greater or equal to **N**. Input should be taken as a list of two positive (>0) integers, first the power P and then the number N. Output should be a list of two integers, the first being smaller or equal to N, the second being greater or equal to N, and both being a power of P. If N is a power of P already, the output should be the list [N, N]. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code (as measured in bytes) wins. # Example Input and Output Input: > > [2, 17] > > > Output: > > [16, 25] > > > Explanation: 16 is the biggest square number (power of 2) less than or equal to 17, and 25 is the smallest square number greater or equal to 17. # Test cases ``` [2, 24] -> [16, 25] [2, 50] -> [49, 64] [3, 8] -> [8, 8] [1, 25] -> [25, 25] [3, 25] -> [8, 27] [4, 4097] -> [4096, 6561] [2, 10081] -> [10000, 10201] [11, 2814661] -> [177147, 4194304] [6, 1679616] -> [1000000, 1771561] ``` [Answer] # JavaScript (ES7), 39 bytes Expects `(p)(n)`. ``` p=>n=>[x=(q=n**(1/p)|0)**p,(q+=x<n)**p] ``` [Try it online!](https://tio.run/##bY9LbsIwEIb3PYWXduo2M854bEs1F0EsEIWKCjmhIMSid09tUyGRMKtZfP/re31ZnzY/@@H8lvrP7biL4xAXKS6W1yiPMTWNxHZQv6CaZtDy@BqvH6n8q3HTp1N/2L4f@i@5k0ZJQ0qJ27WtWCJrYezqZcZZeOAoaME05Tol/R2rnNfCTynMqfbBzdhnqd2My27GTTFSkiC4f7CWg5BnsGV8MgQBPN7gOhjyaYFgYEZjaeqRmIug0s4hOS0IA3Uw28/Znl1g5BJwt68BWVkKjX8 "JavaScript (Node.js) – Try It Online") ### Alternate version (same size) ``` p=>n=>[0,1].map(i=>(n--**(1/p)+i|0)**p) ``` [Try it online!](https://tio.run/##bc/PboMwDAbw@54ix4SGYgfHSQ7wIlUPqH8mqhaiddpp785COlUq1Oefv8@@dD/d/fDVx@9yGI@n6dxMsWmHpt2Bxv321kXZN60cyrIoJFZRbfpfUEUR1XQYh/t4PW2v46c8S6OkIaXEY6pK7JC1MHb/sXIWXhwFLZiWrlbSP1l2Xgu/VJha7Uuase9a65VLacYtGSlJENw/zMdBSG@wZXzzCAJ4fOD8MKTRAsHASuN8qUdinheydg7JaUEYqIbV/5zi2QVGngue8bkgbc4HTX8 "JavaScript (Node.js) – Try It Online") [Answer] # [R](https://www.r-project.org), ~~36~~ ~~35~~ 33 bytes ``` \(P,N)abs(c(r<-N^(1/P),-r)%/%1)^P ``` [Attempt This Online!](https://ato.pxeger.com/run?1=TY9BDsIgEEX3ngJjmkBCU4YOAyTqEZru1SZq0gNUPY2bauKhvIRnECg1smF48-f_4f4Yxme_ed2ufeneyz1vZSOOpws_82FdNh2HqhWyHERRFSC6Ngs_PdeSaRQrVm7ZDig8zGGRqFGZopeMMNJaMpehC2VEECcy02Yer_9oUGobIUqGytvZVfmQRoYg54FSDuZFVDgRaZXaEGMcINFPYS2gDY7gsVZpu2AHZD0B_bsknyCOQdOvx3G6vw) [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 7 bytes ``` Ėe₍⌊⌈$e ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyIiLCIiLCLElmXigo3ijIrijIgkZSIsIiIsIjFcbjI1Il0=) Trivial implementation. ``` Ėe₍⌊⌈$e­⁡​‎‎⁡⁠⁡‏⁠‎⁡⁠⁢‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁣‏⁠‎⁡⁠⁤‏⁠‎⁡⁠⁢⁡‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁢⁢‏⁠‎⁡⁠⁢⁣‏‏​⁡⁠⁡‌­ Ėe # ‎⁡Exponentiate N with the reciprocal of P ₍⌊⌈ # ‎⁢Pair results of floor, ceil in a list $e # ‎⁣Swap (returns first input) and exponentiate with P 💎 ``` [Answer] # [Python](https://www.python.org), 46 bytes *based on port of [Arnauld's JavaScript answer](https://codegolf.stackexchange.com/questions/266255/finding-the-power-sandwich/266257#266257)* ``` lambda p,n:[int(q:=n**(1/p))**p,(-(-q//1))**p] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY39XISc5NSEhUKdPKsojPzSjQKrWzztLQ0DPULNDW1tAp0NHQ1dAv19Q3BvFiornkFRSC1aRpGOkYmmppcCK6CqQES31hHwQKJa6ijYGSKKo3CN9FRMDGwNEc10NDAwMIQ2RCQKRaGJmZmyKJmQIVm5pZmhmZAQYgrFyyA0AA) `floor` and `ceil` of p-th root to the power of p [Answer] # [BQN](https://mlochbaum.github.io/BQN/), 10 [bytes](https://github.com/mlochbaum/BQN/blob/master/commentary/sbcs.bqn) ``` (⌊⋈⌈)∘√´⋆⊑ ``` Try it [here.](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAgKOKMiuKLiOKMiCniiJjiiJrCtOKLhuKKkQoK4oCiU2hvdyBGIFsyLCAyNF0K4oCiU2hvdyBGIFsyLCA1MF0K4oCiU2hvdyBGIFszLCA4XQrigKJTaG93IEYgWzEsIDI1XQrigKJTaG93IEYgWzMsIDI1XQrigKJTaG93IEYgWzQsIDQwOTddCuKAolNob3cgRiBbMiwgMTAwODFdCuKAolNob3cgRiBbMTEsIDI4MTQ2NjFdCuKAolNob3cgRiBbNiwgMTY3OTYxNl0KCkA=) Explanation: ``` (⌊⋈⌈)∘√´⋆⊑ # tacit function which takes a list [P,N] ⌊⋈⌈ # take the floor paired with the ceil ( )∘√´ # of the P-th root of N ⋆⊑ # and raise to the power P ``` [Answer] # [Desmos](https://www.desmos.com/), 51 bytes ``` f(l)=[floor(l[2]^{1/l})^l[1],ceil(l[2]^{1/l})^l[1]] ``` [Try it on Desmos!](https://www.desmos.com/calculator/c7wznzknjm) Expects list `[p,n]` and returns list `[x^p,y^p]` as per specifications. Explanation: ``` f(l)=[ , ] Given a list, return a list floor(l[2]^{1/l})^l[1] floor(n^1/p)^p ceil(l[2]^{1/l})^l[1] ceil(n^1/p)^p ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes ``` *İ}Ḟ,ĊƊ* ``` [Try it online!](https://tio.run/##y0rNyan8/1/ryIbahzvm6RzpOtal9f/wcgd9b83I//@juaKNdBSMTGJ1wAxTAxDDWEfBAkQbAmVMoQIQhomOgomBpTlUtaGBgYUhWCFIpYWhiZkZmGsGlDIztzQzNAPyYgE "Jelly – Try It Online") Profoundly boring direct floor-ceil solution. However, if the N-is-a-power-of-P case can be relaxed to permit outputting just `[N]`... # [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes ``` *İ}¹ị*€ ``` [Try it online!](https://tio.run/##y0rNyan8/1/ryIbaQzsf7u7WetS05v/h5Q763pqR//9Hc0Ub6SgYmcTqgBmmBiCGsY6CBYg2BMqYQgUgDBMdBRMDS3OoakMDAwtDsEKQSgtDEzMzMNcMKGVmbmlmaAbkxQIA "Jelly – Try It Online") ...we actually have a builtin for floor-ceil. Namely, the index-into dyad `ị`. ``` *İ} Pth root of N. ¹ (Break undesired initial 2,2,2 chain.) ị Index that into *€ the list of x^P for all x <- 1..N. ``` [Answer] # [Desmos](https://desmos.com/calculator), 37 bytes ``` f(p,n)=[floor(k),ceil(k)]^p k=n^{1/p} ``` [Try It On Desmos!](https://www.desmos.com/calculator/cg5g5ud8t2?nographpaper) [Try It On Desmos! - Prettified](https://www.desmos.com/calculator/zygbhr2gee?nographpaper) The best I could think of for now. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` zmDî‚ï¹m ``` Port of [*@AidenChow*'s Desmos answer](https://codegolf.stackexchange.com/a/266310/52210). Inputs in the order \$P,N\$. [Try it online](https://ato.pxeger.com/run?1=m73MwDQxyTB1wYKlpSVpuhZrq3JdDq971DDr8PpDO3OXFCclF0NlFiwx4jI0h7AB) or [verify all test cases](https://ato.pxeger.com/run?1=m73MwDQxyTB1wYaySnslhUdtkxSU7CsTig-tXFpakqZrsbYq1-XwukcNsw6vP7Qud0lxUnLxQh2I1IKbYdHRRjqG5rE6QMrIBEyZGgApYx0LIGmoY2QK5oApEx0TA0uIUkMDAwtDkAKgCgtDEzMzEMdMx9DM3NLM0Cw2FmI8AA). **Explanation:** $$[N\_a,N\_b]=\left[\left\lceil N^\frac{1}{P}\right\rceil,\left\lfloor N^\frac{1}{P}\right\rfloor\right]$$ ``` z # Push 1/P, where P is the first (implicit) input-integer m # Take N to the power this 1/P, where N is the second (implicit) input-integer D # Duplicate it î # Ceil the copy ‚ # Pair the two together ï # Floor/cast both to integers ¹m # Take both values in the pair to the power P # (after which the resulting pair is output implicitly) ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 29 bytes ``` NθNη≔¹ζW‹Xζθη≦⊕ζIX⟦⁻ζ›Xζθηζ⟧θ ``` [Try it online!](https://tio.run/##XYyxCsIwFEX3fkXGPIiDilMncZCCle7iEOPDBNrXNi@x0J@PKXYQx3M55xqrvel1m1JFQwzX2D3QyxHK4pdt5iOze5HcKjFnmqxrUcgLMsumn7IzKzGCEhZA1HpY7YqMxw4p4PPbNd5RkCfNYc1utaPIS332qENe/u9yeF8AoExpX@wOafNuPw "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` NθNη ``` Input `P` and `N`. ``` ≔¹ζ ``` Start with `y=1`. ``` W‹Xζθη≦⊕ζ ``` Increment `y` until it is large enough. ``` IX⟦⁻ζ›Xζθηζ⟧θ ``` Output the `P`th powers of `x` and `y`. 61 bytes for a more efficient version: ``` NθNη≔¹ζ≔¹εW‹Xεθη≦⊗εW›⁻εζ¹«≔÷⁺εζ²ιF¬‹Xιθη≔ιεF¬›Xιθη≔ιζ»IX⟦ζε⟧θ ``` [Try it online!](https://tio.run/##fY89C8IwFEXn9ldkTKAOVpycREEKtnQXh6jRPoiJTdIWKv72@Irxo4vDGy7ccw/vWHFz1Fx6n6lb44rmehCG1mwR/@YK89JauCg6TUg/SgJTV4EUhG6FtbTUHRIiITVLSMUYyfkttNe6OUhxGjEbI7hDIAfV2AHrEZsido@jgGXKraGFk6Cl/HZSPMCd6KwNoYV2v3r46BkJK/DSfutv8z9iePURlwaUoytuXSjvehzbDwRjC@9ncTr3k1Y@AQ "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` NθNη ``` Input `P` and `N`. ``` ≔¹ζ≔¹ε ``` Start with both `x` and `y` equal to `1`. ``` W‹Xεθη≦⊗ε ``` Double `y` until it is large enough. ``` W›⁻εζ¹«≔÷⁺εζ²ιF¬‹Xιθη≔ιεF¬›Xιθη≔ιζ» ``` Perform a binary search to narrow down the range of `x` and `y`. ``` IX⟦ζε⟧θ ``` Output the `P`th powers of `x` and `y`. 19 bytes using floating-point arithmetic: ``` Nθ≔XIη∕¹θηIX⟦⌊η⌈η⟧θ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/98zr6C0xK80Nym1SKNQ05rLsbg4Mz1PIyC/HCjgnFhcopGhqaPgklmWmZKqYaijUKgJ5GYAFQYUZeaVQFRAFEe75eTnF4GVO6dm5mTmpQPZsWAdmtb//xtzGZn@1y3LAQA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` Nθ ``` Input `P`. ``` ≔XIη∕¹θη ``` Take the `P`th root of `N`. ``` IX⟦⌊η⌈η⟧θ ``` Output the `P`th powers of the floor and ceiling. [Answer] # [GolfScript](http://www.golfscript.com/golfscript/), ~~25~~ ~~24~~ 23 bytes ``` {0\{@@).2$?.-1$<}do@;@} ``` [Try it online!](https://tio.run/##S8/PSStOLsosKPlf97/aIKbawUFTz0jFXk/XUMWmNiXfwdqh9n9dgULBfxMFEwNLcwA "GolfScript – Try It Online") I’m pretty sure this method is optimal, considering GolfScript doesn’t have floats and thus no min/max. ~~It’s possible that there’s a shorter way to do the stack manipulation, but that seems pretty unlikely to me at this point.~~ I stand corrected (by myself)—I was able to get rid of the variable `i`. Now I think this is optimal…but then I’ll probably find another 1-byte save somewhere else 😂 This is a block (function) taking N then P on the stack and leaving the two values on top of the stack. Explanation: | Code | Stack (bottom to top) | | --- | --- | | `{…}` Block | `2 17` | | `0\` | `2 0 17` | | `{…}do` Run until result is 0… | Showing first pass over: | | `@@` Stack shift | `17 2 0` | | `)` Increment | `17 2 1` | | `:` Duplicate | `17 2 1 1` | | `2$` Push third from stack | `17 2 1 1 2` | | `?` Exponentiate | `17 2 1 2` | | `:` Duplicate | `17 2 1 2 2` | | `-1$` Push bottom of stack | `17 2 1 2 2 17` | | `<` Less than? | `-1 2 1 2 0` | | (pop and either repeat or stop) | `17 2 1 2` | At the end of the loop, the stack looks like `17 1 4 9 16 2 5 25` so we do `@;@` to make the top of the stack be `25 16`. It took like twenty minutes of fiddling around to get the stack manipulation to work right. [Answer] # [C#](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 79 bytes ``` (p,n)=>(Math.Pow(Math.Pow(n,1d/p)is{}x?(int)x:x,p),Math.Pow(Math.Ceiling(x),p)) ``` Alternate approach that uses 87 bytes ``` (p,n)=>{var(i,x)=(0,0d);for(;(x=Math.Pow(++i,p))<n;);return(Math.Pow(x==n?i:~-i,p),x);} ``` [Try it online!](https://tio.run/##lVPfT9swEH7vX3GKJmFrJsQhTVu6ghCFiY1JaEXbw9hDSNzirYtD40CqKH97d3boT3VI80PO9nf33ee7S5wfxrlcXBVp/EGmmoH9kEQVD1PBoLH0FMYwWJCMpXRwSr5E@tG9VS/rTcp4cpRRmVd1eUaQgpYnJcso23a9EHIq0wkpKWJ00W@1bF6yTEz3ZZ7AAEoYoARSutda/OEMmo1PkaH1HM1Ai1yjWypeYChjLVUazeZv8xLaqlqAqwLiM@Ad48RDBn6bQs02ID/4J9T2DBT0GITBJnTMoGuQrrEb99xyIOC3d9mOlxDG@J1NJGAQeD2rDy3KCNsh3xHCPa/LrUwPlzn73pYPN6m7PAjDxq3T4UEHiXkvOPa2tGMCHnZ6IQ9XfJYRI5q8rRrL/qxkAspU@MdPyKnpz2ieY1PcoYwmqcq1jHN3KB6Kift9JrW4kakguZ5h/91PSqbkgB0wjMQeWq6MqIdfItb/QWbab0SbCciiPBcJzoDXt3djNRNR/AjEgL@fMxwDOyW0eab9LmNFmWEgOrnfomkh@itwd2hgovQabR5jM68v9Wy@2q@zmIWxmGVCTJ7PYk77W@ir/vcD4@dePhXRNCcojMIZcDhZPmvTHfb5Orfno5GDAc7V@fWNs46qV7s40qYwl2UsMvOrgKBvSk7EOCqmmuxWg@6VJNyPQt/NM0Goe6dGtkaE7tNxodJcTcVGR985Y1K91qemcAiVIa2BoJATuHcqtPW9w0zH7Bktnqnzyt9w7@M1VbkcNnwiqY8qMwvuhSpSXS@jl3FfRZTYMLxf/AU "C# (Visual C# Interactive Compiler) – Try It Online") [Answer] # APL+ WIN, 18 bytes Prompts for power and integer: ``` ((⌊p),⌈p←⎕*÷n)*n←⎕ ``` [Try it online! Thanks to Dyalog Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcQJanP5BlyPWooz3tv4bGo56uAk2dRz0dBUBRoKzW4e15mlp5EM5/oCKu/2lcRlxGJlxASoHL1ABIG3NZAElDLiNTMAdMmXCZGFiagxRxGRoYWBiCFABVWBiamJmBOGZchmbmlmaGZgA "APL (Dyalog Classic) – Try It Online") [Answer] # [MATL](https://github.com/lmendo/MATL), 14 bytes ``` w1Y\^tkwXkh1G^ ``` [Try on MATL Online](https://matl.io/?code=w1Y%5C%5EtkwXkh1G%5E&inputs=6%0A1679616&version=22.7.4) or [Test all cases](https://tio.run/##TYyxDoIwFEX3fsVNjFujfVgeZXJxJE4OtViimwbdmoAD315bNYS3nXvufa9beMbrA0G4I/YYsYEAMMFNeINgm5St7SqHPg50vnShH2x/p6aL9gA34pREW0gU2uN7IlOpZtpJmD8kotQsl25BWkKruvLzF1LKkP/t8tCQZiYvWk6Oq5qJPYTaqg8 "MATL – Try It Online") ``` w % Get both inputs and bring P to the top of the stack 1Y\ % Take the inverse of P ^ % Raise N to that power i.e. take N's P-th root tk % Take a copy of that root and floor it wXk % And ceil the original copy h1G^ % Raise both those values to the power of P ``` [Answer] # [Vyxal 3](https://github.com/Vyxal/Vyxal/tree/version-3), 7 bytes ``` ė*∦⌊⌈$* ``` [Try it Online!](https://vyxal.github.io/latest.html#WyIiLCIiLCLElyriiKbijIrijIgkKiIsIiIsIjExXG4yODE0NjYxIiwiMy4xLjAiXQ==) Takes two integers as its argument and returns two integers. Works the same as various other answers including [@mathscat’s Vyxal one](https://codegolf.stackexchange.com/a/266261/42248) and [@UnrelatedString’s Jelly one](https://codegolf.stackexchange.com/a/266269/42248). ## Explanation ``` ė*∦⌊⌈$* ė | Reciprocal of n * | To the power of p ∦⌊⌈ | Pair ceiling with floor and wrap in a list $* | To the power of p ``` ``` [Answer] # [Rust](https://www.rust-lang.org/), ~~67~~ 66 bytes ``` |p,n:f64|{let x=n.powf(1./p);(x.floor().powf(p),x.ceil().powf(p))} ``` [Try it online!](https://tio.run/##hVPLjtowFN3zFR4WyKmCG4cQIFNG6gdUXVQaVYoQygRnsOo4aewMtJBvp9cOaYChqhexde55XD9S1UqfyvoFZRLlCZfYQeMnBN/DAMEQTKM3tESnY@nKKAuD48FA@6UkZbHLMCUfS@cR70kmiqLCTouWjrsnKeOiB5zm9PjXUekNl@AKcxTxIoosgJ2ekdcavdRZxiqgfdMVl69RJNmu4@y2XDDL/PoDmiBLa1Ur/ptF0ZfP353WnUtSsWSzFlwyPOpNu@11caYOirZIIC7vgszgmSUQrtYsL/UvfCk3Iy2k5rJmvaS5si@TSqsIPbP00/oJcqybKgXXeDh@GjokT0p8VEekztkxbEkRweBMxv6K6GKt7BlgxyFpIQRLtWnwqkPIibksa@2yfQkEtllB1OiDDb9p@F5TVtt15d5p6p9tXDq/i8HwcJwIYXg7LoKPuRlss2NvRWChGFjXcldBnOO2bcX0fem/QaLYuVv@ujUJbxCL5I3EsCqmaqGBkRVVnugHPDxExGtcZKehi4wLsjbX4hI2roUEQXxoVuYnMTMI2jNHo9b5RpUoxSq9Zj8fcHcr96j9czk/wVSwpOrOthk0p9h3kR@0uTSE9XQ1MNjUa7Fg4aIwAGzionkLzc1qEFNLtog/PQsnPQYsfwYQ3E7gLWZnN28BGeE0pG0K9bw5PYd7MAzie6ZIjf2cBmHY1WczGszAjC6CiWc6AicazhYhDS8crAdQTcQf "Rust – Try It Online") Trivial implementation: takes `n` to the power of `1/p`, and then calculates `floor` and `ceil` to the power of `p`. Takes the integer inputs as 64-bit floats and returns its output as a tuple of 64-bit floats. *-1 byte thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)* ]
[Question] [ # Objective You're on a nonempty list of integers that wraps around. You start at the leftmost entry of the list, and keep jumping to the right to the amount of the integer entry you're at. Eventually, you'll end up in a cycle. The objective is to output the length of this cycle. # I/O format Provided that the inputted list has \$n\$ entries, each entry \$m\$ is assumed to satisfy \$0 \leq m < n\$. Otherwise flexible. # Examples ``` Input, Output [0], 1 [0, 1, 2], 1 [1, 0, 2], 1 [1, 1, 2], 2 [2, 2, 2, 2], 2 [2, 3, 2, 1], 2 [3, 3, 3, 2], 3 [1, 1, 1, 1], 4 ``` # Worked Example ``` [1, 2, 3, 2] ^ [1, 2, 3, 2] ^ [1, 2, 3, 2] ^ [1, 2, 3, 2] ^ Cycle detected; halt. The output is: 2. ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` Ėṙ`ḢṪƊÐḶL ``` A monadic Link that accepts a list of integers and yields the cycle length. **[Try it online!](https://tio.run/##y0rNyan8///ItIc7ZyY83LHo4c5Vx7oOT3i4Y5vP/6OTHu6coXO4PetRwxwFWzuFRw1zNSP//4@ONojV4VKINtBRMNRRMAKzgQwDJDZc3AjIgCAY1xjMNQRzjcFcY1SNhhDZWAA "Jelly – Try It Online")** ### How? Keep a record of the original indices along with their jump-values and repeatedly rotate this left by its first jump-value to find the cycle and output its length. The implementation actually rotates by all indices and jump-values then picks out the one we want (rotated by first jump-value). ``` Ėṙ`ḢṪƊÐḶL - Link: list of integers, Jumps Ė - enumerate -> [[1, jump1], [2, jump2], ...] ÐḶ - start with that and collect up while distinct then yield loop, applying: Ɗ - last three links as a monad - f(Current): ` - use as both arguments of: ṙ - rotate {Current} left by {Current} (vectorises) Ḣ - head -> rotations by the first index and first jump Ṫ - tail -> rotation by the first jump L - length ``` [Answer] # [R](https://www.r-project.org), 65 bytes ``` \(a){while(!(T=(T+a[+T]-1)%%sum(a|1)+1)%in%F)F=c(T,F) match(T,F)} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGiNNulpSVpuhY3HWM0EjWryzMyc1I1FDVCbDVCtBOjtUNidQ01VVWLS3M1EmsMNbWBnMw8VTdNN9tkjRAdN02u3MSS5AwwsxZq0NQ0jWQNA01NBWUFQy4wW0fBUEfBCEkEyDXAEIGrMQKLGAG5EIQqaAwWNEQSNAYLGsNUGiMZaAhTaQJx3IIFEBoA) [Answer] # [Python](https://www.python.org), 62 bytes *-4 bytes, thanks to loopy walt* ``` lambda L,i=0:len({*[i:=(i+L[i])%len(L)for _ in 2*L][len(L):]}) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY37XISc5NSEhV8dDJtDaxyUvM0qrWiM61sNTK1faIzYzVVQUI-mmn5RQrxCpl5CkZaPrHREDGr2FpNqCkPCooy80o00jSiDWI1NZV1FAy5ECJAno6CEYY4UNAAhzhCvRFC3AjIgyBsUsZgKUMMKWOwlDFclzG6RYZwXSZYpGDegfhzwQIIDQA) ## Explanation 1. compute list of first `2*len(L)` jumps 2. find the number of unique indices in the last `len(l)` jumps --- # [Python](https://www.python.org), 93 bytes ``` lambda l,i=0,s=[0]:1+len([(s:=s+[i:=j])for _ in l if(j:=(i+l[i])%len(l))not in s])-s.index(j) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=dY_dCoIwFIDve4pBBBvOUNdFDPYka4Sho8ma4hbUs3QjRL1Tdz1KU0shCw4czvedH87lXp3dvjTNVbLN7ehkuH4InR52WQo0VizClvFI0DjQuYEcWspswBVlhUCyrMEWKAM0UBIWlEEVaK4EWrS9GiFTulZbgUK7VCbLT7BA7yPPqlbGQQn9doTmGMSzkfgKg2TCPYz-8LE_GXniqz5-KdKpeKJIp8gwRb4PxcPU6of6vNP_2TR9fgE) ## Explanation 1. go through the first `len(l)` jumps, stop if a duplicate is found 2. return the (1-based) index of the duplicate element in the list of indices counted from the end of the list [Answer] # JavaScript, 56 bytes ``` a=>(g=t=>t-(a[i=(i+a[i|0])%a.length]||=t++)||g(t))(i=.5) ``` ``` f= a=>(g=t=>t-(a[i=(i+a[i|0])%a.length]||=t++)||g(t))(i=.5) t = ` [0], 1 [0, 1, 2], 1 [1, 0, 2], 1 [1, 1, 2], 2 [2, 2, 2, 2], 2 [2, 3, 2, 1], 2 [3, 3, 3, 2], 3 [1, 1, 1, 1], 4 `.trim().split('\n').map(l => JSON.parse(`[${l}]`)); t.forEach(([i, e]) => { console.log(f([...i]) == e, f([...i])) }); ``` [Answer] # JavaScript (ES6), 54 bytes ``` f=(a,i=j=0)=>j-a[~i]||f(a,(i+a[i])%a.length,a[~i]=j++) ``` [Try it online!](https://tio.run/##hc5NCsMgEAXgfU/hpqBoftRu7UXExZDGVBEtTegq9Oo2pJTQUOkwq3kfj/HwgLG7u9tUxXTpc7YKA3PKq5aos69AP52ZZ7scsaOgnSFHqEMfh@nK1lB5SknuUhxT6OuQBmyxbg36DCGoaRA/7AVDnCFhymKJ27/iu0PshVji95qykKvgJSFXIbcO@fsPvnWc8gs "JavaScript (Node.js) – Try It Online") --- # JavaScript (ES12), 52 bytes -2 bytes by using nullish coalescing assignment, as suggested by [@tsh](https://codegolf.stackexchange.com/users/44718/tsh). ``` f=(a,i=j=0)=>j-(a[~i]??=j++)||f(a,(i+a[i])%a.length) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70kLz8ldcGCpaUlaboWN03SbDUSdTJts2wNNG3tsnQ1EqPrMmPt7W2ztLU1a2rSgJIamdqJ0ZmxmqqJejmpeeklGZoQvbcY-ZPz84rzc1L1cvLTNdI0og1iFWBAU1NBX1_BkAtdhY6CoY6CUSxuFUBpA4IqUM0wQldhBJSGoFjcKozBKgxxqTAGqzBGmGGM3R2GCDNMIOECC1sA) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~11~~ 10 bytes ``` +J,1ị@\ÐḶL ``` [Try it online!](https://tio.run/##y0rNyan8/1/bS8fw4e5uh5jDEx7u2Obz/3C77aGlRvqR//9Hc0UbxOooGOoAaRClYATlAZkGKDyonBGQZwSiwAghYAwWMIQKGIMFjCEqjOEGGEJUmOhwxQIA "Jelly – Try It Online") *-1 [thanks to Bubbler](https://chat.stackexchange.com/transcript/message/64427282#64427282)* ``` +J Add every jump number to its 1-index. ,1 Pair that with 1. ÐḶ Loop while unique then extract the cycle: \ scan by ị@ modular 1-index right into left. \ÐḶ (Dyadic ÐḶ doesn't reuse the right argument.) L Take the length of the cycle. ``` [Answer] # [Python](https://www.python.org), 99 bytes ``` lambda x,y=0,z={}:next(i-z[y]for i in range(len(x)+1)if y in z or[z:=z|{y:i},y:=(y+x[y])%len(x)]*0) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=XVDtasMgFGV_fYpLYKCrHfnYjyH4JGkoLjWbkJqgdsR0fZL9CYztnbanmaldWyZy9Zxzj_de37967146PX00fPW5c83y8btuxfZpI2Cgnqd05PsD03JwWC3H0ldNZ0CB0mCEfpa4lRoPZJER1YCf6RE6U46Mj297z9SBesaxXwzBSW5jcnWXkljq5wY5ad26FlZa4FvRY_kqWpokSZlWFDJUpiFSyCMIt_QanJQclXmIcZ9xccRZxMURF1Ev_sxZ1B9CvXvbt8rhZKUTQhCapzy3RkEOvayd3KyNtLvWzXNeGmcIwuqN0g5feXDMZby5sIRQiDTn_948fck0xfMX) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 16 bytes ``` 0λIā<+sè}Igô1èÙg ``` [Try it online!](https://tio.run/##yy9OTMpM/f/f4NxuzyONNtrFh1fUeqYf3mJ4eMXhmen//0cb6yhAkFEsAA "05AB1E – Try It Online") [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 12 bytes ``` ẏYd‡hǓ~↲t$↲L ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyJ+IiwiIiwi4bqPWWTigKFox5N+4oaydCTihrJMIiwiIiwiWzBdID0+IDFcblswLCAxLCAyXSA9PiAxXG5bMSwgMCwgMl0gPT4gMVxuWzEsIDEsIDJdID0+IDJcblsyLCAyLCAyLCAyXSA9PiAyXG5bMiwgMywgMiwgMV0gPT4gMlxuWzMsIDMsIDMsIDJdID0+IDNcblsxLCAxLCAxLCAxXSA9PiA0Il0=) [Answer] # [Scala](http://www.scala-lang.org/), 95 bytes Golfed version. [Try it online!](https://tio.run/##HY49r8IwDEX39yv8BiRbhIqPrVWQGJFADIgJMZiSQlAI4ER8Vf3tJXS4tnyOhxtKdtxe92dTRliy9VD/ARxMBZd0IMsx5DAT4fd2HcX6445y2HgbQXefALdEo/NY4cKGiGM1UWM1IqJkm5QHO6jyn9vOfdzpaZqgW6en9YMFRTFpXJt7Z5HUkIrnyTqD/5KVVx9TjYBMVEve11ywRu67H@i5LNiPaQrp9kAy6w/mtaqSbNqm/QI) ``` l=>{var(r,a)=(Seq[Int](),0);while(!r.contains(a)){r:+=a;a=(a+l(a))%l.size};r.size-r.indexOf(a)} ``` Ungolfed version. [Try it online!](https://tio.run/##PY49b8IwEIZ3fsXbAeksAmrTLRIDIxKoQ9Up6nANDhgZg85WC63y29OLFWU53/vhRxcb9tz316@zbRL27AL@ZsDBtrioIJZjrLAR4Uf9nsSF46ep8BFcwjo3gZu6yQdqaediorJ4LcrixRijaTcbYS35CkNeb0MaEPpMhG8WiKopJzP5rP5zVj8n5y3oSVbNNSQ9LhIbMyKQAYJqAR6N4ScxFvC5N4dfRfdrc9rlKdnAUhcXDvb@1mozX931/T8) ``` object Main { def main(args: Array[String]): Unit = { println(f(List(2,3,2,1))) } def f(l: List[Int]): Int = { var r = List[Int]() var a = 0 while (!r.contains(a)) { r = r :+ a a = (a + l(a)) % l.size } r.size - r.indexOf(a) } } ``` [Answer] # [J](https://www.jsoftware.com), ~~41 34 31 30~~ 29 bytes ``` ##@~.@}.0]F:.(#@[|]+{~)2###,: ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70wa8FNVUtFK8NYM0UrS3V1LiU99TQFWysFdQUdBQMFKyDW1VNwDvJxW1pakqZrsVdZ2aFOz6FWzyDWzUpPQ9khuiZWu7pO00hZWVnHCqLm5iNNrtTkjHyFNAUDOEPBUMEIxjEEcpE4SDJGEIjgGgOxIYxrDIYoOg1BshWZJUCXRxvE6gB50QZAUkfBCMIBsgyQOVAZI65oIyAJQXC-MZhvCOEbg_nGEHljmGZDiLwJxKcLFkBoAA) *-3 thanks to a nice observation by ovs: If you run the simulation 2\*n times, as I was, you can ensure you get only the cyclic elements by removing the first `n`* *I also shaved another byte off by applying a trick from another of ovs's suggestion* This is a combination of two suggestions from ovs, using `F:.` for folding. ## [J](https://www.jsoftware.com), ~~41 34 31~~ 30 bytes, saved for a new J trick ``` ##@~.@}.<@+:@#@[(#@[|]+{~^:)&0 ``` [Attempt This Online!](https://ato.pxeger.com/run?1=fZHBSgMxEIbxuk8xNdhNuttskhWxYReCQk_iwWtIRaSL9eKlgrA1L-JlPfgAvoDvoU_jNOnW9VKSmczH_88kkLf3x-77ZDbS0p2N9CxNk2OeNlBrSCEHARpjyuHy5mr-8bxupudfhBjPzSuvTKYNMZZibFzW-oVmYxFNP0efLLm-4HDYHCyScKuprAgruN_rbKGpqswEuTdaHYZR4mWFTUvODrkpdRnPeAF8guqd9sxQVxeeGLfJ2Iobshta4cMEdTltfavZdpKrxwQvcljfeoIXBPfy_uEJGhD7AiSoHiTiAAaKiusPSwzZYxnWv065VV9Wa_wKK1yOZAXmHFQErMQQdopKrMIc957LwDJyGbiMetk3y6ifxp_runj-Ag) * `<@+:@#@[(#@[|]+{~^:)&0` Simulate the jumps 2\*n times. For J lang enthusiasts, we are using a partially applied conjunction as an adverb here: `(#@[|]+{~^:)` -- it modifies the verb `<@+:@#@[`, and is equivalent to the standard form `(#@[|]+{~)^:(<@+:@#@[)`. It is acting here as a syntactic trick that allows us to save to some parens. * `##@~.@}.` Now remove the first n elements (ensuring we only have cyclic elements left), and take the count of the uniq [Answer] # [Ruby](https://www.ruby-lang.org/), 62 bytes ``` ->l{*r=a=0;1while r!=r|=[a=(a+l[a])%l.size];r.size-r.index(a)} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y6nWqvINtHWwNqwPCMzJ1WhSNG2qMY2OtFWI1E7JzoxVlM1R684syo11roITOsW6WXmpaRWaCRq1v4vUEiLjjbSMdYx0jGMjf0PAA "Ruby – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 29 bytes ``` UMθ⁺ικ⊞υ⁰F⁺θθ⊞υ§θ↨υ⁰I⊕⌕Φ⮌υκ⊟υ ``` [Try it online!](https://tio.run/##NU3JCoMwFLz3K97xBVLocvTUCgUPgvQqHkJ8xdCYaBbp36eJpXMYhlkYOQknrdAptWKp7TwLM@LKodPRo@LwZqw6dNFPGDmcsn5ZB7inubUyBv/wFhoz0qfYd@Hp19/XTpmAtfABGyMdzWQCjfhQppAO5PBJG7myYeUxv9sl64Iqpb4/c7hwuGYehnTc9Bc "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Port of @bsoelch's Python answer. ``` UMθ⁺ικ ``` Add the index to each element to give its (cyclic) destination index. ``` ⊞υ⁰ ``` Start on the leftmost index. ``` F⁺θθ ``` Repeat enough times to guarantee a cycle. ``` ⊞υ§θ↨υ⁰ ``` Get the next index. ``` I⊕⌕Φ⮌υκ⊟υ ``` Find the length of the cycle. ]
[Question] [ ## The Challenge Given an input string (or array) consisting of `<` and `>`, output a sequence (array or string) of integers such that: * the operators are all correct when applied in order between consecutive numbers in the output * all integers are positive (1 or greater) * the sum of the integers is as small as is mathematically possible Inputs can vary to match "greater than" and "less than" in your chosen language. As an alternative output, just specify the sum of the numbers in the output. State which version you're solving in your Answer title. Usual exclusions and rules apply, smallest bytes wins. You can assume that the input string will never lead to an integer overflow in your language, if that helps. ## Examples * `>` gives `2 1` which sums to `3` * `>>>` gives `4 3 2 1` which sums to `10` * `><` gives `2 1 2` which sums to `5` * gives `1` which sums to `1` * `>>>>>>>>>` gives `10 9 8 7 6 5 4 3 2 1` which sums to `55` * `>><<>><>>>` gives `3 2 1 2 3 2 1 4 3 2 1` which sums to `24` * `><>><>><>` gives `2 1 3 2 1 3 2 1 2 1` which sums to `18` * `<<<<>` gives `1 2 3 4 5 1` which sums to `16` * `<<<<><<>` gives `1 2 3 4 5 1 2 3 1` which sums to `22` * `>><<` gives `3 2 1 2 3` which sums to `11` [Answer] # [><>](https://esolangs.org/wiki/Fish), ~~40~~ 38 bytes ``` 1v!rnr~<oa ?\i:0(?^3%\+$ {/?:-{:}-1/1: ``` [Try it online!](https://tio.run/##S8sszvj/37BMsSivqM4mP5HLPibTykDDPs5YNUZbhata395Kt9qqVtdQ39Dq/387GzsA "><> – Try It Online") An appropriate language. For reference `><>` itself yields 2,1,2,1. ### How it Works: ``` 1v Initialise the stack as 1 and enter loop \i:0(?^ If we're out of input, go to the first line 3%\ Otherwise mod the input by 3, yielding 0 for < and 2 for > -1/Subtract 1 to get -1 and 1 respectively -{:} Copy the previous number and subtract the above from it /?: If the number is not 0, repeat the loop ?\ \+$ Otherwise: Increment each number until we reach the original 0 {/ /1: And enter the first loop again ~< When we're out of input, pop the extra -1 from EOF rnr Output the first number 1v! Push a 1 oa Print a newline and repeat, popping the extra 1 each time ``` [Answer] # Python 3, 93 bytes ``` k=0 for r in input().split('<'):p=len(r);print(max(k,p)+1,*range(p,0,-1),end=' ');k=1+(p<1)*k ``` [Try it online!](https://tio.run/##DcNRCsIwDADQf0/RvyZblBX/XJu7DKxaOrOQVdDT18F7@muvTa691zSdHps5c0UO@mmAl13X0sBHjzdNaxYwnNWKNHgvX6ikOAYabJFnBqWJzgEpyz1553GuKYygMeBQe2eO8cjMfw) Unscrambled: ``` # offset, will be explained later k = 0 for run in input().split('<'): # p = length of sequence of '>'s, which will produce p+1 decreasing integers p = len(run) # will print: # p+1 p p-1 ... 1 or k+1 p p-1 ... 1 print(max(k, p) + 1, *range(p, 0, -1), end=' ') # offset of the next sequence: (i.e. -1 + the minimal value of the first integer) k = 1 + (k if p > 0 else 0) ``` [Answer] # [Haskell](https://www.haskell.org/), 119 bytes ``` n%">"=r[1..n] n%"<"=[1..n] n%(c:b)|c==b!!0=(n+1)%b|a:s<-2%b,e:z<-r$n%[c]=r z++last(max:[min|c>'<'])a e:s r=reverse (2%) ``` [Try it online!](https://tio.run/##bY5BCoMwFET3nkKDwQSrVJchPxcRF0karFTTkkgp4t1TC6XY2lnNmz8M/yz9xQxDCBYjgcA1VVnaNlqJI/gA0UzRRQOoJDkCsXlFsVok87yosToYNvPCpRY3ugUXz3k@SD@RUT5YM/Z20SLjWUtlbJiPHDhzN86bqANSYxpG2Vs4XaP45no7pd36x8YLzjfIV4nv@67xin4W/mzseu8UhSc "Haskell – Try It Online") ## Explanation The idea here is that we have runs of either `>`s or `<`s, which each map to ascending and descending ranges. So we use `group` to split the string into groups of consecutive characters. Our job is to then stitch these together in the proper fashion. When we have `<>` we want to stitch the two lists together taking the larger end value for example ``` <<<<<<>> ``` is split ``` <<<<<< >> ``` mapped to ranges ``` [1,2,3,4,5,6,7] [3,2,1] ``` Then when we stitch we drop `3` because it is smaller (`3` isn't larger than `7`). ``` [1,2,3,4,5,6,7,2,1] ``` When we have `><` we do the opposite, we drop the larger value. The actual code attains this by making an operator `%`. The definition of `%` is quite complex, but basically it reads from left to right keeping track of how many consecutive characters are the same. It does this in the left had value of the operator. When we reach a place where the characters change we perform the stitching as I described. [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 36 bytes ``` 1 {`\b(1+)>\1 1$& }`(1+)<\1\b $&1 1 ``` [Try it online!](https://tio.run/##K0otycxL/K@q4Z7wn8uQqzohJknDUFvTLsaQy1BFjas2AcSziTGMSeJSUQOK/f9vx2VnB8Q2XCAaAoAsGxsghkjYQRCXDRBASRADpAYA "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: ``` 1 ``` Insert `1`s before, between and after the `<`s and `>`s. ``` {`\b(1+)>\1 1$& }`(1+)<\1\b $&1 ``` Repeatedly increment integers until all the comparisons are satisfied. ``` 1 ``` Sum the integers and convert to decimal. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 19 bytes ``` 0;+×¥@\ =”<µCṚÇṚ»Ç‘ ``` [Try it online!](https://tio.run/##y0rNyan8/9/AWvvw9ENLHWK4bB81zLU5tNX54c5Zh9uBxKHdh9sfNcz4/3D3loc7Fz9qWgOUrzm09eHOVQ93bAoD8Rv3PNyx6HC7ivehrUDuw10L/v9XV1e3qzFSMOSys7OrMVEwVgCzbUBCCkZcNWBxCKgxNFCwVLBQMFcwUzBVgCu1s7EBYpA8WACIITTCLDsIAhsJkYOpNOSyAQKgyWBdJkBjoSJogmAWxC6ELUCXAwA "Jelly – Try It Online") The value of each number is **max(** number of `>` immediately to the right of it **,** number of `<` immediately to the left of it **) + 1** . --- Alternatively... [Try it online!](https://tio.run/##y0rNyan8/9/AWvvw9Ic7Z5@cHsNl@6hhrs2hrc4Pd8463A4kDu0@3P6oYcb/h7u3PNy5@FHTGqB8zaGtD3euerhjUxiI37jn4Y5Fh9tVvA9tBXIf7lrw/7@6urpdjZGCIZednV2NiYKxAphtAxJSMOKqAYtDQI2hgYKlgoWCuYKZgqkCXKmdjQ0Qg@TBAkAMoRFm2UEQ2EiIHEylIZcNEABNBusyARoLFUETBLMgdiFsAbocAA "Jelly – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), 87 bytes ``` r=reverse s#c=(+1).length.takeWhile(==c)<$>scanr(:)[]s f s=zipWith max(s#'>')$r$r s#'<' ``` [Try it online!](https://tio.run/##DcbBCsMgDADQe78itEKVQWHXYfIbPYwdRNIptVISGWM/73p48FLQnUvpXVD4w6I86BTR3u5uKVzfLS0t7LymXNgiRucNaQxV7MM9XzpsoPjL55pbgiN8rU4zzc6IEbjq536EXAHhlFwbGNhgJPL@QkRj/wM "Haskell – Try It Online") A port of my Jelly answer. [Answer] # Java 10, ~~198~~ ~~181~~ 180 bytes ``` s->{var p=s.split("(?<=(.))(?!\\1)");int l=p.length,L[]=new int[l],i=l,r=0,a,b;for(;i-->0;r-=a*~a/2+(i<l-1?p[i].charAt(0)<61?a<(b=L[i+1])?a:b:1:0))a=L[i]=p[i].length()+1;return r;} ``` -1 byte thanks to *@ceilingcat*. [Try it online.](https://tio.run/##jVLLbtswELz3K1idyOpR0amNwhQlBEVvaS45KjrQMpMwZWiBpNwWgfvrLh@yUSs9lCAhaHZ2h7PLZ7Zn@fP2@7GXzBjwjQn1@g4AoSzXD6zn4Nb/BgD08M5qoR6BQcSBB3fcNpZZ0YNboAAFR5PXr3umwUBNYQYpLExgU1FYIASb9/f3GCWI@GKSDoXk6tE@ZTdtRxX/4TVa2WWCykzTMmPZhjzsNCQiz@uS6JyyD7/Zx0UKRSVz3Ayt6Ir@ielrC0tUrXDDKrihN61IcYcatt6s8bpEiHmoo4EeFSFKMdHcjloBTQ5HEp0M40Y6J5Oh/U5swYvrx@S67RiKvbDcOFt1koGr0IgzUnsMl5dg5bDlBeRJ88S4PHU5C1WVOzG2@DQrXcftC36@CFVuBXj1Fo6RxeKNjufjuYIDV/8Yd@hOIJ3eRBbeCJ96NKGWvwzuWSRffw68t3y7BknKyd@MQfs0Gpgx4GfuMUHxkgA/fB87j47ElJQmIJku69mam1H6QqrooTm7CPKnhOvejkz6O0T2XO@q/D@9E/Blp7Wz5QtCTmksOnHufhlXptiNtgh0qWD4Tr08HP8A) **Explanation:** ``` s->{ // Method with String parameter and integer return-type var p=s.split("(?<=(.))(?!\\1)"); // Split the String into parts // (i.e. ">><<>><>>>" becomes [>>, <<, >>, <, >>>]) int l=p.length, // Get the amount of parts L[]=new int[l], // Create an integer-array of the same size i=l, // Index-integer, starting at this size r=0, // Result-integer, starting at 0 a,b; // Two temp integers to reduce the byte-count for(;i-->0; // Loop downwards over the array; range: (`l`,0] ;r-= // After every iteration: decrease the result with: a*~a/2 // The negative triangle number of the current item + // And add to that negative triangle number before subtracting: (i<l-1? // If it's not the last item: p[i].charAt(0)<61? // And the order of the current and previous is "<>": a<(b=L[i+1])?// If the current item in `L` is smaller than the previous: a // Add the current item : // Else (the current is equal or larger than the previous): b // Add the previous item : // Else (the order of the two parts is "><" instead): 1 // Add 1 : // Else (it's the last item in `L`): 0)) // Leave the result `r` unchanged by adding 0 a=L[i]= // Set both `a` and the current item in `L` to: p[i].length()+1; // The length of the part + 1 return r;} // Return the result ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), 21 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` éda╓~/└↨☺∟╒←║ç Γφ5←9h ``` [Run and debug it](https://staxlang.xyz/#p=826461d67e2fc017011cd51bba8720e2ed351b3968&i=%22%3E%22%0A%22%3E%3E%3E%22%0A%22%3E%3C%22%0A%22%22%0A%22%3E%3E%3E%3E%3E%3E%3E%3E%3E%22%0A%22%3E%3E%3C%3C%3E%3E%3C%3E%3E%3E%22%0A%22%3E%3C%3E%3E%3C%3E%3E%3C%3E%22%0A%22%3C%3C%3C%3C%3E%22%0A%22%3C%3C%3C%3C%3E%3C%3C%3E%22%0A%22%3E%3E%3C%3C%22&a=1&m=2) It works by run-length encoding the input, and then concatenating generated ranges together. Unpacked, ungolfed, and commented, it looks like this. ``` |R run-length encode { begin block H^R range from [1 .. run length] _hh|1 -1 ** (character code / 2) * multiply run; this will reverse it iff character is '>' m map runs using preceding block O push a 1 under the top of stack { begin block h|M get the start of the generated range, and take max of it and top of stack _DE push the rest (tail) of the generated range to the stack F foreach generated range L|+ sum of all values on the stack ``` [Run this one](https://staxlang.xyz/#c=%7CR+++++%09run-length+encode%0A%7B++++++%09begin+block%0A++H%5ER++%09range+from+[1+..+run+length]%0A++_hh%7C1%09-1+**+%28character+code+%2F+2%29%0A++*++++%09multiply+run%3B+this+will+reverse+it+iff+character+is+%27%3E%27%0Am++++++%09map+runs+using+preceding+block%0AO++++++%09push+a+1+under+the+top+of+stack%0A%7B++++++%09begin+block%0A++h%7CM++%09get+the+start+of+the+generated+range,+and+take+max+of+it+and+top+of+stack%0A++_DE++%09push+the+rest+%28tail%29+of+the+generated+range+to+the+stack%0AF++++++%09foreach+generated+range%0AL%7C%2B++++%09sum+of+all+values+on+the+stack&i=%22%3E%22%0A%22%3E%3E%3E%22%0A%22%3E%3C%22%0A%22%22%0A%22%3E%3E%3E%3E%3E%3E%3E%3E%3E%22%0A%22%3E%3E%3C%3C%3E%3E%3C%3E%3E%3E%22%0A%22%3E%3C%3E%3E%3C%3E%3E%3C%3E%22%0A%22%3C%3C%3C%3C%3E%22%0A%22%3C%3C%3C%3C%3E%3C%3C%3E%22%0A%22%3E%3E%3C%3C%22&a=1&m=2) [Answer] # [Perl 5](https://www.perl.org/) `-p`, 53 bytes ``` #!/usr/bin/perl -p s//1/g;1while s/(?=\b(1+)>\1)|(1+)<\2\b\K/1/;$_=y/1// ``` [Try it online!](https://tio.run/##K0gtyjH9/79YX99QP93asDwjMydVoVhfw942JknDUFvTLsZQswbEsIkxikmK8QYqs1aJt60E0vr//9sAgd2//IKSzPy84v@6Bf91fU31DA30DAA "Perl 5 – Try It Online\" It Online") [Answer] # [Red](http://www.red-lang.org), 185 bytes ``` func[s][repeat n 1 + length? s[l: 0 i: n - 1 while[i > 0 and(s/(i) = #"<")][i: i - 1 l: l + 1]r: 0 i: n while[(i <= length? s)and(s/(i) = #">")][i: i + 1 r: r + 1]prin[1 + max l r""]]] ``` After user202729's explanation... [Try it online!](https://tio.run/##ZY7LDsIgEEX3/Yob3LQxRrslFP/BLWHRWGpJkBhao3@PQ2vsw0lImDNzDwTTxItplM5aHtunv6peq2Aeph7gUWIPZ/xt6M7oleM4wXLiB5q8OuuMspAEa9/k/TG3BSrsmGCFVrQHOy5SzJGn1OGXn7K5hahmf7G2yK/FpiwCz8IoeQTrVfrXvX6TNzCmtY6JDmhBqWy@S8mwaMVitl6basWEoLOBExJLJqj@@jVKrs1zZGHxAw "Red – Try It Online") ``` f: func[s][ repeat n 1 + length? s[ l: 0 i: n - 1 while [i > 0 and (s/(i) = #"<")][ i: i - 1 l: l + 1 ] r: 0 i: n while [(i <= length? s) and (s/(i) = #">")][ i: i + 1 r: r + 1 ] prin[1 + max l r ""] ] ] ``` ]
[Question] [ ## Challenge This is a simple challenge. Given **two positive integers** `w` and `h` create an ASCII fence with a width of `w` and a height of `h`. The fence should be constructed using the following rules: * The `+` character will represent a post. * The `-` character will be used to represent the width of the fence. * The `|` will be used to represent the height of the fence. * After *exactly* three `-` characters have been outputted, a `+` character *must* be outputted afterward. Excluding the four corners, any other time you output a `+` would be invalid. You are allowed to follow this rule starting either from the left or the right (see examples), but you must be consistent. * After *exactly* two `|` characters have been outputted, a `+` character *must* be outputted afterward. Excluding the four corners, any other time you output a `+` would be invalid. You are allowed to follow this rule starting either from the top or bottom (see examples), but you must be consistent. * Each fence will have exactly four corners, and each corner will be represented with a `+`. In other words: At every three `-` characters, you must output a `+`. And at every two `|` characters, you must output a `+`. You can assume that the fence will **always** be a rectangle, and that both `w` and `h` will never be greater than `100` or less than `1`. Trailing and/or preceding whitespace is allowed. ## Examples/Test Cases ``` w = 1 h = 1 +-+ | | +-+ w = 3 h = 2 +---+ | | | | +---+ w = 5 h = 7 +---+--+ or +--+---+ | | | | | | + + + + | | | | | | | | + + + + | | | | | | | | + + + + | | | | | | +---+--+ +--+---+ w = 10 h = 5 +---+---+---+-+ or +-+---+---+---+ | | | | | | + + + + | | | | | | | | + + + + | | | | | | +---+---+---+-+ +-+---+---+---+ w = 4 h = 4 +---+-+ or +-+---+ | | | | | | | | + + + + | | | | | | | | +---+-+ +-+---+ ``` ## Rules * [Standard loopholes apply](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default). * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins! [Answer] # C, 131 bytes ``` #define L for(i=0,j=w;j;)putchar(i++%4?--j,45:43);puts("+") f(w,h,i,j,c){L;for(j=1;h;printf("%c%*c\n",c,i,c))c=j++%3?--h,124:43;L;} ``` [Try it online!](https://tio.run/##ZY3RCoJAEEXf/YphQ9jNEdxcCRqkH/ATepGpzV3IogwfxG@3CerJ@zZnLudyfmVels354kN/gQb8/alDXWCsR4pkHu@Bu1ZQlqXumOcRXXVwpSF5vLTKlEm8HrHDgBHZTA19BbG21NHjGfrBa5VyuuVTr5ClxcZwHcVWiq1Du3Oio4bmRcpwa0OvTTIlIPHaItj/lDL0oyXCbk0rhP2a2gKhWmOH4OSYlw8) **Explanation:** ``` // The first and the last line are always similar, so let's use a macro // to avoid code duplication. #define L // Let's initialize 'i' and 'j'. 'i' will be used to keep track of which // character ('+' or '-') we should print, whereas 'j' starts from the // input width and the loop terminates when 'j' reaches zero. for(i=0,j=w;j;) // We post-increment 'i' and take a modulo 4 of its previous value. // If i%4 == 0, we print '+' (ASCII 43), otherwise we decrement 'j' // and print '-' (ASCII 45). putchar(i++%4?--j,45:43); // After the loop we print one more '+' and newline. puts("+") // The function declaration which takes the two input parameters, and // also declares three integer variables. These three variables could // also be declared as global variables with the same bytecount. f(w,h,i,j,c) // The start of the function body. We use the macro 'L' to print the // first line along with a newline. {L; // This loop prints all the lines between the first and the last. 'j' // keeps track of when we should output a '+' instead of a '|'. 'h', // which is the input parameter for height, serves as a terminator // for the loop as it reaches zero. for(j=1;h;<stuff missing from here>) // We post-increment 'j' and check if its previous value is divisible // by three, and if it isn't, we decrement 'h' and assign 124 (ASCII // value for '|') to 'c'. Otherwise we assign '+' (ASCII 43) to 'c'. c=j++%3?--h,124:43; // The following is inside the 'increment' part of the 'for' loop. // We print the character corresponding to the value of 'c', then // the same character again, but padded with i-1 spaces before it // ('i' hasn't been touched since the first loop, so it still stores // the length of the first line), then a newline. printf("%c%*c\n",c,i,c) // Lastly we print the first line again using the same macro 'L'. L;} ``` [Answer] # [Pip](https://github.com/dloscutoff/pip), 38 bytes 37 bytes of code, +1 for `-n` flag. ``` Ph:'-Xa<>3JW'+PsX#h-2WR:'|Xb<>2J'+^xh ``` Takes width and height as command-line arguments. [Try it online!](https://tio.run/##K8gs@P8/IMNKXTci0cbO2CtcXTugOEI5Q9coPMhKvSYiycbOyEtdO64i4////7p5/03/mwMA "Pip – Try It Online") ### Explanation ``` a,b are cmdline args; s is space; x is empty string (implicit) Ph:'-Xa<>3JW'+ '-Xa String of hyphens of length a <>3 grouped into substrings of (maximum) length 3 JW'+ Join on +, also wrapping the result in + h: Assign that string to h (mnemonic: "header") P and print it (with newline) PsX#h-2WR:'|Xb<>2J'+^xh '|Xb String of pipes of length b <>2 grouped into substrings of (maximum) length 2 J'+ joined on + ^x and split on empty string (i.e. converted to list of chars) sX#h-2 String of len(h)-2 spaces WR: Wrap the spaces with the list of chars Note 1: WR operates itemwise on lists, so the result is a list, each item of which consists of the spaces wrapped in an item from the list of chars Note 2: the : compute-and-assign meta-operator is here abused to give WR: lower precedence than J and ^ and avoid parentheses P Print that list, newline-separated (-n flag) h Autoprint the header a second time as the footer ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~140~~ ~~137~~ ~~128~~ ~~119~~ ~~106~~ 105 bytes ``` def f(w,h):a=~-w//3-~w;b=("+---"*w)[:a]+'+';print(b,*[i+' '*~-a+i for i in"||+"*h][:h+~-h//2],b,sep='\n') ``` [Try it online!](https://tio.run/##Xcy7CoMwFADQvV9xyZLXvaS@KCh@iXVQakiWKCqEguTX06WT6xnO9j3dGqqcP4sFKyI62U59omhMRSl2cy@YJiKmohzaadRc827bfTjFjGrwmgNXiSbtwa47ePCBXZdmyo1D63QiZ0w54ozHsvX8HbjMVhQIhfwvjMnuYUWFUN6oQXjdqHgiNDerEWqZfw "Python 3 – Try It Online") [Answer] # Mathematica, 165 bytes ``` v=Column;d[w_,y_,m_,n_]:=Table[If[Mod[i,y]==0&&i!=w,m,n],{i,w}];(a="+"<>d[#,3,"-+","-"]<>"+";b=v@d[#2,2,"|\n+","|"];v[{a,Row[{b,""<>Table[" ",#+Floor[#/3]],b}],a}])& ``` [Answer] # Charcoal, ~~47~~ ~~45~~ 40 bytes ``` F⁴«¿﹪ι³FIη↓⁺×+¬﹪κ²|FIθ⁺×+¬﹪κ³-P+¿⁼ι¹J⁰¦⁰ ``` Explanation: Works by drawing each side's `-`s/`|`s in turn, inserting `+`s where necessary, then finishing with a `+`. After drawing the top and right sides, jumps back to the start to draw them in reverse order, effectively drawing the left and bottom sides. I don't know whether rotational symmetry is permitted, but if so, then for ~~27~~ 25 bytes: ``` F⁴«FI⎇﹪ι²ηθ⁺×+¬﹪κ⁻³﹪ι²-⟲T ``` Takes the above idea to the extreme by drawing the top side, rotating left, drawing the right side, rotating again, and then repeating to draw the bottom and left sides in reverse. [Answer] # JavaScript (ES6), ~~133~~ 132 bytes ``` w=>h=>(a="-".repeat(w).replace(/--?-?/g,"+$&")+`+`)+(` |`.padEnd(a.length)+`|`).repeat(h).replace(/(\|( +)\|\n)\1/g,`$&+$2+ `)+` `+a ``` Takes input in currying syntax: `f(width)(height)`. ## Test Snippet ``` f= w=>h=>(a="-".repeat(w).replace(/--?-?/g,"+$&")+`+`)+(` |`.padEnd(a.length)+`|`).repeat(h).replace(/(\|( +)\|\n)\1/g,`$&+$2+ `)+` `+a O.innerHTML=f(W.value=5)(H.value=10) ``` ``` <div oninput="O.innerHTML=f(+W.value)(+H.value)"> W <input id=W type=number min=1> H <input id=H type=number min=1> </div> <pre id=O> ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 40 bytes ``` AQj++KjJj\+c*\-G3"++"m++d*lJ;dj\+c*\|H2K ``` [Test suite](http://pyth.herokuapp.com/?code=AQj%2B%2BKjJj%5C%2Bc%2a%5C-G3%22%2B%2B%22m%2B%2Bd%2alJ%3Bdj%5C%2Bc%2a%5C%7CH2K&test_suite=1&test_suite_input=1%2C1%0A3%2C2%0A5%2C7%0A10%2C5%0A4%2C4&debug=0). [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), ~~178~~ 177 bytes ``` w->h->{int i=0;String t="",m,r;for(;i<w;)t+=i++%3<1?"+-":"-";r=t+="+\n";m=t.format("|%"+(t.length()-3)+"s|\n","");for(i=0;i<h;)r+=i++%2<1&i>1?m.replace("|","+")+m:m;return r+t;} ``` [Try it online!](https://tio.run/##jZDNbsIwEITvPMXKElVcJxaBVpVwEm5IPfTEse3BhYSYxk7kbEAI8uypCT/qDU4erb@ZWXsjtzIoq9RsVr@d0lVpETZuxhtUBc8as0RVGv4sBlXzU6glLAtZ1/AhlYHDAEAZTG0mlynM4QALtMqsIfPcGHb@6RZyKqB15MVfo0R3bEu1Au1SvLPn8xukXde0DwV4Nzi/dEf/9RlOEsjibhckeZAcTh0qHolLN8aE@Nq3IiutJ1S0ExRZrBgbTqJwRlhApiQgwsZuStiXIULHyB2sJXrkOCTMQ16kZo25R4MJZaQ@OsonhPaRpyoV5YLac@o4Cp9UEs40t2lVuI9wIY5mhDI91cKm2FgDlqFoO9G/bbGvMdW8bJBXbmUsjJdxWVXF3gvpTdC78OQKjx@AX6/w2wNwOKI32336hd5ED7eDtvsD "Java (OpenJDK 8) – Try It Online") -1 byte thanks to @KevinCruijssen [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 47 45 37 bytes ``` A…+---÷⁺²×⁴N³αA…+||÷⁺¹×³N²βPα↓βα+↖↑⮌β ``` [Try it online!](https://tio.run/##S85ILErOT8z5///9noWPGpZp6@rqHt7@qHHXoU2Hpz9q3PJ@z7pDm89thErW1EDkdh6efmgzSGrTuU3v92w4t/FR2@Rzm85t1H7UNu1R28RH63rObfr/39BAwRQA "Charcoal – Try It Online") * 2 bytes saved after playing with the signs in the string creation. * 8 bytes saved thanks to Neil, who came up with a much simpler way to calculate the lengths of the fences. A different approach from [@Neil's](https://codegolf.stackexchange.com/a/128754/70347): first I create the strings `α` and `β` containing the chars in the horizontal and vertical borders, using the `Range` operator that creates a repetition of a string until a given length is reached. Then I print them in the proper order: * Print α without moving the cursor. * Print β downwards. * Print α. * Print a "+". * Move the cursor up and to the left. * Print β upwards, reversed. Link to a [verbose version](https://tio.run/##bczNCoJAFAXgfU8xuLqDM5Bam1wJboKKkHwAf242oOPgjLbx3acmKKHaHO7lcL7qVgxVX7TWJlqLRkJWyAbB8znnHiN7aVIxiRohqWsIGbmIDjVsXKNGcxq7EgeglDISuShovPqC5vnHCd5O9McJXZRP5zi2RqhBSAOOPb@uXdrfJSs//9J4vudG/YSwy9UBr2YZ5YplOOGgEUpKY2uDNdlaPlmu2wc). [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 58 bytes ``` D3/ó+DU'-×'+.ø©'|DXú«²D2/ó+.D®»'-4×D'+3ǝ.:¶¡ø'|3×D'+2ǝ.:ø» ``` [Try it online!](https://tio.run/##MzBNTDJM/f/fxVj/8GZtl1B13cPT1bX1Du84tFK9xiXi8K5Dqw9tcjECSeq5HFp3aLe6rsnh6S7q2sbH5@pZHdp2aOHhHeo1xmAhI5AQUOfu//9NuUwB "05AB1E – Try It Online") Harder in 05AB1E than I thought. ]
[Question] [ [Zeckendorf's theorem](https://en.wikipedia.org/wiki/Zeckendorf%27s_theorem) shows that every positive integer can be uniquely represented as a sum of non-adjacent Fibonacci numbers. In this challenge, you have to compute the sum of two numbers in Zeckendorf representation. --- Let Fn be the *n*-th Fibonacci number where > > F1 = 1, > > F2 = 2  and > > for all *k* > 2, F*k* = F*k* - 1 + F*k* - 2. > > > The *Zeckendorf representation* Z(*n*) of a non-negative integer *n* is a set of positive integers such that > > *n* = Σ*i* ∈ Z(*n*) F*i*  and > > ∀*i* ∈ Z(*n*) *i* + 1 ∉ Z(*n*). > > > (in prosa: the Zeckendorf representation of a number *n* is a set of positive integers such that the Fibonacci numbers for these indices sum up to *n* and no two adjacent integers are part of that set) Notably, the Zeckendorf representation is unique. Here are some examples for Zeckendorf representations: > > Z(0) = ∅ (the empty set) > > Z(1) = {1} > > Z(2) = {2} > > Z(3) = {3} ({1, 2} is not the Zeckendorf representation of 3) > > Z(10) = {5, 2} > > Z(100) = {3, 5, 10} > > > In this challenge, Zeckendorf representations are encoded as [bit sets](https://en.wikipedia.org/wiki/Bit_array) where the least significant bit represents if `1` is part of the set, etc. You may assume that the Zeckendorf representations of both input and output fit into 31 bits. Your task is to compute Z(*n* + *m*) given Z(*n*) and Z(*m*). The solution with the shortest length in octets wins. You can find a reference implementation written in ANSI C [here](http://fuz.su/~fuz/src/zeck.c). It can also be used to generate Zeckendorf representations or compute a number from its Zeckendorf representation. Here are some pairs of sample input and output, where the first two columns contain the input and the third column contains the output: ``` 73865 9077257 9478805 139808 287648018 287965250 34 279004309 279004425 139940 68437025 69241105 272794768 1051152 273846948 16405 78284865 83888256 9576577 4718601 19013770 269128740 591914 270574722 8410276 2768969 11184785 16384 340 16724 ``` [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 39 bytes ``` ⊥1↓⍧|/⌽(+/g[⍸⌽+/⊤⎕]),↑,\⌽g←(2+/,)⍣38⍨⍳2 ``` [Try it online!](https://tio.run/##PY89TgNBDIX7OcWUiZJobY/H9hyBigMARaT8NBGkoACJOqCIRSBESQUIehoaLjMXWYzYpbP93vfmzXy7mS0u55uz9Wx5cb48XSwXXb17Ojisu3sI9eZ61dX9G9bdY23fr5p6@z2aNOuj2n75OGnq/tXdJ@Np3T1Mj/20dm5Ek2Y6ru1Lstp@1PaTOg/qVrG2z7GwmkEOmkxyLKBKWcOfRqZFMmUImIqB/R6EDdAGgxYAZsohcb8kKL0ohRjRox0uDFGMk4J7BzYZS2ELpI6yikV3I2bqHZbMjLIEFIYc1cjYS/YqFsCkCqFklawaWdEE8D8esrISBZKCXtwb5IIFeeARzf@egzECqTghVmRoj6LE/rKXjInhBw "APL (Dyalog Extended) – Try It Online") Changed into a full program taking one argument of length 2, and also changed the Fibonacci generator. Thanks to @ngn for lots of ideas. Uses `⎕IO←0` so that `⍳2` evaluates to `0 1`. ### Fibonacci generator (new) Note that the last two numbers are inaccurate, but it doesn't change the output of the program. ``` (2+/,)⍣38⍨⍳2 → 0 1 ((2+/,)⍣38) 0 1 Step 1 0 1 (2+/,) 0 1 → 2+/ 0 1 0 1 → (0+1) (1+0) (0+1) ⍝ 2+/ evaluates sums for moving window of length 2 → 1 1 1 Step 2 0 1 (2+/,) 1 1 1 → 2+/ 0 1 1 1 1 → 1 2 2 2 Step 3 0 1 (2+/,) 1 2 2 2 → 2+/ 0 1 1 2 2 2 → 1 2 3 4 4 ``` ### Zeckendorf to plain (partial) ``` ⍸⌽+/⊤⎕ ⎕ ⍝ Take input from stdin, must be an array of 2 numbers ⊤ ⍝ Convert each number to base 2; each number is mapped to a column +/ ⍝ Sum in row direction; add up the counts at each digit position ⌽ ⍝ Reverse ⍸ ⍝ Convert each number n at index i to n copies of i ``` --- # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 47 bytes ``` g←1↓(1,+\⍤,)⍣20⍨1 {⊥1↓⍧|/⌽⍵,↑,\⌽g}+⍥{+/g[⍸⌽⊤⍵]} ``` [Try it online!](https://tio.run/##HY8xTgMxEEV7n2JLUDbKjD32jAsqGlIhETpCESnJNhFQUIBCKqQUEY5AiBOQCDoqJBoajuKLLONtLHue//fz5GbRn95PFtdNf3Z3O7uazqZt2@T1M@b16wHWvXFOu/owp3cLOX2iWebNvrCcPh4G@ek3p@86r1/qse6bVS@n/bI3aC5y@ilws1N@uWrn2pjTNm/fhqd58/j35TSjp9HZsa7nJ8NRG4lFwFdHFTsJvppXEZitZ2OFY/DWgzJ0UUAU6jCQAIqxHAGIbIk6KqgbOIgmREuIXakGI4HSIOQYrNecEwqRRKllDRGH0qz3Eb014kTE@lDCgaAYsVghlTMYAR1zMYqeg2dWSowSALUYPBNbW4pDRFXtXvYRI5JBRNG/FikhBMuhcw4SQzQY2FL3osrp3BH8Aw "APL (Dyalog Extended) – Try It Online") Changed Part 1 of the previous answer to reuse the Fibonacci numbers. Also, drop the duplicate 1 to save some bytes in other places. ### Part 1 (new) ``` {+/g[⍸⌽⊤⍵]} ⊤⍵ ⍝ Argument to binary digits ⍸⌽ ⍝ Reverse and convert to indices of ones g[ ] ⍝ Index into the Fibonacci array of 1,2,3,5,... +/ ⍝ Sum ``` --- # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 52 bytes ``` {⊥1↓¯1↓⍧|/⌽⍵,↑,\⌽(1,+\⍤,)⍣20⍨1}+⍥({+∘÷⍣(⌽⍳≢⊤⍵)⍨1}⊥⊤) ``` [Try it online!](https://tio.run/##HY@xSgNBEIb7e4orE5LgzO7szmxhZWMqwVimCSTaBLWwUKKVEDR4QRHBWhO0SyFiZRPfZF7knL1m2Jl//n@@HZ1Pe@Or0fTspDe5vJicjifjup7pYo06f95uctXq43pHH361@u7q/Kk7tHcLu52hVqtuW6t3B1p94k1Hq3Vr1tG7178fm7Yay5fev@liZd52s2TJ1rbrY50/arXU5Uv/QBe32423aOsGh3tWj/b7gzoRi0Aod0v2EkN5XCZgdoELJ5xicAFMQ58ExEQbRhJAKRwnACKXrZ6y1Aw8pCImR4hNqBkTgalRyDO4YD4vFBOJqY7NRBxzsu0jBleIFxEXYjZHgkzE4oQMrsAE6JkzUQocA7OpxCgR0IIhMLFzOTgmNNTmckiYkApEFPtrhhJCcBwb5igppgIjO2ouGpzNPcE/ "APL (Dyalog Extended) – Try It Online") ### How it works No fancy algorithm to do addition in Zeckendorf because APL isn't known for operation on individual elements in an array. Instead, I went ahead to convert the two inputs from Zeckendorf to plain integers, add them, and convert it back. ### Part 1: Zeckendorf to plain integer ``` {+∘÷⍣(⌽⍳≢⊤⍵)⍨1}⊥⊤ ⍝ Zeckendorf to plain integer ⊤ ⍝ Convert the input to array of binary digits (X) { ( ≢⊤⍵) } ⍝ Take the length L of the binary digits and ⌽⍳ ⍝ generate 1,2..L backwards, so L..2,1 {+∘÷⍣( )⍨1} ⍝ Apply "Inverse and add 1" L..2,1 times to 1 ⍝ The result looks like ..8÷5 5÷3 3÷2 2 (Y) ⊥ ⍝ Mixed base conversion of X into base Y Base | Digit value ------------------------------- 13÷8 | (8÷5)×(5÷3)×(3÷2)×2 = 8 8÷5 | (5÷3)×(3÷2)×2 = 5 5÷3 | (3÷2)×2 = 3 3÷2 | 2 = 2 2÷1 | 1 = 1 ``` ### Part 2: Add two plain integers ``` +⍥z2i ⍝ Given left and right arguments, ⍝ apply z2i to each of them and add the two ``` ### Part 3: Convert the sum back to Zeckendorf "You may assume that the Zeckendorf representations of both input and output fit into 31 bits" was pretty handy. ``` {⊥1↓¯1↓⍧|/⌽⍵,↑,\⌽(1,+\⍤,)⍣20⍨1} ⍝ Convert plain integer N to Zeckendorf (1,+\⍤,)⍣20⍨1 ⍝ First 41 Fibonacci numbers starting with two 1's ⌽ ⍝ Reverse ↑,\ ⍝ Matrix of prefixes, filling empty spaces with 0's ⌽⍵, ⍝ Prepend N to each row and reverse horizontally |/ ⍝ Reduce by | (residue) on each row (see below) ⍧ ⍝ Nub sieve; 1 at first appearance of each number, 0 otherwise 1↓¯1↓ ⍝ Remove first and last item ⊥ ⍝ Convert from binary digits to integer ``` ### The Fibonacci generator ``` (1,+\⍤,)⍣20⍨1 → 1 ((1,+\⍤,)⍣20) 1 ⍝ Expand ⍨ → Apply 1 (1,+\⍤,) x 20 times to 1 First iteration 1(1,+\⍤,)1 → 1,+\1,1 ⍝ Expand the train → 1,1 2 ⍝ +\ is cumulative sum → 1 1 2 ⍝ First three Fibonacci numbers Second iteration 1(1,+\⍤,)1 1 2 → 1,+\1,1 1 2 ⍝ Expand the train → 1 1 2 3 5 ⍝ First five Fibonacci numbers ⍣20 ⍝ ... Repeat 20 times ``` This follows from the property of Fibonacci numbers: if Fibonacci is defined as $$ F\_0 = F\_1 = 1; \forall n \ge 0, F\_{n+2} = F\_{n+1} + F\_n $$ then $$ \forall n \ge 0, \sum\_{i=0}^{n} F\_i = F\_{n+2} - 1 $$ So cumulative sum of \$ 1,F\_0, \cdots, F\_n \$ (Fibonacci array prepended with a 1) becomes \$ F\_1, \cdots, F\_{n+2} \$. Then I prepend a 1 again to get the usual Fibonacci array starting with index 0. ### Fibonacci to Zeckendorf digits ``` Input: 7, Fibonacci: 1 1 2 3 5 8 13 Matrix 0 0 0 0 0 0 13 7 0 0 0 0 0 8 13 7 0 0 0 0 5 8 13 7 0 0 0 3 5 8 13 7 0 0 2 3 5 8 13 7 0 1 2 3 5 8 13 7 1 1 2 3 5 8 13 7 Reduction by residue (|/) - Right side always binds first. - x|y is equivalent to y%x in other languages. - 0|y is defined as y, so leading zeros are ignored. - So we're effectively doing cumulative scan from the right. 0 0 0 0 0 0 13 7 → 13|7 = 7 0 0 0 0 0 8 13 7 → 8|7 = 7 0 0 0 0 5 8 13 7 → 5|7 = 2 0 0 0 3 5 8 13 7 → 3|2 = 2 0 0 2 3 5 8 13 7 → 2|2 = 0 0 1 2 3 5 8 13 7 → 1|0 = 0 1 1 2 3 5 8 13 7 → 1|0 = 0 Result: 7 7 2 2 0 0 0 Nub sieve (⍧): 1 0 1 0 1 0 0 1's in the middle are produced when divisor ≤ dividend (so it contributes to a Zeckendorf digit). But the first 1 and last 0 are meaningless. Drop first and last (1↓¯1↓): 0 1 0 1 0 Finally, we apply base 2 to integer (⊥) to match the output format. ``` [Answer] # CJam, ~~76~~ ~~74~~ ~~70~~ ~~63~~ 59 bytes ``` 2q~{32{2\#I&},}fI+32_,*{WUer$Kf-[UU]/[-2X]*2,/2a*Kf+}fKf#1b ``` Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=2q~%7B32%7B2%5C%23I%26%7D%2C%7DfI%2B32_%2C*%7BWUer%24Kf-%5BUU%5D%2F%5B-2X%5D*2%2C%2F2a*Kf%2B%7DfKf%231b&input=%5B73865%209077257%5D) or [verify all test cases at once](http://cjam.aditsu.net/#code=qN%2F%7B%5B~%5D)2%40%7B32%7B2%5C%23I%26%7D%2C%7DfI%2B32_%2C*%7BWUer%24Kf-%5BUU%5D%2F%5B-2X%5D*2%2C%2F2a*Kf%2B%7DfKf%231b%3Dp%7D%2F&input=73865%20%20%20%20%20%20%20%20%20%20%209077257%20%20%20%20%20%20%20%20%209478805%0A139808%20%20%20%20%20%20%20%20%20%20287648018%20%20%20%20%20%20%20287965250%0A34%20%20%20%20%20%20%20%20%20%20%20%20%20%20279004309%20%20%20%20%20%20%20279004425%0A139940%20%20%20%20%20%20%20%20%20%2068437025%20%20%20%20%20%20%20%2069241105%0A272794768%20%20%20%20%20%20%201051152%20%20%20%20%20%20%20%20%20273846948%0A16405%20%20%20%20%20%20%20%20%20%20%2078284865%20%20%20%20%20%20%20%2083888256%0A9576577%20%20%20%20%20%20%20%20%204718601%20%20%20%20%20%20%20%20%2019013770%0A269128740%20%20%20%20%20%20%20591914%20%20%20%20%20%20%20%20%20%20270574722%0A8410276%20%20%20%20%20%20%20%20%202768969%20%20%20%20%20%20%20%20%2011184785%0A16384%20%20%20%20%20%20%20%20%20%20%20340%20%20%20%20%20%20%20%20%20%20%20%20%2016724). ### Idea We start by defining a minor variation of the sequence in the question: > > **G-2 = 0** > > **G-1 = 1** > > **Gk = Gk-1 + Gk-2** whenever **k** is a non-negative integer > > > This way, the bit **0** (LSB) of the bit arrays input or output corresponds to the Fibonacci number **G0** and, in general, the bit **k** to **Gk**. Now, we replace each set bit in **Z(n)** and **Z(m)** by the index it encodes. For example, the input **53210 = 10000101002** gets transformed into **[2 4 9]**. This yields two arrays of integers, which we can concatenate to form a single one. For example, if **n = m = 100**, the result is **A := [2 4 9 2 4 9]**. If we replace each **k** in **A** by **Gk** and add the results, we obtain **n + m = 200**, so **A** is *a* way to decompose **200** into Fibonacci numbers, but certainly not the one from Zeckendorf's theorem. Keeping in mind that **Gk + Gk+1 = Gk+2** and **Gk + Gk = Gk + Gk-1 + Gk-2 = Gk+1 + Gk-2**, we can substitute consecutive and duplicated indexes by others (namely, **(k, k + 1)** by **k + 2** and **(k, k)** by **(k + 1, k - 2)**), repeating those substitutions over and over until the Zeckendorf representation is reached.1 Special case has to be taken for resulting negative indexes. Since **G-2 = 0**, index **-2** can simply be ignored. Also, **G-1 = 0 = G0**, so any resulting **-1** has to be replaced by **0**. For our example **A**, we obtain the following (sorted) representations, the last being the Zeckendorf representation. **[2 2 4 4 9 9] → [0 3 4 4 9 9] → [0 5 4 9 9] → [0 6 9 9] → [0 6 7 10] → [0 8 10]** Finally, we convert back from array of integers to bit array. ### Code ``` 2 e# Push a 2 we'll need later. q~ e# Read and evaluate the input. { e# For each integer I in the input: 32{ e# Filter [0 ... 31]; for each J: 2\# e# Compute 2**J. I& e# Compute its logical AND with I. }, e# Keep J if the result in truthy (non-zero). }fI e# + e# Concatenate the resulting arrays. 32_,* e# Repeat [0 ... 31] 32 times. { e# For each K: WUer e# Replace -1's with 0's. $ e# Sort. Kf- e# Subtract K from each element. [UU]/[-2X]* e# Replace subarrays [0 0] with [-2 1]. 2,/2a* e# Replace subarrays [0 1] with [2]. Kf+ e# Add K to each element. }fK e# f# e# Replace each K with 2**K. 1b e# Cast all to integer (discards 2**-2) and sum. ``` --- 1 The implementation attempts substituting 32 times and does not check if the Zeckendorf representation has in fact been reached. I do not have a formal proof that this is sufficient, but I've tested all possible sums of 15-bit representations (whose sums' representations require up to 17 bits) and 6 repetitions was enough for all of them. In any case, augmenting the number of repetitions to 99 is possible without incrementing the byte count, but it would cripple performance. [Answer] # Haskell, 325 ~~396~~ bytes EDIT: new version: ``` s f[]=[] s f l=f l x((a:b):(c:d):(e:r))=x(b:d:(a:e):r) x(a:b:((c:d:e):r))=x((c:a):b:e:((d:s head r):s tail r)) x[]=[] x(a:r)=a:x r w l|x l/=l=w.x$l|True=l l=length t n x=take n$repeat x j 0=[] j n=t(mod(n)2)1:j(div(n)2) i n=[[],[]]++j n++t(32-(l$j n))[] u[]=0 u(a:r)=2*u r+l a o(_:a:r)=u r+l a z a b=o$w$zipWith(++)(i a)(i b) ``` `z` does the job. [Answer] # [K (ngn/k)](https://bitbucket.org/ngn/k), ~~45 43 42~~ 41 bytes ``` {2/<':(+/F@&+/'|2\x){y!x}\|F:64(+':1,)/0} ``` [Try it online!](https://tio.run/##NY/NTgJRDIX3PsU1MQJBM21vb3@mLlzxEkCCmzEGgwlhMZMBX328QNyd9PScft2/Hj4P09S1IzVvs3a@bFbvz8tmdqZNvxiHx/6yOa9a4fly1uLLooHLdGrHp/Xwe2y71MfuZx/zXffx9R19DHFcbC8Pp7Vmk5IcVKloOKsZlG01MLuBJTIVNkCLqlwKFbi6mROpA3AGj7ti@s85QxLjrEAlxIkR752kdZVVLNUBYqEazcbibLeoMJSkRsYVKiybGRW5Wl5UimpiRRPAQAfMqjcWEscKV48WR0eupVCUlejqGiOQSsUVc/FARKtf3lmlXk@ZIVCUeDv9AQ "K (ngn/k) – Try It Online") [@Bubbler's algorithm](https://codegolf.stackexchange.com/questions/54287/summation-under-zeckendorf-representation/196175#196175) `{` `}` function with argument `x` `64(` `)/0` do 64 times, using 0 as initial value: * `1,` prepend 1 * `+':` add each prior (leave the first element intact) `F:` assign to `F` for "fibonacci sequence" `|` reverse `(`..`){y!x}\`.. starting with the value on the left, compute cumulative remainders (left-to-right) for the list on the right. the value on the left is the plain sum of the inputs without zeckendorf representation: * `2\x` binary encode the inputs. this will be an nbits-by-2 matrix * `|` reverse * `+/'` sum each * `&` where are the 1s? - list of indices. if there are any 2s, the corresponding index is repeated twice. * `F@` array indexing into `F` * `+/` sum `<':` less than each prior (the first of the result will always be falsey) `2/` binary decode [Answer] ## ES6, 130 bytes ``` (n,m)=>{for(a={},s=0,i=x=y=1;i<<1;i+=i,z=y,y=x,x+=z)s+=((n&i)+(m&i))/i*(a[i]=x);for(r=0;i;i>>>=1)s>=a[i]?(s-=a[i],r|=i):0;return r} ``` I originally tried to compute the sum in-place (effectively along the lines of the CJam implementation) but I kept running out of temporaries, so I just converted the numbers to and back from real integers. (Yes, I can probably save a byte by using eval.) [Answer] # [Ruby](https://www.ruby-lang.org/), ~~85 73~~ 65 bytes ``` ->*a{r=(0..2*a.sum).select{|r|r^r*2==r*3};r[a.sum{|w|r.index w}]} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf104rsbrIVsNAT89IK1GvuDRXU684NSc1uaS6pqimKK5Iy8jWtkjLuNa6KBosXV1TXlOkl5mXklqhUF4bW/u/QCEt2tDM2MJEx9jEIJYLxDU3tjAz1VGwNDA3NzI1j/0PAA "Ruby – Try It Online") ### How? First get an upper bound for the encoded sum: (a+b)\*2 is ok. Now filter out all non-zeckendorf numbers from (0..limit). We have a lookup table, it's downhill from here. [Answer] # Python 3, 207 bytes ``` def s(n): p=1 while n>=2*p: p*=2 return n if n<=p else s(n+p//2)if n>=3*p/2 else s(m)if (m:=s(n-p)+p)!= n else n a=lambda n,m:(b:=n&m)>-1 and s(a(a(a(s((n|m)-b%4),b//4*2),b//4),b%4*2+b%4//2))if m else n ``` [Try it Online! (Verify all test cases)](https://tio.run/##NY/tboMgFIZ/16tgJl2g4uT7wwxvpOkPTW1qUilRl3XJ7t2B7SCBw3Pe97wh/CzXu@cmTOt67i9ghh7V2S44mu2@r8OtB75x7BAi24WDY9lu6pevyQMPhgvwny6A/jb3yVeEqmIo0cbxQ6jYf2dMEI61i6IyoCKgNxf9W9dnrbu1Y3dugcdjDbva@fcRNSUFrT9Hc7vtGUL/O6Ky2wuEu6oSB/a847mPjyKeKT0lja/J69LPy@yOueZGSWyJ1kzqHGc55dYQg5nRShhCTWJcYKYtIYIT@9JYQbAygmvCZEJMR4XQymBKJKWSbToliMTaMCNiSiJWaiW1xkJTowjdnMrSmBbnSUstFYkZQQnTKqYqY9UzU3EjMBckP2XZ5T6BAQwebN@oMxDXww0fc7gNC8xxjjYUpsEv8HEkpyIyDB5HesIgL5tYt/C/h/CzoieE0PoH) ## Explanation This program directly manipulates the binary translations of the Zeckendorf representations. The function `a(n,m)` performs the main calculations, and `s(n)` is a helper function that gets rid of adjacent numbers contained in the Zeckendorf representation. Let's start with the function `s(n)` (expanded for clarity): ``` def s(n): p=1 #This finds the highest digit of the binary form of n. while n>=2*p: p*=2 if n<=p: #If n is a power of two (i.e, our number is already a Fibonnaci number)... return n #Then return it normally. This also works for zero. (A) if n>=3*p/2: #If n's first digit is followed by a 1 (i.e, it starts with 11X) return s(n+p//2) #Then replace that with 100X (B) m = s(n-p)+p #Otherwise, apply s to the rest of the number (C) if m==n: #If this is out final result, we're done! (D) return n return s(m) #Otherwise, reapply it. (E) ``` For example, the number 107 (`1101011` in binary, representing 1+2+5+13+21=42), undergoes the following process: ``` 1+2+5+13+21 [1101011] -> 1+2+5+34 [10001011] (B) 1+2+5+34 [10001011] (C) 1+2+5 [1011] (C) 1+2 [11] -> 3 [100] (B) ->3+5 [1100] (A/E) (E): 3+5 [1100] -> 8 [10000] (B) ->8+34 [10010000] (A/E) (E): 8+34 [10010000] (C) ->8+34 [10010000] (A/E) ``` [Try it Online! (s with detailed output)](https://tio.run/##fVTBjpswEL3zFVNX1eJASGAPrVAdadum0p566S3aA1mcxaqxLeMIpT@fjoEAyUa1IgXGnnnz3jxjTq7S6vGLsedzyQ9wEPtQ0TwAXOIAirEUtPX/WR/0y3J3tApUMHvpEpcpjfqHjAaBr2f5Qdu6cGNRfXTm6BghPQQwSLunmvXl2kpIDmqznuB8H58y7GQKTZUi1jgbelBBaUQiMqVFLB1fFFOrVTZvuE/f5cv0JSKwIxDBXqiwprssx8gL6Qk0oYolW9McumSDetxZH39XokENVNmAqzhU4q3ijYNSvAkH@tAFsXxhT@AF8SGVXBFm2cJMBM2CZeMQvjKT3wI@YxwQswCjW247jFZDKBIeIzcc2bHeY9wfkZYX5QmP/hR7rVTxKoZdmiTJu6le0@LqsoFElJ@llKcEoCNcyEZDq@2fxrOCv9zqBMInOna@YY8Ls8ry284fvFh2FMhrp6VEIiXsfaPpQAT3GldY10ArXAVpig3TSSQrlAsJkIWMZkbDcS43QGahyODwaQQEwm@U0FvKzXAilnSkbGTxynFshRug12vE9vnB/6HD7xeEGs2NpZcmlhFeDHMR4BeawbaiQX6FMfIE6BndOcR6zwxuGeaH5d4BkuVmxq7uUJ9W2wsuCl8zpu5Zxvmp4c8bBN1aSA95lC6Glj9YDqVW/AOEP@j9u37VRLjFS0Fi4KrE60yDK0Frr@UEPaOMXuxIC4dqbvEz0YTp@jM9n/8B) Here is an expanded version of `a(n,m)`: ``` def a(n,m): if m==0: return n b=n&m t=s((n|m)-b%4) #(A) t=a(t,b//4*2) #(B) t=a(t,b//4) #(C) return s(a(t,b%4*2+b%4//2)) #(D) ``` This function converts the two Zeckendorf representations into four binary numbers which are easier to combine. Line (A) is the bitwise OR of the two binary Zeckendorf representations--these correspond to one copy of each Fibonacci number in either group. (B) and (C) are the bitwise AND of the two numbers right-shifted 1 and 2 times, respectively. We know that when the corresponding Fibonacci numbers for (B) and (C) are added together, they will be equivalent to the bitwise AND of our `n` and `m` because F(n)=F(n-1)+F(n-2). For example, let's say that we have the binary numbers n=101001 (corresponding to 1+5+13) and m=110110 (2+3+8+13). Then we will have (A)=111111 (1+2+3+5+8+13), which is converted to 1010100 (3+8+21) by our function `s`, (B)=10000 (8), and (C)=1000 (5). We can check that (1+5+13)+(2+3+8+13)=(3+8+21)+(8)+(5)=45. This process repeats with ((3+8+21)+(8))+(5)=((3+8+21)+(5)+(3))+(5), etc. The one difficulty with this system is that it doesn't work for the Fibonacci numbers 1 and 2, since they don't obey the property `F(n)=F(n-1)+F(n-2)` (they're the lowest two numbers)! Because of that, whenever 1 or 2 is contained in both `n` and `m`, they are removed from A, B, and C, then their sum placed in D under the property that 1+1=2 and 2+2=1+3. For example, if we add 1+3 (101) + 1+3+5 (1101), we get: (A): 3+5 (1100) = 8 (10000) (B): 2 (10) (C): 1 (1) (D): 2 (10) Notice that the 3 and 5 were placed into A, the duplicate 3 was split into 2+1 in B and C, and duplicate 1s were removed from A, B, and C, added together, and put into D. Similarly, if we add 2+3 (110) + 2+3+5 (1110), we get: (A): 3+5 (1100) = 8 (10000) (B): 2 (10) (C): 1 (1) (D): 1+3 (101) [Try it online! (a with detailed output)](https://tio.run/##fVNRb5swEH7Pr7gxdcWBkECraUJzpbVVpT3tZW9RH0zjFGvGtoxTlGn/PTvjJJAmG4oCHN/dfd99Z7N1tVY3X4zd7VZ8DWtRxYqUE8BLrEFRmoO2/l6EoL8sdxurQE1GL33iLCdJeCjIZOLrWb7WtmHuWFRvnNk4GkWhBVDI@6eGhnJdLSQHdbcY2nkeVwUyGUJDpYS2zsa@qSAkiZJoSEtofnxRVM3nxZhwSF@Ws/w5iWAZQQKVUHFDlkWJkecoCGhjlUq6ICX0yQbncXZ9/FmLFiegVi24mkMtXmveOliJV@FAr/sgFmd2C34cPqSyE7m0mJpBnpnS4mjBV2rK03bfMQrYkYHRHbd9h05DLDKeoi60a9NUGPcQaTlbbRH6JCqtFHsR@68ky7IzR8eSuDqEUYTyLkq5zQB6sUy2Gjptf7VeEfzmVmdHxnf0ZmrmRXnK@NqPyB7H4iempUQBK6g8wXwvAL@1jlnXQidcDXmORMl7pmhLYtDRVJIjVyPZC8dZM7fPXCwOGhvcM0yZmVQmuKNmYPYDvbGdaLExM0ZuAS3UvWHWW7g3L4zsILChVJ1b4vxc8OcNwF1g0lfYSJdCx68th5VW/MN/z1AbN17PRXJoY09PuCwsJsPFbMJqjngt/nFKK6o@NWGDrVAO4giiqUxGxzPxJyAaIg1GZrO7iJxnRfE3UkbpcLjbOFZ/GjKrrm4JQUPw@6Ws@9Osaj6/nRY9/v4i/uEc36MfLqIf36GvsHiC/7glfdZjyHJ0xBbXoSDvDvOBvKMsdmkgeQE3sB6Al2AwEH7D1j10RK1PGek5yPGjH8x420P2nr4FORMWf07zW7Lb/QU) [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 218 bytes ``` Fold[#+##&,Total@PadLeft@IntegerDigits[#,2]//.{{p=n_/;n>1,r=y___}:>{0,n,y},{q=x___,i_,p,j_,k_,r}:>{x,i+1,n-2,j,k+1,y},{q,i_,p,j_}:>{x,i+1,n-2,j+1},{q,i_,p}:>{x,i+1,n-2},{1,1,r}:>{1,0,0,y},{q,i_,1,1,r}:>{x,i+1,0,0,y}}]& ``` [Try it online!](https://tio.run/##XY5Na4NAEIb/yoKQSyZ1Zt3d2W0x5FAKhR5y6E1EpDGp@TCp9ZAg/na7xjaQspfleZ@Zdw5581kc8qb8yPu1iPuX436VBNMgmMD7scn3i2W@eivWzeK1aopNUT@Xm7L5TgKQaRg@tO0prrLwqZoT1PEly7Lucd4iVHDpoP2Kz55AmcEJthnsMqiH@AzllKCaSdjCzv@u6p/1T5jSLbxLPCWgcR8B@nfbcuOjPGZdOumXdVk1SSBmc7FOgjQVExEuRNtyZI0G4ZBZau5AtBQ5ixaEtGyURbIDjJQH7BBVhO7XcgpBGKsiRqkHJtkrio0fJtREWl5No9A3sJVW@a4BOc1GM4NQTNYgXYeNI1857NSOHKkBWkUo2QzdxjozNpvI@msihV3X/wA "Wolfram Language (Mathematica) – Try It Online") Simply pattern matching. Ungolfed: ``` FromDigits[Total@PadLeft@IntegerDigits[#, 2] //. {{n_ /; n > 1, y___} :> {0, n, y}, {x___, i_, n_ /; n > 1, j_, k_, y___} :> {x, i + 1, n - 2, j, k + 1, y}, {x___, i_, n_ /; n > 1, j_} :> {x, i + 1, n - 2, j + 1}, {x___, i_, n_ /; n > 1} :> {x, i + 1, n - 2}, {1, 1, y___} :> {1, 0, 0, y}, {x___, i_, 1, 1, y___} :> {x, i + 1, 0, 0, y}}, 2] & ``` ]
[Question] [ ## Challenge Write a program to compute the the first N (<= 10^3) digits of [e](http://en.wikipedia.org/wiki/E_%28mathematical_constant%29). Your program should take an integer **N** as input. **Input:** ``` 100 ``` **Output:** ``` 2.718281828459045235360287471352662497757247093699959574966967627724076630353547594571382178525166427 ``` **Input:** ``` 7 ``` **Output:** ``` 2.718282 ``` **Input:** ``` 1000 ``` **Output:** ``` 2.718281828459045235360287471352662497757247093699959574966967627724076630353547594571382178525166427427466391932003059921817413596629043572900334295260595630738132328627943490763233829880753195251019011573834187930702154089149934884167509244761460668082264800168477411853742345442437107539077744992069551702761838606261331384583000752044933826560297606737113200709328709127443747047230696977209310141692836819025515108657463772111252389784425056953696770785449969967946864454905987931636889230098793127736178215424999229576351482208269895193668033182528869398496465105820939239829488793320362509443117301238197068416140397019837679320683282376464804295311802328782509819455815301756717361332069811250996181881593041690351598888519345807273866738589422879228499892086805825749279610484198444363463244968487560233624827041978623209002160990235304369941849146314093431738143640546253152096183690888707016768396424378140592714563549061303107208510383750510115747704171898610687396965521267154688957035035 ``` **Shortest solution wins!** [Answer] ## Mathematica (12 bytes) ``` N[E,Input[]] ``` [Answer] ## Python, 69 ``` e=f=n=1;N=input()+2;exec"e+=10**N/f;f*=n;n+=1;"*N;print'2.'+`e`[1:-4] ``` Computes N+2 iterations of the standard power series for e. [Answer] # Python, 67 ``` import decimal as d d.getcontext().prec=input() print d._One.exp() ``` [Answer] # J, 20...ish. Computational, but... Very inefficient. With n defined (20): ``` (0 j.<:n)":+/%!i.x:n+9 ``` As a monadic function (32): ``` ge =. 3 : '(0 j.<:y)":+/%!i.x:y+9' ``` As a tacit function (33, fixed): ``` (0 j.<:)":(+/)&:(%&!&i.&x:&(9&+)) ``` [Answer] # 05AB1E, 4 3 2 bytes [Crossed out 4 is still regular 4 ;(](https://codegolf.stackexchange.com/questions/77899/substitution-cipher/77913#77913) Thanks to @Adnan for a byte. ``` žt ``` Uses **CP-1252** encoding. Explanation: ``` žt - Push input. Pop a, push e to a places (up to 10000). ``` **Update:** Remove `I`, as `žt` takes input anyway if none is on the stack. [Answer] # Ruby, 68 ``` require 'bigdecimal/math';include BigMath;puts E(gets.to_i).to_s 'F' ``` [Answer] # GolfScript 43 41 ``` ~10\?1:b 461,{)b*:b@+\}460*;*b/`);(;'2.'\ ``` Edit: I might as well replace the 0 with the leftover 1 from initializing b, the resulting difference is far too small to make it to the output. I left the old version as that is what I have documented below. ``` ~10\?1:b;0 461,{)b*:b@+\}460*;*b/`);(;'2.'\ ``` `~10\?` Take input and calculate 10^input, leave the result on the stack. `1:b;` Store 1 in b. `0 461,` Put 0 on the stack, put the array [0 1 ... 459 460] on the stack. `{ }460*` Execute function 460 times. `)b*:b` Take the last element of the array, multiply it by b, store result in b and leave the result on the stack. `@+\` Switch the 0 (which is only a zero at the first iteration) to the top of the stack, add it to the leftover b value, and switch the result back again. `;` Remove the rest of the array (only [0] is left). The number that was initialized to 0 now hold the value e\*460! and b hold 460! `*` Multiply 10^input by e\*460! (they are at this point the only 2 elements left on the stack). `b/` Divide the result by b. The stack now hold the value e\*10^input which when converted to a string will hold all the decimals, but not the dot. ``);(;'2.'\` A bunch of string operations to fit in the dot. e\*460! is calculated as 1 + 460 + 460\*459 + 460\*459\*458 etc. [Answer] # [bc](http://www.gnu.org/software/bc/manual/html_mono/bc.html), 17 chars ``` scale=read() e(1) ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 2 bytes ``` ∆Ė ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLiiIbEliIsIiIsIiJd) Built in solution. [Answer] **J, 17** ``` (":&(x:^1)@*&0j1) ``` Example: ``` (":&(x:^1)@*&0j1) 50 2.71828182845891281655718620537435347047040502245993 ``` Uses built in exponential verb - so, "compute" is on shaky grounds. Basically: ``` ^1 - computes e**1 x: - does extended precision 0jy ": - formats the number to y digit ``` [Answer] ## Mathcad, [tbd] bytes [![enter image description here](https://i.stack.imgur.com/ZNztU.jpg)](https://i.stack.imgur.com/ZNztU.jpg) Uses a spigot algorithm - <http://comjnl.oxfordjournals.org/content/11/2/229.full.pdf+html>. --- Byte count not given as Mathcad byte count equivalence is yet to be determined. However, using a symbol equivalence it is roughly 121 bytes ... and not going to win any brevity prizes no matter how the equivalence is determined. [Answer] # Mathematica, 7 bytes ``` N[E,#]& ``` My answer is a further golfing of [this](https://codegolf.stackexchange.com/a/1577/75323) answer. [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73y/aVUc5Vu1/QFFmXkl0WrShQWwsF4ID5P0HAA "Try it online") For some reason, the output over at TIO looks funny but I tested it on my machine and the code works just fine. [Answer] ## [GTB](http://timtechsoftware.com/?page_id=1309 "GTB"), 14 ``` eS?`AS;_,1,A+1 ``` **Explanation** `e` - Put `e` as the last calculated value `S?` - Convert `e` to string `_` ``A` - Input A `S;_,1,A+1` Display the first `A` digits of `e` [Answer] # [Perl 5](https://www.perl.org/) `-Mbignum=bexp -p`, 12 bytes ``` $_=bexp 1,$_ ``` [Try it online!](https://tio.run/##K0gtyjH9/18l3jYptaJAwVBHJf7/f0Mjg3/5BSWZ@XnF/3V9kzLT80pzwfL/dQsA "Perl 5 – Try It Online") ]
[Question] [ Given a non negative integer number tell if it can be erased by repeatedly removing **all** occurrences of the length of that number from it **including overlapping matches**. * Erasing means cancel all its digits. For example the number *4440* is not lengthy because after removing all 4's you obtain *0* which cannot be erased. Neither the number *50022* or *50044* is lengthy A because you first remove 5 obtaining *0022* or *0044* and there's no way to cancel leading 0's. **Examples** ``` 3610106336 has 10 digits: remove 10's 36xxXX6336 -> 366336 366336 has 6 digits: remove 6's 3xx33x -> 333 333 remove 3's -> erased ``` Here an example with **overlapping matches**. ``` 11111666661 has 11 digits xxXX1666661 \ overlapping 11's 1XXxx666661 / We have 5 '1' for a total of 4 '11' matched, remove all 666661 -> remove 6's 1 -> and finally 1 ``` # Test cases Truthy ``` 1, 12, 21, 22, 123, 321, 322, 331, 333, 4441, 4444, 12345, 987654321, 3610106226, 1010101010, 11111111111, 10812816208148888188, 82428208832101683082414123828341883888,3919555395539111955255533922519455392511539551925395511, 1515515551555515555515555551555555155555155551555155151, 999199999915999991599999999915999915999999919399999999991915999999999999999999999915999999929999999, 10121111011011011011011011011011011012110110110121101110110121111011123101101101101121011011110110111, 15101251011012229752519101110101010101010111111101101101101101111011011011011110111101101101101101915, 2020220202202022020220202232020220202202022020223220232020222220220222202202202202202202202202202202202220223202202202202202202202202222022022022022022022222202202202202202222022022022022022023876543213 ``` Falsy ``` 0, 2, 9, 10, 11, 23, 233, 4440, 50022, 50044, 1101010101, 11131111311, 121666626162, 181811818128181818, 127271272722672224724122727122712242722472727272722472727272247272127272, 1001023010023100160010010010010061110250100123001001001230061001010100102370100610016001001001110230, 1241242212412241241241241241241241241241241241141624124114241241241242612412412416241222412411424221241244124142412412144124, 108484298442981044294284942984429844294291042942942942849429429484284948429484842942942984104842984429429844298448429429429429429429429428494294294842942942948429428484942942942942984429429844284948429428494842849484284942942942942942984484294294284942942942942942942942942942910429429484294294 ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), standard rules apply. * Input can be given in any convenient method. * Output any two different values telling if the number is lengthy or not lengthy. [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 16 bytes ``` +~`^.* v`$.&¶ ^$ ``` [Try it online!](https://tio.run/##jVLLTsQwDLz7OxaEQFrF46TrfAF/sSoHDlw4IMSRz@ID@LEySdPHVt0VTuKZjCduG/Xj9fPt/UWHu4fnfnj67s/HR/nqD8f73x85H4ZBRSFQAUhMjNTIzYhmEmPUkmKpxiTZT12K1dVp0NABnRQyDtElKLvCtQMxOkPdxRHhVJw9gnZugYpGdne4RVqMTrGsOaVkuSw2I6LsLQNJcywyiVaHklbkM5OmMusaU8uXMJerXSVnPrCGpjUsdBY0W15qa@NFzDoalmtCuZhwa2JLZz7uYBcH0HDa1xugPbVjQD6lcmOt1XqMsXmDnd3Ww08TBI7dZFdU5lYCRnnGG3PqeKW6q/3HZtN/bH8 "Retina – Try It Online") Link includes test cases. Explanation: ``` ^.* v`$.&¶ ``` Replace the input with a Retina program that erases all overlapping occurrences of its length from it. (Replacing overlapping matches can do weird things in Retina but fortunately only if the matches are variable length.) ``` ~` ``` Execute that program on the input. ``` +` ``` Repeat the above until no more erasures can be made. ``` ^$ ``` Test whether the input was completely erased. [Answer] # [J](http://jsoftware.com/), 42 bytes ``` ''-:(#~1-]+./@(-@i.@#@]|.!.0"{E.~)":@#)^:_ ``` [Try it online!](https://tio.run/##jVTfb9MwEH7vX@GtEllFmvnOdmKnAkWg7WniAfGGyoQQ00BISPx4QEP918t35yRNSzvNse@@u/t8dhxfvm7TWeuatTW3BmMGi9b1WZuKYnZeFXfmRWsKUyLWYiwr8/rtzfW2KJbtxXxDy/Xz6rK7WHZfqm7erf9WZ5U9f7iqNovztpsvPrS328XszavK2FX3sL6Yr@bd/KF6v3j2cnOJYLeipRCvqrWynp52Nvv86f67Kd79@P3r/k@RrbtVdcvYbYF9bkxBpSEuDUMzC3alcWI5MZ0T5ODz3pNKryQfSpNiUwefyTVZsjVzjagdHuBdk0AkjlQztI9oFGNpInuOcEUkslRHZ@EhjzUiR@fBcaCWLlEKIbgkA@mgWWyXmAMlL24AUgYBqpZVAwXpOrLo5b4aw0rHxJSwpDYKU7WDo4OSS7vYlLjXRj/3Wg@L5XTsY50P4YizxW5vAvd6sPMhgB/6ecypCXJqfa7pk9vBFo5Yhxy8HG6QxXNUuBNeyD7EnN2jfqQPGU9Ej/qeQnPDjXZlMRTP9cdvP0/UDi44akS/olx1WE5Grha4grVSRFBaNeMZa104ykLKiWo0rlEasFAWpIKjqiiMhhsVqDAM9g1qhLNXh5eQb3h4djijPFl2ig2wg7Bya1Bw4tj1Wj4sB7VAGwICa8Vk@xRNpu@lIM0t@8XuPLNqxY91FHs9oIkf5zFaGucdqU/t1TFMIjX1P@Oj5xS9CLKi8I/xafRlD65/1pO49JiNmHEcOdFjQpzMH5LFSZp0KuU@lLx77GnOcfUBTRQfzor/r3asj@868HHDt/8A "J – Try It Online") Handling overlaps made this awkward, and this was the shortest approach I could find. Consider string input `'82428208832101683082414123828341883888'`. The approach is to do the following until a fixed point: * Find all matches `E.` of the length within the input. This returns a boolean vector where the ones indicate the *start* of each match. ``` 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 ``` But we need to mark every position of each match.... * `-@i.@#@]` So we generate the numbers `0 1 ... <length of length>` (in this case just `0 1`) and then rotate our boolean vector right by each, creating copies of it: ``` 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 ``` * `+./` And sum the rows: ``` 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 1 1 0 0 ``` * Finally we invert the mask and use that to filter the input: ``` 8242820883210168308241412283418888 ``` * `''-:` Once the fixed point is reach, we just check if the final result is empty. [Answer] # [Ruby](https://www.ruby-lang.org/), ~~90 ...~~ 65 bytes ``` ->n{n.gsub!(/#{n.size.to_s[/(.*)(.*\1)\2*/]}(#$2)*/){}?redo:n<?0} ``` [Try it online!](https://tio.run/##jVTbbtswDH3fV3joHpLAS0RKsqlhWz8kDYYVa4c9LC2aFeiW5tuzQ8rXzAkmS@QheUTJsuin59vfx/tPx/eft/vt8vvu@fbtbHUFuPvx52756@HLbr2aLRdzjBua3/BitTnMrt7xfLGa7w/XT3ffHj5sP167w/GxWFNZEJcFQzMr9mXh1fJqeq/IwxdCIJPBSCGWRZK6iiGTK3LkKuYKUdc@wH3TgBALVQwdBI1EykI4sMAlSOSoEu/goYA1hMUHcDyopU@UYow@6UA6aFbbJ@ZIKagbgIxBgKZ11UhRu40sGjlWXdjomJgSlrRGcah62Dko@dTHhsRR6/zcaDss1tNxlzqfwg5ni/1oAje6tfMhgB@becypjnpqTa7hk9vJFiasUw5eDjfI4ZkU/owXsgkxZ3enL/Q245nopO9/aL690X6z/Pn1cf/68nq/frGS2hzeoFpwpVEV9t30csPyOnJ9wBWd07KBsjrpTtUqwVMWWkBUoXGFYoCFQiATLKZEGTXXJlBTGBxqVAVnr42goVBz@/Q4ozxZd4oNsIdwek9QYuroe6WfkqNZoLUBhZVhck2KOtNHKchy636xu8Bs2vCljvKuWjTw4zw6y@Lck5rUwRztJDLT/ixBAicJKsipwl8lpM6XPbjwWQ/i2iUbkrF0HAmYIIP5bTIZpEnnUo6h5h2xhzm71Vs0UHw6S/5dbap379ryJ@708S8 "Ruby – Try It Online") ### How? To replace overlapping occurrences use the following regex to split: ``` /(.*)(.*\1)\2*/ ``` This will always match the whole number that we are searching, but if some parts are repeated in an `ABABABABA` pattern, then the regex groups will capture A and BA. B will be empty if only A is repeated, and A will be empty if the pattern is not repeating. So, now that we have captured `A` plus any number of occurrences of `BA`, we can use a new regex to find overlapping matches, we need to add `(BA)*` at the end: ``` /#{n.size.to_s[/(.*)(.*\1)\2*/]}(#$2)*/ ``` Repeat until there is nothing left to substitute, then check if the string is empty. Thanks AZTECCO and Dingus each for -1 byte ideas which put together brought the byte count down by 3. [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), ~~36~~ 33 bytes -2 bytes from @Traws' improvement, -1 more from tweaking more ``` ~#{x@i^/(#n:$#x)#[n~x@;]':i:!#x}/ ``` [Try it online!](https://ngn.codeberg.page/k/#eJztFV1vmzDwnV+RJZXaSlDw2SYGXvq0X7C3qlOzjLRRU+hIMhFV7W/f3RkM+WhXVYsmTTP2fd/ZmDtulr6MnurL+dfwbFSkJ6P6fHRVvNSX2fVpOk8/jern0PNW6dPJ1ealSmeDOrsp77Ozm9lkvsjqbJNV59fPaHGVievTM38ohtlQAAIgCoBZiVCyQLJESqYlyZVSwiJlbZVGnJhxrFXjE4tIRDFATAZR+xDTDVYZAUbEgFgZHMIYFBtQYFBmMFokYiMjlAiFOxkwUqGRNGwoE5ForWVCC0MiBuJlAqBFokiMhGALgSRj3lkLTZOXBQ3cRk7N5uSZJLgpD6H7qCOdQCQy6XR9w63h5NBge2lAlxS9NWGXdLTlQG45QINbvrkHdNCNI0Ay1nRzTbD+Y8fOGQ5wuzb4epRWET4HgXxFirBRAVixw2/MNuIr2oOy95jJNrvl8JxrJ+LawZT2h0DAfjTOcHpdyaCpFhLrKOJCQmzLxl2srQopLOCKEjEOiLEwiMWqEAzAMDJsM4YxAywyXKDGWCJgpbwUqdQY2qejLWWd+dR4CpAIIkoYLDgSdDOmTwqaOTRrFUTGTIuoCTG25lshBMfmE+P5FABjpt+aWO1xS/XkeCeOYz10Rk1oxYLWSTBrfzXKKEiMIiAiQviXUYmTWQmmvsU9PU1jGWNp42yMQgfT82+DmV6Y5LWQ2yTF3bLux3S7t1QPwa6X2d/t0HTv2tpTcnuhd7daPS7TMJyW3/PbcjG7WK4m0/u8nt5Nitv8Ylo+hD/W+XI1L4tlCFrFoMNFXtyu7jZBsX74llfLYLV5zINJUOUP5U8kFougnE7XVZUX03wZlLPAOnjel2qNfp4n/IEAfwCIAYiW/kASJ4nFBkQAZdR+GCo2UtofuN6DJq71oNb9vZDuBin2+44/eF/bwS0+1nVw2481HXy/4/ccvq3jtxy+hON3HEyhf6bheN7nyWKJBYJZjIXAX4ryGTlJy5YEirjFMOLScPfIyd/2F6qZrr0gt9ddyOLPNBc66fF7C53377UW/pn87yy/7Sye9wu0kJ3n) Takes input as a string. If it is okay to return empty lists for "Truthy" inputs, and non-empty lists for "Falsy" inputs, 2 bytes can be trimmed (the leading `~#`). * `{...}/` set up a converge-reduce, running the code in `{...}` until two successive iterations return the same value or the original input + `(#n)#[...;]':i` set up a stencil-apply, with a `(#n)` window size, applying `#[...;]` to each slice of `i` - `i:!#x` generate a list of indices of the input, storing in `i` - `(#n:$#x)` determine the string to remove, storing in `n`; calculate its length, and use that as the window size - `#[n~x@;]` filter each slice down to those that match the string to remove (`n`) (slices that do not match the string to remove become empty lists) + `i^/` remove those indices + `x@` index into the input, and (implicitly) return * `~#` convert empty lists to `1`, and non-empty lists to `0` [Answer] # Mathematica, 114 bytes ``` StringReplacePart[#,"",List@@Interval@@StringPosition[#,ToString@StringLength@#,Overlaps->All]]&~FixedPoint~#==""& ``` [View it on Wolfram Cloud!](https://www.wolframcloud.com/obj/8a6bcc18-5d29-4d03-82db-e10b84e883d0) [Answer] # [PowerShell Core](https://github.com/PowerShell/PowerShell), 144 bytes ``` param($a)for(;($i=$a|% Le*)*($l-$i)){$a=-join$a[(($k=0..($l=$a|% Le*))|?{$_-notin($k|?{$a|% su* $_|% s*h "$l"}|%{$_..($_+"$l".Length-1)})})]}!$a ``` [Try it online!](https://tio.run/##jVZtb9owEP7Or8iQOyWsVPHZCbYmtEpV96lSp3XfqqrKWBh0FDoStEnAb2dnO84LParZju/uubsntoNPvKz@5Otili8Ww8lqnR/YdLw9vGTr7DlkWTRdrcOPIZuPWbY7C27yQTQI2WLI5lG0Zdl4@LSaL1l2H4bs1zi@uEBfExntPm3Z43C5KudL9BvLuIrNIGCPRhnMgj5b9Pe7M4wzyY8fjH1xky9/lrMhj/bYH/bvWHbY93qXYS/Adh5chn3ePw9Yud7kUQsDAgQqEoBMFwQqSAJBMghBxgqKV0rJaVjSa5MJgWs1ShN5Yo0pj3mcAqQUYew75Wwamao4KJ4CSqmwcaWIMAUSFMYoXF3MUyViRLjEnShQQmKSUGSi0FwnSSK0eXAJKMHYQgMkXEsDo8JtBEfVSnKlCU/MsI@bqrkrarcNp5i0xkXZxpO2aNQa4FroxtcO7LQah0rSHwnMR4jfGnCs1rqzQHQSoJLePnFuSJBURAB6lJiTr8jb3bWjNRHWcQxun7qWMXZyEidQnCsXgINr@cbwjCe8JPY/YcLfRurC24s2zRZFZ8cUqCmQk/nu871iFTRKwlhwSOokjgFOOFyNer0Y/7OgvVxwN5Fu4Ck2SLGwkH4sM9xOoKxQNMsIRnbCsocPyBEWHXCofaRxyRH43uhOc8n0F8CtgcApNncKa5oBmpGaXzkk1sIw7zBqanUeVxQjF96h4Jab3hPuQAJYafW3BlbY1GstHM@1tqwfmqCKWlrAJ3Fr0uegpJKglTQTj43AUi91jTkE64WTLb8ZyhnK6aqOURITVCvfk6kWjT5F2VUNbye6zVm/3WstAcdZ6vXbqFHv1ce3Tq4XBbvg82p9nU1mw9vvT/mkDLb2PFmZF@VVVuTnzsz/vqAz/xGM8Q@Sg9Z5sVmUCLxn0ya@Z533X@6uNkW5enakD5eO1bS7zWSSF0VgmGrWYf7bE9aB3ypGE1ize@dX93LLcpR33Vqqf4F17nv7wz8 "PowerShell Core – Try It Online") Takes the number as a `string`, returns `$true` or `$false`. The timeout is caused by the "overlapping remove" that generates lots of strings in memory So here is a version that does not timeout, calculating the array of characters to remove only once: [Try it online!](https://tio.run/##jVRtb9owEP7Or8iQOyVdQfHZCbYmNKRq@1Rp07pvVYUyZkY7WjqSapOA387OdpwEelRzHN/dc3dP/BLf0@qPWZcLs1wOZqu12bP5eLN/KtbFQ8yKZL5ax@9jdjdmxfYsujLnyXnMlgN2lyQbZsYx@zVOh0OE2oBk@2ETD@5Xd4@suGHT4ZAtbxP0leeLqM@W/d32bGPhmE3fWXt4ZR5/VosBT3Y9VoxD5gS5kYlNB4@rChGzS253b1ix3/V6k7gXYbuIJnGf9y8iVq2fTdLBgACBigQg0wWBCpJAkAxCkLGC4pVSchqW9NxkRuBajfJMnphjzlOe5gA5RZiGh3K2jUxVHBTPAaVU2LhSRJgCCQpjFM4u5bkSKSJc4koUKCExSSgyUWiusywT2r44BZRgbaEBMq6lhVHhLoKj6iQ504xntrvXD/V4KBq3C6eYtMZJucazrmjVBuBa6NbXDTxoDQ61pA8J7CGkr3U4VhvdWyAOEqCWwT6xb0iQ1UQAepTZna/Ju49vR3MirOMYXD51LVN8yEGcQHGsXQAebuQrPTCe8JLY/4SJcBupC@8u2rxYlgcrpkBNgZzM98f3glXQKAljwSGpszQFOOHwNerlZMJvQXu54H4g3cBzbJBjYSH9WGa4G0A5oWiWEYzcgGUPX5AjLDrgUfdK65IjCE@re80n0yeASwOBQ2rvFNY0C7Q9t385ZM7CsOCwau50ntYUIx9@QMEdN70mXIEEcNLpr3WssHnQOjjua2M5P7RBNbV0QEjizqT3QUklQStpB55agaVe6gbzCNYLLzt@25U3lNdVE6MkJqhOfiBTHRp9ivJQtbwH0V3O5utB6wg4zlIvv0b1Zq0hvrNzvSTaRp9W64/FbDH4/P3ezKpo4/aTVaasLovSXHjT/H1Cp/kRjSM29dDalM/LCoG3bN7G95zz5sv15XNZrR486e3Es9p2/TybmbKMLFPDOjC/A2ET@K1mtIENe3B@9R93LEd5HztTDR9wzl1vt/8H "PowerShell Core – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 22 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ΔÐgU.sRXδÅ?XgGDÁ~}_Ï}d ``` Port of [*@Jonah*'s J answer](https://codegolf.stackexchange.com/a/254637/52210). Outputs `0` for truthy and `1` for falsey. [Try it online](https://tio.run/##yy9OTMpM/f//3JTDE9JD9YqDIs5tOdxqH5Hu7nK4sa42/nB/bcr//xZGJkYWRgYWFsZGhgaGZhbGBkARQxNDI2MLIwtjE0OghIWFBQA) or [verify all test cases](https://tio.run/##tVTNihNBEH6VYbwoNNJV3TNT7SUX0dseRGEhBIkaVkEQnLiQQwQPelXEh/ABxOuCc9@H8EWyX3XPb0zCXuzuqfqq6qvqnp@ad/XyxZvV7vIsf/r@w/r1Jnu0fFuvNvmds@Zn3lxld5ure9l6Va@zl8t6VT/IcrO53Mzy7O@X71k@2@yufzTfLp7dr5@cX/9qPs/OLx4/bD593D5vvm5f7cz2z@/Zbj4nQ2yYDDOAMw7QATsH7Zzx3pMKr1FfmCBVWXhlke1mhK3XldFgLg0NAwwhFioZ2gsGiRhhzwKPINFSKc7CQx4bCYvzoDi5PY0KKnTFK4lWTlUfjnScOFCA5YJeOCs0q@0Cc0HBqxuAIoMAoyYTAhLjoGKsBtg7KLgwxMbEyej93OrRM/6PU3dhfUv21OJ92ONksZskcKs7m/T9gF60acyhKvT5tqXGM429Exyw9jl4gIYt5kHhjngh2xBzcvf6xOoqHoke9N2G5rr@cgszt4aNfgRoJYPe5NSP1hQWXJXalqP3SOQoCXQrlRhcoucMod0oCpao0C1ccRUFWhUX@wpNxckbL68hX3E3B5xQSsbpsDc7CKufABpUHcMq9TVxES3QuoDCMmKybYkq0SclKNbGaXE2zxx1xKcW/g1lh0Z@PIveinEeSG1pHx1dEkVT/11ePAfxKsiqwh/Jh96XPPiUkx7FdUkyJGHpOeKRIKP8rpiMyoRjJadQ607Y45r97h0aKd7Pkn93O7T6e@34i8UN). **Explanation:** ``` Δ # Loop until the result no longer changes: # (using the implicit input-integer in the first iteration) Ð # Triplicate the current integer g # Pop one, and get its length U # Pop and store this length in variable `X` .s # Pop another one, and get a list of its suffices R # Reverse this list of suffices δ # Map over the list of suffices: X Å? # Check which suffix starts with the length we stored in variable `X` X # Push the length from variable `X` again g # Get the length of that length G # Loop that length-2 amount of times: D # Duplicate the current list of 0s/1s Á # Rotate it once towards the right ~ # Bitwise-OR the values at the same positions together }_ # After the inner loop: invert all 1s/0s Ï # Only keep the digits in the integer at the truthy indices }d # After the changes-loop: check if what remains is a non-negative number # (resulting in 0 for the empty strings; 1 if any digits still remain) # (which is output implicitly as result) ``` Unfortunately 05AB1E lacks a builtin to get all indices of a match (it only has a builtin `k` for the first index of a match). Otherwise the `.sRXδÅ?` could probably have been a bit shorter. PS: Without having to deal with overlapping matches, this could be 6 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) instead: `ΔDgK}d`. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 23 bytes ``` W⌕AθILθ≔Φθ¬⊙ILθ№ι⁻λνθ¬θ ``` [Try it online!](https://tio.run/##XYy9CgIxEIR7nyLlHsQiWF4VBCsVXyHchcvCsiE/p/j064brnGKa@b5ZUqhLDiTySUjRwA159URQrLmG1uEeeesJyqQxvjXcWBnqsQ7kmTt4/sIfqm7euQNa80DeG5A1PB50KdN8elXUdcgKzyLOuYs7Ss5v@gE "Charcoal – Try It Online") Link is to verbose version of code. Outputs a Charcoal boolean, i.e. `-` for lengthy, nothing if not. Explanation: ``` W⌕AθILθ ``` While there are overlapping matches of the inputs length in the input... ``` ≔Φθ¬⊙ILθ№ι⁻λνθ ``` ... filter out each character that matched at least one of the digits in the length. ``` ¬θ ``` Output whether the input was lengthy. [Answer] # JavaScript (ES6), 101 bytes Returns a Boolean value. ``` f=s=>s==(s=s.replace(/./g,(c,i)=>[...q=s.length+''].some(_=>s.slice(i--).match('^'+q))?'':c))?!s:f(s) ``` [Try it online!](https://tio.run/##jVXbjtowEH3fr0h5IdFCNh7biQ0K@9R@Qd9YWkWUW8XCLqGVqqrfTsczdkgooDrOzJkzFyeOB75XP6t6fti8HYe7/bfF6bQs63JSl2Vcl3V6WLxtq/kifkqfVoN4Ptgk5WSapuk7@raL3eq4fuz3Z2m9f13EXzEtrbcbDN8Mh0n6Wh3n67j/pf/4niTP/f5ojupDPVrGdXIaTx@mUU/0BijASSAMwIx0SjInmZSSLUk@pZTwWvkUpR2wpsi1Cqm5yESWA@QUk4WLrPNgpxFgRA6olcEhjHG8AQUGSYMlM5EbmSEjFK5nwEiFUdJwpLTCaq2ldTdWRQ3OlhZAC6scjUBQhEBImhfXQrtJNwsvu6pxUzilWovL0hC6rc6wIYSV9uxrB3ZGw4PXfu/AbVV2b8IlbDBbIDsJ4HWww1ZghvaZALbQbvd8tfbF4@IhrliXMfiCdNQyvK4KeYNF6V0ATDf6zgwVb3ivcv8TJsNBl71oNnDdRMeaesV/Mj7mxEqWoXfIpbOMWwuB76Jmc32HSMGCW0zkOCDHJiEbW0SQAEPKcFQBBQnsOrxBFdgvwCzdyrlUAeE6Y0aczG@AjwISReaODrafI84zd98WNFkYFhwO5oRF5ksUHN4pIag2PzM@oQIgTfjexObPA2rxuC@NRX44B/nSioiQJMj0vz3KKLBGOSEyp/BXR9mGYwa7gHXL76ZhwzA2TYxRmGBa@aGYaZWxt0p2oavbiW7XbFYPqKXgMsv8u9q12bxriMdj/jB7SJf7w8cK/1jiahBtkqicRL@j@X5X77eLdLtfxZvoOeq97Kafqm39a9aLRlFv@vnw47hGIxlHVVOgdrntTPfHlCTRn2R8@gs "JavaScript (Node.js) – Try It Online") Or **92 bytes** by throwing an error if the input cannot be fully erased: ``` f=s=>s&&f(s.replace(/./g,(c,i)=>[...q=s.length+''].some(_=>s.slice(i--).match('^'+q))?'':c)) ``` [Try it online!](https://tio.run/##jVXNcpswEL7nKTQcYpg4BK0ESPE4ObVP0JvjdhhKEreOScDtTKaTZ3dXuxLGrpOpELvffvsjkLXmR/W76utu9by93LTfm93uft7Pb/rz8/u4T7vmeV3VTXyVXj1M43q6SuY3izRNX@Z9um42D9vHi8lkmfbtUxN/w6y0X68wfHV5maRP1bZ@jCdfJxcvSXI7mVzXSbKbLc4WIpLRFAU4CYQBmFFOKeYUk0qxpcintZZea5@icwesKYtch9RCZjIrAAqKycJF1n6w00gwsgDU2uCQxjjegAaDpMGSmSyMypCRGtczYJTGKGU4Ullp8zxX1t1YFTU4W1mAXFrtaASSIiRC0rx4LnM36Wbh5aEa3BROqdbisjRkPlZ7OBDSKrv3jQMPxsCD137vwG1V9tGEYzhgtkAdJIDXwQ5bgRm5zwSwZe52z1cbXzyOHuKEdRyDL0hHLcPrpFDvsCi9C4DpQX8wQ8V3vCe5/wlT4aCrSCynrpvoWFOv@J@MjzmximXoHXLlWcathcB30bC5vkOUZMEtJgscUGCTkI0tIkmAIWU4qoSSBHYd3qBL7Bdglm7tXLqEcO0xI07mN8BHAYUic0cH288R@1m43xZysjAsOBwsCMvMlyg5/KCEpNr8zPiEGoA04Y8mNn8R0IjHfRks8sM@yJfWRIQkSab/79FGgzXaCZk5hf862g4cM9gFrEd@Nw0bhrEZYozGBDPKD8XMqIx9r@QhdHUPosc1h9UDGik4zjL/rnZqDu8a4vGYny3P0vu2@1ThByWupmKViPmN@CPqdtO36yZdtw/xStyK6G6z@Fyt@9dlJK5FtPjS/do@opHMRDUU6Dl3272ixI8cOrsGyaj9Gc3Em6jpu9Uk6CVeRE3XtR37RguiE1PfEpyz3V8 "JavaScript (Node.js) – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~153~~ ~~142~~ 137 bytes -4 bytes thanks to [AZTECCO](https://codegolf.stackexchange.com/users/84844/aztecco) ``` char*o,*a,b[999];k;z;d;f(i,n){a=i;o=b;for(z=k=0;*a;a++)atoi(strndup(a,d=log10(n)+1))^n?k<1?*o++=*a:k--:(z=1,k=d-1);*o=0;z=z?f(b,o-b):!n;} ``` [Try it online!](https://tio.run/##jVV7b5swEP87fAoWqRIkoPrOBuww1A/SdRJ5dSgpVEmqSan61ZedX4RkaTVj3@N3Dxvjw4v0ebE4nRa/6t2kSyZ1Mn9USj2Vm/JYLst11CRt/F5XTdlV83Ld7aJjtalYOanLejqN60PXRPvDrl2@vUZ1sqy23TOwqI2nEMc/24fNd3iYdNNpNalnmzSdUTQkm2qZQlxOOspzrI4P62iedOk8nn1ry4/TS920URy8ByOzpvCw2h/2j09hFRI0ur8PD7u3FUljGCfhGFBTNDKiRbhm3GLcgpxbjRubEAIcF@PE5EIuMg0pWeSZ8ME5MGA5Ym4SM/8Y7dysUQJKyJG4kNRASpc6g0x3Myxx9JL1ZuMONliiQEk5Ja2IQS45IwQELVei5IIm4VJPNOYKFMVypQetiThqnSvEDJTQMAlgPIBEw90s9MFBmQbZkJ3FHgDF1dk2dLxoPY6Ou71ggHrH2Fcdr8VethryiwB03OvQbzvFZC4WURWZ3giXb/jYdrWMG9q1D72knQoZPTcJ/wQl6kyIFu75F91n/MR6E/sfN@7PPDfvQyW2rrd7U2PmqJsKUvaU26NvUG6pryhjyhizBUeCri3t7PfZVQ0HS2ytQk4Ncyoc99mocMAQlIZJ61dgYQjVIg0UBZUBWtQMoU2iQP@cZSvZYH8KaTnIiTB9lqiuNHDuuf7UmBmN3LxBi7mRgbkUhXW/SAEmt/@t0CoFouFG/qpTXedeGuC0O71m7Hh2cqmFAXwQGJVWoP9KQgpUUmgCTDP6oQjVYxahsrB8YNddWkVaWfY@UlCAHMT7ZHKQRn2W8lLUeS@8hzn72b00YHgdJf@d7Vbv39X7@1O/apcksGD0UQbBiO66MGraQ9jQ1cNKdw81T2XY0MUXjPRt9Lojh3U0vtvPwrvlj5bOqndLwnV0lumK3K7aHojjuKRpgo/g9Gex3tbP@1P6@5RuX/4C "C (gcc) – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), ~~117~~ 109 bytes -8 bytes thanks to [AZTECCO](https://codegolf.stackexchange.com/users/84844/aztecco) ``` f=->s{a=*0...x=s.size s.scan(/(?=#{x})/){a-=[*(y=$`.size)...y+x.to_s.size]} s!=(x=a.map{s[_1]}*"")?f[x]:s>""} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=vVFLDsIgEI3bnkLRRVstBcTWmFAP0pCKxiYu_EQ0oTY9iZsu9FB6GisojReQ4c1MZt5jAlxvx_OyqOv7-ZQH08c2Z0EiS8F8BCFUTEK5uaydJqzEzg3dOeuXqvJCrxQBS323YIOFpngNvRgqeNpnRsMrR_aYq5iAW3EoZZphXvkAePM8VXwmEwAqM_TZGR26eQrGEUYYRYREgDu6gttlS-gPZodN8OS9NYz7-N9g25pu5ZRSZI8iMYm1a-7XgNCYUExMVYO-WzQmX2tzkxkx4ObRvj_2Ag) [Answer] # [Pyth](https://github.com/isaacg1/pyth), 32 bytes ``` W&znz=sm*@zd.Amx>z-dklzl`lzlz;!z ``` [Try it online!](https://tio.run/##K6gsyfj/P1ytKq/KtjhXy6EqRc8xt8KuSjclO6cqJwGIq6wVq/7/NzQ1NAUhMIYQUBKVgkuDlRsCAA "Pyth – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt), 26 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` _ðZl)rÈhXÊs îS Y}Z kS}gUÊN ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=X/BabClyyGhYynMg7lMgWX1aIGtTfWdVyk4&input=IjExMTExNjY2NjYxIg) Input is a string, output is an empty string for "truthy" or a non-empty string for "falsy". A version which specifically outputs "true" or "false" requires [just an added flag](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LSE&code=X/BabClyyGhYynMg7lMgWX1aIGtTfWdVyk4&input=IjExMTExNjY2NjYxIg). All test cases can be run [here](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&header=Ck49W1Vd&code=X/BabClyyGhYynMg7lMgWX1aIGtTfWdVyk4&footer=VSsiIC0%2bICIrIVc&input=WwoiMSIKIjEyIgoiMjEiCiIyMiIKIjEyMyIKIjMyMSIKIjMyMiIKIjMzMSIKIjMzMyIKIjQ0NDEiCiI0NDQ0IgoiMTIzNDUiCiI5ODc2NTQzMjEiCiIzNjEwMTA2MjI2IgoiMTAxMDEwMTAxMCIKIjExMTExMTExMTExIgoiMTA4MTI4MTYyMDgxNDg4ODgxODgiCiI4MjQyODIwODgzMjEwMTY4MzA4MjQxNDEyMzgyODM0MTg4Mzg4OCIKIjM5MTk1NTUzOTU1MzkxMTE5NTUyNTU1MzM5MjI1MTk0NTUzOTI1MTE1Mzk1NTE5MjUzOTU1MTEiCiIxNTE1NTE1NTUxNTU1NTE1NTU1NTE1NTU1NTUxNTU1NTU1MTU1NTU1MTU1NTUxNTU1MTU1MTUxIgoiOTk5MTk5OTk5OTE1OTk5OTkxNTk5OTk5OTk5OTE1OTk5OTE1OTk5OTk5OTE5Mzk5OTk5OTk5OTkxOTE1OTk5OTk5OTk5OTk5OTk5OTk5OTk5OTE1OTk5OTk5OTI5OTk5OTk5IgoiMTAxMjExMTEwMTEwMTEwMTEwMTEwMTEwMTEwMTEwMTEwMTEwMTIxMTAxMTAxMTAxMjExMDExMTAxMTAxMjExMTEwMTExMjMxMDExMDExMDExMDExMjEwMTEwMTExMTAxMTAxMTEiCiIxNTEwMTI1MTAxMTAxMjIyOTc1MjUxOTEwMTExMDEwMTAxMDEwMTAxMDExMTExMTEwMTEwMTEwMTEwMTEwMTExMTAxMTAxMTAxMTAxMTExMDExMTEwMTEwMTEwMTEwMTEwMTkxNSIKIjIwMjAyMjAyMDIyMDIwMjIwMjAyMjAyMDIyMzIwMjAyMjAyMDIyMDIwMjIwMjAyMjMyMjAyMzIwMjAyMjIyMjAyMjAyMjIyMDIyMDIyMDIyMDIyMDIyMDIyMDIyMDIyMDIyMDIyMDIyMjAyMjMyMDIyMDIyMDIyMDIyMDIyMDIyMDIyMDIyMjIwMjIwMjIwMjIwMjIwMjIwMjIyMjIyMDIyMDIyMDIyMDIyMDIyMjIwMjIwMjIwMjIwMjIwMjIwMjM4NzY1NDMyMTMiCiIwIgoiMiIKIjkiCiIxMCIKIjExIgoiMjMiCiIyMzMiCiI0NDQwIgoiNTAwMjIiCiI1MDA0NCIKIjExMDEwMTAxMDEiCiIxMTEzMTExMTMxMSIKIjEyMTY2NjYyNjE2MiIKIjE4MTgxMTgxODEyODE4MTgxOCIKIjEyNzI3MTI3MjcyMjY3MjIyNDcyNDEyMjcyNzEyMjcxMjI0MjcyMjQ3MjcyNzI3MjcyMjQ3MjcyNzI3MjI0NzI3MjEyNzI3MiIKIjEwMDEwMjMwMTAwMjMxMDAxNjAwMTAwMTAwMTAwMTAwNjExMTAyNTAxMDAxMjMwMDEwMDEwMDEyMzAwNjEwMDEwMTAxMDAxMDIzNzAxMDA2MTAwMTYwMDEwMDEwMDExMTAyMzAiCiIxMjQxMjQyMjEyNDEyMjQxMjQxMjQxMjQxMjQxMjQxMjQxMjQxMjQxMjQxMjQxMTQxNjI0MTI0MTE0MjQxMjQxMjQxMjQyNjEyNDEyNDEyNDE2MjQxMjIyNDEyNDExNDI0MjIxMjQxMjQ0MTI0MTQyNDEyNDEyMTQ0MTI0IgoiMTA4NDg0Mjk4NDQyOTgxMDQ0Mjk0Mjg0OTQyOTg0NDI5ODQ0Mjk0MjkxMDQyOTQyOTQyOTQyODQ5NDI5NDI5NDg0Mjg0OTQ4NDI5NDg0ODQyOTQyOTQyOTg0MTA0ODQyOTg0NDI5NDI5ODQ0Mjk4NDQ4NDI5NDI5NDI5NDI5NDI5NDI5NDI5NDI4NDk0Mjk0Mjk0ODQyOTQyOTQyOTQ4NDI5NDI4NDg0OTQyOTQyOTQyOTQyOTg0NDI5NDI5ODQ0Mjg0OTQ4NDI5NDI4NDk0ODQyODQ5NDg0Mjg0OTQyOTQyOTQyOTQyOTQyOTg0NDg0Mjk0Mjk0Mjg0OTQyOTQyOTQyOTQyOTQyOTQyOTQyOTQyOTQyOTEwNDI5NDI5NDg0Mjk0Mjk0IgpdLW1S). Explanation: ``` _ðZl)rÈhXÊs îS Y}Z kS}gUÊN N # Starting with the input string as Z _ }gUÊ # Repeat this process a number of times equal to its length: ð ) # Find indices of this string: Zl # The current length of Z rÈ }Z # For each index Y apply this function to Z consecutively: XÊ # Get the length of Z s # Turn it into a string îS # Replace each character with a space h Y # Overwrite Z with that string starting at index Y kS # Remove all spaces ``` [This](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=CspzCvBWIHLIaFbuUyBZfVUga1MKpVc/VzrfVw&input=IjIzNDU2Nzg5MTAi) recursive alternative is a little longer, but I figured I would include it in case it has more room to golf. ]
[Question] [ I recently solved a coding challenge in one of the challenge papers that my IT teacher gave to us. It was a seemingly simple, but fun challenge, so I thought it will make fun golfing. ## The task Given an input of a 2x2 matrix that contains 4 strictly positive integers (i.e. non-negative and non-zero), like this: $$\begin{pmatrix}a&b\\c&d\end{pmatrix}$$ We call the value of the matrix given is \$\left\lfloor\dfrac{a}{c}\right\rfloor - \left\lfloor\dfrac{b}{d}\right\rfloor\$. Your task is to calculate the amount of rotation needed to get the maximum value of the matrix. A rotation rotates the matrix 90 degrees clockwise. ## Input and Output The input can be a 2x2 matrix (as shown above), a flattened list `[a b c d]`, or any other reasonable input. Note that with the case of flattened lists, the numbers can be in any order you preferred. (e.g. `[a b d c]`). The output must show a number that is the amount of rotation required. ## Clarifications * In case of a tie, we will choose the one with the least amount of rotation needed. * In case where no rotation is required, we simply output `0` or `4` (the maximal rotation). * The division used here is integer division (i.e. the result of the division will always be an integer). ## Examples ``` [a b c d] -> output [1 2 3 4] -> 3 [5 7 9 2] -> 1 [5 6 7 8] -> 0 or 4 [1 9 2 3] -> 3 [2 5 6 8] -> 3 ``` These examples are hand-calculated and written, so correct me if I'm wrong! As always, [standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes ``` ZU$Ƭ:/€INM’Ḣ ``` [Try it online!](https://tio.run/##y0rNyan8/z8qVOXYGiv9R01rPP18HzXMfLhj0f/D7UBu5P//0dGGOkaxOtHGOiaxsToK0dGmOuZAriVQEMw11zEFcs2AZCwA "Jelly – Try It Online") ## How it works ``` ZU$Ƭ:/€INM’Ḣ - Main link. Takes a matrix M on the left $Ƭ - Do the following until a repeat is found: Z - Transpose U - Reverse rows. This rotates clockwise 90° € - To each rotation: :/ - Reduce each column by integer division I - Get the (negative) differences N - Negate M - Get the index of the maximal element ’ - Decrement Ḣ - Get the first (minimal) element ``` [Answer] # Excel (ms365), ~~153~~, 148 bytes -5 bytes by [@jdt](https://codegolf.stackexchange.com/users/41374/jdt) ``` =LET(a,INT(A1/C1)-INT(B1/D1),b,INT(C1/D1)-INT(A1/B1),c,INT(D1/B1)-INT(C1/A1),d,INT(B1/A1)-INT(D1/C1),m,MAX(a,b,c,d),IF(m=a,0,IF(m=b,1,IF(m=c,2,3)))) ``` --- Original 153 bytes answer: ``` =XMATCH(9,BYROW(REDUCE(A1:D1,ROW(1:3),LAMBDA(a,b,VSTACK(a,SORTBY(TAKE(a,-1),{2,4,1,3})))),LAMBDA(c,SUM(INT(INDEX(c,{1,2})/INDEX(c,{3,4}))*{1,-1}))),-1)-1 ``` It's painstaking in Excel, but my thought process here was: * `REDUCE(A1:D1,ROW(1:3),LAMBDA(a,b,VSTACK(a,SORTBY(TAKE(a,-1),{2,4,1,3}))))` - Create a vertical array where we keep stacking a 90° tilted array to our previous array; * `BYROW(~,LAMBDA(c,SUM(INT(INDEX(c,{1,2})/INDEX(c,{3,4}))*{1,-1})))` - Loop over each row from said array and do the math as per question: Devide the 1st and 3rd integer by the 2nd and 4th, discard the fractional part and do a negative summation of the resulting integers; * `XMATCH(9,~,-1)-1` - Find a nine (the largest possible outcome) or the next lower value. Deduct one from the given index. [![enter image description here](https://i.stack.imgur.com/W74PK.png)](https://i.stack.imgur.com/W74PK.png) [Answer] # JavaScript (ES6), 72 bytes Expects four BigInts as `[a,b,c,d]`. ``` A=>A.map(m=(_,i)=>(([a,b,c,d]=A,v=a/c-b/d)<=m||(j=i,m=v),A=[c,a,d,b]))|j ``` [Try it online!](https://tio.run/##fY1dC4IwGEbv@xW73ODVZVYm9Ar7HSIxp4binGR45X9fM8qgr4tz9Rye08hRDupS91evM0VpK7QCE@Fr2VON9AQ1w4TSVEIOCooMBYwoufJyXrAj6mmiDdagcWQgMFUgoYA8Y2xqrDLdYNrSb82ZVjQNOiAvnEI4J@vVF2vjCB3bpxW@Wzu3Ro74bj@s4NMisHdEjsPfYrxUfxXnda7uHctXaG8 "JavaScript (Node.js) – Try It Online") ### Commented ``` A => // A[] = input list A.map( // repeat 4 times, m = // with m initialized to a non-numeric value (_, i) => ( // and i as the rotation index: ( // [a, b, c, d] = A, // split A into [a, b, c, d] v = a / c - b / d // compute the value v for this rotation ) <= m // do nothing if it's less than or equal to m || (j = i, m = v), // otherwise update m and the best index j A = [c, a, d, b] // rotate the flattened view of the matrix ) // (see below) ) | j // end of map(); return j ``` ### Rotation Below are the details of the 90° clockwise rotation of the flattened matrix: $$[a,b,c,d]\rightarrow\begin{pmatrix}\color{blue}a&\color{blue}b\\\color{green}c&\color{green}d\end{pmatrix}\rightarrow\begin{pmatrix}\color{green}c&\color{blue}a\\\color{green}d&\color{blue}b\end{pmatrix}\rightarrow[c,a,d,b]$$ [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 14 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` 4FDøí})ε`÷Æ}Zk ``` Input as a matrix. Outputs `0` if no rotation is necessary. [Try it online](https://tio.run/##yy9OTMpM/f/fxM3l8I7Da2s1z21NOLz9cFttVPb//9HRhjpGsTrRxjomsbEA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeV/EzeXwzsOr63VPLc14fD2w221Udn/df5HR0cb6hjF6kQb65jExuooREeb6pgDuZZAQSjXDMg117GAcA11LIFcIx1jCNdIxxTINYPJmoK5IDI2FgA). **Explanation:** ``` 4F # Loop 4 times: D # Duplicate the current matrix # (which will be the implicit input-matrix in the first iteration) øí # Rotate it once clockwise: ø # Zip/transpose; swapping rows/columns í # Reverse each inner row }) # After the loop: wrap the stack of five matrices into a list ε # Map over each matrix: ` # Pop and push both pairs/rows separated to the stack ÷ # Integer-divide the items at the same positions in the pairs Æ # Reduce the pair by subtracting }Z # After the map: push the maximum (without popping the list) k # Get the (first 0-based) index of this maximum in the list # (which is output implicitly as result) ``` [Answer] # [Factor](https://factorcode.org), 81 bytes Thanks to @chunes for -22 ``` [ 3 [ dup reverse flip ] times 4array [ first2 v/ vfloor first2 - ] map arg-max ] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=RY9BTsMwEEX3OcW_QIIaSlvgAIgNEkKsqi6sMAaLxDHjSdQqyknYZFOu0jP0NnUcAht_682bkf73j1aF1DycT68vj08Pd_gktlTC01dDtiCPSslHfDLd2EJMbT0Uszp4OCaRg2NjZTJaGo_5_-2M9sLK4z5JuqRDhwVy9CGvsQzZR3aDdWS3cTazVWRrbP7YIhgjy8P2zPJgjmz16_XHRnS6OT9vg7TFW-PA1BJ7gi6Nww5iqtBqGSsEQxv2kqO9QqvLuuYZpEGtlAtV39NK7bGbDh9Hlk3_YZjyAg) ## Explanation | code | explanation | | --- | --- | | `3 [ dup reverse flip ] times 4array` | Generate a 4-item array of all rotations, by sequential `reverse` and `flip`s | | `[ first2 v/ vfloor first2 - ] map` | Calculate the value of each matrix, according to the scheme. (First does vectorized floor division, then outputs difference of first 2 items.) | | `arg-max` | Index of the largest item | [Answer] # [Ruby](https://www.ruby-lang.org/), 58 bytes ``` ->a,b,c,d{(1..4).max_by{a,b,c,d=c,a,d,b [a/c-b/d,-_1%-4]}} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsEiN9ulpSVpuhY3rXTtEnWSdJJ1Uqo1DPX0TDT1chMr4pMqq6Gitsk6iTopOklc0Yn6ybpJ-ik6uvGGqromsbW1UBPKCxTcog11FIx0FIx1FExiFZQVdO0UjLlAwqY6CuY6CpZASaiwIUzYDCxjARU2UMgvUjDhgppkCTEMxSSgAEQXTIsxxPoFCyA0AA) [Answer] # [Factor](https://factorcode.org), 62 bytes ``` [ 4 [ -rotd swap 4dup [ swap /i ] 2bi@ - ] replicate arg-max ] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=ZZC_TsNADMb3PMWHmK_QNEAKUsWGWFgQU9ThuDpwapocPkcUVX0SlizwFjxI3wYrrVIkvPjPz_4s-_O7tE4a7nY_T4_3D3fXWBLXVGFl5RWR3lqqHcURrYVtRGAS-QjsazlC3CTJJoHaBmOkmCDDVrMTmBkmB3CBK0wVDmA8gEtF-RGcD1LTXuyfVNrP5H_B9quV0uS7WaG7CxhuZIH4bgOyRRu00sdnHnOkz_4WRgOmUHlnhWD5xazsGvODymmB0nOUTLv04tBE0n8ERLFuOYKryPK-tev2_hc) Takes 4 integers as input in the order `a b c d`. * `4 [ ... ] replicate` Create a sequence of 4 elements where the elements are determined by the output of `[ ... ]`. Now let's take a look at what happens inside the `replicate` quotation: ``` ! 2 5 6 8 (example input) -rotd ! 6 2 5 8 swap ! 6 2 8 5 (this is the next rotation of the matrix) 4dup ! 6 2 8 5 6 2 8 5 [ swap /i ] 2bi@ ! 6 2 8 5 0 0 (apply [ swap /i ] to the top two pairs of items) - ! 6 2 8 5 0 (so 0 is the first element of the sequence) ! 6 2 8 5 (now the next element will be determined...) ``` * `arg-max` Get the index of the largest element. [Answer] # ARM Thumb-2 machine code, 34 bytes ``` 03 24 e7 07 0f b4 08 bc 07 bc b0 fb f3 f5 b1 fb f2 f6 ad 1b bd 42 a4 bf 2f 46 a4 46 01 3c f1 da 70 47 ``` Assembler source: ``` .syntax unified // doesn't work with clang?! // .arch armv7ve .arch armv7-a .arch_extension idiv .globl rotation .thumb .thumb_func // input: r0=A, r1=B, r2=D, r3=C // output: r12 // Uses r0-r7, r12 rotation: // Register aliases since it is otherwise confusing A .req r0 B .req r1 D .req r2 C .req r3 rot .req r4 res .req r12 max .req r7 // Current rotation. This loops backwards, so we rotate backwards. movs rot, #3 // 3 << 31 = 0x80000000 = INT_MIN lsls max, rot, #31 .Lloop: // Rotate COUNTER-CLOCKWISE by pushing/popping in a different order // Push and pop are the only things that make Thumb viable for this :) // A, B, D, C = B, D, C, A push {A, B, D, C} pop {C} pop {A, B, D} // r5 = A / C udiv r5, A, C // r6 = B / D udiv r6, B, D // r5 = (A / C) - (B / D) subs r5, r5, r6 // Is this less than or equal to the max? cmp r5, max // If so, save the new lowest rotation and the new max itt ge movge max, r5 movge res, rot // Loop while rot >= 0 subs rot, rot, #1 bge .Lloop // Return bx lr ``` Uses the idiv extension. Accepts arguments as `r0=A`, `r1=B`, `r2=D`, `r3=C`, and returns 0, 1, 2, or 3 in `r12`. This cannot be called from C so I provide a wrapper which allows it to be called with this signature: ``` int rotation_c_wrapper(int A, int B, int D, int C); ``` ``` .syntax unified .arch armv7-a .thumb .thumb_func .globl rotation_c_wrapper // Wrapper to be called from C // int rotation_c_wrapper(int a, int b, int d, int c); rotation_c_wrapper: // Save callee-saved registers push {r4-r7, lr} // call the function bl rotation // move result to r0 mov r0, r12 // Restore callee-saved registers and return pop {r4-r7, pc} ``` [Answer] # [Python 3](https://docs.python.org/3/), 74 bytes ``` f=lambda a,b,c,d,*m:m.index(max(m))if 3<len(m)else f(c,a,d,b,*m,a//c-b//d) ``` [Try it online!](https://tio.run/##HcpBDsIgFIThtZ6CJa8ZJS1aa6MnMS6gQCQptKld6Onx1cUkXyb//F1fU9alhPtoknVGGFgMcKhSn44xO/@RyfCIYhD6NvrM9uPbiyAHGC4ttzBKDQerlKMSpkVEEbN4yBoNNE4EecYFVzR/teyOVW8PNKvB9nb07Pe7eYl5lUFWkaj8AA "Python 3 – Try It Online") [Answer] # Java 8, ~~116~~ 99 bytes ``` a->{int r=0,i=-1,m=0,t;for(;++i<4;a=new int[]{a[2],a[0],a[3],a[1]})if((t=a[0]/a[2]-a[1]/a[3])>m){m=t;r=i;}return r;} ``` -17 bytes thanks to *@Neil* by taking four loose integer inputs instead of an integer-array [Try it online.](https://tio.run/##dZDNasMwEITveQrhk4zXTvPTNq2qvEFzybH0oB@7KLXlIK8DJfjZXUkxJaEEwYc0jJjZPYiTyA/6e1S16DryLow9zwgxFktXCVWSXXhGgSgaKCBQRqpInTLvGWYeHQo0iuyIJXykAiQo0Gm@PQef4w9geL6Axl@QVa2jLMvM25ohFyC4AsU1aC5BckxNRanX5yqXc51um/TccGSOGza4EntniWPDyELqsZe1T53CT63RpPGD0D06Y78@PkV6GQLLDukClrCCdew8SY/wDC@wvJWevLi5lhbBA6traQnBt7n9GM@/lcRW0XFviZeO@58Oy6ZoeyyOvj3WloosgSSTkSpSZ8krSTJbqL8dT4HD@As) **Explanation:** ``` (a,b,c,d)->{ // Method with four integer parameters and integer return-type int r=0, // Result-index, starting at 0 i=-1, // Index-integer, starting at -1 m=0, // Max value, starting at 0 t; // Temp-integer, uninitialized ++i<4 // Loop `i` in the range (-1,4) (or [0,3]): ; // After every iteration: t=a,a=c,c=d,d=b,b=t) // Rotate: change a,b,c,d to c,a,d,b if((t=a/c-b/d) // Set `t` to a//c-b//d >m){ // And if `t` is larger than `m`: m=t; // Set maximum `m` to this `t` r=i;} // And update the result with the current index `i` return r;} // Finally, return the result-index `r` ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), 92 bytes ``` y,r;g(a,b,c,d,i){y=i>3?0:g(c,a,d,b,i+1)<(a=a/c-b/d)?r=i,a:y;}f(a,b,c,d){g(a,b,c,d,r=0);r=r;} ``` [Try it online!](https://tio.run/##bY3LDoIwEEX3fkVjYtKJl5SXCtTKj7gpJZAuRNO4IYRvr0BC3HQ758w9JuqN8X6Ekz3XaGDQwtI0KvvI6rjquYFeTg3sOaE710oLEzWipdopC12Ncu72R5r@G07FJJ1ycvYvbQdO04F9nB2@HT@eWvYcjuh4ghQZciIpRBbgF9xQIt14EuTXxSg2HrO3Y3kwUq6ZTWKhSop1p9iF2f8A "C (gcc) – Try It Online") * function *f* initializes gobal *r* to 0 which is kinda default result. Then calls *g* which recursively sets *r* when a greater combination happens. * *g* sets global *y* to a greater value or itself or 0 if the recursion loop is completed(*i>3*), there cannot be greater value less than 0. [Answer] # [Perl 5](https://www.perl.org/), 99 bytes ``` sub f{($a,$b,$c,$d,$i,$m,$I)=@_;$v=$a/$c-$b/$d;$i-4?f($c,$a,$d,$b,$i+1,$v>$m?($v,$i):($m,$I)):$I|0} ``` [Try it online!](https://tio.run/##XY3LToNQFEXnfMVOcwyXeEiLfSmEwrQxsRNnlTQ8DVEotpRoar@dXu51YDo8e@29TpMfPud9fzwlKM6CYqaEKWXKmEqmimlt@eHOo86neEypTcmYMo9KexYUYijGqitH5b3D1K2oCgR18rRcofeWS@vfyaUv9gdhAFtsHcYDY8qYRfBXmCJiDeaMJeNJYgWc/2Ch2OPNwtF1absBMtKj28UQKbZUYIIIlnGWDKh@BJV1w6D8u7HgI6Sd90dA7/tWRoUIh46l8@ZQ1m2B0Z29OA63JKfWhaoMt/TkaZtnrlIOibS4yvVWj/Qj5F9aHsDcf5hwYb5sXrF5Nj3j0l8B "Perl 5 – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 41 bytes ``` NθNηNζNεF⁴«⊞υ⁻÷θζ÷ηε≔θδ≔ζθ≔εζ≔ηε≔δη»I⌕υ⌈υ ``` [Try it online!](https://tio.run/##Xc7LCsIwEAXQdfsVs5xA3PkCV6IIXSj9hdhEM2BTm0eRit8em25aujzDXO6ttLBVI14xFuYd/C3Ud2WxZYd8br1wv7Aa/Ggs4JrBN8/K4DQGDlcywWFh/Jk6kgpbDj3jMB00B8XYEM6OztHTpA85Y8@hnVGl/MQxPVFySDt/eWnJeDwJ5/FCRo5LxIfqUGNgqS7GDWxhB/u46l5/ "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` NθNηNζNε ``` Input `a`, `b`, `c` and `d`. ``` F⁴« ``` Repeat four times. ``` ⊞υ⁻÷θζ÷ηε ``` Push the value of the current rotation to the predefined empty list. ``` ≔θδ≔ζθ≔εζ≔ηε≔δη ``` Rotate the matrix. ``` »I⌕υ⌈υ ``` Find the index of the maximum value. I tried working with lists but the best I could do was 42 bytes: ``` ≔E⁴NθF⁴«⊞υθ≔E1302§θIκθ»UMυ⁻÷⊟ι⊟ι÷⊟ι⊟ιI⌕υ⌈υ ``` [Try it online!](https://tio.run/##dY7bCoJAEIav9SkGr2bBoIMdoCsxAi8MX2FTyyV31T2IED375qGgm64G/vnm@ycrqcxqWlkbKsXuAhPaYOBDLBqjL4ZfC4mE@NCSo3urJWBA4Ok6qVElmjl2fi691Wa59nwIdSzyosfWh4gqjQ/ylbzcgYtqzqnIR0PChFEYC31iHcsLTOsG2cDOk4yf/FmRwZZKJjROFWf2EdKeccPRTIS1B9jBHrZ20VVv "Charcoal – Try It Online") Link is to verbose version of code. Takes input in the order `d b c a`. Explanation: ``` ≔E⁴Nθ ``` Input `d`, `b`, `c` and `a` into a list. ``` F⁴« ``` Repeat four times. ``` ⊞υθ ``` Push the list to the predefined empty list. ``` ≔E1302§θIκθ ``` "Rotate" the list. ``` »UMυ⁻÷⊟ι⊟ι÷⊟ι⊟ι ``` Replace each list with the value of the matrix it represents. ``` I⌕υ⌈υ ``` Find the index of the maximum value. [Answer] # [C (clang)](http://clang.llvm.org/), 84 bytes ``` *t,m,v,i;f(*r,a,b,c,d){r?t=r,i=m=0:0;v=a/c-b/d;v<m||(m=v,*t=i);i++<4&&f(0,c,a,d,b);} ``` [Try it online!](https://tio.run/##pc9Ra8IwEAfw932KQ1hJ67/Yarc5Y9gX2UuaNBJoOolZN1C/@rKgDPag4Ng9Hcf/ftypUvVy2MRYBDiMsNywwkOihYLO9/4lCA8rnKhWFR@FnKmynWk@rt3hwJwYUQRhc26n03WTZYZVaU9Co835MTppB5bT/o5S2SGQ56fWsMyDatActAA1@Xm89Slj2MR3u/c@kKB7Deo@t50KnV7R4nWYgHwK/0IeQE@g50TdhtRXkMeTs7wNqejNU3NJqs@3pLf@8dP856LlX5Fj/FKml5tdLD@@AQ "C (clang) – Try It Online") [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 18 bytes ``` 4(:⁽ḭÞC÷-$∩R)_WÞMh ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwiIDQoOuKBveG4rcOeQ8O3LSTiiKlSKV9Xw55NaCIsIiIsIltbMSwgMl0sIFszLCA0XV1cbltbNSwgN10sIFs5LCAyXV1cbltbNSwgNl0sIFs3LCA4XV1cbltbMSwgOV0sIFsyLCAzXV1cbltbMiwgNV0sIFs2LCA4XV0iXQ==) Unfortunately useful operator `İ` "collect while unique" currently works bad, so simple for-loop is used. ``` 4( # Open for-loop with 4 iterations : # Duplicate ⁽ḭÞC # Reduce columns by integer division ÷- # Calculate value $ # Swap ∩R # Transpose + Reverse = Rotate ) # Close loop _ # Pop unnecessary W # Wrap stack into list ÞM # Find all indices of maximum h # Pick and print one (first) ``` [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-h`](https://codegolf.meta.stackexchange.com/a/14339/), 15 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` 4o ñ@zX yÈrzÃr- ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWg&code=NG8g8UB6WCB5yHJ6w3It&input=WwpbMSAyXQpbMyA0XQpd) ``` 4o ñ@zX yÈrzÃr- :Implicit input of 2D-array 4o :Range [0,4) ñ :Sort by @ :Passing each X through the following function zX :Rotate U clockwise X times y :Transpose È :Map r : Reduce by z : Integer division à :End map r- :Reduce by subtraction :Implicit output of last element ``` ]
[Question] [ ## Background "Fly straight, dammit" ([OEIS A133058](https://oeis.org/A133058)) is a sequence of integers, which has these rules: * \$a\_0 = a\_1 = 1\$ * \$a\_n = a\_{n-1}+n+1\$ *if* \$gcd(a\_{n-1}, n) = 1\$ * *Otherwise,* \$a\_n = \frac{a\_{n-1}}{gcd(a\_{n-1}, n)}\$ In pseudocode: ``` a[0] = a[1] = 1 if gcd(a[n-1], n) == 1 then a[n] = a[n-1] + n + 1 else a[n] = a[n-1] / gcd(a[n-1], n) ``` (GCD stands for "Greatest Common Divisor". For example, `GCD(8, 12)` = 4.) The graph for this function looks like this: [![Graph](https://i.stack.imgur.com/wVICw.png)](https://i.stack.imgur.com/wVICw.png) After n=638, it goes into four straight lines (\$y=1\$ and \$y=2\$ are indistinguishable in this picture, but they are separate lines). > > 'Whenever I look at this sequence I am reminded of the great "Fly straight, dammit" scene in the movie "Avatar".' - N. J. A. Sloane > > > ## Your task You have to: * accept an input, n, from the user (it will be a positive integer) * calculate \$a\_n\$ and output (this is [sequence](/questions/tagged/sequence "show questions tagged 'sequence'") so any output is fine) This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest answer in bytes wins! [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 12 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` 1‚λDN¿DiNOë÷ ``` Outputs the infinite sequence. [Try it online.](https://tio.run/##yy9OTMpM/f/f8FHDrHO7XfwO7XfJ9PM/vPrw9v//AQ) **Explanation:** ``` 1 # Push 1 ‚ # Pair the top two values together. Since there is only one value on the # stack and there is no input, it implicitly uses the last value that was # on the stack, resulting in [1,1] λ # Start a recursive environment, # to output the infinite sequence # (which is output implicitly afterwards) 1‚ # Start with a(0)=a(1)=1 # Where every following a(n) is calculated as: # (implicitly push a(n-1) to the stack) D # Duplicate a(n-1) N # Push n ¿ # Pop one a(n-1) and n, and calculate their GCD D # Duplicate this gcd(a(n-1),n) i # If it's 1: N # Push n again O # Sum the three values on the stack: a(n-1)+gcd(a(n-1),n)+n, # where gcd(a(n-1) is always 1 in this case ë # Else: ÷ # Integer-divide a(n-1) by gcd(a(n-1),n) ``` [Answer] # [C (GCC)](https://gcc.gnu.org), 65 bytes ``` t,r;h(a,b){r=b?h(b,a%b):a;}c(n){n=n<2?:h(t=c(n-1),n)<2?t-~n:t/r;} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m700OT49OXlttJKuv4GSjoKSbrlS7IKlpSVpuhY3HUt0iqwzNBJ1kjSri2yT7DM0knQSVZM0rRKta5M18jSr82zzbIzsrTI0SmyBfF1DTZ08TaBAiW5dnlWJfpF1LdQgbU_r3MTMPA3N6rT8Ig1rTxsjA-uCosy8kjQNJdWUmDwlnWQNT21tTU1NmJYFUDcAAA) This is based on [py3programmer's answer](https://codegolf.stackexchange.com/a/251694); I'm posting this mostly for their benefit since they say they didn't fully understand the golfing suggestions I gave. Here's their current version: ``` h(a,b){if(b){return h(b,a%b);}else{return a;}}c(n){if(n<2){return 1;}if(h(c(n-1),n)<2){return c(n-1)+n+1;}else{return c(n-1)/h(c(n-1),n);}} ``` The first thing I did was convert the `if`/`else` statements into `?`/`:` conditional expressions. You can read `x?y:z` as "if x then y, otherwise z". ``` h(a,b){return b?h(b,a%b):a;}c(n){return n<2?1:h(c(n-1),n)<2?c(n-1)+n+1:c(n-1)/h(c(n-1),n);} ``` GCC has a non-standard extension to C that lets you use `x?:z` to mean "if x, then x, otherwise z": ``` h(a,b){return b?h(b,a%b):a;}c(n){return n<2?:h(c(n-1),n)<2?c(n-1)+n+1:c(n-1)/h(c(n-1),n);} ``` Another quirk of GCC, when used in `-O0` optimisation mode (which is the default), is that the CPU register used for the return value of a function is the same as the one used for its first parameter. As a result, we can replace `return` statements with assignments to the first parameter for both functions: ``` h(a,b){a=b?h(b,a%b):a;}c(n){n=n<2?:h(c(n-1),n)<2?c(n-1)+n+1:c(n-1)/h(c(n-1),n);} ``` Then I noticed that the value `c(n-1)` is reused quite a lot, so I extracted it into a temporary variable: ``` t;h(a,b){a=b?h(b,a%b):a;}c(n){n=n<2?:h(t=c(n-1),n)<2?t+n+1:t/h(t,n);} ``` I declared it as a global variable, because that doesn't require a type in the declaration, but it makes no difference in functionality. Then I made use of [this tip](https://codegolf.stackexchange.com/a/144481) which states that `x+y+1` can be shortened to `x-~y` (because `~y` is equivalent to `-y - 1`) ``` t;h(a,b){a=b?h(b,a%b):a;}c(n){n=n<2?:h(t=c(n-1),n)<2?t-~n:t/h(t,n);} ``` I also noticed that `h(t,n)` is reused, so I modified `h` to store its result in a global variable `r` as well as providing it as a return value. We can then use `r` instead of calling `h` again: ``` t,r;h(a,b){r=a=b?h(b,a%b):a;}c(n){n=n<2?:h(t=c(n-1),n)<2?t-~n:t/r;} ``` As pointed out by Kevin Cruijssen in a comment, the `a=` assignment turns out to be unnecessary. Why, exactly, is beyond me, but it seems GCC just stores the value in the return register by happenstance. ``` t,r;h(a,b){r=b?h(b,a%b):a;}c(n){n=n<2?:h(t=c(n-1),n)<2?t-~n:t/r;} ``` [Answer] # [Prolog (SWI)](http://www.swi-prolog.org), ~~68~~ 56 bytes *-12 bytes thanks to [@Steffan](https://codegolf.stackexchange.com/users/92689/steffan)* ``` N+X:-N>1,N-1+B,C=gcd(B,N),(C<2,X is B+N+1;X is B/C);X=1. ``` [Try it online!](https://tio.run/##Jcy9CoMwFEDhVwlON@TGmkIXfwIma80siIO2KoKaYAQ3Xz1t6XaW77jdLnbi/pxDMKxOuZECDRdMoS6m1xsUGoqg8zvWZPZEMcNE9s@bplldiDikvO8mO0KF/XCcw7BBgo8EK4pPimvnltkf0JStlFB@x6Pd1@6A6HKES3K5a4uwKVG19Afi8AE "Prolog (SWI) – Try It Online") [Answer] # JavaScript (ES6), ~~ 55 ~~ 53 bytes ``` f=(n,a=n,b=q=n>1?f(n-1):-1)=>b?f(n,b,a%b):q/a-~n*!~-a ``` [Try it online!](https://tio.run/##FYxBDoIwEEX3nGJMMOlIq@ISHLwKUwQjIVMB46YpV69l8fPykpc/8o/Xbnl/vkbcs49xICWaSbSlmaQpH4MSU2KVRo3dTVvNR4vVfGGzyemwGY6DW5QAwbUGgTvcdhYFgs8AOierm/rz5F6qZZV7CZjS3KcvDC3WWYh/ "JavaScript (Node.js) – Try It Online") ### Commented ``` f = ( // f is a recursive function taking: n, // n = input a = n, // a = 1st argument of the GCD, initialized to n b = q = // b = 2nd argument of the GCD, initialized to ... n > 1 ? f(n - 1) // q = f(n - 1) if n > 1 : -1 // q = -1 if n ≤ 1 (which will force the GCD ) => // to be evaluated as -1 as well) b ? // if b is not equal to 0: f(n, b, a % b) // keep computing the GCD with a recursive call : // else: // the GCD is now loaded in a q / a - // return q / a ~n * !~-a // add n + 1 if a = 1 // (if q was set to -1, we get -1/-1-~n*0 = 1) ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 47 bytes ``` If[#<2,1,If[(s=GCD[#,d=#0[#-1]])<2,d+#+1,d/s]]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2773zMtWtnGSMdQB8jQKLZ1d3aJVtZJsVU2iFbWNYyN1QTKpWgraxvqpOgXx8aq/Q8oyswr0XdI13cISsxLT4020DE0MIj9/x8A "Wolfram Language (Mathematica) – Try It Online") -4 bytes from alephalpha [Answer] # C (gcc), 234 210 143 139 bytes Thanks to pxeger for removing a few bytes. Check out his improved answer. ``` h(a,b){if(b){return h(b,a%b);}else{return a;}}c(n){if(n<2){return 1;}if(h(c(n-1),n)<2){return c(n-1)+n+1;}else{return c(n-1)/h(c(n-1),n);}} ``` [Answer] # [Python](https://www.python.org), 68 bytes ``` import math f=lambda n:n<2or(a:=f(n-1))//(q:=math.gcd(a,n))-~n*(q<2) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=Nc2xDcIwEEDRnilMdweYOKmQFXcschAusYTPjmWKNFmEJg3sxDYIKfRP_z_faSpDlGV5PQrr0-fsQ4q5qEBl2LC7U7h0pMRK28QMZB2D6BqxqmC07qeO_bUDOgiinmUHY9vg2tpyzMorLyqT9DeojTFoU_ZSYM_gcYX_-Rc) [Answer] # [Ruby](https://www.ruby-lang.org/), ~~59 ...~~ 48 bytes ``` ->n{k=z=1;3.upto(n){|v|z=v.gcd k=z>1?k/z:k+v};k} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y6vOtu2ytbQ2livtKAkXyNPs7qmrKbKtkwvPTlFAShlZ2ifrV9lla1dVmudXfu/QEHDUE/P0EBTLzexQEMtTfM/AA "Ruby – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), ~~115~~ 109 bytes ``` from math import* def f(n): l=1 for i in range(2,n+1): g=gcd(l,i) if g==1:l+=i+1 else:l//=g print(l) ``` [Try it online!](https://tio.run/##FYtBCsMgEADvvmKPbg0EW3oJ@JjQuGZhXcXaQ15vzW2GYerVz6KvMaiVDHnvJ3CupfWHOSIBWcXNgARvgEoDBlZou6Zon4s6f0dIIX0OKwvjFKbpwW/iArt5QZRv3GRdQzJQG2u3goPsDaz11y0ijvcf "Python 3 – Try It Online") Ungolfed: ``` from math import gcd # Function for getting gcd of two numbers def fsd_sequence(n): # Define function to get the nth value of the sequence prev = 1 # The previous value (a[n-1]) for i in range(2, n + 1): # Iterate through numbers from 2 to n+1 greatest_common_divisor = gcd(prev, i) # GCD of previous value and i if greatest_common_divisor == 1: # If GCD equals 1, prev = prev + i + 1 # Increment the previous value by i+1 else: # Otherwise prev = prev // greatest_common_divisor # Set the previous value to itself divided by the GCD return l # Return the last value ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 15 bytes ``` λ1>[‹x~ġ:ċ[ḭ|++ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwizrsxPlvigLl4fsShOsSLW+G4rXwrKyIsIiIsIjFcbjJcbjNcbjRcbjVcbjZcbjciXQ==) [Answer] # [PARI/GP](https://pari.math.u-bordeaux.fr), 44 bytes ``` f(n)=if(n<2,1,2>s=gcd(n,d=f(n-1)),d+n+1,d/s) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMGCpaUlaboWN3XSNPI0bTOBpI2RjqGOkV2xbXpyikaeTootUEzXUFNTJ0U7T9tQJ0W_WBOqRyUtv0gjT8FWwUBHwQiIC4oy80qAAkoKunZAAmSiJlQtzB4A) [Answer] # [Raku](https://raku.org/), 46 bytes ``` 1,1,{$_/($!=(++$+1)gcd$_)+(++$+2)*($!==1)}...* ``` [Try it online!](https://tio.run/##K0gtyjH7n1up4JCoYPvfUMdQp1olXl9DRdFWQ1tbRdtQMz05RSVeUxvMM9LUAsnYGmrW6unpaf23VihOBOmMjjMyjf0PAA "Perl 6 – Try It Online") This is an expression for the infinite sequence. [Answer] # [Japt](https://github.com/ETHproductions/japt), 17 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Outputs the first `n` terms. I feel like I'm missing a trick here to save a byte or 2. ``` ÈjY ?XÒY:X/yY}hBì ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=yGpZID9Y0lk6WC95WX1oQuw&input=Ng) ``` ÈjY ?XÒY:X/yY}hBì :Implicit input of integer U È :Function taking an integer X and an index Y as arguments jY : Are X & Y co-prime? ? : If so then return XÒY : X-~Y = X+Y+1 : : Else return X/ : X divided by yY : GCD of X & Y } :End function h :Repeatedly take the last element of the following array, pass it through the function and push it back to the array until it reaches length U B : 11 ì : To digit array :Implicit output of resulting array ``` [Answer] # [PowerShell Core](https://github.com/PowerShell/PowerShell), 111 bytes ``` for($i=$r=1;$i-lt"$args"){for($a,$b=++$i,$r;$b){if($a-gt$b){$b,$a=$a,$b}$b%=$a}$r=(($r/$a),($r+$i+1))[!--$a]}$r ``` [Try it online!](https://tio.run/##PZDvToMwFMW/9ymwuXMQLrP/KOBCfAKfwJgJWDYMkQlMTXDPPi/M@KHp7e@c23PbY/fl@uHg2jaqut5doM6nS931PjQ59LncQhO1I4ei3w88mBalQCjzMIQGod9CGUxNTTDaj3MNJUKRL54zlCuqznSP70N/B0WAtFNjKIPg6SaKoHgm9XJmDLrT6OWe2Gxs@rOaGPRuOLUzuoXagx3jsHu59/4wZ9A2w@iFuYd/iM2XVMMndSxa9NY172tcM3DfR1eN7pUULlGiwRQVLYNSoSZAmzKEpJ0VQ0xJTFAlaNIr1IrcWqCMMUZt0JoZ2blJW5QpxnOXkZiSR4m5jhdzhlJQTiwwIaAWT0aJhtIyg1lCmkQlLCpLSJOUZjQDRYoUE5I1HQUNaClH07RZttSappA24Yzxx2KsDm548MBfPiByH97/owN@/Vt2@QU "PowerShell Core – Try It Online") Outputs the \$n^{th}\$ term of the sequence [All the terms for 102 bytes](https://tio.run/##HYzBCoIhEITvvkUwhYtKeP7xSaLDbmgJPxgWdBCf3bYuM8PHzDzbJ/fXI@97uLWeF0oaK5poSusWNaGnuIGTc6g0/lAUbhAatVhwuL9/GeK1BfaQCTlqmla3VuUMJq@uDy4SXQ4hgK801zTmhGLWFw "PowerShell Core – Try It Online") ]
[Question] [ ## Introduction: Since it's almost Halloween, I was just thinking of some random Halloween-themed challenges. Eventually I was reading through [Frankenstein's wikipedia page](https://en.wikipedia.org/wiki/Frankenstein), and came across the following text: > > ### The creature > > > Part of Frankenstein's rejection of his creation is the fact that he does not give it a name, which causes a lack of identity. Instead it is referred to by words such as "wretch", "monster", "creature", "demon", "devil", "fiend", and "it". When Frankenstein converses with the creature in Chapter 10, he addresses it as "vile insect", "abhorred monster", "fiend", "wretched devil", and "abhorred devil". > > > [source](https://en.wikipedia.org/wiki/Frankenstein#The_creature) ## Challenge: Given two integers (year and chapter), output a string based on the following rules: 1. If the year is less than 1818: output an empty string *†* 2. If the year is exactly 1818 and the chapter is below 10: output a [random](https://codegolf.meta.stackexchange.com/a/1325/52210) string from the list `["wretch", "monster", "creature", "demon", "devil", "fiend", "it"]` 3. If the year is exactly 1818 and the chapter is 10 or higher: output a [random](https://codegolf.meta.stackexchange.com/a/1325/52210) string from the list `["vile insect", "abhorred monster", "fiend", "wretched devil", "abhorred devil"]` 4. Is the year above 1818 (and thus the book was published), return `"Frankenstein's Monster"`. ## Challenge rules: * You can choose whether to output in lowercase, uppercase, or a combination. * The year will always be in the range `1500-2017` * The chapter will always be in the range `1-24` (if I googled correctly, the book has 24 chapters) * *†* Instead of outputting an empty string for option 1, you are also allowed to output `null`, `undefined`, `false`, `0`, or any other value of your choice not part of the other three options (please specify what you've used in your answer). * The output may not contain any leading or trailing spaces/tabs, nor any leading new-lines. It may contain one optional trailing new-line. ## General rules: * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins. Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language. * [Standard rules apply](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422) for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters, full programs. Your call. * [Default Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden (especially ['Fake random numbers'](https://codegolf.meta.stackexchange.com/a/1739/52210)). * If possible, please add a link with a test for your code. * Also, please add an explanation if necessary. ## Test cases: ``` year,chapter possible outputs: 1700,1 ""; null; undefined; false; 0; etc. 1700,12 ""; null; undefined; false; 0; etc. 1817,10 ""; null; undefined; false; 0; etc. 1818,1 "wretch"; "monster"; "creature"; "demon"; "devil"; "fiend"; "it" 1818,9 "wretch"; "monster"; "creature"; "demon"; "devil"; "fiend"; "it" 1818,10 "vile insect"; "abhorred monster"; "fiend"; "wretched devil"; "abhorred devil" 1818,11 "vile insect"; "abhorred monster"; "fiend"; "wretched devil"; "abhorred devil" 1818,18 "vile insect"; "abhorred monster"; "fiend"; "wretched devil"; "abhorred devil" 1819,1 "Frankenstein's Monster"; "frankenstein's monster"; "FRANKENSTEIN'S MONSTER" 1819,18 "Frankenstein's Monster"; "frankenstein's monster"; "FRANKENSTEIN'S MONSTER" 2017,24 "Frankenstein's Monster"; "frankenstein's monster"; "FRANKENSTEIN'S MONSTER" ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~227~~ ~~220~~ 214 bytes ``` lambda y,c:[[choice([["wretch",m,"creature","demon",d,F,"it"],["vile insect",a+m,F,"wretched "+d,a+d]][c>9]),"Frankenstein's "+m][y>1818],0][y<1818] from random import* m,d,F,a='monster','devil','fiend',"abhorred " ``` [Try it online!](https://tio.run/##ZY7BboMwEETvfIW1F0KzB4wqBaomx/yE64NjL8JKbCPjtuLrqUkvhZ5m9HZnZ8c5DcE3S3/@WB7K3YxiM@o3IfQQrKaDEPAdKekB0CHoSCp9RgIEQy54QINXBJtAooAv@yBm/UQ6AaqjW0e/YTIMjiYzI6XQl05WCNeo/J38lMj6cspzJ8V84S1vJdbZvj9t0cfgWF41WawbQ0wvhXvWqnOZX8j5WGJpKLdn7S15UyKo2xBiXHuXMVqfWH/gp7pGzqpiC5o/oOUn5PUGtNvICro9@B/he9BuQLc/2m02mjr/0bxWyw8 "Python 2 – Try It Online") [Answer] ## [Perl 5](https://www.perl.org/), 172 bytes **171 bytes code + 1 for `-p`.** ``` @a=<><10?($}=wretch,$M=monster,creature,demon,$D=devil,fiend,it):("vile insect",($A="abhorred ").$M,fiend,"$}ed $D",$A.$D);$_=($a[rand@a],"frankenstein's $M",0)[$_<=>1818] ``` [Try it online!](https://tio.run/##LY7NasMwEITvegojFmrDJmgLoUlj5Qd89ROEEBRrQ0Qd2chqcsqrV1VoTzPzMTAzcugXKe2Mrjc1qW0JT/0IHLsrQqtvg58iB@wCm/gdGC1nhNBoy3fX48Wxt@hi9VnKnLlwfuIuSixhr6U5X4cQ2BaymkP7X5bwzAQaibCfQ1Ot4aRLMIdgvN2ZI8pLdl/82nX@bSqglaiqA5xqvaElLY8p0UIpQeKVxOpPiMS7og9BP8MYXX6dZmP/Cw "Perl 5 – Try It Online") ### Explanation Pretty standard, only slightly unsual thing is using the 'spaceship operator' (`<=>`) with `1818` to return `-1`, `0`, or `1`, if the input `$_` is less than, equal to, or greater than `1818` to return the last, first, or second index of the source data. Also, I like the [fish operator](https://codegolf.stackexchange.com/a/103852/9365)! [Answer] # [C# (Visual C# Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), ~~225~~ 209 bytes ``` y=>c=>y<1818?"":y>1818?"frankenstein's monster":"wretch,monster,creature,demon,devil,it,fiend,vile insect,abhorred monster,wretched devil,abhorred devil".Split(',')[new System.Random().Next(c>9?6:0,c>9?11:7)]; ``` [Try it online!](https://tio.run/##dVLBbqswEDyXr7C4xJZchKOqIaGhh0h9l9eqeqnUQ5SDazbFKjHIdtqiqN@etyQQcqmQYHZ2dxgGK3etnDrsnDbvZNk4D9s0uKyil8KCzJFIAyO34GqpgDw/L/7sVSmdI/U@cF56rcjDzqg7bTwfkPMWN7OMbCuDavYJFcj80MwzNc@aO5GI5D4MZ012QhsrzQe0k9qMXL8UzsIvC14VvCO4Qkt@Z4HngBTeP3XJtecbDSbnWADRxoHyXL4VlbWQ91r8pITEaencP5ZhtKxL7emIj9jKwFefwT9p8mpLWfQE356qbHp/O4t5@xRiNmHr9NBF8FnpnDxKbSjbBxQTIA1Iy0mLVCFrdMBWa@LB@YV04Mic4GtWaxwWkzjmgvEejY8wERMu4g4mXb9F04G7aA99kXRwel6aduQ4RtHxDftJg2BTYZSqoL94PTtFdnCN33a1wDyrEqJXqz381QboxS@m/WjUSrKh7HVZGlydDla0LAFqKlrmJzheh/8 "C# (Visual C# Compiler) – Try It Online") -16 thanks to Kevin Cruijssen Not particularly concise, but I would expect C# to take more space to declare and use any repeated strings the way the Python answer does than to just repeat them. The included test runner has a `Thread.Sleep(1)` inside the enumeration of test cases because default seeding for `Random()` uses the current time and the actual function runs fast enough to end up with the same seed on subsequent runs without a delay. Calls to the func use currying syntax, `f(year)(chapter)` (or whatever name the function is stored in instead of f) [Answer] # Bash, ~~229~~, ~~206~~, ~~197~~, 179 bytes ``` m=monster a=("Frankenstein's $m" wretch $m creature demon devil it fiend vile\ insect {abhorr,wretch}ed\ {devil,$m}) echo "${a[$1>1818?0:$1<1818?13:RANDOM%($2>9?5:7)+($2>9?7:1)]}" ``` the explanation about brace/variable expansions ``` m=monster {abhorr,wretch}ed\ {devil,$m} ``` is first expanded to ``` abhorred\ {$m,devil} wretched\ {devil,$m} abhorred\ $m abhorred\ devil wretched\ devil wretched\ $m ``` then variable m is expanded ``` abhorred\ monster abhorred\ devil wretched\ devil wretched\ monster ``` however following doesn't work because `$w` will be first joined with `ed` and `wed` is not defined and will be expanded to empty string. ``` m=monster w=wretch {abhorr,$w}ed\ {devil,$m} ``` it can be done adding explicit braces arround w but will be longer ``` m=monster w=wretch {abhorr,${w}}ed\ {devil,$m} ``` [TIO](https://tio.run/##TcvNCoJAFAXgvU9xkYkccuEU4Q@pBNGugrbZYtQrDuUI41QL8dlt0k2bw3fgnJx39Vg5tB@buGllp1FZPHbso@Lygb8u5LID0tjwUaiL2hAKhVy/FEKJ5mPyLZ4gNFQCZQmmYAZCdlho6Hlet0q583nAMoN@2rukGaiFRd2CTXp@IyxhAQtSLyJsN4ltouv@fLicFg5ZJ2G6jXy6mulHjN4HexwsqwIz9oHNCP7gzQqBjV8) [Answer] ## Perl 5, ~~156~~ ~~153~~ 151 bytes *-3 bytes thanks to DomHastings.* Run with `-p` ``` $_=($d=devil,$m=monster,$w=wretch,<"{creature,demon,it,fiend,vile insect,{abhorr,$w}ed {$d,$d,$m},Frankenstein's $m}">)[/818/?6*/,../+rand 7:$_/606-5] ``` This output distribution is non-uniform, which is [accepted by default](https://codegolf.meta.stackexchange.com/a/10923/6484). Specifically, if the date is 1818 and the chapter is ≥10, the names “abhorred devil” and “abhorred monster” are weighted twice as much. This lets me use `rand 7` for both cases, even though the lists are of different sizes. The output for years before 1818 is “wretched monster”. Despite some similarities, this string is *not* part of any of the other three options, making it okay to use. This fails for years outside of the 1212—2424 range, but luckily the year is guaranteed by the rules to be in the 1500—2017 range. [Try it online!](https://tio.run/##JY7JCsIwEIbvPkWRgNvUJGI3sXrzJURKbUYMtmlJoz0UX92YUBj4mPkXpkNdR9aSIl8SkQv8yBpIkzet6g1qIEM@aDTVE47zsdJYmrdGEOh0kAYeEpUAl8FAqh4rA2N5f7baB78ogpEI8NN84aJL9ULfKtWiD9xpflpdacpTeo7XFLZbunEWESQHUtCYxWF0s5ZHjAGf8ZQnwJlnCtmEac08d8zJu/2v7Yx0j9uwq/8 "Perl 5 – Try It Online") [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 189 [bytes](https://codegolf.meta.stackexchange.com/questions/9428/when-can-apl-characters-be-counted-as-1-byte-each/9429#9429) ``` m←'monster' a←'abhorred ',⊢ f←'fiend' d←'devil' {⊃⍵=1818:{⊃⌽⍵<10:(?7)⊃'wretch'm'creature' 'demon'd f'it'⋄(?5)⊃'vile insect'(a m)f('wretched ',⊢d)(a d)}⍵⋄{⊃⍵>1818:'frankenstein''s ',⊢m⋄''}⍵} ``` [Try it online!](https://tio.run/##NY9BbsIwEEX3OYV3P5FAahZVowjKWUw8JlZjBzluEUKsQF2krcQZeocuexlfpB0HmJX/1//zxnLbzdVedv3mj8fG9wts74ZAHplMSq7b3ntSArM4fmc6edqQU8hUeit6Mx2yQxxP8etnWVZlVU/i85f1onyo89VTwQZ2nkLTwqLxJMOrJwhuMw1KaJiA@HHOV49TlneSMG6gJiCXwhY6v/Xvl6iCfVUcGcK9G/55wkN76V4o/cI4YLgWLMeAlD/@Aw "APL (Dyalog Unicode) – Try It Online") To test, just append the test case to the last curly bracket like so: ``` {⊃⍵=1818:{⊃⌽⍵<10:(?7)⊃'wretch'm'creature' 'demon'd f'it'⋄(?5)⊃'vile insect'(a m)f('wretched ',⊢d)(a d)}⍵⋄{⊃⍵>1818:'frankenstein''s ',⊢m⋄''}⍵}1818 10 ``` Huge thanks to @ngn for helping out with the leading whitespace issue. ### How it works: It's worth noting that APL interprets strings as arrays (*vectors*) of characters, so `'wretch' 'creature'` would be interpreted in other languages as `[[w,r,e,t,c,h],[c,r,e,a,t,u,r,e]]` These are helper functions: ``` m←'monster' #These are pretty self explanatory, variables m, f and d are being set to 'monster', 'fiend' and 'devil respectively. f←'fiend' d←'devil' a←'abhorred ',⊢ # a is being set to 'abhorred ' concatenated with the argument to it's right. ``` This is the main function, which will be broken in 3 parts for better understanding: ``` {⊃⍵=1818:{⊃⌽⍵<10:(?7)⊃'wretch'm'creature' 'demon'd f'it'⋄(?5)⊃'vile insect'(a m)f('wretched ',⊢d)(a d)}⍵⋄{⊃⍵>1818:'frankenstein''s ',⊢m⋄''}⍵} ``` Part 1: ``` {⊃⍵=1818:{Part2}⍵⋄{Part3}⍵} # First conditional : # If ⊃ # the first element ⍵ # of the argument ⍵ =1818 # Equals the literal 1818 {Part2}⍵ # Executes part 2 with argument ⍵ ⋄ # Else {Part3}⍵ # Executes part 3 with argument ⍵ ``` Part 2: ``` {⊃⌽⍵<10:(?7)⊃'wretch'm'creature' 'demon'd f'it'⋄ # Second conditional (?5)⊃'vile insect'(a m)f('wretched ',⊢d)(a d)}⍵ : # If ⊃ # the first element ⌽ # of the inverse ⍵ # of the argument ⍵ <10 # is less than 10 ⊃ # pick the nth (?7) # random element between [1,7] 'wretch'm'creature' 'demon'd f'it' # from this string array ⋄ # Else ⊃ # pick the nth (?5) # random element between [1,5] 'vile insect'(a m)f('wretched ',⊢d)(a d) # from this string array }⍵ # using argument ⍵ ``` Part 3: ``` {⊃⍵>1818:'frankenstein''s ',⊢m⋄''}⍵ # Third conditional : # If ⊃ # the first element ⍵ # of the argument ⍵ >1818 # is greater than 1818 'frankenstein''s ',⊢m # print the string "frankenstein's" concatenated with m (which prints monster) ⋄ # else '' # print an empty string }⍵ # with argument ⍵ ``` [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), ~~275~~ ~~269~~ ~~255~~ ~~207~~ 203 bytes ``` y->c->y<1818?0:y>1818?"Frankenstein's monster":"wretch;monster;creature;demon;devil;it;fiend;vile insect;abhorred monster;wretched devil;abhorred devil".split(";")[c+=Math.random()*(c>9?5:7)+(c>9?6:0)-c] ``` [Try it online!](https://tio.run/##rVCxbsIwEJ2br7CyNIbGgqEFYggbUgfUgRExGMeAQ2JH9oUqqvh2ekCKkJha9YbTu3f37k4vFwcR20qZPNufdFlZByRHjtWgC7apjQRtDevw4KHpwSlRnltBVa8LLYkshPdkLrQhX8GTBwFIztod43cDaqvcC0FwIz/WuZKQpmTjhNkr40GhekJOTZzKOG3G/WF/OO0lTXoB4exu7NmT0p6hC5Pw0ymQO94SXOJvUDvFM4UU5oMuuAa@0cpkHAtFtPF4mov1zjqnsp9d/LoJiavo1r@UIfNVoSEKeUiXsjuZC9gx/CmzZUQ7kUxH09dkQLsX9Jb0aCxXJ3SIYLQutb4crMab6FW0AKfNdrkiwm09RetIG4sGHyqZrYFVOAKFie5tYqKqiiZCYwa0xa@U8t/Lh/8k7/f@pB89nD8GwfH0DQ "Java (OpenJDK 8) – Try It Online") [Answer] # PHP, ~~184~~ 176 bytes ``` <?=strtr([0,1,2,Creature,Demon,It,Fiend,30,31,"2ed 1","Vile Insect","Frankenstein´s 0"][[rand(6*$x=$argv[2]>9,6+4*$x),11][$argv[1]<=>1818]],[Monster,Devil,Wretch,"Abhorred "]); ``` Run with `-n` and give year and chapter as command line arguments or [try it online](http://sandbox.onlinephpfunctions.com/code/1efc4336e2247bcbfcd02fd8bb2d3adb7efa3e5a). index and thus result evaluate to `NULL` for year<1818, leading to empty output. [Answer] # Javascript (ES6), 205 bytes ``` a="abhorred ",d="devil",f="fiend",m="monster" y=>c=>y<1818?0:y>1818?"frankenstein's "+m:(l=c<10?[f,"wretch",m,"creature","demon",d,f,"it"]:["vile insect",a+m,f,"wretched "+d,a+d])[0|Math.random()*l.length] ``` Returns `0` if the year is less than 1818 ``` a="abhorred ",d="devil",f="fiend",m="monster" n=y=>c=>y<1818?0:y>1818?"frankenstein's "+m:(l=c<10?[f,"wretch",m,"creature","demon",d,f,"it"]:["vile insect",a+m,f,"wretched "+d,a+d])[0|Math.random()*l.length] ``` ``` <div oninput="o.innerText=n(y.value)(c.value)"><input id=y type=number value=1817 /><input id=c type=number value=10 /></div><p id=o>0 ``` [Answer] # Javascript 199 bytes ``` M="monster" A=(y,c)=>y<1818?"":y^1818?"Frankenstein's "+M:[W="wretch",M,"creature","demon",D="devil",F="fiend","it","vile insect",(H="abhorred ")+M,F,W+"ed "+F,H+D][Math.random()*(c>9?5:7)+7*(c>9)|0] console.log(A(1700,1)) console.log(A(1700,12)) console.log(A(1817,10)) console.log(A(1818,1)) console.log(A(1818,9)) console.log(A(1818,10)) console.log(A(1818,11)) console.log(A(1819,1)) console.log(A(1819,18)) console.log(A(2017,24)) ``` [Answer] # C, 380 BYTES ``` void ok(int *year, int* chapter){char*below_10[] = {"wretch", "monster", "creature", "demon", "devil", "fiend", "it"}; char*at_10[] = {"vile insect", "abhorred monster", "fiend", "wretched devil", "abhorred devil"}; year < 1818?printf("0"):(year == 1818?(chapter<10 printf("%s",below_10[rand()%8]):printf("%s",at_10[rand()%7])):printf("Frankenstein's Monster"));} ``` [Answer] ## [MBASIC](https://archive.org/details/BASIC-80_MBASIC_Reference_Manual), 288 bytes ``` 1 DIM R$(12):FOR I=1 TO 12:READ R$(I):NEXT:INPUT Y,C:IF Y<1818 THEN 5 2 IF Y>1818 THEN O$="Frankenstein's Monster":GOTO 5 3 IF C>9 THEN O=7 4 O$=R$(O+INT(RND(1)*N+1)) 5 PRINT O$:DATA wretch,monster,creature,demon,devil,fiend,it,vile insect,abhorred monster,fiend,wretched devil,abhorred devil ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~114~~ 110 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` 0…뢼–±¹.•ʒ¦Ë"ìËM₂G¶тá≠•ì#.•1ÏiT¥Ƶʒ“T¡Äg… 5ÀΘO¼™Ãí?ιË%4₄‡‡λYιi¾н••Jtm•17в£‚…'s 'ì³R7£R’¡¬ÿÿ±¹’¸¸)sŽ7X.S>èsT@èΩ ``` Outputs `0` when the year is below `1818`. [Try it online](https://tio.run/##yy9OTMpM/f/f4FHDssOrDy06tOdRw@RDGw/t1HvUsOjUpEPLDncrHV5zuNv3UVOT@6FtF5sOL3zUuQAod3iNMkiJ4eH@zJBDS49tPTXpUcOckEMLD7ekA41SMD3ccG6GP9C0lkWHmw@vtT@383C3qsmjppZHDQuB6NzuyHM7Mw/tu7AXaAYQeZXkggwzv7Dp0OJHDbOAJqgXK6gfXnNoc5D5ocVBjxpmHlp4aM3h/Yf3g9wG4u44tEOz@Ohe8wi9YLvDK4pDHA6vOLfy/39DC0MLLkMDAA) or [verify all test cases](https://tio.run/##yy9OTMpM/W9o4Pbf4FHDssOrDy06tOdRw@RDGw/t1HvUsOjUpEPLDncrHV5zuNv3UVOT@6FtF5sOL3zUuQAod3iNMkiJ4eH@zJBDS49tPTXpUcOckEMLD7ekA41SMD3ccG6GP9C0lkWHmw@vtT@383C3qsmjppZHDQuB6NzuyHM7Mw/tu7AXaAYQeZXkggwzv7Dp0OJHDbOAJqgXK6gfXnNoc5D5ocVBjxpmHlp4aM3h/Yf3g9wG4u44tEOz@Ohe8wi9YLvDK4pDHA6vOLfyv85/Q1MDAy5DLkMLEGUEpA3NuQwNQLQFWBhIWUJ5MFEQMrSEyILkuIwMgJqMTAA). **Explanation:** ``` 0 # Push a 0 …뢼–±¹ # Push dictionary string "creature devil monster" .•ʒ¦Ë"ìËM₂G¶тá≠• "# Push compressed string "demon fiend it wretch " ì # Prepend it: "demon fiend it wretch creature devil monster" # # Split by spaces: ["demon","fiend","it","wretch","creature","devil","monster"] .•1ÏiT¥Ƶʒ“T¡Äg… 5ÀΘO¼™Ãí?ιË%4₄‡‡λYιi¾н• # Push compressed string "abhorred devilabhorred monsterfiendvile insectwretched devil" •Jtm• # Push compressed integer 1249548 17в # Converted to Base-17 as list: [14,16,5,11,14] £ # Split the string into parts of that size: ["abhorred devil","abhorred monster","fiend","vile insect","wretched devil"] ‚ # Pair both string-lists together …'s '# Push string "'s " 'ì³ '# Push dictionary string "liechtenstein" R7£R # Leave the last 7 characters: "enstein" ’¡¬ÿÿ±¹’ # Push dictionary string "frankÿÿmonster", where the "ÿ" are automatically # replaced with the strings at the top of the stack: "frankenstein's monster" ¸¸ # Wrap it twice into a list: [["frankenstein's monster"]] ) # Wrap everything on the stack into a list # (We now have: [0,[["demon","fiend","it","wretch","creature","devil","monster"],["abhorred devil","abhorred monster","fiend","vile insect","wretched devil"]],[["frankenstein's monster"]]]) s # Swap to get the first (implicit) input Ž7X # Push compressed integer 1818 .S # Compare it with the input (-1 if below; 0 if equal; 1 if above) > # Increase it by 1 (0 if below; 1 if equal; 2 if above) è # Use it to index into the list s # Swap to get the second (implicit) input T@ # Check if it's larger than or equal to 10 (results in 0 for falsey; 1 for truthy) è # Use it to index into the inner list Ω # And finally get a random value from that list (which is output implicitly) ``` [See this 05AB1E tip of mine (sections *How to use the dictionary?*; *How to compress strings not part of the dictionary?*; *How to compress large integers?*; and *How to compress integer lists?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why: * `…뢼–±¹` is `"creature devil monster"`; * `.•ʒ¦Ë"ìËM₂G¶тá≠•` is `"demon fiend it wretch "`; * `.•1ÏiT¥Ƶʒ“T¡Äg… 5ÀΘO¼™Ãí?ιË%4₄‡‡λYιi¾н•` is `"abhorred devilabhorred monsterfiendvile insectwretched devil"`; * `•Jtm•` is `1249548` and `•Jtm•17в` is `[14,16,5,11,14]`; * `'ì³` is `"liechtenstein "`; * `’¡¬ÿÿ±¹’` is `"frankÿÿmonster"`; * `Ž7X` is `1818`. [Answer] # JavaScript, 194 B ``` e=Math.random,f=Math.floor;x=(a,b,c=`insect,monster,wretch,creature,demon,devil,fiend,it`.split`,`,d=[`vile `,`abhorred `])=>a<1818||a-1818?`Frankenstein's `+c[1]:(b<10||c[f(e()*2)])+c[f(e()*8)] ``` ]
[Question] [ Given a binary number, your task is to create a 'branch' of that number, with a depth of 2. For example, given `0` as input, you should output exactly this: ``` /000 /00 / \001 0 \ /010 \01 \011 ``` This should be fairly self explanatory of how the branches should be created. Depth 2 means we calculate branches for numbers of up to 2 numbers longer. We also calculate the branches in order, with zeroes at the top and ones at the bottom. More test cases: ``` 0 /000 /00 / \001 0 \ /010 \01 \011 1 /100 /10 / \101 1 \ /110 \11 \111 00 /0000 /000 / \0001 00 \ /0010 \001 \0011 01 /0100 /010 / \0101 01 \ /0110 \011 \0111 10 /1000 /100 / \1001 10 \ /1010 \101 \1011 11 /1100 /110 / \1101 11 \ /1110 \111 \1111 ``` ### Rules * You will never receive characters in the input other than `1` and `0`. * `0 < length of input < 11`. * Trailing whitespace allowed at the end of lines. [Answer] ## Batch, ~~178~~ ~~170~~ 159 bytes ``` @set/pb= @set s=%b:0= % @set s=%s:1= % @set e=@echo %s% %e% %s% /%b%00 %e% /%b%0 %e%/ %s% \%b%01 @echo %b% %e%\ %s% /%b%10 %e% \%b%1 %e% %s% \%b%11 ``` Edit: Saved 11 bytes thanks to @ConorO'Brien. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~39~~ 38 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` L⁶ẋ,W;“/0¶\1 ”ṃ@“ð&ẏ{×ẏĊfẏȷ®ỤṪ⁻ʠaƇGⱮȷ’ ``` **[Try it online!](https://tio.run/nexus/jelly#@@/zqHHbw13dOuHWjxrm6Bsc2hZjqPCoYe7Dnc0OQIHDG9Qe7uqvPjwdSB7pSgOSJ7YfWvdw95KHO1c9atx9akHisXb3RxvXndj@qGHm////lQwNDJQA)** ### How? The art to be printed is: ``` L L /N00 L /N0 L/ L \N01 N L\ L /N10 L \N1 L L \N11 ``` Where `N` is the input string and `L` is a string of spaces of the length of the input string. As such it is comprised of eight components (`L`, `N`, `/`, `0`, the newline character, `\`, `1`, and the space character) and hence may be stored as a base-8 number ( which may be compressed as a base-250 number in Jelly). The `ṃ` atom combines base conversion and indexing into a list (effectively one may define arbitrary digits to be used). ``` L⁶ẋ,W;“/0¶\1 ”ṃ@“ð&ẏ{×ẏĊfẏȷ®ỤṪ⁻ʠaƇGⱮȷ’ - Main link: binary string s e.g. "100" ⁶ - space character ẋ - repeat by: L - length(s) [' ',' ',' '] W - wrap s in a list [['1','0','0']] , - pair [[' ',' ',' '],['1','0','0']] “/0¶\1 ” - char list: ['/','0',<newline>,'\',','1',' '] ; - concatenate [[' ',' ',' '],['1','0','0'],'/','0',<newline>,'\',','1',' '] “ð&ẏ{×ẏĊfẏȷ®ỤṪ⁻ʠaƇGⱮȷ’ - base 250 number: 91531517467460683226372755994113932025707662527 ṃ@ - base decompression [reversed @arguments] - this uses the concatenated list above as - the 8 digits of that number in base 8. - implicit print ``` [Answer] ## JavaScript (ES6), 112 bytes ``` s=>`22 /300 2 /30 2/2 4301 3 242 /310 2 431 22 4311`.replace(/./g,n=>[s.replace(/./g,' '),s,'\\'][n-2]||n) ``` ### Demo ``` let f = s=>`22 /300 2 /30 2/2 4301 3 242 /310 2 431 22 4311`.replace(/./g,n=>[s.replace(/./g,' '),s,'\\'][n-2]||n) console.log(f('0')) console.log(f('11')) console.log(f('101')) ``` [Answer] # [Python 3](https://docs.python.org/3/), 117 109 bytes ``` lambda k:'ll /g00\nl /g0\nl/l \g01\ng\nl\l /g10\nl \g1\nll \g11'.replace('l',' '*len(k)).replace('g',k) ``` [Try it online!](https://tio.run/nexus/python3#RYtBDsIwDAS/4pttVFHnisRPfAkljaoYK6rK@4PbC6fdndGuTx2WP693hvZAMwCYq4i6nRkxB9IqSb3GUjt9urzWgNcjWsL7XrrlpRAaTgh4s@LUmP@84tR49H3zg1bavH8PYuaRRMYP "Python 3 – TIO Nexus") * saved 8 bytes thanks to [JonathanAllan](https://codegolf.stackexchange.com/users/53748/jonathan-allan) (Use of lambda function) The format string when printed looks like: ``` ll /g00 l /g0 l/l \g01 g l\l /g10 l \g1 ll \g11 ``` This looks good already for string of length of 1. All we got to do is replace l by spaces of length equal to that of g and, of course, g is to be replaced by the original string [Answer] # Python 3.6, ~~172~~ ~~153~~ 128 bytes Literally does not get more straightforward than this... This is actually shorter than my original attempt at generating it with an algorithm. How sad. ``` k=input() l=len(k) b=' '*l print(f'{b*2} /{k}00\n{b} /{k}0\n{b}/ {b}\\{k}01\n{k}\n{b}\\ {b}/{k}10\n{b} \\{k}1\n{b*2} \\{k}01') ``` -19 bytes thanks to @Leo -25 bytes thanks to @L3viathan [Answer] # C, ~~170~~ 168 bytes *Thanks to @Neil for saving two bytes!* ``` n;f(char*s){n=strlen(s);printf("%*c%s00\n%*c%s0\n %*c%*c%s01\n%s\n %*c%*c%s10\n%*c%s1\n%*c%s11",2*n+4,47,s,n+2,47,s,n,47,n+3,92,s,s,n,92,n+3,47,s,n+2,92,s,2*n+4,92,s);} ``` [Try it online!](https://tio.run/nexus/c-gcc#dY7NCoNADITvPsWyIOzfwWyFUpa@iReRSoU2FLOexGffZrVKD20u@WYygUkYetXd29GQnvFKcXzcUJEOr3HA2CtZmq6kqmpwgwZFhpWBTfoyYE/BvkE6b9DWrj47cmj9B/JCe3IXzyprhqyP2HrYXjPqsCSuI57tgEoXcyF4uFwluegUSckGGQ8bfvvwJw85XyzpDQ) [Answer] # [Python 3](https://docs.python.org/3/), 96 bytes ``` lambda s:""" /00  /0 / \01  \ /10  \1  \11""".translate([s,' '*len(s),s]) ``` [Try it online!](https://tio.run/nexus/python3#HYtBCsMwDASRj36F8CVSCY10LfQldQ8uTSDgmhC573ftnnbY2d3useX0eb0T2i2EAICIixPxMMLD0ovoRL3zEGE4HS469f9tB@2/az1TsZzqSg@bJ5wueS1kPNuT23HupdJGezm@lZi5qUj7AQ "Python 3 – TIO Nexus") The unprintable characters do not display correctly; the string format is [the same as officialaimm's](https://codegolf.stackexchange.com/a/115987/20260), but with `\x01` for `l` and `\x02` for `g`. ``` ll /g00 l /g0 l/l \g01 g l\l /g10 l \g1 ll \g11 ``` Uses string substitution with [Python 3's flexible `translate`](https://docs.python.org/3/library/stdtypes.html#str.translate). The translate list `[s,' '*len(s),s]` maps `\x01` to `' '*len(s)` and `\x02` to `s`. Any larger characters are unchanged because they give indices that are out-of-bounds for the list. `\x00` could not be used because a null byte is read as a program end, so the first entry is wasted. [Answer] # [PHP](https://php.net/), 128 bytes Only a simple Output ``` <?=$b=str_pad("",strlen($a=$argn)),"$b /{$a}00\n$b /{$a}0\n$b/$b \\{$a}01\n$a\n$b\\$b /{$a}10\n$b \\{$a}1\n$b$b \\{$a}11"; ``` [Try it online!](https://tio.run/##K8go@G9jX5BRwKWSWJSeZ6tkaKhkzWVvBxS0VUmyLS4pii9ITNFQUtIBMnNS8zRUEm3BKjU1dZRUkhQUFPSrVRJrDQxi8oA8CBvE1AfJxcSA@YZAgUSQYEwMSBSsyBCiAaICpCAJbBiUD3TD//8A "PHP – Try It Online") [Answer] # [Stacked](https://github.com/ConorOBrien-Foxx/stacked), 81 bytes ``` {!n#'' '*@s's s /n00 s /n0 s/ s \n01 n s\ s /n10 s \n1 s s \n11' '\l'$#~1/repl} ``` [Try it online!](https://tio.run/nexus/stacked#JYxBCsJQDET3OUVKhdGC/MQTeJC/kVLoosZillKv/s2PizBvZsKcIWBonHSQTpqR4vIZjJd5fbWAERFOd4czOxcToRTyEr6aKBl5zU57V00pfwP6at1wGr9a3su@HW3IYcYVrDee/u7g52NvPw "Stacked – TIO Nexus") Not very interesting, unfortunately. Here's the most interesting part: ``` '\l'$#~1/repl repl replace all '\l' letters $#~ by evaluating 1/ over one argument (otherwise, it would evaluate the "last" thingy) ``` This is basically string interpolating, but 10 bytes shorter than the builtin. [Answer] # [///](https://esolangs.org/wiki////), 116 bytes ``` /[/\\\///x///*/[y\\0[ y\/\/y\\1[ y\//**********/y///s/yx//~/ /~ ss[x00 s[x0 s[~s\\x01 x s\\~s[x10 s\\x1 ~ ss\\x11 ``` [Try it online!](https://tio.run/nexus/slashes#PYqxDcBACAN7pqBOY5gHb0EDza/@gRRBsjjZdxEgCaAmD6JJC22CGPQP8fyHHi3RYx@o4mhmlJnoPsk4SZa5lAycKX236VzWXfB7Xw "/// – TIO Nexus") Input is as follows: ``` /[/\\\///x/INPUT HERE!!!!!!!!//*/[y\\0[ y\/\/y\\1[ y\//**********/y///s/yx//~/ /~ ss[x00 s[x0 s[~s\\x01 x s\\~s[x10 s\\x1 ~ ss\\x11 ``` Works by using a basic template, and adding spaces and characters where needed. The byte count went up because Ørjan Johansen realized that it did not handle spacing at first. But the problem is know fixed. [Answer] # [Python 2](https://docs.python.org/2/), ~~101,91 bytes~~113 bytes ``` lambda y:' ++/_00\n +/_0\n+/ +\\_01\n_\n+\\ +/_10\n +\\_1\n ++\\_11'.replace('_',y).replace('+',' '*len(y)) ``` [Try it online!](https://tio.run/nexus/python2#RYvBCoAwDEN/pbduTnS7Cv5JYUzdQahliB729dp58ZTkJeGZHk7HsiWoEwKAc2P0ngSakrhREVH0gSRqJILWhG@hXPF3ajbgcObCac0GI/bV/tFhj4AdZzHV2qecu1zAZpdyX0YB6vkF "Python 2 – TIO Nexus") Input is a string of 0's and 1's of length 1 or 2! That is 0,01,10 or 11! +12 bytes - corrected the spacing in \ for length two input. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 34 bytes ``` P<³←⮌θF²«J³⁻×⁴ι²θP<²Iι↗F²«P⁺⁺θικ↓↓ ``` [Try it online!](https://tio.run/##bY3NCoJAEMfP@RRznIUNQjtZtzpFgog9gMiaQ6uru6sdwmff/AiS6DLMzP/jl5eZzlUmnYs6aanRVFsMjxwCdvDi5bqKwnJIRC@0EdiyUSmUBvQZvLzNpauaVGHAIaK6M5hSJQzuORDj4E/mzdLTTusPxf/Kp8xYpNkfqV5geGsSupd2eqxw64ZYjrx5tAvuMcc/@bN61n/OwRuc27ltL98 "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` P<³ ``` Print the left pairs of `/`s and `\`s. ``` ←⮌θ ``` Print the input right-justified at the current position. ``` F²« ``` Loop through the branches. ``` J³⁻×⁴ι² ``` Move the the position of the branch. We can do this because the root was printed right-justified so that the middle branch is always at the same absolute position. ``` θ ``` Print the input. ``` P<² ``` Print the right pair of `/` and `\`. ``` Iι ``` Print the branch suffix. ``` ↗ ``` Move to the first leaf. ``` F²« ``` Loop through the leaves. ``` P⁺⁺θικ ``` Print the input and the branch and leaf suffix. ``` ↓↓ ``` Move to the next leaf. Note: If trailing whitespace was acceptable then `F²⁺⁺⁺θικ¶¶` would save a byte. ]
[Question] [ What general tips do you have for golfing in [Nim](http://nim-lang.org/ "Nim programming language")? I'm looking for ideas which can be applied to code-golf problems and which are also at least somewhat specific to Nim (e.g. "remove comments" is not an answer). Please post one tip per answer. [Answer] ## Unsigned operators When working with nonnegative integers, sometimes it's better to use unsigned operators. Specifically, if possible, use `/%` and `%%` instead of `div` and `mod`. [Answer] ## Flexible call syntax Nim is pretty flexible when it comes to function call syntax. For example, here are some ways to call a function with one argument: ``` ord(c) ord c c.ord ``` And ways to call a function with two arguments: ``` max(a,b) a.max(b) a.max b ``` Choose the golfiest version that works right for your situation, especially regarding precedence. For example, compare: ``` abs(n)+2 n.abs+2 (abs n)+2 ``` As opposed to: ``` abs(n+2) (n+2).abs abs n+2 ``` [Answer] # Use the `future` module The `future` module contains two main byte-saving features: lambdas and list comprehensions. Lambdas are extremely useful. For example, this: ``` proc f(s:any):any=s&", world!" ``` can be shortened to this: ``` import future s=>s&", world!" ``` which saves a byte. Note, however, that lambdas can't be used outside of a parameter list -- so to test your code, you'll have to do something like this: ``` import future proc test(f: string -> string) = echo f "Hello" test(s=>s&", world!") ``` As well, list comprehensions can be used with the `future` module. For example, this code prints a seq (`@[...]`) of all squares less than 100 divisible by 4: ``` import future echo lc[x*x|(x<-1..9,x*x mod 4==0),int] ``` [Answer] # Use `on` and `off` as a boolean value `on` / `off` are aliases for true / false. [Answer] # Use `;` to end statements Oftentimes, a lot of Nim bytes come from the mandatory indentation of two spaces. This can sometimes be avoided by utilizing `;` to break statements. For example (a bit contrived, but nevertheless effectively demonstrating the idea): ``` while 1>0:echo "Hello";echo"World" ``` [Answer] # 1>0 for true and 0>1 for false In Nim, there is no implicit conversion of int->bool or bool->int. It is thus advantageous for golfing to use `1>0` or `0>1` to get the values for true and false, as one might use `1`/`0` in C. This can help with, for example, the creation of infinite loops. ]
[Question] [ We all often hear the idiom "walk through the array" to mean "map the function over the following array". However, I need it done (now!), so I want you to *run* through the array. ## How do I run? Imagine there's a wild pack of [wolves](https://codegolf.stackexchange.com/questions/25347/survival-game-create-your-wolf) behind you Running through an array is like walking through one, except you can skip over elements. Yes, it's sometimes messy, but it (generally) works. "Which elements are skipped?", you may ask. Well, this is done at random. Let's walk through running through the array! 1. Let `e` be the current element. 2. Let `random` generate a random float in `[0,1)`. If `random() < 0.5`, then you go the next element and then to step 1. (You may generate a number by other means, so long as their is an (ideally) equal chance of skipping and remaining. E.g., you can use choose an element from a two-member set and perform the action based on the result.) 3. Otherwise, you perform function `f` on `e`. ## Objective Given an array/list/string like either `A` and a number `K`, run through the array, adding `K` to each member accessed. Output/return this array. `A` will only contain non-negative integers, and `K` will only ever be a non-negative integers. This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest program in bytes wins. ## Test cases (examples) ``` K, A => possible K' [1, 2, 3, 4], 0 => [1, 2, 3, 4] [1, 2, 3, 4], 1 => [1, 3, 3, 5] [0, 0, 0, 0], 2 => [2, 0, 0, 2] ``` [Answer] # Clojure, ~~41~~ 37 bytes ``` (fn[a k](map #(+(*(rand-int 2)k)%)a)) ``` Knocked off a couple of bytes by multiplying by 0 or 1 and dropping the "if". Credit to most all of the other submitters! [Answer] # Jelly, ~~9~~ ~~8~~ 7 bytes From `8` to `7` thanks to [@FryAmTheEggman](https://codegolf.stackexchange.com/users/31625/fryamtheeggman). ``` +2X’¤¡€ ``` [Try it online!](http://jelly.tryitonline.net/#code=w7ArMljigJnCpMKh4oKs&input=&args=WzEsIDIsIDMsIDRd+MQ) ### Explanation ``` +2X’¤¡€ € Map over each argument... 2X Choose a random number from {1,2} ’ Minus 1 ¤ (grammar stuff) ¡ Repeat that number of times... + Add the second input (to the argument being mapped over). ``` [Answer] # Pyth, 7 ``` m+*O2vz ``` [Try it here](http://pyth.herokuapp.com/?code=m%2B%2aO2vz&input=%5B1%2C2%2C3%2C4%5D%0A5&debug=0) Uses a random choice instead of floating point comparison, but should be indistinguishable. ### Expansion: ``` m+*O2vz ## implicitly, a d and Q are added to the end of the program m+*O2vzdQ ## Q = eval(input()), z= input() m ## map over each element d of Q + d ## add to d *O2vz ## the product of eval(z) and a random number chosen from [0, 1] ``` Using floating point: ``` m+*<.5O0vz ``` [Try it here](http://pyth.herokuapp.com/?code=m%2B%2A%3C.5O0vz&input=%5B1%2C2%2C3%2C4%5D%0A5&debug=0) [Answer] # [MATL](https://github.com/lmendo/MATL), 11 bytes ``` tZy1$rEki*+ ``` Uses floating point random numbers. [**Try it online!**](http://matl.tryitonline.net/#code=dFp5MSRyRWtpKis&input=WzEgMiAzIDRdCjEw) ### Explanation ``` t % implicit input (array). Duplicate Zy % size (array specifying number of rows and columns) 1$r % random vector between 0 and 1 with that size Ek % duplicate, round down: gives 0 or 1 with the same probability i % input (number K to be added) * % multiply: gives either 0 or K for each element + % add element-wise ``` [Answer] # Japt, 6 bytes ``` ®+V*Mq ``` [Test it](https://ethproductions.github.io/japt/?v=1.4.5&code=ritWKk1x&input=WzAsMCwwLDBdLDI=) --- ## Explanation Implicit input of array `U` and integer `V`. Map (`®`) over the array and, to each element, add `V` multiplied by `Mq`, which randomly generates either `0` or `1`. Implicit output of resulting array. [Answer] # Ruby, 28 bytes ``` ->a,k{a.map{|e|e+k*rand(2)}} ``` [Answer] # Julia, ~~33~~ ~~29~~ 27 bytes ``` x->k->x+rand(0:1,endof(x))k ``` This is an anonymous function that accepts an array with an inner anonymous function that accepts an integer and returns an array. To call it, assign it to a variable and call like `f(x)(k)`. We generate an array with the same length as the input array consisting of zeros and ones chosen at random with equal probability. We multiply this by the input integer and add that to the input array. [Try it online!](http://julia.tryitonline.net/#code=Zj14LT5rLT54K3JhbmQoMDoxLGVuZG9mKHgpKWsKCnByaW50bG4oZihbMSwyLDMsNF0pKDIpKQ&input=) Saved 2 bytes thanks to Dennis! [Answer] # Python 2, ~~60~~ 58 bytes ``` from random import* lambda a,k:[e+choice([0,k])for e in a] ``` This program turned out really simple. There aren't many golfing tricks in there, apart from the the obvious "`from module import*`", using a lambda instead of a regular function and the general lack of whitespace. Other than that it's actually quite idiomatic. If I was writing this for real I'd probably do it in a very similar way: ``` import random def running_addition(seq, k): return [e + random.choice([0, k]) for e in seq] ``` Or perhaps something more fancy: ``` import random import operator import functools def run_through(seq, func): def random_func(arg): if random.randint(0, 1): return func(arg) return arg return [random_func(e) for e in seq] def running_addition(seq, k): return run_through(seq, functools.partial(operator.add, k)) ``` But that's enough showing off :) This is the old, 60 byte version from when using a float for randomness was required: ``` from random import* lambda a,k:[e+k*(random()<.5)for e in a] ``` For each element of the list, add `k*(random()<.5)`. Python booleans evaluate to 0 and 1, so this adds 0 to any elements for which the condition isn't true. Python's `random.random()` returns floats in `[0, 1)`, so I didn't have to worry about that. [Answer] # [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), 56 bytes ``` x=NF{for(srand(systime());++i<x;)rand()>.5?$i+=$x:0}NF-- ``` [Try it online!](https://tio.run/##SyzP/v@/wtbPrTotv0ijuCgxL0WjuLK4JDM3VUNT01pbO9OmwloTLKxpp2dqr5KpbatSYWVQ6@emq/v/v6GCkYKxgomCqYKZgqEBAA "AWK – Try It Online") The random number generator in AWK has to be seeded or it will yield the same sequence of numbers every time the script is run. So that a big chunk of this code. The code expects the "array" to be a list of space separated numbers as commandline argument. The `A` increment value is the last commandline argument. ``` x=NF{ } ``` Setting `x` saves some characters, always evals to `true` and the braces group the code run against the input line. ``` for(srand(systime()); ) ``` The code block just one `for` statement, which starts by seeding the random number generator. ``` ++i<x; ``` The "should I iterate again" check iterates a counter to process all but the last commandline argument. The last one is the `A` value from the challenge, so we need to ignore that. ``` rand()>.5?$i+=$x:0}NF-- ``` The body of the loop increments the current commandline argument by the `A` value using a ternary conditioned on the return value from the random number generator. ``` NF-- ``` Once all the arguments have been incremented (or not), printing them is just a matter of decrementing the number of commandline arguments by one. That's always truthy, directs AWK to ignore the last one, and since there's no code block all the arguments are printed. [Answer] # JavaScript (ES6), 38 bytes ``` solution= a=>k=>a.map(n=>Math.random()<.5?n:n+k) document.write("<pre>"+ [ [[1,2,3,4], 0], [[1,2,3,4], 1], [[0,0,0,0], 2], [[4,22,65,32,91,46,18], 42] ] .map(c=>"["+c[0]+"],"+c[1]+": "+solution(c[0])(c[1])).join`\n`) ``` [Answer] ## PowerShell v2+, 34 bytes ``` param($a,$k)$a|%{$_+$k*(random 2)} ``` Takes input `$a` and `$k`, the array and the int respectively. We then loop through the array and each loop iteration output the current element plus `$k` times `(random 2)` which will execute `Get-Random -Maximum 2` (i.e., either a `0` or a `1`). These are all left on the pipeline and output as an array is implicit. [Answer] ## CJam, 10 bytes ``` {f{2mr*+}} ``` Expects the array and the number on top of the stack in that order and replaces them with the new array. [Test it here.](http://cjam.aditsu.net/#code=%5B1%202%203%204%5D%201%0A%0A%7Bf%7B2mr*%2B%7D%7D%0A%0A~p) [Answer] # php 71 bytes ``` function f($s,$k){foreach($s as $v){$v+=rand(0,2)==0?k:0;echo $v.",";}} ``` [Answer] # k (12 bytes) ``` {x+y*(#x)?2} ``` e.g. ``` k){x+y*(#x)?2}[0 0 0 0;2] 2 2 2 0 ``` More generally, where `f` can be passed as an argument for 16 characters ``` {@[x;&(#x)?2;y]} ``` e.g. ``` k){@[x;&(#x)?2;y]}[0 0 0 0;2+] 0 0 2 0 ``` [Answer] # Python 3 152 110 98 bytes This is my first code golf solution so I don't know any tricks. I tested this using a main function with test cases. The file size is only this function. ``` from random import* def a(x,y): p=0 for z in x: if random()>.5:x[p]=z+y p+=1 print(x) ``` Thanks to @Cᴏɴᴏʀ O'Bʀɪᴇɴ for the advice on removing whitespace. Additional praise to @undergroundmonorail for advice that saved 12 bytes. [Answer] ## Clojure, 32 bytes ``` #(for[i %](+(*(rand-int 2)%2)i)) ``` Thanks you David for `rand-int` idea, definetely shorter than the `if(>(rand)0.5)` approach. Here `for` beats `map`. [Answer] # [Perl 5](https://www.perl.org/), 30 + 1 (-a) = 31 bytes ``` $,=<>;say.5>rand?$_:$_+$,for@F ``` [Try it online!](https://tio.run/##K0gtyjH9/19Fx9bGzro4sVLP1K4oMS/FXiXeSiVeW0UnLb/Iwe3/f0MFMOQy@pdfUJKZn1f8X9fXVM/A0OC/biIA "Perl 5 – Try It Online") [Answer] # [Factor](https://factorcode.org/), 29 bytes ``` [ '[ .5 [ _ + ] whenp ] map ] ``` [Try it online!](https://tio.run/##VYqxCsIwFEX3fsXdHITQRl10cZMuLuIURGJ8pcEmqS8RKdJvjxlc5MI5HLidNilwPp/a42GLjic8iD0NcDr1MMHdrNflEQVrfw8OkZ4v8oYiRqaUppGtT9hV1QcNJFZYY0b9V02p@rcZMissFMQGClcsccG7Jz8WO12YZWK7h4gwA2nOXw "Factor – Try It Online") * `'[ ... _ ... ]` Slot whatever is on top of the data stack (A) into the quotation at the `_`. * `map` Apply a quotation to each member of a sequence (K), collecting the results into a sequence of the same length. * `.5 [ _ + ] whenp` `whenp` is a version of `when` that takes a probability instead of a boolean. In other words, there is a 50% chance that `whenp`'s quotation will be called. [Answer] # Octave, 28 bytes ``` @(A,R)R*(rand(size(A))<.5)+A ``` Sample run on [ideone](http://ideone.com/sqmLOa). [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 10 bytes Code: ``` vždɲ*y+}) ``` [Try it online!](http://05ab1e.tryitonline.net/#code=dsW-ZMOJwrIqeSt9KQ&input=WzAsIDAsIDAsIDBdCjI). [Answer] # Java, 84 bytes ``` int[]r(int[]A,int K){for(int i=0;i<A.length;A[i++]+=Math.random()>.5?0:K);return A;} ``` ### Ungolfed ``` int[] r(int[] A, int K) { for (int i = 0; i < A.length; A[i++] += Math.random() > .5 ? 0 : K); return A; } ``` ### Notes * The afterthought of the loop could also be it's body, there is no difference in size. * The input array is modified but the statement does not contain a restriction regarding this issue. If you would count the modified array as a form of "Output/return", you could shave off another 9 bytes by removing `return A;`. The return type would need to be changed from `int[]` to `void`. This however does not save additional bytes since an additional space is needed between `void` and `r`. ### Shorter version (As mentioned in the note), 75 bytes ``` void r(int[]A,int K){for(int i=0;i<A.length;)A[i++]+=Math.random()>.5?0:K;} ``` ### Output ``` [1, 2, 3, 4], 0 => [1, 2, 3, 4] [1, 2, 3, 4], 1 => [1, 3, 3, 4] [1, 2, 3, 4], 2 => [3, 2, 3, 4] [1, 2, 3, 4], 3 => [4, 5, 3, 7] [1, 2, 3, 4], 4 => [5, 2, 3, 8] [1, 2, 3, 4], 5 => [6, 2, 8, 9] ``` [Answer] ## Mathcad, bytes [![enter image description here](https://i.stack.imgur.com/1gYCF.jpg)](https://i.stack.imgur.com/1gYCF.jpg) --- No formal byte count as Mathcad counting protocol yet to be decided. [Answer] # Java ~~108~~ ~~107~~ ~~85~~ 82 bytes ``` void f(int[]s,int k){for(int i:s)System.out.print((i+=Math.random()<.5?k:0)+";");} ``` 14 bytes saved thanks to @TimmyD ]
[Question] [ Write the shortest program to print the non-trivial powers ≤ 2^12 in order non-trivial power means the base and exponent are > 1 Leading whitespace is optional When there are multiple solutions, the order is not important, so `16 = 4^2, 2^4` is ok Sample output: ``` 4 = 2^2 8 = 2^3 9 = 3^2 16 = 2^4, 4^2 25 = 5^2 27 = 3^3 32 = 2^5 36 = 6^2 49 = 7^2 64 = 2^6, 4^3, 8^2 81 = 3^4, 9^2 100 = 10^2 121 = 11^2 125 = 5^3 128 = 2^7 144 = 12^2 169 = 13^2 196 = 14^2 216 = 6^3 225 = 15^2 243 = 3^5 256 = 2^8, 4^4, 16^2 289 = 17^2 324 = 18^2 343 = 7^3 361 = 19^2 400 = 20^2 441 = 21^2 484 = 22^2 512 = 2^9, 8^3 529 = 23^2 576 = 24^2 625 = 5^4, 25^2 676 = 26^2 729 = 3^6, 9^3, 27^2 784 = 28^2 841 = 29^2 900 = 30^2 961 = 31^2 1000 = 10^3 1024 = 2^10, 4^5, 32^2 1089 = 33^2 1156 = 34^2 1225 = 35^2 1296 = 6^4, 36^2 1331 = 11^3 1369 = 37^2 1444 = 38^2 1521 = 39^2 1600 = 40^2 1681 = 41^2 1728 = 12^3 1764 = 42^2 1849 = 43^2 1936 = 44^2 2025 = 45^2 2048 = 2^11 2116 = 46^2 2187 = 3^7 2197 = 13^3 2209 = 47^2 2304 = 48^2 2401 = 7^4, 49^2 2500 = 50^2 2601 = 51^2 2704 = 52^2 2744 = 14^3 2809 = 53^2 2916 = 54^2 3025 = 55^2 3125 = 5^5 3136 = 56^2 3249 = 57^2 3364 = 58^2 3375 = 15^3 3481 = 59^2 3600 = 60^2 3721 = 61^2 3844 = 62^2 3969 = 63^2 4096 = 2^12, 4^6, 8^4, 16^3, 64^2 ``` [Answer] ## Python, 113 ``` R=range for k in R(4097): v=', '.join(`i`+'^'+`j`for i in R(2,65)for j in R(2,13)if i**j==k) if v:print k,'=',v ``` This takes a few seconds to complete. A faster (148 chars) version, using a dictionary to avoid the outermost loop, runs in ~ 0.01 sec: ``` R=range(2,65) p={} for i in R: for j in R: if i**j<4097:p[i**j]=p.get(i**j,[])+[`i`+'^'+`j`] for k,v in sorted(p.items()):print k,'=',', '.join(v) ``` [Answer] ## Ruby 1.9, ~~112 111~~ 99 characters ``` 4097.times{|x|s=[] 2.upto(64){|a|2.upto(12){|b|a**b==x&&s<<[a,b]*?^}} puts [x,s*", "]*" = "if s[0]} ``` This takes about 0.8 seconds to complete on my system. A faster solution is 111 characters long: ``` h={};(2..64).map{|a|(2..12).map{|b|a**b<4097&&(h[a**b]||=[])<<[a,b]*?^}} puts h.sort.map{|a,b|[a,b*", "]*" = "} ``` [Answer] ## Windows PowerShell, 102 With help by Ventero for the initial code. ``` $OFS=', ' 4..4KB|%{$x=$_ if($s=2..64|%{$a=$_ 2..12|?{[math]::pow($a,$_)-eq$x}|%{"$a^$_"}}){"$x = $s"}} ``` [Answer] ## ~~Interactive~~ J, ~~118~~ ~~101~~ 98 ``` 3 :0"0 i.4097 if.#l=.":2j2+63(<.@%~j.|)I.y=,^/~2+i.63 do.echo(":y),' = ',l rplc j`^,' ';', 'end. ) ``` (last newline unneeded) Still a lot of code for the presentation... Note: in theory changing `63` and `63` to `y` and `y` saves 2 more bytes but that version uses extreme amount of memory. *Edited by randomra.* [Answer] ## Bash, 138 chars ``` i=2;j=1 f(){((v>4096))&&((j=1,++i)) a[$v]+="$i^$j, " ((v=i**++j,i<65))&&f } f f(){ echo $j = ${a[$j]} ((j++<v))&&f } f|sed '/=$/d;s/.$//' ``` ### Edits * **(169 : 155)** 2 `for` for a `while`. * **(155 : 148)** Append with `+=` * **(148 : 147)** output with `while`, reusing j * **(147 : 142)** use sed to remove empty lines * **(142 : 137)** put `v` in `(())`, use v for 4096 (last value) * **(137 : 134)** remove sed quotes, join `(())` expressions * **(134 : 132)** replace loops with recursive functions * **(132 : 142)** forgot the comma `,` :( * **(142 : 138)** tired of updates :p [Answer] ## PHP, 138 characters - [Output](http://codepad.viper-7.com/DszyND.php53) ``` <?for($b=1;++$b<65;)for($e=1;++$e<13;)if(4097>$f=pow($b,$e))$p[$f][]="$b^$e";ksort($p);foreach($p as$n=>$c)echo"$n = ".join($c,", ")."\n"; ``` **Ungolfed** ``` <?php // Array of combinations $powers = array(); // Loop through every base from 2 to 64, as 64 is the highest you can go for($base = 2; $base < 65; $base++){ // Loop through all powers from 2 to 12, as 12 is the maximum for($power = 2; $power < 13; $power++){ // Calculate the power $end = pow($base, $power); // Kill the loop if the result is too high if($end > 4096){ break; } // Add the combination if the result is within limits $powers[$end][] = $base."^".$power; } } // Sort the powers by the total amount ksort($powers); // Output the powers in the correct format foreach($powers as $number => $combinations){ echo $number." = ".implode($combinations, ", ")."\n"; } ``` [Answer] ## Python, 127 chars ``` F={} for i in range(693):a,b=i/11+2,i%11+2;F[a**b]=F.get(a**b,'')+', %d^%d'%(a,b) for k in sorted(F)[:81]:print k,'=',F[k][2:] ``` [Answer] # Mathematica, 152 byte ``` Print/@Cases[Range@4096,n_/;(2<=##&&##==##&)@@(f=#2&@@@FactorInteger@#&)@n:>{n,Row[{n^(1/#),#}~Row~"^"&/@Reverse@Rest@Divisors@#,", "]&@@f@n}~Row~" = "] ``` This got embarrassingly long. Something like 25 characters are spent on output formatting. The actual code is fairly simple: filter those numbers where all exponents in the prime factorisation are equal. Then, for each of those produce one result for each divisor of the exponent (excluding 1, including itself). [Answer] ## C (589 bytes) ``` int pow(int a,int b){ int res = 1; while(b>0){ while(b%2 == 0){ a *= a; b/=2; } b--; res = res*a; } return res; } char s[99],t[9]; int main(){ int N,T,a,i,f,e,n; for(n = 2; n <= 1<<12; n++){ strcpy(s,""); T = N = n; f = 0; int sqt = sqrt(N)+1; for(i = 2; i <= sqt; i++){ for(e=0;0==N%i;e++,N/=i); for(a = i; e > 1;e = e%2?(e+1)/2:e/2) for(a=i;a<T;pow(a,e)==T?f++?0:printf("%d =",T),sprintf(t,", %d^%d",a,e),strcat(s,t):0,a*=i); } f?puts(s+1):0; } return 0; } ``` I didn't golfed also this approach is not the best one but yet fast enough to produce an exact 0s in [ideone](http://ideone.com/6P8NS). [Answer] # OCaml + Batteries, 220 206 158 156 characters Taking a hint from the best-scored solutions: ``` Printf.(iter(fun x->match String.join", "[?List:sprintf"%d^%d"b e|b<-2--64;e<-2--12;float x=float b**float e?]with""->()|s->printf"%5d = %s\n"x s)(4--4096)) ``` (Line endings at significative whitespace to keep lines short.) A faster but longer version that generates powers instead of testing them: ``` Printf.(List.(iter(fun l->printf"%5d = %s\n"(fst(hd l))(String.join", "(map snd l)))(group(fun(x,_)(y,_)->x-y)[?List:truncate p,sprintf"%d^%d"b e|b<-2--64;e<-2--12;p<-List:[float b**float e];p<=4096.?]))) ``` [Answer] ## Haskell, 146 characters ``` c[a]=a c(a:z)=a++", "++c z n#[]="" n#s=shows n$" = "++c s++"\n" main=putStr$(\n->n#[shows x$'^':show y|x<-[2..64],y<-[2..12],x^y==n])=<<[4..4096] ``` [Answer] # JavaScript, 160 ``` o={} i=2 s='' n=4097 for(k=4;k<n;k=++i*i)for(j=2;k<n;k*=i) {a=i+'^'+j if(o[k])o[k]+=', '+a else o[k]=a j++}for(i=0;i<n;i++)if(o[i])s+='\n'+i+' = '+o[i] alert(s) ``` ### 194 ``` o={},i=2,s='',n=4096 for(k=4;k<=n;k=i*i){for(j=2;k<=n;k*=i){o[k]=o[k]||[] o[k].push(i+'^'+j) j++}i++} for(i=0;i<n;i++){if(o[i]){s+='\n'+i+' = ' for(j in o[i])s+=(j==0?'':', ')+o[i][j]}} alert(s) ``` [Answer] # Pyth, 39 bytes ``` jm++^Fhd" = "j", "jL\^d<.g^Fk^tS64 2 81 ``` Try it online [here](https://pyth.herokuapp.com/?code=jm%2B%2B%5EFhd%22%20%3D%20%22j%22%2C%20%22jL%5C%5Ed%3C.g%5EFk%5EtS64%202%2081&debug=0). ``` jm++^Fhd" = "j", "jL\^d<.g^Fk^tS64 2 81 S64 [1-64] t Discard first element ^ 2 Cartesian product of the above with itself .g Group the pairs, as k, using: ^Fk [a,b] -> a^b < 81 Take the first 81 results of the above (those where exponential <= 4096) m Map the remaining groups, as d, using: jL\^d Join each pair in d on "^" j", " Join on ", " + " = " Prepend " = " +^Fhd Prepend the result of the exponent of one of the pairs j Join the result of the above on newlines, implicit print ``` If the output format is flexible enough to remove the need for spaces, -5 bytes to replace `" = "` with `\=` and `", "` with `\,` [Answer] ## Haskell, 131 ``` p[]=return() p((x,y,z):s)=do print$show x++" = "++show y++"^"++show z;p s main=p [(x,y,z)|x<-[2..2^12],y<-[2..x],z<-[2..x],x==y^z] ``` [Answer] ## JavaScript, 148 chars ``` s='' for(i=2;i<4097;i++){q='' for(a=2;a<65;a++)for(b=2;b<13;b++)if(Math.pow(a,b)==i)q+=a+'^'+b+', ' if(q)s+=i+' = '+q.slice(0,-2)+"\n"}alert(s) ``` [Answer] # C 184 Should compile (with warnings) with any C compiler ``` char*l[5000],*t=l+4100,*u; main(b,e,r) { for(;++b<65;) for(e=2,r=b;(r*=b)<4100;l[r]=u) t+=1+sprintf(u=t,"%s, %d^%d",l[r]?l[r]:"",b,e++); for(r=1;++r<4097;) l[r]&&printf("%d =%s\n",r,l[r]+1); } ``` [Answer] ## Pyth, 55 chars ``` =Tr2 64V^2 12JYFZTFbTIqN^ZbaJj\^[Zb))))IJjk[Nd\=dj", "J ``` My first time using Pyth, so it can probably be improved. It's a brute force that checks up to 64^64, thus is quite slow. You can save time by only checking up to 64^12 but it would cost a byte. [Answer] # JavaScript (ES6) 134 ~~127~~ **Edit** revised, bugfixed and shortened **Edit 2**After some research, I realized that this answer was invalid for chronological reasons. The question predates `arrow functions` by years. All that said, the other JS answers are way too complicated ``` /* for TEST:redefine console.log */ console.log=x=>O.innerHTML+=x+'\n'; for(l=[],b=1;++b<65;)for(e=2,r=b;(r*=b)<4197;)(l[r]=l[r]||[]).push(b+'^'+e++);l.some(function(v,i){console.log(i+' = '+v.join(', '))}) ``` ``` <pre id=O></pre> ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 36 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` 2žxŸãΣ`m}99£.γ`m}εн`m'=yε'^ý}„, ý)}» ``` I have the feeling this can be improved a bit by using a slightly different approach.. [Try it online.](https://tio.run/##ATwAw/9vc2FiaWX//zLFvnjFuMOjzqNgbX05OcKjLs6zYG19zrXQvWBtJz15zrUnXsO9feKAniwgw70pfcK7//8) **Explanation:** ``` 2žxŸ # Create a list in the range [2,64] ã # Create each possible pair by taking the cartesian product with itself Σ`m} # Sort these `a,b`-pairs by their result of `a ** b` 99£ # Only leave the first 99 pairs .γ`m} # And then group the `a,b`-pairs by their result of `a ** b` ε # Now map each list of pairs `y` to: н # Take the first pair of list `y` `m # Take the `a ** b` value '= '# Push character "=" to the stack yε # Inner map over the pairs of list `y`: '^ý '# Join each pair with a "^" delimiter }„, ý # After the inner map: join these strings with a ", " delimiter ) # Wrap all values on the stack into a list }» # After the outer map: join every inner list by spaces, # and the outer list by newlines (and output the result implicitly) ``` ]
[Question] [ Suppose we have a sequence \$P\$. Every element \$P\_n\$ represents the distance between the \$n^{th}\$ prime number and the average of the next two prime numbers. For example, \$P\_1\$ would be the distance between the first prime number (2) and the average of the next two prime numbers (3 and 5), so \$P\_1 = \frac{3+5}{2} - 2 = 2\$. Similarly, \$P\_2 = \frac{5+7}{2} - 3 = 3\$. ## Input Your input is an integer \$n\$. You may assume \$n>0\$. ## Output Your task is to print out the sequence \$P\$ up to \$n\$, starting from \$P\_1\$. You can format your output however you like as long as every element is clearly separated. ## Rules * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest number of bytes wins. * You can assume that every computed number will be within the limits of the language you choose, so no need to worry about how big \$n\$ or \$P\_n\$ can get. ## Test cases ``` Input Output n = 1 2 n = 2 2, 3 n = 5 2, 3, 4, 5, 4 n = 10 2, 3, 4, 5, 4, 5, 4, 7, 7, 5 ``` (If you're curious, this sequence is [A305748](https://oeis.org/A305748)!) [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 8 bytes *-1 byte thanks to AndrovT* ``` ƛ⇧ṡ‹ǎḣṁε ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLGm+KHp+G5oeKAuceO4bij4bmBzrUiLCIiLCIxMCJd) | [7 bytes to output the nth number](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLih6fhuaHigLnHjuG4o+G5gc61IiwiIiwiMTAiXQ==) | [9 bytes as an infinite list by emanresu A](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLDnnAzbMabw7crwr3OtSIsIiIsIiJd) **Explantion:** ``` ƛ⇧ṡ‹ǎḣṁε ƛ Implicitly take input, convert it to a range and open mapping lambda :P ⇧ṡ Range between n and n+2 ‹ǎ Decrement and get the respective prime (1-indexed) ḣṁε Head extract; push mean and get the abs difference ``` [Answer] # JavaScript (ES6), 76 bytes Returns a space-separated string. ``` f=(n,q=p=3,r=2,x=p++)=>n?--x?f(n,q,r,p%~x?x:p++):(p+q)/2-r+' '+f(n-1,p,q):'' ``` [Try it online!](https://tio.run/##ZcpBDsIgEEDRvadwY2DCoILphmTKWZpajKaBgRrDqldHuzTdvv9fw2dYxvLkt47pPrUWSEbMxHTDQhYrsVJAffRaVx@2hgX5tFZf3ZacZJXhYnVR4ijU79AGGTM4IdqY4pLm6TynhwzSABz@xe6k24m5ArQv "JavaScript (Node.js) – Try It Online") ### Commented ``` f = ( // f is a recursive function taking: n, // n = number of terms to generate q = // q = previous confirmed prime p = 3, // p = current prime candidate r = 2, // r = penultimate confirmed prime x = p++ // x = divisor (post-increment p here) ) => // n ? // if we still have some terms to generate: --x ? // decrement x; it it's not zero: f( // do a recursive call: n, q, r, // pass n, q and r unchanged p % ~x ? // if x + 1 does not divide p: x // keep using x as the divisor : // else (p is composite): p++ // reset the divisor to p and increment p ) // end of recursive call : // else (p is prime): (p + q) / 2 - r // append (p + q) / 2 - r, which is the next + // term of the sequence by definition ' ' + // followed by a space f( // followed by the result of a recursive call: n - 1, // decrement n p, q // set (q, r) = (p, q) ) // end of recursive call : // else: '' // stop ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 10 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ÌÅpü3ε`+;α ``` [Try it online](https://tio.run/##yy9OTMpM/f//cM/h1oLDe4zPbU3Qtj638f9/QwMA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/wz2HWwsO7zE@tzVB2/rcxv@1Ov@jDXWMdEx1DA1iAQ). Or alternatively: ``` >ÝØDü2ÅA¦α ``` [Try it online](https://tio.run/##ARwA4/9vc2FiaWX//z7DncOYRMO8MsOFQcKmzrH//zEw) or [verify all test cases](https://tio.run/##ATEAzv9vc2FiaWX/dnk/IiDihpIgIj95/z7DncOYRMO8MsOFQcKmzrH/LP9bMSwyLDUsMTBd). **Explanation:** ``` Ì # Increase the (implicit) input-integer by 2 Åp # Pop and push the first input+2 amount of prime numbers ü3 # Get all overlapping triplets of this list ε # Map each triplet to: ` # Pop and push the three values in the triplet separated to the stack + # Add the top two together ; # Halve this sum α # Get the absolute difference with the third one # (after which the list is output implicitly as result) > # Increase the (implicit) input-integer by 1 Ý # Pop and push a list in the range [0,input+1] Ø # Get the 0-based index for each of these values D # Duplicate this list ü2 # Get all overlapping pairs of the copy ÅA # Get the arithmetic mean of each inner pair ¦ # Remove the first one α # Get the absolute difference between the values in the two lists # (the trailing additional item of the prime-list is discarded) # (after which the list is output implicitly as result) ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 10 bytes ``` ↑Ẋ₁İp ≠⁰½+ ``` [Try it online!](https://tio.run/##ASEA3v9odXNr///ihpHhuorigoHEsHAK4omg4oGwwr0r////MTA "Husk – Try It Online") ``` ≠⁰½+ # helper function with 3 args: ≠ # absolute difference between ⁰ # first arg and ½ # half + # the sum of # the (implicit) other 2 args ↑Ẋ₁İp # main program: ↑ # get the first input elements of Ẋ₁ # applying helper function ₁ to groups of 3 İp # from the infinite list of primes ``` Same byte-count to output the `n`-th element (by swapping the initial `↑` for `!` [index]), or one byte less to output the infinite sequence ([9 bytes](https://tio.run/##ARsA5P9odXNr///huorigoHEsHAK4omg4oGwwr0r//8), by omitting the initial `↑`). [Answer] # [Factor](https://factorcode.org) + `grouping.extras math.primes`, 46 bytes ``` [ 2 + nprimes [ + 2/ - abs ] 3 clump-map ... ] ``` [![running the above code in Factor's REPL](https://i.stack.imgur.com/YoifF.gif)](https://i.stack.imgur.com/YoifF.gif) Could be 42 bytes without the restrictive IO. ``` 2 + nprimes ! get the first input+2 primes [ ! begin clump-map + 2/ ! the average of the next two primes - abs ! subtracted by the current prime ] 3 clump-map ! map over every three elements with overlapping ... ! prettyprint a sequence of any length to stdout ``` [Answer] # Java 8, ~~111~~ 106 bytes ``` n->{for(int a=2,b=3,c,k=5;n>0;){for(c=1;k%++c>0;);if(k++==c){System.out.println((b+c)/2-a);a=b;b=c;n--;}}} ``` Prints the results on separated newlines to STDOUT. [Try it online.](https://tio.run/##jZCxasMwEIb3PMURKEhIdmOXLBHK0ilD0iFjyCBf5OLYkY0lpxSjZ3dl1@nUQheB/vt09@mu6q6i66UcsFLWwl4Vpl8AFMbpNleo4TBeAe51cQEkIQdDRYj8IhzWKVcgHMCAHEy07fO6nRglU57JF468lGthtitBpxrKRJRPjOGYiCInJWNSIu2Pn9bpW1x3Lm7a0KEyhGQM6XMaKSqUzEQmUZgoEt77QYzDmy6rwvDZYRK8BX1ydKHB@@ms6Lf6w8lp616V1bABoz/GL57OfcJTvubJys8wwC8my51pOreBJXv0mFbwF/3WuYDbwP9gJkbyn7dzzU8L9sMX) **Explanation:** ``` n->{ // Method with integer parameter and no return-type int a=2,b=3, // Previous two primes, starting at hard-coded 2 and 3 c, // Current prime, uninitialized k=5; // Prime-loop integer, starting at the third prime 5 for(;n>0;){ // Loop as long as the input `n` is not 0 yet: for(c=1; // Reset `c` to 1 k%++c>0;);// Keep increasing `c` as long as `c` is NOT divisible by `k` if(k++==c){ // If `k` and `c` are now equal (which means `c` is a prime number): // (and increase `k` by 1 afterwards for the next iteration with `k++`) System.out.println((b+c)/2-a); // Print (b+c)//2-a with trailing newline a=b;b=c; // Then set a=b and b=c for the next iteration n--;}}} // And decrease `n` by 1 ``` [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 95 bytes ``` \d+ __¶$&$*#___ #(#*(_+)) $2¶$1_ }+`\b(__+)\1+$ $&_ M!&`\b_+¶_+¶_+ (_+)¶\1(_+)¶\1(\2(_+))\4 $.3 ``` [Try it online!](https://tio.run/##K0otycxL/P8/JkWbKz7@0DYVNRUt5fj4eC5lDWUtjXhtTU0uFSOgsGE8V612QkySRjxQLMZQW4VLRS2ey1dRDSgWr31oGwRzgXQc2hZjCKdjjMCGxJhwqegZ//9vaAAA "Retina 0.8.2 – Try It Online") Explanation: ``` \d+ __¶$&$*#___ ``` On the first pass, convert the input to `2,n,3` where `n` is a unary run of `#`s while the primes are unary using `_`s. ``` #(#*(_+)) $2¶$1_ ``` Replace `n,p` with `p,n-1,p+1`. ``` +`\b(__+)\1+$ $&_ ``` Increment the last value until it becomes prime. ``` }` ``` Repeat the above until `n=0`. ``` M!&`\b_+¶_+¶_+ ``` Extract overlapping windows of three primes. ``` (_+)¶\1(_+)¶\1(\2(_+))\4 $.3 ``` Match each set of three primes as `\1, \1+\2, \1+\2+\4+\4` and calculate `\2+\4` in decimal; `\1+\2+\4` is the average of the second and third primes so `\2+\4` is the difference between that and the first prime. [Answer] # Haskell, 92 bytes ``` (`take`((zipWith3(\x y z->div(x+y)2-z)=<<tail)=<<tail)[x|x<-[2..],all((0/=).mod x)[2..x-1]]) ``` [Answer] # [J](http://jsoftware.com/), ~~21~~ 20 bytes ``` 3(-~-:)`+/\p:@i.@+&2 ``` [Try it online!](https://tio.run/##y/r/P03B1krBWEO3TtdKM0FbP6bAyiFTz0Fbzeh/anJGvkKagrHRfwA "J – Try It Online") * `+` `&` `2`: Add 2 to *n*. * And then (`@`, composition), `i.`: Make a list of the first *n*+2 nonnegative integers. * And then (`@`, composition), `p:`: Get the prime numbers of those indices. * `3` ...`\`: Apply the inside verb to each three consecutive prime numbers. + `(-~-:)` ``` `+` `/`: Insert the two subverbs between the prime numbers, turning `p q r` into `p (-~-:) (q + r)`. - `q + r` adds (`+`) `q` and `r`. - `(-~-:)` is a hook; it halves (`-:`) the sum of `q` and `r`, and then subtracts (`-`) `p` from the result; `~` swaps the operands from their usual order. [Answer] # [Python 3](https://docs.python.org/3/), 98 bytes ``` f=lambda n:n and f(n-1)+[(g(n+1)+g(n+2))//2-g(n)]or[] g=lambda n,i=1,p=1:n and-~g(n-p%i,i+1,p*i*i) ``` [Try it online!](https://tio.run/##PYsxCoAwEAR7X5FGuDMJGu2EvEQsIhI90DNIGhu/HiOC1Q7LTLjienCXkreb26fZCe5ZOJ6FB9YG5QALsMzwTotY163OiONxDmOx/JUia1Sw5qv1nR0dSlIk811RRZjCSRzBg2kQ0wM "Python 3 – Try It Online") I couldn't find a better way than using a helper function, `g`, (stolen from [Lynn's amazing answer on the tips question](https://codegolf.stackexchange.com/a/152433/114446)) to get the nth prime. However, with default [sequence](/questions/tagged/sequence "show questions tagged 'sequence'") rules, it would be [77 bytes](https://tio.run/##NYoxDsIwDEV3TuEFyW4SVS5bpZwEGFK1SS0VN4o6lIWrhzAw/af3fn4f6663Gv2jbuE1zQF0xIRqmMxvBqK@H1xDuiT/v1jxbLPnUSHo7D4tu3wVK6bpTjqhmovogfeIJ0HcC5wgCiVoWpAtMNOT6hc). [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 40 bytes ``` (#2+#3)/2-#&@@Prime[#+{0,1,2}]&~Array~#& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n277X0PZSFvZWFPfSFdZzcEhoCgzNzVaWbvaQMdQx6g2Vq3OsagosbJOWe0/UCqvREHfIV3fQaEaKKljqmNoUPv/PwA "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 41 bytes ``` Nθ≔¹ηW‹ⅉθ«≦⊕η¿⬤υ﹪ηκ«F‹⁴η⟦I⁻⊘⁺η↨υ⁰§υ±²⟧⊞υη ``` [Try it online!](https://tio.run/##LY69DsIwDITn9ik8OlKQALExFRYqUdQVIYbQGhIRUsgPICGePSTAZp/vu3Mnhe0GoWOszTX4TbgcyOKNzcvKOXUyOOEg0/aQShPgmpzDLTION8bgVRaNuP6NteksXch46n9IoY6AldYYODRDH/SAksOZ/cDiONh/3iz7GbRWGY@7pXAeG2WCw5XQd@qx1WlO6EI4ymHjFMGh8rXp6ZmFDZ2EJ5wmne1zc9EGJ/Pl@8e7fMc4GcfRXX8A "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` Nθ ``` Input `n`. ``` ≔¹η ``` Start looking for primes after `1`. ``` W‹ⅉθ« ``` Repeat until `n` results have been obtained. ``` ≦⊕η ``` Increment the candidate prime. ``` ¿⬤υ﹪ηκ« ``` If it is indeed prime, then: ``` F‹⁴η ``` If it is at least the third prime, then... ``` ⟦I⁻⊘⁺η↨υ⁰§υ±²⟧ ``` ... output the difference of the average with the previous prime with the prime before. ``` ⊞υη ``` Add the prime to the list. [Answer] # [Wolfram Language (Mathematica)], 42 bytes ``` ListConvolve[{1,1,-2}/2,Prime@Range[#+2]]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73yezuMQ5P68sP6csNbraUMdQR9eoVt9IJ6AoMzfVISgxLz01WlnbKDZW7T9QKK8kOi3aNDaWC8Y2NIiN/Q8A "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Raku](https://github.com/nxadm/rakudo-pkg), 49 bytes ``` {(-*+(*+*)/2)(|grep(&is-prime,2..*)[^3+$++])xx$_} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/WkNXS1tDS1tLU99IU6MmvSi1QEMts1i3oCgzN1XHSE9PSzM6zlhbRVs7VrOiQiW@9r@1QnFipUKahpGB5n8A "Raku – Try It Online") Without the requirement for preceding elements, this could output the nth element for 42 bytes: ``` -*+(*+*)/2 o{grep(&is-prime,2..*)[^3+$_]} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPtfV0tbQ0tbS1PfSCG/Or0otUBDLbNYt6AoMzdVx0hPT0szOs5YWyU@tva/tUJxYqVCmoZKvKZCWn6RQpyhwX8A "Raku – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes ``` 3Ḷ+)ÆNḋ-,.,. ``` [Try it online!](https://tio.run/##y0rNyan8/9/44Y5t2pqH2/we7ujW1dHT0fv//7@hAQA "Jelly – Try It Online") This *has* to be possible in 11 bytes if a hardcoded dot product ties everything else I've come up with... ``` 3Ḷ [0, 1, 2] + plus ) each [1 .. n], individually. ÆN Get the x'th prime for each x in that matrix, ḋ then return each row's dot product with -,.,. [-1, 0.5, 0.5]. ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~53~~ 47 bytes ``` (#3+#2)/2-#&@@@Partition[Prime@Range[#+2],3,1]& ``` Thanks to @ZaMoC [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7X0PZWFvZSFPfSFfZUM3BQVlN3yEgsagksyQzPy86oCgzN1XfISgxLz3VQUNZ20hTx1jHMFbtP1AiryQ6Ldo0NpYLxjY0iI39DwA "Wolfram Language (Mathematica) – Try It Online") [Answer] ## BSD/Linux command line, 52 bytes Requirements: * any Bourne-style shell; * awk; * the [`primes`](https://man.freebsd.org/cgi/man.cgi?query=primes&apropos=0&sektion=6) program from the classic BSD games collection ([`bsdgames`](https://packages.debian.org/search?keywords=bsdgames) package on Debian, Ubuntu and derivatives, [`bsd-games`](https://packages.fedoraproject.org/pkgs/bsd-games/bsd-games/) on Fedora, …). ``` primes 2|awk '{a=b;b=c;c=$0;$0=(c+b)/2-a}a'|head -$1 ``` Try it online: there seems to be a bug in the version of awk on TIO which causes it to print blanks when printing `$0` (implicitly or explicitly) and `$0` is numeric. The version in my answer does work on my machines. Here's [modified code with a workaround](https://tio.run/##yy7O@P@/oCgzN7VYwagmsTxbQb060TbJOsk22TrZVsXAWsXAViNZO0lT30g3UUmpNlG9JiM1MUVBV8Xw////hgYA "ksh – Try It Online") — obviously the workaround for the bug on TIO increases the length (by two bytes: an extra `""`). [Answer] ## F#, 188 bytes ``` let x=Seq.initInfinite let p n=n=2||Seq.forall(fun c->n%c<>0)[2..n-1] let f n=x(fun i->n+i+1)|>Seq.find p let s n=x(fun i->i+2)|>Seq.where p|>Seq.map(fun p->(f p+(f p|>f))/2-p)|>Seq.take n ``` [Try it online!](https://tio.run/##TY/BasMwDIbvfQpRKMSkzhrDLsti2LGw246lhyyzqViqaI7DevC7Z7GTwC6WrP/7ZGwH2fbOTFNnPDzqD/NTIKE/k43F7OKYgWqqVQgxtb1rui6zI0ErNR3aV30SF1UUJMtrwu2MPxKAM5BjXoqgk4r0BZyY4T@DuVqJ35txBni53BtOBEudWeA8HkFbIZ6U5FXwzbcBmi5lparnqjxdd0HDKkOyabx/GgdSQ7a0x/j4MlxZ37/j4IXY3PnfbpEzJB79EfrRz1XELeyQvCXYn2P0Aoe3LY79HpKxCdMf) Didn't think it would end up so big, to be honest. I wonder if my approach is maybe wrong... but it's all functional, stateless, and inefficent. Anyway, a brief explanation: `x` is a shorthand for `Seq.initInfinite`, which creates endless, lazy-evaluated sequences. `p n` determines if a number `n` is prime. `f n` gets the next prime number after `n`. `s n` is the main sequence function. First it creates a sequence of primes, then for each of them, gets the next prime and next-next prime, and calculates the average. Finally, it takes the first `n` elements in the sequence. ]
[Question] [ Your input is a non-empty set of non-empty sets of positive integers. For example: ``` {{1}, {2, 3}, {2,4}, {1,4}} ``` Your task is to output the maximal number of elements that can be picked from the sets with the following conditions: * You can only pick at most 1 element from a set * You can't pick the same element from 2 different sets In this example you can pick `1` from the first set, `3` from the second set, `2` from the third set and `4` from the last set, for a total of 4 elements. Io is flexible. You can take a list, instead of sets, etc. There are no gaps in the numbers (eg. `{{2,3},{3,4}}` is not a valid input). Or in other words, the input flattened must contain all numbers `[1,n]` where n is the largest number in the input. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code wins. # Examples ``` {{1}} -> 1 {{1}, {2, 3}, {2,4}, {1,4}} -> 4 {{1}, {2}, {1,2,3,4}} -> 3 {{1}, {2}, {2,3}} -> 3 {{1, 2, 3}, {2, 4, 5, 6}, {3, 5, 6, 7}, {1, 2}, {2, 3}, {1, 3}} -> 5 {{1,2,3,4,5}, {1,2}, {2,3}, {1,3}} -> 4 {{1,2},{1,3},{1,4},{2,3},{2,4},{3,4},{1,2,3},{1,2,4},{1,3,4},{2,3,4},{5,6,7,8,9,10}} -> 5 {{1,4}, {2,3}, {1,3}, {1,2,3}} -> 4 ``` # Background Recently [@AnishSharma](https://codegolf.stackexchange.com/users/110533/anish-sharma) posted [this](https://stackoverflow.com/questions/70814560/select-one-element-from-each-set-but-the-selected-element-should-not-be-repeated/70814859) question on Stack Overflow. This is a slightly modified version of that question [Answer] # [Python 3](https://docs.python.org/3/), 66 bytes ``` lambda x:max(map(len,map(set,product(*x)))) from itertools import* ``` [Try it online!](https://tio.run/##ZY9NDoIwFIT3nOIti5mFUPAv8STIAhUiCaVNqUkN4ewILUSjXfTrTF9mWvUyD9nysTpfxqYQ13tB9iQKy0ShWFO2mNmVBkrL@/Nm2MaG0woqLQXVptRGyqajWiipzWZUum4NyypmQ6qkJkt1S1mQ9dGQwwHUxyDumcyIJnxdeisG/7cnc7FAnxBKQCloNyvuj6C9j6H4uzCauQS4AqRL25ru1GdmgJNwb4Sf8M/uudtdzkKv@TrpmGKHPQ44ItquqclP2frfIQ/yPBzf "Python 3 – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jellylanguage), 6 bytes ``` ŒpQ€ẈṀ ``` [Try It Online!](https://jht.hyper-neutrino.xyz/tio#WyIiLCLFknBR4oKs4bqI4bmAIiwiIiwiIixbIltbMSwgMiwgM10sIFsyLCA0LCA1LCA2XSwgWzMsIDUsIDYsIDddLCBbMSwgMl0sIFsyLCAzXSwgWzEsIDNdXSJdXQ==) ``` ŒpQ€ẈṀ Main Link Œp Cartesian Product; get all possible selections Q€ Uniquify each Ẉ Length of each Ṁ Maximum result ``` [Answer] # [Python 3](https://docs.python.org/3/), 63 bytes ``` f=lambda s,*v:s and max(f(s[1:],x,*v)for x in s[0])or len({*v}) ``` [Try it online!](https://tio.run/##fVDLDoMgELz3K/YIZg9S7MvELyEcaNTURNGIMTZNv50iio099DLDzu4sk@2ew6PV3Noyq1VzzxUYjMbUgNI5NGoiJTGCpRInJ9Oy7WGCSoMRsaSuqAtNXtH4pnYozGAgAyGYlOgJxRG5x8Qhc/hteMG1f8XZsQi4mfGEZ/fiM@NlcW7L2c4wD/8ZWMslzD4eX0MGUwjNw6RnnwCveEMWh63J7quwQx4OXV/pgYiSTBS2y/k7SWo/ "Python 3 – Try It Online") [Answer] # JavaScript (ES6), 70 bytes Expects an array of arrays. ``` f=([b,...a],s)=>b?Math.max(...b.map(v=>f(a,new Set(s).add(v)))):s.size ``` [Try it online!](https://tio.run/##rZM9b4MwEIb3/AqPRro6dUz6KcjUsVNGy8MBpkmV4ihGpOqfJweBUIYOFdxwPlnW896H7xMr9OlpfyzvCpfZus4jrhMQQqABH0RxsnnHcie@8JvTZULBkVdRnHOEwp7Z1pbcBwKzjFcB2YsXfv9j61e9YExraQywmW25ZLKDg16Ban1IXpKfKkfwcIC3UJKYAdzB1QjeZD9XgwY43JoCa3igSDUnPF6ruTVN/kOc4OsB3oAnwP7uOaw61HWY4/Gqbsi9YD901b9sz7ZSeIJnkPdNRr8yD0fZ9igz9beYhcjd6Q3THUcWxSx1hXcHKw7ug9Oa0FLUFw "JavaScript (Node.js) – Try It Online") ### Commented ``` f = ( // f is a recursive function taking: [b, // b[] = next list ...a], // a[] = all remaining lists s // s = current set, initially undefined ) => // b ? // if b[] is defined: Math.max( // return the maximum of ... ...b.map(v => // for each value v in b[]: f( // do a recursive call: a, // pass a[] new Set(s) // create a new set from s // (an empty set if s is undefined) .add(v) // add v to it ) // end of recursive call ) // end of map() ) // end of Math.max() : // else: s.size // return the size of s ``` [Answer] # [R](https://www.r-project.org/), ~~55~~ 54 bytes *Edit: -1 byte thanks to pajonk* ``` function(x)max(lengths(apply(expand.grid(x),1,table))) ``` [Try it online!](https://tio.run/##dZDdDoIwDIXvfYom3mxJNY5toBf6LsifJHMSwASffg4YQwJetVu/np62NvnV5G@dtOVLk44@446oTBftoyFxVakPyboq1umxqMvU1pFhG99VRik1OVFl05KEMPvaH27AdrufP4SEBMhdFENkNo6sWLOOsD2e4n@oXneDQAgQpokgECRCODz5mCNEbgpMQo5nfTJKyoXkYAflZG6xFvM2xLLHV6elt47B/VFmvflQfO5ymcQQIzzjBdlp06pYmZvlnU3zBQ "R – Try It Online") Test setup stolen from [pajonk's R answer](https://codegolf.stackexchange.com/a/241642/95126). 48 bytes using [R](https://www.r-project.org/) ≥ 4.1 by exchanging `function` for `\`. [Answer] # Haskell + [hgl](https://gitlab.com/WheatWizard/haskell-golfing-library), 10 bytes ``` xMl<nb<<sQ ``` Works as of commit [4a9f6d27](https://gitlab.com/WheatWizard/haskell-golfing-library/-/commit/4a9f6d27aecd3e27a45fb7168355f67cd8ad6993). Older version below. ## Explanation The functions involved are: * `sQ` can do many things but on lists it performs the cartesian product. * `nb` removes all duplicate lements from a list. * `xMl` gets the length of the longest list in a list of lists So we get the Cartesian product, nub the results and then get the maximum of their lengths. # Haskell + [hgl](https://gitlab.com/WheatWizard/haskell-golfing-library), 13 bytes ``` mx<l.^nb.^sQ ``` This no longer works in recent versions of hgl since `(.^)` was renamed to `(<<)`. To test it run: ``` mx<l<<nb<<sQ ``` ## Explanation This works the same as the new implementation above except we have to get all the lengths and then get the maximum separately. The new functions are: * `l` gets the length of a list * `mx` gets the maximum of a list. So we get the Cartesian product, nub the results and then get the maximum of their lengths. ## Reflections * First things first we don't have a set type. This is unfortunate and needs to be fixed at some point. * `l<nb` seems like something that would be useful to have a builtin for. * It would be nice to have some sort fold and sequence or fold and traverse combined function. * ~~I could have used a "maxmap". If we wanted to get the actual choices we could have done, `xB l<nb.^sQ` to save two bytes. But `xB` returns the original list not the modified version.~~ This has been fixed in newer versions with the function is called `xM`, but `xMl` was also added which saves another byte. [Answer] # [Factor](https://factorcode.org/), 42 bytes ``` [ [ members ] product-map longest length ] ``` [Try it online!](https://tio.run/##jVG7DsIwENv5Cv8AiFLefABiYUFMiCGUo1SkaUiOAap@e6EPmiIYmGw5tu9OOYmAE5NvN6v1cg5L1xupgGxPm@R4CxghKTJCRg/BUaLsy8EWFzKKpHNDG2K@axMpxqLTSZHCQ4asYSkG8GscluiV@Omo9ML5@63qeOvtxhHGJfdLNmma2pO9r3SR@8fptPfe3/f4zV2uxd3qt1IVq/acYgav3xo2/LGIK83yHXaIKT6Qsdij/qVuLDRkokKyDEkq5DP2@RRKaC3v6FkEkoTJnw "Factor – Try It Online") Uniqueify the elements of the product sequence of the input, then find the longest length. [Answer] # [R](https://www.r-project.org/), 60 bytes Or **[R](https://www.r-project.org/)>=4.1, 53 bytes** by replacing the word `function` with a `\`. ``` function(x)max(sapply(apply(expand.grid(x),1,table),length)) ``` [Try it online!](https://tio.run/##dZDbDoIwDIbvfYom3mxJNY5toBf6LshJkokEMMGnn8AOSMCbtdu@/v3bRudXnb@rpCtfFenpM@5JG9e1@hBzZn0dV@mxaMp0@EaGXXxXGUWVVUX3oFTnRJVtRxLCKKX7ww3YbvfzhpCQALmNYopsiIYVa9YSQ42n@B9q1N0gEAIE1xEEgkQIpys3OUJku4ATsjwbEyMpF5KTHZTO3GIs5m2IZY3/dUNvLYP7pcx686L4XGUziSFGeMYLstOmVbEyN8tbm/oL "R – Try It Online") --- Solution shorter in [R](https://www.r-project.org/)>=4.1: ### [R](https://www.r-project.org/), 66 bytes Or **[R](https://www.r-project.org/)>=4.1, 52 bytes** by replacing two `function` occurrences with `\`s. ``` function(x)max(apply(expand.grid(x),1,function(a)sum(table(a)|1))) ``` [Try it online!](https://tio.run/##dZDbDoIwDIbveYom3mxJNY4N0At9l8nBkAASDgkmvvscMDYJeNWu@/r3bxuV3VTWV3GXvyoy0FIORNZ18SbpUMsqOT2bPNF1ZGgpSdu@JJ18FKnOP4xSqjJS5G1HYjK@Dsc7MM/7qSHExEduopgi03FmxZY1hO6xFP9Djbo7BIKPsEwEgRAghNOTzzlCZKbAImR4NiazZLCSnOxgsJhbrcWsDbHusb/L0nvH4PYoTs8dirsukwUYYoQXvCI771oVG3NO3thUXw "R – Try It Online") [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 6 bytes ``` Πv‡ULG ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLOoHbigKFVTEciLCIiLCJbWzFdLCBbMiwgM10sIFsyLCA0XSwgWzEsIDRdXSJd) ``` Π # Cartesian product - get all possibilties v # Over each... ‡-- # Do the next two elements U # Uniquify L # Get length G # Maximum ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 32 bytes ``` I⌈EEΠEθLιEθ§λ÷ι∨ΠE…θμLν¹LΦι⁼μ⌕ιλ ``` [Try it online!](https://tio.run/##VUxdC4MwDPwrfWwhg6n7ZE/DTRA25rv4ULTMQq2zVnG/vtPQDRbI3eWSXFlzU7ZcOZcZqS2NeW/pnU@yGZqZX9iZaauhtKg7IDehn7amkjEGxHtnm@pKTFQBSbW9yFFWgkogD/P3Hb9LJeK6xZ@G/bI0ZgWMIXszkcoKs6Rcu4GrnjZAEqmrxVHM18m5PM8DCAuYMULczBiiDlFHiPON34d@jr6XyFvYwR4OcIRgXRSFW43qAw "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` θ Input array E Map over lists ι Current list L Take the length Π Take the product E Map over implicit range θ Input array E Map over lists λ Current list § Cyclically indexed by ι Outer value ÷ Integer divided by θ Input array … Truncated to length μ Inner index E Map over array ν Innermost list L Take the length Π Take the product ∨ Logical Or ¹ Literal integer `1` E Map over lists ι Current list Φ Filtered where μ Inner index ⁼ Equal to ⌕ Index of λ Inner value ι In current list L Take the length ⌈ Take the maximum I Cast to string Implicitly print ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 10 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` .»âε¸˜Ùg}à ``` [Try it online](https://tio.run/##yy9OTMpM/f9f79Duw4vObT204/ScwzPTaw8v@P8/OtowVifaSMcYTJoASUMoaRwbCwA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeV/vUO7Dy86t/XQjtNzDs9Mrz284L/O/@joaMPYWB0FEKUTbaRjDCZNgKQhkERIgAWA0uiCIB0QAR24Zh1THTMgyxhE65hDdMINN0TRAFKMRwGUC3EMqvOMoY6EaYI52himEkyDXaBjoWOpY2gAM9UExSqYGbGxAA). **Explanation:** ``` .» # (Left-)reduce the (implicit) input-list by: â # Cartesian product ε # Then map over each inner list: ¸ # Wrap it into a list (workaround for input [[1]]) ˜ # Flatten it Ù # Uniquify it g # Pop and push the length }à # After the map: pop and push the maximum # (which is output implicitly as result) ``` [Answer] # Julia, 55 ``` J(l)=maximum(length.(Set.(Iterators.product(l...))[:])) ``` [ATO](https://ato.pxeger.com/run?1=nVI9T8MwEBUj-RWWJ0e6RqRJ2oKUiLUgxMBYOpjWhYDrRrbDh0J_CUuX_qgy8FvwR0ILI0ve3bu79852PraPNS_p5vPoqRRVLlnF6YwRSV8wxk0Tr9e9AsWBjQA1fUCJx9RCbMDW05-6Z_uQtJXkV8XwexbQXg2lgDJAA5slPgQ09GKof-gcW7QamdNwTpC1tp2Hy5L9arbiGHArg2_yp2gS93VSLfo86TodZjCAIYzgFOKTA__0j2V3fO9trhBQgBucF3hiQry20RSH21oveqPd8ILwMF_S13JZLwln4l4_ROSG6YiMNZNUr6SKKrma1zNNeBRFYTg5m4bd-FclS6G5aF_rn2Jm8r3w7WZDdPemmcJhsFhJNKMKlQKpipeamN8D8K0wpWMOVKjc06YHcK9wdM6eKSdXTNOoolIxs5Chba9Px0LbScOdU6WY1MTtnDuOiXnQHQhfX3aXtNl4_AY) ]
[Question] [ [Risky](https://github.com/Radvylf/risky) is a new language of mine, which features an interesting form of tacit programming. In this challenge, you'll take a Risky program as input, and visualize the parsing. No knowledge of Risky is needed for this challenge, but it's a pretty interesting language so I'd recommend trying it :p. ## Task Risky's parsing is based purely on the length of the program. It follows three rules: 1. If the program consists of one operator, it is parsed as a nilad 2. If the program consists of an even number of operators, the first operator is parsed as a monad and the rest is parsed as its argument 3. Otherwise, the middle operator is parsed as a dyad, and both sides are parsed as arguments This is recursive; the argument(s) to a monad or dyad are parsed as if they are their own programs. This forms a tree of operators. For example, the program `-1+!2` would look roughly like this: ``` + / \ - ! | | 1 2 ``` Your task will be to represent this by offsetting the operators lower in the tree, showing the structure of the program. For example: ``` + - ! 1 2 ``` All of the operators stay in order, but are vertically offset in order to show the structure. ## Input Input will consist of a string of operators. If you want, you can assume the input doesn't contain any invalid Risky operators, though it would not affect the parsing. ## Output You can output a visualization of the program in one of four ways: **Top-to-bottom:** ``` + - [ + ? ! ! 2 0 1 } ] [ ``` **Bottom-to-top:** ``` 1 } ] [ ! ! 2 0 + ? - [ + ``` **Left-to-right:** (Using a shorter program for the next two to save space) ``` 2 ? + 1 [ ! ``` **Right-to-left:** ``` ! [ 1 + ? 2 ``` Both LTR are RTL can be flipped upside down if you prefer. ## Test cases Note that the above examples can be used as more complicated test cases. For the top/bottom ones, `-!1+!}+[2]?0[` is the program shown. For the rest, it's `![1+?2`. **Program:** `1` ``` 1 ``` **Program:** `-1` ``` - 1 ``` (Top-to-bottom) **Program:** `1+1` ``` 1 1 + ``` (Bottom-to-top) **Progam:** `-1+2` ``` 1 + 2 - ``` (Left-to-right) **Program:** `!!!!!` ``` ! ! ! ! ! ``` (Right-to-left) ## Other This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer (in bytes) per language wins! [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 35 bytes ``` ↑{⊃{0~⍨⍺-1-∊1⍵0⍵}/-⌽⍬⊂⍛,1↓⊤1+≢⍵}↑¨⊢ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTflfraFZXalhqGOoramfqWOok2llqF1Rq28YbxRjqK1cUctV/aht4qPerWByxaEVuo@6mqs1HvXuAgvs0tQBEtpgjY/aJhhqA1XW6j/q2avxqKvpUe8aTR3DR22TH3UtAcp0LgJJEmUeUHVHF1CRAXnGgYyAGmkA1IJuGNAgsHGziTPNoA7Ihrvq0HpDIs0CGlJNiQFA/YdWPOpa9B9kELI5uoa6QHMQpugSZ0waMIIe9fYBTTq03hjkw76pwUHOQDLEwzP4f5qCuq6iobZirXa0Uay9QbQ6l66uLhdQVDHaUNveSB0A "APL (Dyalog Extended) – Try It Online") Takes a string and puts each command on its own line top to bottom, indenting from left to right. ## The algorithm Given the length of the input `n`, the indentation pattern (the length of each line) looks like the following: ``` f(1) = [1] f(2n + 2) = let prev = f(n) in [1] ++ (2+prev) ++ [2] ++ (2+prev) f(2n + 1) = let prev = f(n) in (1+prev) ++ [1] ++ (1+prev) ``` If we add 1 to the input, the recursive formula becomes nicer (with adjusting the base case): ``` g(1) = [] g(2n + 1) = let prev = g(n) in [1] ++ (2+prev) ++ [2] ++ (2+prev) g(2n) = let prev = g(n) in (1+prev) ++ [1] ++ (1+prev) ``` which means we can use single reduction on the binary representation to get the job done. ## The code ``` ↑{⊃{0~⍨⍺-1-∊1⍵0⍵}/-⌽⍬⊂⍛,1↓⊤1+≢⍵}↑¨⊢ Input: s ⊤1+≢⍵ Binary representation of 1+n ⌽⍬⊂⍛,1↓ Remove leading 1, prepend an empty list, and reverse - Negate the bits (for golfing purposes) ⊃{...}/ Reduce from right to left... (⍵: prev list, ⍺: next bit) ∊1⍵0⍵ Shorthand for 1,⍵,0,⍵ ⍺-1- Add ⍺-1 (-1 if zero bit, -2 if one bit) 0~⍨ Remove zero if present which gives -1,(⍵-2),-2,(⍵-2) for 1 bit and (⍵-1),-1,(⍵-1) for 0 bit {...} Compute negative padded lengths ↑ ↑¨⊢ Pad each char on the left side and rectify ``` [Answer] # [J](http://jsoftware.com/), 67 bytes ``` g=:(0,1+$:@<:)`([:(,0,])1+$:@<.@-:)`0:@.(=&1+2&|) f=:' '&,.#"1~1,.~g@# ``` [Try it online!](https://tio.run/##dYtBDsIgEEX3PQW0pgMBJsByIko8gBcgTUyM0LjxAsrVEW3izrf77@XfWyuBhNVO7SjuSV5EIqGtXuRmMJouLUUUYXbKz0855EDAYNY4ja46jbXEqZ1PyErAHgxWloiNxA4U83C7rg@Wu3aKe9gmmC/wi/zDv2h4v75U8svRJmhv "J – Try It Online") This produces an upside-down left-to-right tree, which should be valid per the comments. For example, `f '-1+!2'` produces: ``` - 1 + ! 2 ``` ## the idea * First notice the numerical pattern in the number of space indents: ``` 1 -> 0 2 -> 0 1 3 -> 1 0 1 4 -> 0 2 1 2 5 -> 1 2 0 1 2 6 -> 0 2 3 1 2 3 7 -> 2 1 2 0 2 1 2 ``` * Then notice that all the heavy lifting can be put into a recursive function that does nothing but implement the function described by the above table, since it's easier to work with integers than strings. This is `g`. * Zip a space and the input like so: ``` - 1 + ! 2 ``` * Finally, use the output of `g` and J's copy verb `#` to expand the spaces of that zip as needed. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 32 bytes ``` ⁹ð:2ß‘},`j⁹ð’ß‘}⁹;ðḂ?Ị? Lç0⁶ẋż¹Y ``` [Try it online!](https://tio.run/##y0rNyan8//9R487DG6yMDs9/1DCjVichC8x/1DATIgDkWR/e8HBHk/3D3V32XD6Hlxs8atz2cFf30T2Hdkb@//9fKTEpOSU1LT0jMys7Jzcvv6CwqLiktKy8orJKCQA "Jelly – Try It Online") -2 bytes thanks to caird coinheringaahing This uses essentially the same approach as Jonah, so upvote [their answer](https://codegolf.stackexchange.com/a/229611/68942) as well. I came up with this solution independently, but Jonah's answer helped me consolidate a similar idea (to generate the indent array and convert that to indentation), and although I pretty much knew how I wanted to do it already, it helped me see that it was the correct approach and how to go about it. ``` ⁹ð:2ß‘},`j⁹ð’ß‘}⁹;ðḂ?Ị? Helper Link (dyad); given x and y, return the length x indentation array with minimum indentation y Ị? If x is insignificant (abs(x) <= 1) ⁹ Return just y Ḃ? Otherwise, if x is odd (x % 2) ð:2ß‘},`j⁹ð Dyadic chain for odd case: :2 - floor divide by 2 ß‘} - recursively apply this function to floor(x / 2) and (y + 1) ,` - pair that result with itself (exploit symmetry) j⁹ - join on y ð’ß‘}⁹;ð Otherwise, if x is even, then dyadic chain for even case: ’ - decrement x ß‘} - apply this link to (x - 1) and (y + 1) ⁹; - prepend y Lç0⁶ẋż¹Y Main Link (monad) L Length of the input ç0 Apply the helper link to that (x) and 0 (y) ⁶ẋ Return a list of whitespace, each row having number of spaces equal to the indentation level ż Zip with / interleave ¹ (identity is applied to the right argument of the above to prevent the 2,1 chain with `Y`) Y Join on newlines ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~34~~ 33 bytes ``` FΦ↨⊕Lθ²κ≔⁺…⟦¹⟧ι⁺⊕ι⁺⁺υ⟦⁰⟧υυEυ◧§θκι ``` [Try it online!](https://tio.run/##VYyxDoIwEEB3vwK2uyAJsDIYHExI0LAThgYOaKxF2mJc/PZaqwwOl1zevXfdxFQ3M2HtMKsATlwYUnBkmqCUnaIbSUM9VCRHM8GCuA8yN1fEoNCaj3JLarHqv4Q7zcPmQiMzBCm2P7Jul8SRFRH9x8@a72rFpYEzu3uL9RUNBgpTyp6esHw97orc2jhMo/AVNVl7SBobP8Qb "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Based on @Bubbler's answer, so prints downwards indenting from left to right. ``` FΦ↨⊕Lθ²κ ``` Take the length of the input plus 1, convert to binary, and loop over the bits after the first. ``` ≔⁺…⟦¹⟧ι⁺⊕ι⁺⁺υ⟦⁰⟧υυ ``` Concatenate two copies of the current list (predefined to be the empty list) together with `[0]` in between, then add 1 more than the bit to all the elements, then concatenate `[1]` to the beginning of the list if the bit is `1`, and save that as the current list. ``` Eυ◧§θκι ``` Pad each element of the input according to the calculated indentation. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~26~~ 25 bytes A port of [Jonah's J answer](https://codegolf.stackexchange.com/a/229611/64121). -1 byte thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen)! ``` S¯¸λNÈi>0šë0N2÷₅>.ø]Igèú» ``` [Try it online!](https://tio.run/##ATUAyv9vc2FiaWX//1PCr8K4zrtOw4hpPjDFocOrME4yw7figoU@LsO4XUlnw6jDusK7//8tMSshMg "05AB1E – Try It Online") ``` S # split input into list of characters ¯¸ # push [[]] λ ] # starting with a(0)=[], calculate a(n) for n=0,1,... according to: NÈi # if n is even: > # each value of a(n-1) incremented by 1 0š # prepend a 0 ë # else: 0 # push a 0 N2÷ # floor(n/2) ₅ # a(floor(n/2)) .ø # surround the 0 with a(floor(n/2)) Ig # push the length of the input() è # index into the infinite list of indentations ú # pad each character of the input with the right number of spaces » # join by newlines ``` [Answer] # [Haskell](https://www.haskell.org/), 97 bytes ``` f x|n<-length x,odd n,(p,q:r)<-splitAt(n`div`2)x=g p++[q]:g r f(x:y)=[x]:g y f[]=[] g=map(' ':).f ``` [Try it online!](https://tio.run/##FcjBCoIwGADgu0/xJ4Eb0yCPwxHd69RxCAq6OZx/c66Y0LuvOn7f1G/zaG1KCuIHm8qOqMMEsXwOA2BJXLlyT5tqc9aEayDYDebd1TQKDY4xubZcg88UiXynQsY/90zJVsg202LpHSmg4PSk0tIbBAG/uoN7hUfwN4QjKMgP8swudZ6@ "Haskell – Try It Online") Defines `f :: String -> [String]`. Upside-down left-to-right output. [Answer] # [JavaScript (V8)](https://v8.dev/), 223 bytes ``` f=(c,d=(s,x=0,y=0,u=s.substr.bind(s),l=s.length,h=l/2|0)=>l==1?{[x]:y}:l%2==0?{[x]:y,...d(u(1),x+1,y+1)}:{[x+h]:y,...d(u(0,h),x,++y),...d(u(++h),x+h,y)},r=d(c))=>Object.entries(r).map(k=>" ".repeat(k[1])+c[k[0]]).join("\n") ``` [Try it online!](https://tio.run/##TY3NToQwFEZfxTQxuTe9UykrM@aOj@ADIAsoneGnFtKWCUR5dsREExff4pyz@PrqXkUTuimd7s/7fmUw1DBEWjij9djMUcW5jimouvMNRCR3KGf9LbXUsnvKvzLki2PWr5/FUp7X7ewec@bsF0kp1cAMGmmRmlapcTsfSbb/YkbtkUnKFf@UlD9KtrTiRoEbMHj8vNW9NUlZn0JnIwRUH9UEA1/Eg1DBTrZKMBS6RGmKocjKElU/dh7Euxe4m9HH0VnlxhtcQZy0zAXiy/4N "JavaScript (V8) – Try It Online") --- Maps the input source into a lookup of token index and indentation amount, then transforms it into a proper string in the inverted left-to-right format. Indented: ``` f = ( c, // Helper method that calculates the indentation. d = (s, x = 0, y = 0, u = s.substr.bind(s), l = s.length, h = l / 2 | 0) => l == 1 // Case 1: Nilad ? { [x]: y } : l % 2 == 0 // Case 2: Monad + Arguments ? { [x]: y, ...d(u(1), x + 1, y + 1) } // Case 3: Dyad : { [x + h]: y, ...d(u(0, h), x, y + 1), ...d(u(h + 1), x + h + 1, y + 1), }, r = d(c) ) => // We take advantage of the fact that the object entries are automatically sorted. Object.entries(r) .map((k) => " ".repeat(k[1]) + c[k[0]]) .join("\n"); ``` [Answer] # [JavaScript (V8)](https://v8.dev/), ~~162~~ 157 bytes ``` d=>(j=(r,b="")=>r.map(o=>o.map?j(o,b+" "):b+o).join` `)((p=(r,x=r.length)=>x>1?x%2?[p(r.slice(0,z=x/2)),r[z|0],p(r.slice(z+1))]:[r[0],p(r.slice(1))]:[r])(d)) ``` [Try it online!](https://tio.run/##VcvLCoMwEIXhfZ@iBAozJKbqqggTHyQIXtsarAlRJEjf3SoUSneH7/CbaqmmxvdujpbbdqetJQWGwIuaGENSXr4qB5aUPUZuwIqaszPDrOYWpbH9WJ5KBHBHFMjLoRsf83NPg0rycElz7cDLaeibDmKxUrimiMLr9R0X4netPEEsMu31H3@xQGgRN@f7cYY7sCjhKdvhAw "JavaScript (V8) – Try It Online") **Explanation:** Parses using recursion, and puts arguments into arrays. Then, it takes the result, and recursively indents anything in an array. Left-to-right, upside-down. ]
[Question] [ # Task Given a positive integer number and a threshold, split into every possible way without generating any numbers above the threshold. # Examples > > Input: **15008** > > Threshold: **400** > > > Valid Output: `[[1, 5, 0, 0, 8], [15, 0, 0, 8] [1, 50, 0, 8], [150, 0, 8]]` Invalid outputs: * `[[1, 5, 0, 0, 8], [15, 0, 0, 8], [150, 0, 8], [1, **500**, 8] ...` (500 is above threshold) * `[[1, 5, 0, 0, 8], [15, 0, 0, 8], [150, 0, 8], [1, **5008**] ...` (5008 is above threshold) * `[[1, 5, 0, 0, 8], [15, 0, 0, 8], [150, 0, 8], [1, 5, **00**, 8] ...` (double zeroes not allowed) * `[[1, 5, 0, 0, 8], [15, 0, 0, 8], [150, 0, 8], [1, 5, 0, **08**] ...` (leading zero not allowed) * `[[1, 5, 0, 0, 8], [15, 0, 0, 8], [150, 0, 8], [1, 5, **008**] ...` (leading zeroes not allowed) > > Input: **15008** > > Threshold: **17** > > > Valid Output: `[[1, 5, 0, 0, 8], [15, 0, 0, 8]]` Invalid output: `[[1, 5, 0, 0, 8], [15, 0, 0, 8], [**150**,0,0,8]...` (150 is above threshold) # Rules * Valid threshold values are between 10 and 999. * Double zeroes are not allowed on output. * Leading zeroes are not allowed on output. * Duplicates must be removed. * Output order is not relevant # Scoring * Shortest answer in bytes wins [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes ``` ŒṖḌfV⁼³ʋƇḶ} ``` [Try it online!](https://tio.run/##ASkA1v9qZWxsef//xZLhuZbhuIxmVuKBvMKzyovGh@G4tn3///8xNTAwOP8xNw "Jelly – Try It Online") -1 byte [thanks to](https://codegolf.stackexchange.com/questions/217008/split-a-number-in-every-way-possible-way-within-a-threshold/217009?noredirect=1#comment506395_217009) [Jonathan Allan](https://codegolf.stackexchange.com/questions/217008/split-a-number-in-every-way-possible-way-within-a-threshold/217009?noredirect=1#comment506395_217009) -1 more byte [thanks to](https://codegolf.stackexchange.com/questions/217008/split-a-number-in-every-way-possible-way-within-a-threshold/217009?noredirect=1#comment506397_217009) Jonathan Allan ## How it works ``` ŒṖḌfV⁼³ʋƇḶ} - Main link. Takes n on the left and t on the right ŒṖ - All partitions of the digits of n Ḍ - Convert the lists of digits to a list of numbers } - To t: Ḷ - Yield [0, 1, 2, ..., t-1] Ƈ - Filter the partitions p, keeping those for which the following is true... ʋ ...with each partition p on the left and the lowered range on the right: f - Keep the numbers in the lowered range (i.e. less than t) V - Concatenate the numbers into a single number ⁼³ - Is that equal to n? ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 9 bytes Generates all valid partitions and keeps those that join to the input number. This is *really slow* because it generates partitions of up to as many integers as the input number. ``` Ýsã0δÛʒJQ ``` [Try it online!](https://tio.run/##yy9OTMpM/f//8Nziw4sNzm05PPvUJK/A//@NuAwNAQ "05AB1E – Try It Online") Don't try the cases from the challenge, even for the one with threshold 17 this tries to generate roughly \$1.35 \cdot 10^{18839}\$ partitions. **Commented:** ``` # first input: threshold, second input: number Ý # inclusive range [0 .. threshold] s # swap to the input number ã # take the range to this cartesian power # this generates all input-tuples of integers in [0 .. threshold] 0δÛ # for each tuple remove leading 0's ʒ # only keep the partitions JQ # which are equal to the input if joined into a single string ``` --- # [05AB1E](https://github.com/Adriandmen/05AB1E), 10 bytes This is more efficient, starting with actual partitions of the number and keeping the valid ones. ``` .œʒà@y*J¹Q ``` [Try it online!](https://tio.run/##yy9OTMpM/f9f7@jkU5MOL3Co1PI6tDPw/39DUwMDCy5DcwA "05AB1E – Try It Online") **Commented**: ``` # first input: number, second input: threshold .œ # all string partitions of the first input ʒ # keep all partitions where à # the maximum string @ # is less or equal compared to the second input y* # multiply this (0 or 1) with each number in the partition # all strings are converted to integers here, which removes any leading 0's J # join into single string ¹Q # is this equal to the first input? ``` [Answer] # [Perl 5](https://www.perl.org/), 131 bytes ``` sub{($n,$t)=@_;grep{!grep$_>$t,/\d+/g}grep$n==s/,//gr,map$n=~s|.|$_/=2;$_*2%2?"$&,":$&|egr=~s/\b0+\B|00+//gr,0..2**($n=~y///c-1)-1} ``` [Try it online!](https://tio.run/##VY7bToQwEIbveYrajIRDYVqymzU2VeNryKZxFVgTQVIwkQC@ei3dmOhczOGb/PNPX5n3vW0nqJUdPk9zBB2DMVYPWjam6uerLYO@g5Fh@Zpis3rQKTUgQ2wMa5@38XtY8gU0qkKCTorr4p5CyOgthEvVGLfG8sTT8nHhPPUynudFkkSbdELEl0zEmVitDOoPEwXExZPYc37Ddpwf2V8gDm6OZ4/a6fLw2X0MWnrWm7duJDSjX4IzWnb0HwbtCHEmJIT6VyyD1drLdeKLda6uPfwA "Perl 5 – Try It Online") [Answer] # [JavaScript (V8)](https://v8.dev/), ~~97 90~~ 89 bytes Expects `(threshold)("integer")`. ``` t=>g=([v,...a],p=[],c='',u=[...p,c])=>c&&[+c]!=c|c>t?0:v?g(a,p,c+v)||c&&g(a,u,v):print(u) ``` [Try it online!](https://tio.run/##dcmxCoMwEIDhvW9RB83hNURoUYTTBwkZwlHFIiZozOS7p3Zrh47//71stBuvkw@32KSBUqBuJKEjSimtQU/aIFNR4E76XB7ZAHWc57pkcyU@uAu9amM/CounlhGO4@RP7hih9eu0BLFDYrdsbn7K2Y1iEHelQGTVQ6kmA7j8YlX/t29Kbw "JavaScript (V8) – Try It Online") [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 128 bytes ``` Union@(w=Select)[d=#2;(f=Flatten)[Permutations/@Subsets@w[FromDigits/@Subsequences[s=(i=IntegerDigits)@#],#<d&],1],f[i/@#]==s&]& ``` [Try it online!](https://tio.run/##NcvRCoIwFIDhVwkEURioQRTUgV2E0J0gXY1dLD2uA27SdsTHX0J0@/H/zvAbnWEaTLKQnp4WL4sNepxx4FKNkB2vxQTtbJjRl6rD4Fbeh8XHSvbrKyJHuak2LO5OlvivnxX9gFFFKAgentFi@AWlzLTIbmOuRaPFpKjaASDmOk9dIM8HaVVzquuLaM46pS8 "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~31~~ 40 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` Êo1 Ôà ËF=UD£F=iSXÃFÃm¸®mnÃf_e<VÃâ f@¥Xq ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=ym8xINTgIMtGPVVEo0Y9aVNYw0bDbbiubW7DZl9lPFbD4iBmQKVYcQ&input=IjE1MDA4Igo0MDAKLVE) * Input : number as string. * Output : arrays of numbers. ``` 0oUÊÉJ - enclosed indexes in descending order à - combinations Now we have all the arrays of indexes to split. ËF=U - map each group of indexes using a copy of number(F) D£F=iSXà : inserting a space at every index(in reverse) Fà - return the spaced number m¸ - split each f_e<V - filter out the result ``` * Edit : fixed deduplicate requirements and $00..$ [Answer] # [Perl 5](https://www.perl.org/) (`-p`), 93 bytes ``` s/(.*\d)(\d.*)/$1,$2 $1.$2/?redo:y/.//d;$t=<>;$_=join$/,grep!(/\b0\d/|grep$_>$t,/\d+/g),/.+/g ``` [Try it online!](https://tio.run/##JcfRCoIwGIbhc@8i@A@crX2bJEU2gyCik65gIMhEDHFDdxLVrbeKjt7n9e00FPF4Ol@uDzKaIAivOCMVmbEsNVZkDKQ45QkpQTkOU2vd7g4B2JKC3lcl1frm@pHAu6n1ixSmkcbi@TuqKwocxi7RMQ7xTYyqkHKbrKVM/lKbt/Ohd@McV4P/AA "Perl 5 – Try It Online") [Answer] # [Python 3.8](https://docs.python.org/3.8/), 106 bytes Recursive function taking the number as a string and the threshold as an integer. ``` f=lambda s,t:[[]][s>'':]or[[d]+p for i in range(s<'1'or len(s))if t>=int(d:=s[:i+1])for p in f(s[i+1:],t)] ``` [Try it online!](https://tio.run/##XcuxDsIgFEDR3a9gg5d2gKixIaU/8vIGDEVJKhBg8euxrK4n9@Zve6d4XXLp3ZvDfp7Osjo3jUiEdeNcUyqIjqbMfCossBBZsfG1i7pyxU869igqQPCsbSbEJpw2FXWYFMFY8li8qHiKprkB9VxG5wVXdykXPt@kBLj8q3oA9B8 "Python 3.8 (pre-release) – Try It Online") **Commented**: ``` f=lambda s,t: # recursive function taking arguments: # s: str - the number to split # t: int - the threshold [[]][s>'':] # if s is the empty string, return [[]] or # otherwise: [[d]+p # a prefix of s prepended to a valid partition of the corresponding postfix for i in range( ) # iterate over every possible (decremented) postfix lengths i s<'1'or len(s) # if s starts with a 0, this can only be i=0, otherwise i=0, 1, ..., len(s)-1 if t>=int(d:=s[:i+1]) # the prefix is valid if it is not larger than the threshold as an integer for p in f(s[i+1:],t)] # iterate overall partitions of the postfix ``` [Answer] # [Scala](http://www.scala-lang.org/), ~~164~~ ~~155~~ ~~132~~ 131 bytes ``` s=>t=>1 to 1<<s.size-1 map(i=>s.indices.map(j=>s(j)+","*(i>>j&1)).mkString.split(','))filter(_.forall(i=>i.toInt<=t&i==i.toInt+"")) ``` [Try it online!](https://tio.run/##bZBfa8IwFMXf/RSXIJo7XWn9wzYxBR/3shfZk4jUNtV0Me2aq3MTP7tL7TaG9AYS8rvh5Jxr40hHl3ydyZjgZb9by3JeaEUgjyRNYmFWFHBqARwiDeneTGBOpTIbECE8G6qPRB5lMpfvi1lZRp@L@sVyCeJiRUgiDIByCKZT61n1Je8D2EUFVyK0njKJiqX1KpA5wDPssT674yoMs06A6O3eajnPVrZ4t99FTJUmWfKVl@ZlpHUlpTzKnZ@poI4S4ufWYwzxApDIFEhaiiMruf2N0AeaVBlwAq/GJRbXnACFa5I23DJznQe0LXwo2gJtS2m3uU6gTbBRB@mk2ic3FG6RE15DrP4Mc8Zdkmoh@5fDQWB4Zuj@Orfc9meMBWPff3Ttke9jYyN4aOZPVeGN2GA4cq3BrVSNR4102EjHrrB1vnwD "Scala – Try It Online") Generating all partitions is still the most byte-consuming part, since there is no built-in for that. The original version took a different approach (164 bytes), which was optimized by @user via three nice tricks (155 bytes), see comments for details and code. Now, I changed the strategy itself, which gives the current solution (132 bytes), and another byte removed thanks to another hint by @user (now: 131 bytes). The current version uses the 1-bit-index-positions of a counter variable as split-positions. The original version generated the indices of split-positions directly via combinations of all valid lengths and ranges. **Some details on the "bit-hacking"**: The outer loop generates all numbers from `1` up to `2^(numDigits-1)`, where the upper bound is represented via bit-shifting as `1<<s.size-1` (side note: as a consequence, this solution, based on signed Integer shifts, does only work for input numbers of at most 31 digits, which should be fair enough, but could easily be extended via BigInt to arbitrary input lengths). In binary representation, the outer loop variable `i` goes, for example, from `00001`, `00010`, `00011`, ... up to `10000` for a 5-digit input such as `15008`. The `j`'th bit position (counted from the right, starting at 0) indicates whether we should inject a "comma character" after the `j`'th index position of the input string. This is executed by the inner loop: The inner loop traverses the input string `s` char by char at index `j` and evaluates the expression `i>>j&1`. This expression "probes" whether the `j`'th bit of `i` is set by shifting `i` by `j` bit-positions to the right and then bit-AND-ing it with 1, which evaluates to 0 or 1, depending on whether the `j`'th bit is 1 or 0. As a consequence, the current char `s(j)` is preceeded by either the empty string `","*0` or by a comma `","*1`, depending on the `j`'th bit of `i`. (side note: bit representation `10000` represents the case of not including any comma, since it is injected after the last position. This case could also be achieved via `00000` instead, but then one would have to use the longer loop expression `0 until 1<<s.size-1` instead). [Answer] # [J](http://jsoftware.com/), ~~73~~ 70 bytes ``` (]#~0=1#.<:&>)<@](-:"1&(,&":/@>)#])[:<@;"1]<@#.~&10;.1~1,.2#:@i.@^<:@# ``` [Try it online!](https://tio.run/##Tc2xCsIwEIDhvU9x5CBtID3vRFGuaTkQnJxcJV3Eoi6@QV49Flwc/uVb/nd11C4wKrQQgUHXeoLT9XKuXcbCoyAl9VNIlrtenfgueqcbmwLmcNNkg5OcDKl44YGkSKQtqr3I5qSGNTTN4/78wI4ZFhDYrwuG4w/lAP9Yvw "J – Try It Online") Turned out to be harder than I thought, and could likely be golfed more, but this will do for now. Takes the threshold as an int, and the number to partition as a list of digits. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 54 bytes ``` ⊞υ⟦S⟧Fυ«≔§ι⁰ηFLη¿∧κ∨⁼⊖LηκI§ηκ⊞υ⁺⟦…ηκ✂ηκ⟧✂ι¹»NηΦυ¬‹η⌈Iι ``` [Try it online!](https://tio.run/##TY/NasMwEITP0VPscQUqKNBCwSfjtBBIU0OOIQdVViwRWU70U1JKn12VHVI6sIdZZodvpRZejsLm3KagMTHYr905xV30xvVID7Qix9EDJgrfZFGHYHqHdVy7Tl3RMOCUgS6hxZzaKNdHjZpSMEfA2nV4YvDu8eWShA24UtKrQbmoun9ZBqcyjQjxr1lPuyK4Y7U2Bdw3X9KqRo/nW4DBzhqpbuZwd4VqWU4r8kPmX7Zp@FAeJ8q2fBXx1dhYFqV1O8bCEcLU8CauZkgDzhyGzqpyXj5x/kweOc8Pn/YX "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ⊞υ⟦S⟧ ``` Start a breadth-first search for all partitions of the integer (as a string). ``` Fυ« ``` Loop over each partition. ``` ≔§ι⁰η ``` Get the first string in the partition. ``` FLη ``` Loop over each character index. ``` ¿∧κ ``` If this is not the start of the string, and... ``` ∨⁼⊖Lηκ ``` ... either this is the last character of the string, or... ``` I§ηκ ``` ... the current digit is not zero, then... ``` ⊞υ⁺⟦…ηκ✂ηκ⟧✂ι¹ ``` ... create a new partition with the first string split at the current index. ``` »Nη ``` Input the threshold. ``` Φυ¬‹η⌈Iι ``` Print all partitions whose maximum value is not greater than the threshold. [Answer] # [Stax](https://github.com/tomtheisen/stax), 18 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` âë┴fτ♪C┼Hnm♥ì╩≈╘9ù ``` [Run and debug it](https://staxlang.xyz/#p=8389c166e70d43c5486e6d038dcaf7d43997&i=400,%2215008%22) first input is the threshold and second input is the number as a string. [Answer] # [Python 3.8](https://docs.python.org/3.8/), 210 bytes ``` def f(n,t): l=len(n);r=[] for i in range(2**l):c=[0]+[i for i,d in enumerate(f'{i:0{l}b}')if'1'==d]+[l];e=[n[g:h]for g,h in zip(c,c[1:])];r+=[e]*all(j and(k:=int(j))<t and(k>9or len(j)<2)for j in e) return r ``` [Try it online!](https://tio.run/##jVHLbsIwELznK/YWL3WlhIegAfMjrg9psoFAMJFtpLZRvp3aBirRU60cPLOZ9exO/@X2Zz1b9eZ6ramBhmnusEigEx1ppnFthFQJNGcDLbQaTKl3xKaTSYdFJWSmXmR7q/I61ElfTmRKR6xJh7bIhm78GFNsmzRPhaj9751ak5Ba7oq9CsId3wfhd9uzilcyLxSqtXkRktSk7Dp2gFLX7FiIVjt2QNy4G7F98@Jg8oCbKYZOh2gAEzDkLsZ7vTqyzoIAloA/LF9k2YrDPMuQPzH5Ejkm9NlT5aj@FUiZc1hwyOK3Uhxk/gf6@lP1ART/TwflX632VB3JhEfT98t0Oa9SDvGWz1JMwmBhDE6PLcWhODzchrT80b6BdSZWfSwYSefJSOQq4rCLW8QRkoeya61jp7JnXs0tYkzTxlXeRL0Jm/dxhk4jvG5hsCMMd9/Sno13wQiFuF8tKh/59Qc "Python 3.8 (pre-release) – Try It Online") Inputs a number as a string and the threshold as an integer. Returns all splits as a list of lists of strings. [Answer] # [Haskell](https://www.haskell.org/), 89 bytes A port of my Python answer. ``` ""!t=[[]] s!t=[d:p|i<-[1..last$length s:[1|s<"1"]],p<-drop i s!t,d<-[read$take i s],d<=t] ``` [Try it online!](https://tio.run/##FYtBCsMgEADvfcVm8ZgEhQRK0JfIHgSlkVgrusf83ZrbMMycrl0hpd4RJzbWEr3aA/4od9SLVeuaXGORQv7wCe2w6m4aFRLNRS@@/gpEGMvsR12D84LdFR5HQxmm/nUxg4FSY2YQgGqX8o3TJmX/Aw "Haskell – Try It Online") ]
[Question] [ *I will preface this by saying that I made this for fun; I have absolutely no formal knowledge on cryptography or error correction. Do not use this algorithm in anything remotely important.* I was kind of bored a few days ago, so I decided to write a simple function to take some data and return an easily memorable (but not necessarily secure :p) checksum of it. The output format is a number of digits in base 36, between `0` and `z` (think of it like hexadecimal, but with all the letters used). Your program or function will take two inputs: `data`, and `block_size`. The `data` will be a list of values `0` to `255`, and the `block_size` will be at least `4`. It will return a base 36 string (or list of values 0-36) with the length `block_size`. Using `[182, 109, 211, 144, 65, 109, 105, 135, 151, 233]` and `4` as the inputs, this is how you would find the checksum: 1. The length of the `data` is padded with zeroes to a multiple of the `block_size` ``` 182, 109, 211, 144, 65, 109, 105, 135, 151, 233, 0, 0 ``` 2. The `data` is broken into blocks based on the `block_size` ``` 182 109 211 144 65 109 105 135 151 233 0 0 ``` 3. For each item `n` of the resulting block, take the sum of all items at position `n` in one of the above blocks mod 256 ``` 182 109 211 144 + 65 109 105 135 + 151 233 0 0 -------------------- 142 195 60 23 ``` 4. Take the binary representation of each item in the result ``` 10001110 11000011 00111100 00010111 ``` 5. For each item, add the least significant five bits of the next (wrapping) item, and the least significant bit of the (wrapping) item after that (note that this value can be higher than `256`) ``` 10001110 11000011 00111100 00010111 + 00011 11100 10111 01110 + 0 1 0 1 -------------------------------------------- 10010001 11100000 01010011 00100110 ``` 6. Convert back to decimal, and take the mod 36 ``` 1, 8, 11, 2 ``` 7. Covert into base 36 ``` 18b2 ``` A reference implementation can be found [here](https://gist.github.com/RedwolfPrograms/cf650c0b22274a019ae91e92eb6b7380). Input and output can be in any reasonable manner. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest in bytes per language wins! ## Test cases ``` []; 8 -> 00000000 [0, 1, 2, 3, 4, 5, 6, 7]; 8 -> 14589cd8 [0, 1, 2, 3, 4, 5, 6, 7]; 6 -> eb589b [0, 4, 2, 1]; 48 -> 473100000000000000000000000000000000000000000000 [195, 180, 1, 0]; 4 -> 0123 [31, 32, 65, 4]; 4 -> wxyz [20, 8, 247, 41]; 4 -> tw4p [250, 175, 225, 200]; 4 -> ewhb [33]; 3 -> (does not need to be handled) ``` [Answer] ## Thumb-2 (ARMv6T2, no div instructions), ~~118~~ ~~116~~ ~~112~~ 110 bytes (ascii base 36)/102 bytes (values) I believe there is still some optimization room for sure. Raw machine code, 16-bit hex little endian Base 36 ASCII version: ``` b5f0 ebad 0d03 466f 001d 2600 3d01 557e d1fc b151 5dbc f810 5b01 192d 55bd 1c76 429e bf08 2600 3901 d1f4 003c 1e9d 7866 78a1 f000 f80c 3d01 d1f9 7866 7839 f000 f806 783e 7879 f000 f802 449d bdf0 f814 0b01 f006 061f 0849 4170 3824 dafd f110 01fb bfc8 3027 3054 f802 0b01 4770 ``` Without ASCII conversion ('values') ``` b5f0 ebad 0d03 466f 001d 2600 3d01 557e d1fc b151 5dbc f810 5b01 192d 55bd 1c76 429e bf08 2600 3901 d1f4 003c 1e9d 7866 78a1 f000 f80c 3d01 d1f9 7866 7839 f000 f806 783e 7879 f000 f802 449d bdf0 f814 0b01 f006 061f 0849 4170 3824 dafd 3024 f802 0b01 4770 ``` Uncommented assembly: ``` .syntax unified .arch armv6t2 .thumb .globl redwolf .thumb_func redwolf: push {r4-r7,lr} sub.w sp, sp, r3 mov r7, sp movs r5, r3 movs r6, #0 .Lmemset_loop: subs r5, #1 strb r6, [r7, r5] bne .Lmemset_loop .Lmemset_loop_end: cbz r1, .Lsum_loop_end .Lsum_loop: ldrb r4, [r7, r6] ldrb.w r5, [r0], #1 adds r5, r4 strb r5, [r7, r6] adds r6, #1 cmp r6, r3 it eq moveq r6, #0 subs r1, #1 bne .Lsum_loop .Lsum_loop_end: movs r4, r7 subs r5, r3, #2 .Lchecksum_loop: ldrb r6, [r4, #1] ldrb r1, [r4, #2] bl checksum subs r5, #1 bhi .Lchecksum_loop .Lchecksum_loop_end: ldrb r6, [r4, #1] ldrb r1, [r7] bl checksum ldrb r6, [r7] ldrb r1, [r7, #1] bl checksum add sp, r3 pop {r4-r7, pc} .thumb_func checksum: ldrb.w r0, [r4], #1 and.w r6, r6, #31 lsrs r1, r1, #1 adcs r0, r6 .Lmodulo_loop: subs r0, #36 bge .Lmodulo_loop .Lmodulo_loop_end: #ifdef ASCII cmp.w r0, #9 - 36 it gt addgt r0, #'a'-10-'0' adds r0, #'0'+36 #else adds r0, #36 #endif strb.w r0, [r2], #1 bx lr ``` [Try it online! (sorta)](https://travis-ci.com/github/easyaspi314/easyaspi-ppcg/jobs/471971267#L500) ### Explanation C signature: ``` void redwolf(const uint8_t *data, size_t data_size, char *block, size_t block_size); ``` First, we push our registers and set up a VLA. (`uint8_t chars[block_size]`) ``` push {r4-r7,lr} sub.w sp, sp, r3 ``` Since we like narrow instructions, and there is no narrow `ldrb Rd, [Sp, Rn]` instruction, we use a frame pointer to cut down code size. ``` mov r7, sp ``` Zero out the VLA we created. ``` movs r5, r3 movs r6, #0 .Lmemset_loop: subs r5, #1 strb r6, [r7, r5] bne .Lmemset_loop ``` If we have data, sum everything up. ``` .Lmemset_loop_end: cbz r1, .Lsum_loop_end .Lsum_loop: ldrb r4, [r7, r6] ldrb.w r5, [r0], #1 adds r5, r4 strb r5, [r7, r6] ``` `r6 = (r6 + 1) % block_len` without division ``` adds r6, #1 cmp r6, r3 it eq moveq r6, #0 ``` Decrement data\_len and loop if non-zero. ``` subs r1, #1 bne .Lsum_loop ``` Now, we checksum the data and convert to base 36. We do a simple loop for all but the last two bytes in `chars`, calling a subroutine (with a custom calling convention) to handle the arithmetic. We pass the second two bytes as parameters, while `checksum()` will do `*r4++` to load the first byte and increment. ``` .Lsum_loop_end: movs r4, r7 subs r5, r3, #2 .Lchecksum_loop: ldrb r6, [r4, #1] ldrb r1, [r4, #2] bl checksum subs r5, #1 bne .Lchecksum_loop ``` Process the wrapped data. I feel this could be optimized better. ``` .Lchecksum_loop_end: ldrb r6, [r4, #1] ldrb r1, [r7] bl checksum ldrb r6, [r7] ldrb r1, [r7, #1] bl checksum ``` Restore the stack, pop registers, and return. ``` add sp, r3 pop {r4-r7, pc} ``` checksum subroutine We call `checksum` with `r6 = chars[i + 1]` and `r1 = chars[i + 2]`, with `r2` still pointing to `block`. Load `chars[i]` from `r4` and increment the pointer. This is a step outlined from the other three calls. ``` ldrb.w r0, [r4], #1 ``` Now we need to do `chars[i] + (chars[i + 1] & 31) + (chars[i + 2] & 1)`. First, we mask the lowest five bits of `chars[i + 1]`. ``` and.w r6, r6, #31 ``` Now, we use `lsrs` to get the lowest bit of `chars[i + 2]` in the carry flag... ``` lsrs r1, r1, #1 ``` ...so we can add them both with an add-with-carry. Done. ``` adcs r0, r6 ``` Modulo by 36 using a naïve subtraction loop. No `udiv` required. Not that I would use it anyways - `movs` + `udiv` + `mls` would be 10 bytes, this is 4. Note that this will end up negative, we need to add 36 after to get the correct result. ``` .Lmodulo_loop: subs r0, #36 bge .Lmodulo_loop ``` Convert to base 36 (ascii version): If r0 + 36 is > 9, we add the additional offset to get it from `r0 + '0'` to `r0 + 'a' - 10`. ``` .Lmodulo_loop_end: cmp.w r0, #9 - 36 it gt addgt r0, #'a'-10-'0' adds r0, #'0' + 36 ``` Adjust offset (non-ascii) If we are outputting integers, just add 36. ``` adds r0, #36 ``` Store the char into block and increment the pointer. ``` strb.w r0, [r2], #1 ``` Return back to the main function. ``` bx lr ``` [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), ~~84~~ ~~67~~ 63 bytes -17 bytes by reshuffling things, inspired by @Neil's comment, -4 bytes from more golfing ``` {(`c$&2!&49\5673099)36!+/256 32 2!'y':(y+2)#+/(0N;y)#x,&y-y!#x} ``` [Try it online!](https://ngn.codeberg.page/k#eJyVkdtum0AURd/5ikMcOSAPZm5cR8on9Klv1JIxDCHyBcdgGRq1394zYEeq3EbKSLzsvdjnzOwqfXfWxeOc23OZ/AjCSNAkcUVoL3wehCA4cPtpeEqdYcHd2cJ36Dc1uLOezAdvsGf9L8v6nr4/ZsPvU1rBEnq1brbKWVf56071alAnd2WYzHFcFbvqgV7Pw8qIdjyKTAZxUpTxhxiiqDcobiaJggQOTElDy0gw+oUzRbAkABZTYECVNIswLiZHMHPPMAA5Gpd++DkZnEIMXEYg2eh0F3m8OgEGRQFwjh+dAvWlvm5LhFAClZ4xFCzfqrvu2Ka+XzSlfml21bLt8mKr+6LODy96WTR7/+2s2+61ObQ+Z2HAOLL747nTXldr76TLC/7mFbUutu157zWV1zZ77ZV5l/uWla0Ubvr/4z3D7TGsjBJgBDgBQUASCAiEBKKPBGRvdXzChjd2amkk5UgydOXdMkh+tTYrw8qI6Wxcgprcu1thiVYm0BY4OkRc3mGGM51aGcekmJhGkWP/yjMNIxeYkRGmYb/EFPwXa26NXeNcgbr47NWdstEtHJoODlqX0DWw0YCllztdun8A/1vGNg==) * `+/(0N;y)#x,&y-y!#x` take the column-wise sum of the input split into `y`-length chunks (filling with 0s) * `y':(y+2)#` build a list containing the original input, it rotated once, and it rotated twice * `256 32 2!'` mod the original input by 256, the rotated-once input by 32, and the rotated-twice input by 2 * `36!+/` sum column-wise, modding by 36 * `(`c$&2!&49\5673099)` build list of base-36 characters (digits followed by lower case letters), which is indexed into by the results of the above [Answer] # [J](http://jsoftware.com/), 59 bytes ``` (Num_j_,Alpha_j_){~]($!.0)36|[:+/256 32 2|i.@3|."{+/@([\~-) ``` [Try it online!](https://tio.run/##ldDLasJAFAbgfZ7irxSSITrOPZNAQVvoqrjoViUYL8TQ0m6KVYOvnk6MXcTLwgMHZvHNzzmnqDrUX@EpgY8uGBLXPYqX97fXKhj9fKZF2h1@fOcz9yD7wzR4fKCMSFOOk7AvtIEUEOWaDmRJO/uwPwjGk0OPVMRbzvMvBL5PsILFlRo9U7BTNZqBQ0BCQcMgan2sNVfaxvOFvaVNSy8zp7N/q5zlzih7bQ4VSc7uqCaVxxrc1nOwOvlyOy5kIyWvD2W0Q@fwKDe/210jhXZ5kYYQrlk797jVJs88r/oD "J – Try It Online") * `([\~-)` data x split in blocks of size y, padded with zeros * `+/@` sum each column * `i.@3|."{` rotate row by 0, 1 and 2, so we get 3 rows * `256 32 2|` mod rows by 256, 32 and 2 * `[:+/` sum again * `36|` mod 36 * `]($!.0)` lengthen list to size of y, padded with zeros * `(Num_j_,Alpha_j_){~` take the indices from `0…Z` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~24~~ 18 bytes ``` ιO₁%DÀ31&DÀÉ++₆%₆B ``` [Try it online!](https://tio.run/##yy9OTMpM/f//3E7/R02Nqi6HG4wN1YDk4U5t7UdNbapA7PTf678JV7ShpamOgqGFAZDQUTCIBQA "05AB1E – Try It Online") or [Try all cases!](https://tio.run/##lY/NSsNAEMfv@xRDaFywmyabbJOUQA8iXn2A1EM@VhOUJHQj8RO0B8FH8ty7D9EXiZOYKtIqODCzzMyP/382jlTWtjLJSjAKoO9vp5vVs368fnL4Adb163i8Wb3omEcU5pCUqZxEsSSkyfIrCUsZpZAX1XUdQFoSgK2SNuqnGixw@ABKpkCVCaZ5QYdWmcbkEPuBiJpLME5oQIHeV8u8qM9B09Wi0JXGYGRj8kc6sGZZ1WapojiXw/N9WFoWsm3DswB8@D2MOVhDkNBiwBmghcNAMJgycBl4XwrIcjH1Z0nq/8G6W1bGyMY9KXqS41b4ey4QnsOtfwQJ@QwNuf95hNXp7vyK2w4JHVw7aO0iLnawjmtubu9IaKOSj0cKDzm@T69uRIXctLP0UM22u2L99O5@3WQx@QA) **Commented**: ``` ι # create block_size lists of every block_size-th element # [data[0::block_size], data[1::block_size], ..., data[block_size-1::block_size]] O # sum each list ₁% # modulo 256 DÀ # duplicate the resulting list and rotate the copy left 31& # bitwise and 31 / take the 5 least significant bits DÀ # duplicate this list and rotate left again É # is the value odd? / least significant bit ++ # sum the three lists element-wise ₆% # modulo 36 ₆B # convert to base 36 ``` [Answer] # [R](https://www.r-project.org/), 122 bytes ``` function(d,b,m=matrix)c(0:9,letters)[1+colSums(m(rowSums(m(c(d,!1:(b-sum(d|1)%%b)),b))%%256,b+1,b)[1:3,]%%2^c(8,5,1))%%36] ``` [Try it online!](https://tio.run/##RY7LasMwEEX3/Qp1YZDIDWj0sGWTfkWXIYXasYshssEPmkX/3R3hFi9G3DnDmdG0deJyFlu3Ds3Sj4O8o0Z8i5/L1D9VI3VV4tEuSzvN6kqnZny8r3GWUU7j919q2HmlStbneY3y/kMqy2qlwJVlxueoT8TNlSqLG5OPRgZ4UBrb/LZ1sh@W9qudpFYI6qXjo8UR8hT4I3AwLMGFHVDJO4IGgTW3M0uwBrnn/h8ZjQDjCjg6mGet8DCGSx86BQNBuoQwRJycg@BlOyKdkk2P56GxNnnbLw "R – Try It Online") Output as a list of base 36 digits (lowercase). [Answer] # JavaScript (ES6), ~~122 121~~ 114 bytes Expects `(data)(block_size)`. Returns an array of characters. ``` a=>w=>a.map((v,i)=>b[i%w]+=v,b=new Uint8Array(w))&&[...b].map((v,j)=>((v+b[++j%w]%32+b[-~j%w]%2)%36).toString(36)) ``` [Try it online!](https://tio.run/##lY9BbsIwEEX3nGI2gK0YEzsmCQtH6hmqriIWDgSaiCYoWLh00aunY0hbUCtVncV4LL///7g2J3Ncd9XBzpp2U/Zb3RudOZ0Z/mIOhJxYRXVW5NXYrQJ9YoVuSgdPVWPTh64zZ@IonUxyznmx@lTUqMAzKPIgqFE3jiTOs/fLLOk4iim37aPtqmZH8EJ7Wx4taDCgM3C@rdvm2O5Lvm93ZEsMxRhet1VDplNKRyPPk3xFSUrh95rPIRxqoEMGgoFkEDFQDBYMYgbJ1QNpoRbpcr1J/6LjC10WSBffrLqwAt/V/UrIqiQS4T9qcBVLDBXpdZHQO9O73wkZDWSEQITxMQrUPehJ93p@G0iJbimuqhIkxQ9P69Thi/TBCTpK6Vt4s4FPd8@2/wA "JavaScript (Node.js) – Try It Online") ## Commented ### Step 1 to step 3 ``` a.map((v, i) => // for each value v at position i in a[]: b[i % w] += v, // add v to b[i mod w] // there's an implicit modulo 256 because ... b = new Uint8Array(w) // ... b[] is initialized to an array of w unsigned bytes ) // end of map() ``` ### Step 4 to step 7 ``` [...b] // we need to split b[] so that the results returned by the // callback function of map() are not forced to unsigned bytes .map((v, j) => // for each value v at position j in b[]: ( // ( v + // compute the sum of v b[++j % w] % 32 + // and b[(j + 1) mod w] mod 32 b[-~j % w] % 2 // and b[(j + 2) mod w] mod 2 ) % 36 // modulo 36 ).toString(36) // converted to base-36 ) // end of map() ``` [Answer] # [Pip](https://github.com/dloscutoff/pip), 87 bytes ``` Y($+_)%256M(@>g<>@g)ZD0 ((,tALz)Jx)@_M($+_)%36M Z[{@RVTBa}My{FB((TBa)@>-5)}M(@>y)AL@yy] ``` [Try it online!](https://tio.run/##K8gs@P8/UkNFO15T1cjUzFfDwS7dxs4hXTPKxYBLQ0OnxNGnStOrQtMh3heiyNjMVyEqutohKCzEKbHWt7LazUlDA8jUdLDTNdWsBRlQqeno41BZGfv/vwmXoYURl6GBJZeRoSGXoYkJl5kpmGtoAKSNgdjUkMvI2Pi/bhEA "Pip – Try It Online") This was much harder than I expected. Input is taken as a list of lines. First line is `block_size`, rest of the lines are the data. [Answer] # [Perl 5](https://www.perl.org/) `-a`, 96 bytes ``` $#r=<>-1;map$r[$i++%@r]+=$_,@F;say map{((0..9,a..z)x9)[$_%256+$r[++$j%@r]%32+$r[($j+1)%@r]%2]}@r ``` [Try it online!](https://tio.run/##dYu9DoIwFIX3PkUTLwmkpWkrBUytYXLzCQwhHRwgqKQ6@BNf3XphdznJOef7plMYTYywCm67y5U9@wnCEXrGkia0zEHHm729@SfF552mUogN90K8sscmO0KXaFMyNBiDYTaStZ5rCgNT2TLo9tOEaJvg0sxC72Bw0kbJacGp5lSRoibaYFeVwUXPISUpiMatxlJUyCJGZmZx1ouMYMlpRep/R/m9Tvf@ernF/GCEVDLmfvwB "Perl 5 – Try It Online") [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), ~~161~~ 159 bytes ``` lambda d,b:(d:=d+[0]*(b-len(d)%b),r:=range(b),s:=[sum(d[i::b])%256for i in r],[[str(k:=(s[i]+(s[(i+1)%b]&31)+(s[(i+2)%b]&1))%36),chr(k+87)][k>9]for i in r])[2] ``` [Try it online!](https://tio.run/##lZLZbsMgEEXf/RUjVamgJpJZvATJ@RHKQyhObSXGlu0qTX/eBTfqorSROg8jQGculxn681R3jhf9MO/Lx/m4a43dgSVGIitLG6tEPyCzPlYOWbwymAyyHHbuuUJ@PcpSjS8tsqqR0mi8Ymm27wZooHEwaKLUOA3oIEs0qkbHPqMmpl5G33OKL3u27CnGK55h8lT7grjIsVaH7UZ/U8OK6bktVYSUJgWGv@NuvYXkEhFBKiFACTACnIAgkBLICOSfIgGnIi02T7a4hWdfeGU8bi6wWGCqibh2FWCRc5r8I4Is3fhrafFhJfHS@PqFlPGAck9wbyDzFeKKXNDT6/ktoMzrFd6tyD1Kf1WdTqJf0DTcnXtNxkJKfppYmnCqlxZwrgnHN6eBbFeN4LoJXFVZmDowFdQ7Z4@VxZGOojBnF@bcyigU@Q8IJbhl3Q@Nm9Ae@TOM53c "Python 3.8 (pre-release) – Try It Online") Edit: * changed `range` to variable to reduce 2 characters [Answer] # [Ruby](https://www.ruby-lang.org/), 106 bytes ``` ->a,n,c=[0]*n{a.size.times{|i|c[i%n]+=a[i]&255};(1..n).map{|i|((c[i-1]+c[i%n]%32+c[-~i%n]%2)%36).to_s 36}} ``` [Try it online!](https://tio.run/##lc/baoNAEAbg@z7FELBosy57VEOwLyJLUWvIXsRKNJiTfXU7RtsU24t2LpaF/f6Znf0hO/WbuPefU1KSPE6YeSovKa3tuaCN3RX15WqveWKd0izjNLHmUWjdrV1OaenRXVoN766LwudmOUJHCrz577e78BwZeLR5e6lBBl3XV4emhk2SGAKRgTiGBZtqQfNtuq8fPgUjwAkIApKAIqAJBATCe44rHa3y1@jPuWDMFRnmsl9S6pbiKNU0QoWSs3/UvClf4XQejT9iQ@NpZS7k3EokEucHemBftD2eznMq9NAxRCjEcLBvrYt2@2M3gTxCp0Jk/G6bVlWT7T8A "Ruby – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 29 bytes ``` ⭆η⍘﹪ΣE851﹪↨Φθ¬﹪⁻⁻ξμιη¹X²Iλ³⁶φ ``` [Try it online!](https://tio.run/##NYvBDoIwEER/ZcOpTdbEUiAYb5p4w5BwJBwaRGlSqEJR/75uFQ/zdjIz2/Zqaq0y3peTHh2rHJ1boe6sRzioufsFrLCXxVhWLQMLZZSnIkJY07BjJ21cN7EHwtm6/77Q4zKvfCMMHEGTes6JglTaFz3FCEc1O2Y4/zYyI1zJ7r2va5FTL7Y7hFgIckmCkKVrJLbByYCUyljKBiFp/OZpPg "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` η Block size ⭆ Map over implicit range and join 851 Literal string `851` E Map over characters θ Data array Φ Filtered where ξ Data index ⁻ Minus μ Character index ⁻ Minus ι Outer index ﹪ Modulo η Block size ¬ Leaves no remainder ↨ ¹ Convert from base 1 ﹪ Modulo ² Literal `2` X Raised to power λ Current character I Cast to integer Σ Take the sum ﹪ Modulo ³⁶ Literal 36 ⍘ φ Convert to 0-z Implicitly print ``` At one point conversion from base 1 is used to take the sum in case the list is empty (in which case the conversion is zero but the sum is None). [Answer] # [Pyth](https://github.com/isaacg1/pyth), 55 bytes ``` KeQJm%sd256.TchQKsm@+."/9ª!"G%++@Jd%@Jhd32%@Jhhd2 36K ``` [Try it online!](https://tio.run/##K6gsyfj/3zs10CtXtTjFyNRMLyQ5I9C7ONdBW09J3/LQKn5pRSV3VW1tB68UVQevjBRjIxCVkWKkYGzm/f9/tKGFkY6CoYGljoKRoSGQZWKio2BmChUyNACxjEGEKVDSyNg4VkfBBAA "Pyth – Try It Online") ]
[Question] [ You are given an array **A** of **n** strictly positive integers, with **n ≥ 2**. Your task is to map each entry **Ai** to: * **1** if **Aj mod Ai** is odd for each **j** such that **1 ≤ j ≤ n** and **j ≠ i** * **2** if **Aj mod Ai** is even for each **j** such that **1 ≤ j ≤ n** and **j ≠ i** * **0** otherwise (mixed parities) ## Example For **A = [ 73, 50, 61 ]**, we have: * 50 mod 73 = **50**, 61 mod 73 = **61** → mixed * 73 mod 50 = **23**, 61 mod 50 = **11** → all odd * 73 mod 61 = **12**, 50 mod 61 = **50** → all even Therefore, the expected output is **[ 0, 1, 2 ]**. ## Rules * You may use any three distinct values (of any type) instead of **0**, **1** and **2** as long as they're consistent. *Please specify your mapping* if you're not using the one described in the challenge. * Should there be any doubt about that, [zero is even](https://en.wikipedia.org/wiki/Parity_of_zero). * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins! ## Test cases ``` [ 1, 2 ] --> [ 2, 1 ] [ 3, 4 ] --> [ 1, 1 ] [ 1, 2, 3 ] --> [ 2, 1, 0 ] [ 4, 4, 4 ] --> [ 2, 2, 2 ] [ 73, 50, 61 ] --> [ 0, 1, 2 ] [ 941, 459, 533 ] --> [ 1, 0, 0 ] [ 817, 19, 928, 177 ] --> [ 1, 2, 1, 1 ] [ 312, 463, 336, 729, 513 ] --> [ 0, 2, 0, 0, 0 ] [ 53, 47, 33, 87, 81, 3, 17 ] --> [ 0, 0, 0, 1, 0, 2, 0 ] ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~68~~ ~~67~~ 66 bytes -1 byte thanks to Mr. Xcoder -1 byte thanks to ovs ``` x=input() for j in x:k=sum(i%j%2for i in x);print(k<len(x)-1)+0**k ``` [Try it online!](https://tio.run/##HchLDkAwFEDRuVW8iaSlEvUJ8VmJGBJPeRoqqdVXGZ2bqx@zHJQ5Z3skfRvGg/k4YQUksI3qr3tnGK5h9l38L2/1iWSY6raJmOWJ5HEaRcq5AcpcQFEJyL21t5a@BcgKxhc "Python 2 – Try It Online") Returns `1,0,2` instead `0,1,2`. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes ``` %þœ-€0Ḃ‘Ṭ ``` Returns **[1, 1], [0, 1], [1]** instead of **0, 1, 2**. [Try it online!](https://tio.run/##PU67DcJADO2Zwg2dkeLzfUdBUUoalAXoUBp6aDJEBiANTZRBLoscdqSLZMnvPfs9@37r@0cp5@W3fi7bMDX5O2zPMc9TWV7C13eeR@nXUtoTQAuEYKDDHTOCrVh1BK7U4l6VBll1DYKnqiQrDuuS6Hy4IgUEEi2ZKCCE4xJJuPWSwuwRglEfHT6nnwQdIkTpUbJZA3Sh@wM "Jelly – Try It Online") ### How it works ``` %þœ-€0Ḃ‘Ṭ Main link. Argument: A (array) %þ Build the modulus table. œ-€0 Remove one 0 from each list of moduli. Ḃ Take the last bit of each. ‘ Increment, mapping 0 and 1 to 1 and 2. Ṭ Untruth; map each array to an aray of 1's at the specified indices. This yields: [1] if the array contains only 1's (all even). [0, 1] if the array contains only 2's (all odd). [1, 1] if the array contains 1's and 2's. ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 12 bytes ``` !G\o~tAws1=- ``` This uses `0`, `-1`, `1` instead of `0`, `1`, `2` respectively. [Try it online!](https://tio.run/##y00syfn/X9E9Jr@uxLG82NBW9///aAVTYx0FE3MdBWMgbQGkLQyBbB0FQ3OFWAA) Or [verify all test cases](https://tio.run/##JY0xCwIxDIV3f8Vzj2CatmkHB8HpZgfhPNBdcfDgNv96TVoI9OXlfa/v5/pqj3ab9tP981vP25dPh3a5thlMCFh2M4QQu3CHIF1H6tO1WiIdCZn7WqMFY6pmyggXVgKbUUMxoTp62dpiNlgkEzQ4wYNI/qn6hVDsLVYpjmL5Aw). ### Explanation ``` ! % Implicit input: row vector. Transpose into a column G % Push input again \ % Modulus, element-wise with broadcast. Gives a square matrix o % Parity: gives 1 for odd, 0 for even ~ % Logical negate: 0 for odd, 1 for even t % Duplicate A % All: gives 1 for columns that contain only 1 w % Swap s % Sum of each column 1 % Push 1 = % Is equal? Gives 1 if the column sum was 1, 0 otherwise - % Subtract, element-wise. Implicit display ``` [Answer] # Mathematica, ~~57~~ ~~49~~ 48 bytes ``` (s=#;And@@#.Or@@#&@OddQ@Rest@Sort[s~Mod~#]&)/@#& ``` This returns: * `False.True` for **0** (mixed) * `True.True` for **1** (all odd) * `False.False` for **2** (all even) [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7X6PYVtnaMS/FwUFZz78ISKo5@KekBDoEpRaXOATnF5VEF9f55qfUKceqaeoDZf@nOVSbGusomJjrKBgDaQsgbWEIZOsoGJrX/v@vW1CUmVcCAA) Here's a slightly longer alternative (49 bytes): ``` Sign[(s=#;Tr@Mod[s~Mod~#,2]&)/@#/.Tr[1^#]-1->-1]& ``` This one returns: * `1` for **0** (mixed) * `-1` for **1** (all odd) * `0` for **2** (all even) [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7PzgzPS9ao9hW2TqkyME3PyW6uA5I1inrGMWqaeo7KOvrhRRFG8Ypx@oa6trpGsaq/U9zqDY11lEwMddRMAbSFkDawhDI1lEwNK/9/1@3oCgzrwQA) [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~118~~ ~~114~~ ~~97~~ ~~92~~ ~~91~~ 86 bytes * Thanks to [Peter Cordes](https://codegolf.stackexchange.com/users/30206/peter-cordes) for bugfixing. * Saved ~~four~~ twenty-one bytes thanks to [Peter Cordes](https://codegolf.stackexchange.com/users/30206/peter-cordes); suggesting to use a different output value mapping; `[0 1 2] ~ [3 2 1]`. * Saved five bytes; using yet another mapping; `[0 1 2] ~ [  ]`. * Saved a byte; golfed `for(i=0;i<n;i++,putchar...` to `for(i=~0;++i<n;putchar...`. * Saved five bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat). ``` i,j,r;f(A,n)int*A;{for(i=~0;++i<n;putchar(r))for(r=0,j=n;j--;)r|=j-i?A[j]%A[i]%2+1:0;} ``` [Try it online!](https://tio.run/##fdLdaoMwFAfw6@0pDoWCWY9gEm3sUjfsd59BvChCN4W54bqrrnt1l491rI1ODhjw8Mv/JBb@U1G0bYkVNnLvpViTsj7cpfK4f228MvkK5GhUTmv59nEonneN1xCivzRJgFVSy8r3JWk@k8ovH9OsyodpVuZDNqL3gTy1L7uy9sjx9kaZkGZ5cgSKwKDzOZn9GdFbvXsDmPoPkAFDoJAPrnqJtObMmBwh7Ddnjkn/Nee/ORF4jzlH3pETIbhiz@bCmCGa6jEXXaauHnNpTKGGjwKEMe0yl44ZoL2CbnNlzEmoWsJoomTOHXPlmHrw/tnXxoypUDsrcsJitRDiwlxj6Jr2SC9u6mxu7L1T1RKO1QlwPkYQTCem/MfcYOTOzmzUv2nP5taYkf6ZhBYRYvWOVQSuAxtzi8I1bdlDYFZW5qn9Bg "C (gcc) – Try It Online") [Answer] # [Red](http://www.red-lang.org), 101 bytes ``` g: func[b][foreach n b[a: copy[]foreach m b[append a m % n % 2]sort a a: copy next a print unique a]] ``` [Try it online!](https://tio.run/##XY47DoMwEER7TjENfZY1GDhGWssFH0MoYogDUnJ6sigfQcp5b2a1wbXr2bUwdu1LdItvTG1NNwZXNRd41KYq0YzT09gvvG5wmpxvUUmIpRUjsfcxzAI@dXj32OIUBj9j8cNtcaisXd@ghyHZRL/EUBaI9ha88wrqr6EZ6QkZ2R0rFEGlBVLmQzcnDSpQJDlI64NiSqAyBnMGnciUjtNUPtNikWvkBJYD4tcX "Red – Try It Online") Returns `1 0` for mixed, `1` for odd and `0` for even ``` g: func[b] [ foreach n b [ a: copy [] foreach m b [ append a m % n % 2 ] sort a a: copy next a print unique a ] ] ``` [Answer] # JavaScript (ES6), 46 bytes ``` a=>a.map(A=>a.map(B=>d+=B%A%2,d=0)|!a[d+1]-!d) ``` Returns -1 (even), 1 (odd), and 0 (mixed). **How it works:** The `d` accumulator will be: 1. Zero if all even moduli. (`!a[d+1]` == false, `!d` == 1, `false - 1` == **-1**) 2. One less \* than the length of the array if all odd moduli. ( \* The accumulator includes an element modulused against itself, resulting in *one* even modulus.) (`!a[d+1]` == true, `!d` == 0, `true - 0` == **1**) 3. Two or more less than the length of the array if a mix. (`!a[d+1]` == false, `!d` == 0, `false - 0` == **0**) **Test cases:** ``` let f= a=>a.map(A=>a.map(B=>d+=B%A%2,d=0)|!a[d+1]-!d) console.log(f([ 1, 2 ] ) + ''); // [ -1, 1 ] console.log(f([ 3, 4 ] ) + ''); // [ 1, 1 ] console.log(f([ 1, 2, 3 ] ) + ''); // [ -1, 1, 0 ] console.log(f([ 4, 4, 4 ] ) + ''); // [ -1, -1, -1 ] console.log(f([ 73, 50, 61 ] ) + ''); // [ 0, 1, -1 ] console.log(f([ 941, 459, 533 ] ) + ''); // [ 1, 0, 0 ] console.log(f([ 817, 19, 928, 177 ] ) + ''); // [ 1, -1, 1, 1 ] console.log(f([ 312, 463, 336, 729, 513 ] ) + ''); // [ 0, -1, 0, 0, 0 ] console.log(f([ 53, 47, 33, 87, 81, 3, 17 ] ) + ''); // [ 0, 0, 0, 1, 0, -1, 0 ] ``` [Answer] # [J](http://jsoftware.com/), 27 20 bytes ``` [:<@~.@}:@\:"1~2||/~ ``` [Try it online!](https://tio.run/##VY6xCsJAEET7fMWQJgh6Zm/vbnOHwoFgZWWrnRiCjT8Q8@vnYpFEli3eDjM7r1KbpscxocEWLZLuzuB0vZzLLR3yZPIn5XuqabLjuJ/KpkL1fAxv9CBYzMBw@FN4QfebGYXhWwRaLtERnI/wvHJ1JKCIaDuQyOoTWbjAYA4QqyZambz2EJXQiQZoCQ1B@QI "J – Try It Online") Uses [1 0] [1] [0] instead of 0 1 2 ## Explanation: `|/~` - makes a table with remainders: ``` |/~ 73 50 61 0 50 61 23 0 11 12 50 0 ``` `2|` odd or even? : ``` 2||/~ 73 50 61 0 0 1 1 0 1 0 0 0 ``` `<@~.@}:@\:"1` - sort down, drop last element (always a zero), keep the ùnique elements and box each row: ``` <@~.@}:@\:"1~2||/~ 73 50 61 ┌───┬─┬─┐ │1 0│1│0│ └───┴─┴─┘ ``` [Answer] # [Ruby](https://www.ruby-lang.org/), ~~58~~ 56 bytes ``` ->r{r.map{m=r.shift;s=r.map{|e|e%m%2}.uniq.sort;r<<m;s}} ``` Returns **[0, 1], [1], [0]** instead of **0, 1, 2** (i.e. **[0]** for all even , **[1]** for all odd, and **[0, 1]** for mixed). [Try it online!](https://tio.run/##PU8xjoMwEOx5xYoonbECNhhEyCOuRS5yh1EogMQ2pzuB307WMkq1M7Mzs1q9fP/vfbMnN71qOt6f69hoah5Db2vTBGVTmzqP58zRZRpe1Mza1vp6HWvj3P5crIH4S9lFTwbai4R@1qB@1USgTQObuw7JhcDBx@FPdXHURoAWApkkHjECPCCvEWCBcJQ/G4GmHIuKNPCKo5fnFars8JepwEOoVFmJQIijPcVKXmCesYKAyHwmPTK5vy38ikCJs8RW5sMyklTdfx6wbnaD8OtptQ6S5AantW@tdLHb3w "Ruby – Try It Online") [Answer] # Perl, 38 bytes Includes `+3` for `-p` ``` #!/usr/bin/perl -p s/\d+/$@|=$_%$&%2+1for<$`$'>;$@/gee ``` Outputs 1 for all even, 2 for all odd, 3 for mixed [Answer] # [Clean](https://clean.cs.ru.nl), ~~95~~ ~~65~~ 63 bytes ``` import StdEnv ``` # ``` \l=[sum(removeDup[-1^(j rem i)\\j<-l|j<>i])\\i<-l] ``` [Try it online!](https://tio.run/##DcuxCoMwFIXh3ae40MWCDmKLDtrJDoVujomFEGOJ5EbRRCj02Xt7p/98w9HOKE@4jNEZQGU9WVyXLUAfxrs/qA9qC8kJJmhBulbsEdPN4HKYLq4iL17pDGywZynnJnffubnZgWEZQ9LyUcC1zOBSZVBya25d8M6gqGCgn56ceu@UP57UfbxCq/c/) As a lambda, taking `[Int]` and returning `[Int]`, mapping to: * `0`: mixed * `1`: all even * `-1`: all odd [Answer] # [Perl 5](https://www.perl.org/), ~~71~~ 69 + 1 (`-a`) = 70 bytes ``` map{//;$j=$s='';$j++-$i&&($s+=$_%$'&1)for@F;say$s?0|$s==$#F:2;$i++}@F ``` [Try it online!](https://tio.run/##DcrBCgIhFEDRXxF6aaE22iQzJNKs3PUN4aLAqJR5baL69V6u7lncep5vjuie6rvrPFwDYBCiQUoNmfMVoAxwWoLgdn0p8xQ9phfgwXzaGWAR91sPWcrvFIlcr9huUKxvHVtH26yYHX6lPnN5IOmj2xhrSKc/ "Perl 5 – Try It Online") [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 42 bytes ``` a->[[!s=vecsum([x%y%2|x<-a]),s>#a-2]|y<-a] ``` Returns `[0, 0], [0, 1], [1, 0]` instead of `0, 1, 2`. [Try it online!](https://tio.run/##LY39CoIwFMVf5WYICnfQPnQT0hcZ@2NERlAxtELBd193TRjs/M7OOQt@urNbiCP00bPB2sPcf6@X@fOs7FKupdiWM/Ouxnk4eibctiaMPoTHWnlgA4Tp/nqTLBIUMFa@rhGsBY4gwJEEiaCySh6CzKDwfzJoCjUnhJZn7hRlVdORK/e84RqBk9MJQ0LrfZ3TpGqpL2WLoEXq8L3TpL91ekIwdBtalakMztXxBw "Pari/GP – Try It Online") [Answer] # Java 8, ~~91~~ 89 bytes ``` a->{for(int z:a){int s=1;for(int y:a)s+=y%z%2;System.out.print(" "+(s<a.length)+(s<2));}} ``` * Using `truetrue` instead of `2` for even * Using `falsefalse` instead of `1` for odd * Using `truefalse` instead of `0` for mixed **Explanation:** [Try it online.](https://tio.run/##lZJBboMwEEX3PcUoUiRQJqjGgKGU3qDZZFl14RKSkhKDsJMqQZydDoQu2p0lW/J8@89/sn2UF7mum0Idd19DXkmt4VWWqnsAKJUp2r3MC9iMJcClLneQO6S/vYN0UxJ7mjS0kabMYQMKMhjk@qXb1@14EG5P0u3Ghc5Y@iteSdSr7Lq8Lf10e9WmOHn12XhNS7vOAhYrRz9LryrUwXy6Y@G7btr3Q3qPa84fFcXNqRPWiaCdraEGhwnuTqy83FHFN0zIHUO/n6gB/odWypl3/lo4BrYWSkFuawowsE8SHMNHjJitLwkYBmGCIbfmjJlAlmDix8iEsL5N5mMQceQ8QuETALMGCOlFBDXAWGDMkBNGP//EfvgB) ``` a->{ // Method with integer-array parameter and no return-type for(int z:a){ // Loop over the array int s=1; // Sum-integer, starting at 1 for(int y:a) // Inner loop over the array again s+=y%z%2; // Increase the sum by `y` modulo-`z` modulo-2 System.out.print(" " // Print a space +(s<a.length) // + "true" if the sum is smaller than the length of the array // (this means there is at least one even) +(s<2));}} // + "true" if the sum is still 1 // (this means all are even) ``` [Answer] ## Clojure, 82 bytes ``` #(for[R[(range(count %))]i R](set(for[j R :when(not= i j)](odd?(mod(% j)(% i)))))) ``` A complete example with output conversion: ``` (def f #(for[R[(range(count %))]i R](set(for[j R :when(not= i j)](odd?(mod(% j)(% i))))))) (->> [ 53, 47, 33, 87, 81, 3, 17] f (map {#{true} 1, #{false} 2, #{true false} 0})) ; (0 0 0 1 0 2 0) ``` ]
[Question] [ As a follow up to my previous challenge [Count to 20 with Words!](https://codegolf.stackexchange.com/questions/133564/count-to-20-with-words/), we will once again be using the word list from that challenge to perform another task. This time, you will be exclusively using: [https://github.com/Magic Octopus Urn/wordListsByLength/blob/master/10.txt](https://github.com/carusocomputing/wordListsByLength/blob/master/10.txt) To choose 26 different words, each starting with a unique letter, and output them in ascending order from A to Z. Here's a valid example: ``` aardwolves babbitting caravaning debilitate evaporator fantasized geographer hawfinches imbecility juvenility kalanchoes lamaseries malodorous nudibranch oligophagy pantywaist quarreling russetting scantiness teetotaler undercount voodooisms wentletrap xenophobic yeomanries zwitterion ``` --- This is an [aardwolf](https://en.wikipedia.org/wiki/Aardwolf), this is a [hawfinch](https://en.wikipedia.org/wiki/Hawfinch), this is a [kalanchoe](https://en.wikipedia.org/wiki/Kalanchoe), this is a [nudibranch](https://en.wikipedia.org/wiki/Nudibranch) and a [wentletrap](https://en.wikipedia.org/wiki/Wentletrap). --- # Rules * No reading directly from the repository, or any other loopholes. * You may select any 26 of the words provided [in the link](https://github.com/carusocomputing/wordListsByLength/blob/master/10.txt). + You choose words and these are the words your program should output every time. * One word beginning with each of the following letters must be selected: + `[a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z]` * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), lowest byte-count wins. --- Any other suggestions for spin-offs using the word lists? Also, feel free to steal my word-lists and make challenges. [Answer] # [Bubblegum](https://esolangs.org/wiki/Bubblegum), ~~100~~ 99 bytes ``` 00000000: 45ce 4502 0420 0800 c0bb bfb4 3bc1 adcf E.E.. ......;... 00000010: 6f23 b7a1 910b 63b3 0016 84da 40d4 fd41 o#[[email protected]](/cdn-cgi/l/email-protection) 00000020: 344c 2b81 e824 e09f 9e19 e4e9 8d3a 1353 4L+..$.......:.S 00000030: 3f7c c3fc 59b8 b732 5b07 62e7 c383 4fcc ?|..Y..2[.b...O. 00000040: 4d5f 88c5 bd60 6f44 8c8d b87d 215e 78c3 M_...`oD...}!^x. 00000050: 359e ec4d 360c bd4a 94e2 6e25 e06f ef43 5..M6..J..n%.o.C 00000060: d286 17 ... ``` [Try it online!](https://tio.run/##hdC7TgQxDAXQnq@4CKiQrDycTLIUgGAbxIqCCiEB4zxogK1WooBvHzz7qLGUNJZPriMbkY/2vvmcJrOvBTiUppdxMOwMTDIGxYhAujC8FIuxlg4saUkE2taFnqOdYNWI3XnIMFpkawTRi4d2IhLXEWwqo1e2wPpkni5b44roem84NTxzgZNk0ZJjNJM7crMZjVtGqn6E9cEDfH9OdLrLQQt63Bt@NvpQUHwvCFmSJvIOQcyA6NqgjeTBvRTg8ofoicg9kyjycNiF5/@ooSOlEiA1Gl2NGamkCklDhbOhYUhFc6xedfRtfav37/HL98EIc46QG1rhCh9NUYhHZG4Osbmgq8WO1lmNQLSKRHdEX2e0ppu9EdWoLkXYAf@Wvj9Nfw "Bubblegum – Try It Online") Output: ``` artinesses businesses cozinesses dozinesses easinesses fastnesses gastnesses hazinesses ickinesses jokinesses kindnesses lazinesses mazinesses nosinesses oozinesses pastnesses queasiness rosinesses sexinesses tininesses uglinesses vastnesses wilinesses xanthomata yeastiness zaninesses ``` The words were again selected with simulated annealing: ``` from __future__ import print_function import math import random import zopfli.zlib wordlists = [[] for n in range(26)] for word in open('wordListsByLength/10.txt', 'rb').read().splitlines(): wordlists[ord(word[:1]) - ord('a')].append(word) words = [random.choice(wordlist) for wordlist in wordlists] temperature = 1. score = 9999 best = score while True: old_score = score n = random.randrange(len(wordlists)) old_word = words[n] words[n] = random.choice(wordlists[n]) score = len(zopfli.zlib.compress(b'\n'.join(words)) - 6 if score > old_score and random.random() >= math.exp((old_score - score) / temperature): words[n] = old_word score = old_score else: temperature *= .9999 if score < best: best = score print(best, repr(b'\n'.join(words))) ``` [Answer] ## JavaScript (ES6), 168 bytes For each starting letter, outputs either the first word ending in *-inesses* or the first available word. ``` _=>`ash0bus0coz0doz0eer0foz0gor0hom0ink0jok0kaiserdoms log0mir0nos0ooz0pun0quackeries ros0siz0tin0ugl0vacantness wir0xanthomata yardmaster zan0`.split`0`.join`inesses ` ``` ### Demo ``` let f = _=>`ash0bus0coz0doz0eer0foz0gor0hom0ink0jok0kaiserdoms log0mir0nos0ooz0pun0quackeries ros0siz0tin0ugl0vacantness wir0xanthomata yardmaster zan0`.split`0`.join`inesses ` o.innerHTML = f() ``` ``` <pre id=o></pre> ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 69 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) *This is the naive approach it may be improvable by some clever ticks* ``` “6)ọʋtL⁺%ḍʠ9ƲȮṆ'ṫZpɲṇḃb7ṗ³ðʠ©q€©[ẠṾṠɠ+ȯ!?^_iṘ©ð⁴ạ'8œÐṣTP³ḃXŻDƭƇM⁽H>Ỵ» ``` **[Try it online!](https://tio.run/##AYsAdP9qZWxsef//4oCcNinhu43Ki3RM4oG6JeG4jcqgOcayyK7huYYn4bmrWnDJsuG5h@G4g2I34bmXwrPDsMqgwqlx4oKswqlb4bqg4bm@4bmgyaAryK8hP15faeG5mMKpw7DigbThuqEnOMWTw5DhuaNUUMKz4biDWMW7RMatxodN4oG9SD7hu7TCu/// "Jelly – Try It Online")** (Assumes that "Valid separators are ASCII-printable non-alphabetical characters (even numbers, don't care)" holds from the previous challenge) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 49 bytes ``` “J9,⁹FṾ»ŒVŒlµL=⁵µÐf ¢Ḣ€OIT+“¢&ĠUṗɓṃ€~ƙṂ’D¤;@0‘ị¢Y ``` [Try it online!](https://tio.run/##AWMAnP9qZWxsef//4oCcSjks4oG5RuG5vsK7xZJWxZJswrVMPeKBtcK1w5BmCsKi4bii4oKsT0lUK@KAnMKiJsSgVeG5l8mT4bmD4oKsfsaZ4bmC4oCZRMKkO0Aw4oCY4buLwqJZ//8 "Jelly – Try It Online") (Takes about 22 seconds on TIO) Outputs: ``` aardwolves babbitting cabalettas daftnesses earlywoods fabricants gadgetries habiliment iatrogenic jaborandis kaiserdoms labialized macadamize naboberies oafishness pacemaking quackeries rabbinical sabadillas tabernacle ubiquinone vacantness wadsetting xanthomata yardmaster zabaglione ``` **How it Works** ``` “J9,⁹FṾ»ŒVŒlµL=⁵µÐf - all length 10 Jelly dictionary words “J9,⁹FṾ» - literal string "dictionary.long" ŒV - Python eval: get list of long words Œl - set all to lowercase µ µÐf - filter keep only those which meet: L - length = - equal to ⁵ - 10 ¢Ḣ€OIT+“¢&ĠUṗɓṃ€~ƙṂ’D¤;@0‘ị¢Y - main link ¢ - length 10 Jelly dictionary words from helper Ḣ€ - first letter of each. O - ord: character values I - difference between consecutive elements T - indices of nonzero elements (gets indices of first word starting with each letter) + - add “¢&ĠUṗɓṃ€~ƙṂ’D¤ - the list [2,0,5,9,1,3,3,1,1,6,1,2,0,0,0,0,2,1,1,1,0,3,1,8,0] ;@0 - append 0 to beginning (golfable?) ‘ - increment each element ị¢ - index into the above length 10 words Y - join by newlines ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~256~~ ~~231~~ 220 bytes ``` i=97 for w in"uto ibli aco emo ntom utur laci olo deo ackfishes ymo exic alac omo cean alyn uaternion eno eri omo rban eno avelessly ero outhfully witterion".split():print chr(i)+(w+["graphy","ology"][w[3:]>''])[:9];i+=1 ``` Saved 36 bytes thanks to Jonathan Allan, who did most of the hard work for this (I just found the words :P) [Try it online!](https://tio.run/##JY7BasMwDIbvewrhSxMyBmsPoxndi4QcXFepxVwp2PIyP30muuOn7/tBa9MofNx3upw/XhbJsAGxqypA10TggwA@BFjlAVVrhuQDgSSBG4rp74VKxALNIvylAN4CEKOAno0aQ/WKmUkYkK3K9PT56v8P/gcTlpKaKQGpGpeajDZS29nMvZU1kXb9uGZihRBzR/3QbcPk7tmvsblXZy/dm5unbTqN89fhMPfTeJ4/abi87/sf "Python 2 – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~169~~ 107 bytes ``` `a® ¾n ¯g ¸w e fox g z jo ê] ¦m µt nos oil po qua×@i c  x d ugl void °r xopb yeÇ z`·£`ê£`hX ``` [Try it online!](https://tio.run/##DcyxDsFQGAbQ2ORbPYd38Awmi6SlVbep/hetXt0kgkFEItJJSCQGAxZhMnx9sKvbmU7o6sRax@UD/MXgMwC/GXyuMBCDgDvwmAOhoLxz262BtxH4ThDLFKIiaME4dcuipcBzH7wY8OAhDSLMRHngawLDhWgWPcz9cl3nCTmXDj@8OtxU7b5Radixttn@Aw) I [wrote a program](https://tio.run/##ZZBBa4NAEIXv8yseksNKQJperdBLeyiBQkNFECnrZjc1Na7ZXUtJ8bfbVaylBOYwzPvmvWGOvHXDcH4BvZ7usyQzQdVIa6UNNngWGWqsd@ushxc9dDrvIHo0lCapejt49e7Wa8cNBK3okxs8Vg2vt5V1SJAXMZHSho1CjapBGn4TsJXOSfPw5SnrMcVrK2M/9/VLq5FevKYtoFJsGeWqyG8KJAnSvB7bmblyd6abzIF@SuhpNAL7j81XzCZLStR29p2NCWE87fZET/5jke5c27m/cyKrjWNhSKthCATt6aI1SeIkuKOLLA2nkkqtP2ivD8EP) that helps me optimize the compression. It sorts a list by its [shoco](http://ed-von-schleck.github.io/shoco/) compression size. [Answer] # [Japt](https://github.com/ETHproductions/japt), 85 bytes ``` 97 `...`£`...`hXiU°d}R ``` where the two pairs of backticks represent strings of seemingly random printable and unprintable characters. [Try it online!](https://tio.run/##DcYxCsIwAEbhVd7qYYrXEATHBC0aW2ghOig4iMUWRBdHEQpdRdzc/xwsZnh8b2PrbYyTDKMPugG6pO5YFgVVQa5TekvlwdXswtnria441LEqsQm17MPD6Uce2pFeqDEajN6H0IzVe7Oeu5m@y@M0xj8 "Japt – Try It Online") Output: ``` achinesses boninesses cozinesses dozinesses easinesses fozinesses gorinesses hazinesses ickinesses jokinesses keennesses lazinesses mazinesses nosinesses oozinesses pipinesses quadrantes riminesses sizinesses tininesses uglinesses vainnesses warinesses xylotomies yeomanries zaninesses ``` ### Explanation The basic technique is: ``` 97 Set U to 97 `ch on ...`£ }R Map each line X in this multiline string to: U°d Take U.toCharCode() and increment U. ["a", "b", "c", ...] Xi Prepend this to X. ["ach", "bon", "c", ...] `cozinesses`h Overwrite this onto the beginning of "cozinesses". ["achinesses", "boninesses", "cozinesses", ...] £ }R Rejoin with newlines and implicitly output. ``` I found `cozinesses` by starting with `nesses` as some other answers have used and repeatedly finding the previous letter that appeared the among the most of the 26 letters. Since greedy techniques are not often optimal, I later wrote a script to find the real optimal word: ``` alphabet="abcdefghijklmnopqrstuvwxyz".split``; wordlist=alphabet.map(x=>[]); document.body.innerText.split`\n`.slice(0,-1).map(x=>wordlist[x.charCodeAt()-97].push(x)); f=(q="",n=7,s=0,words=wordlist,z=n&&alphabet.map(x=>[x+q,words.map(y=>[y=y.filter(z=>z[n]==x),t+=0 in y][0],t=0),t]))=>n?z.filter(x=>x[2]>=Math.max(1,...z.map(x=>(x[2]-2)*2/3))).map(x=>f(x[0],n-1,s+26-x[2],x[1])).sort((a,b)=>a[1]-b[1])[0]:[q,s]; console.time("find optimal word"); console.log(f()); console.timeEnd("find optimal word"); ``` (I don't care that it's incredibly ugly. This is how PPCG has taught me to code :P Don't worry, I don't do this in production.) Anyway, when run in the browser console on [the 10-letter word list](https://raw.githubusercontent.com/carusocomputing/wordListsByLength/master/10.txt), this outputs ``` [ "ozinesses", 57 ] ``` The `57` being the number of letters that would have to appear in the multiline string. It also took about 17 seconds on my computer, so be patient when you run it. By replacing the `f=` line with ``` f=(q="",n=9,s=0,words=wordlist,z=n&&alphabet.map(x=>[x+q,words.map(y=>[y=y.filter(z=>z[n]==x),t+=0 in y][0],t=0),t]))=>n?[for(x of z.filter(x=>x[2]>=Math.max(1,...z.map(x=>(x[2]-2)*2/3))))for(y of f(x[0],n-1,s+26-x[2],x[1]))y].sort((a,b)=>a[1]-b[1]).filter((x,i,a)=>x[1]<=a[0][1]+20):[[q,s]]; ``` you can get all suffixes within 20 chars of the optimal one. (Change the `20` at the end to something else to adjust this. Note: this function probably only works in Firefox.) You can find a list of all suffixes under 100 [here](https://gist.github.com/ETHproductions/5eade24e3741e7252d0c04d572014667). Anyway, from there on it's just a task of finding the word for each letter of the alphabet that has the longest suffix in common with `ozinesses`. I wrote a [Japt script](http://ethproductions.github.io/japt/?v=1.4.5&code=cVIg80BYZyA9PVlnfSBtX21AW1gsWGFAWCE9IiNvemluZXNzZXMiZ1l9XX0gckBYZ0ogPllnSiA/WTpYZ0ogPFlnSiA/WDpPY1hnIHMxWGdKICsxICBsID5PY1lnIHMxWWdKICsxICBsID9ZOlh9W0FdfSBtX09jWmcgczFaZ0ogKzEKVWNVcVIgbCArMjI=&input=IiIgLVI=) to do this, as well as compress the necessary prefixes for me and tell me how long the resulting program will be. (You'll have to manually paste the word list between the quotation marks though.) This explanation was probably somewhat confusing, so please feel free to ask any questions you may have. [Answer] # [Bubblegum](https://esolangs.org/wiki/Bubblegum), ~~110~~ 106 bytes Hexdump: ``` 0000000: 45cc 4116 8240 0c83 e1bd b72c 50a1 0ed3 E.A..@.....,P... 0000010: 2015 454e 2fcf 4727 bb6f 91fc 1293 b946 .EN/.G'.o.....F 0000020: 68dc 3aec c91e 4772 2055 2279 e776 94aa h.:...Gr U"y.v.. 0000030: 1727 695b f392 7ca0 b1b8 f445 573b 39f3 .'i[..|....EW;9. 0000040: 5679 7344 1236 2717 169e 5b2b acdc 0663 VysD.6'...[+...c 0000050: 2f72 1b5b e10d 1b2e 7ed8 ddd5 b14c e84e /r.[....~....L.N 0000060: 7e15 55fc df3d c473 f003 ~.U..=.s.. ``` [Try it online!](https://tio.run/##XdC7SkNBEAbg3qf4sUmhTPa@ZyOCgjGNBJtokerMXlRQhIQIAcmrH@ck2jjFsM1@88/wjvm9vuw@hkGdagbnc4bTOqAzTkHlzqJqLuBoMrzqNVQtFpjTLdENjXX5KO3sCGghjNJeHFdhWm5w0UQwh4akW4Y2yYKTCwBovpzSYkKfR@b@RBghQlcybF8zctJViGiE9R7GxIQaY0ByfQ@80kx@LjZYne/p6y@FFUKPY0PyjGaTQcy9Amvu0Jzz8NEybGqyCE3e1kTfY4L581X6JZwQPsiwaJ2T0DbARB2hQ6rwbBh9lowqBCGe9ts7ChMR1hfS8onw4y2aJNcsKapWRV6mItbSoZTiJY/LqJ1cCtMNrccIh7E90PJEBCFilXN6L6crzRZkFy2a7Ij/daAV0TVtiYbhBw "Bubblegum – Try It Online") Prints: ``` ashinesses boxinesses cozinesses dozinesses easinesses foxinesses gamenesses hazinesses inkinesses jokinesses knackeries lamenesses mazinesses nosinesses oilinesses pokinesses quackeries rosinesses samenesses tamenesses uglinesses voidnesses wilinesses xenophobes yeomanries zaninesses ``` [Answer] # Javascript (ES6), 163 bytes ``` _=>`ach bon c d eas f gam ha ick jok keen la ma nos o pip quackeri rac si tid ugl vain war xenogami yeomanri zan`.replace(/.+/g,s=>s+"-ozinesses".substr(s.length)) ``` ``` f= _=>`ach bon c d eas f gam ha ick jok keen la ma nos o pip quackeri rac si tid ugl vain war xenogami yeomanri zan`.replace(/.+/g,s=>s+"-ozinesses".substr(s.length)) o.innerText = f() ``` ``` <pre id=o> ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~168~~ 166 bytes ``` i=97 for w in"ch on ag ew as ox am az ck ok azatsk ac at os il ip uacker ac ex id gl agilit ar enogam eomanr an".split():print"%c%si%ses"%(i,w,"ness"*(len(w)<3));i+=1 ``` **[Try it online!](https://tio.run/##FYzbCsIwEETf/YohEGi0COqDeOnHLDG2S@OmdCOp/nyNTzPMGc70yUOS47pydzlvnmlGAYvxA5KAeoQCUqQF9AJ94UeksRbKWsODMpKCI3jCm/wY5v8aFvADfawCjpxBM4KkvipCepHUj5i9ThU17jrNLNlYb5WtBjW24ba0RoKq2TYxSFPc/eTcjXfdYV1/ "Python 2 – Try It Online")** ### How? Initialises `i` to `97` (the ordinal of the character `a`) then loops through a list formed by `split`ting a string at spaces forming and `print`ing the words, incrementing `i` as it goes. Most of the entries, `w`, in the list are of length two, these are words that start with the alphabetic letter and end in `inesses`, i.e. of the form: `chr(i)+w+'inesses'`. The entries of length 6 are of the form: `chr(i)+w+'ies'` This means a formatting may be used to prepend the alphabetic letter and add an ending with the `'ness'` inserted like `'i'+?+'es'` when `w` is short like so: `"%c%si%ses"%(i,w,"ness"*(len(w)<3))` - %c converts `i` to a character; the two `%s` insert `w` and `"ness"*(len(w)<3)`, where the latter is `"ness"` if `w` is short or `""` if `w` is long. [Answer] # [SOGL V0.12](https://github.com/dzaima/SOGL), 66 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) ``` "⅟μ█X§¡Ψ}|μ⁾k,²9γ↑č─[╝B4mh|c↑′ρ╤τnE╗Ζ±$ņ¦Pγ9¬oΘ′`║F→█#▲xpņRe└ωηηƨ‘ ``` [Try it Here!](https://dzaima.github.io/SOGLOnline/?code=JTIyJXUyMTVGJXUwM0JDJXUyNTg4WCVBNyVBMSV1MDNBOCU3RCU3QyV1MDNCQyV1MjA3RWslMkMlQjI5JXUwM0IzJXUyMTkxJXUwMTBEJXUyNTAwJTVCJXUyNTVEQjRtaCU3Q2MldTIxOTEldTIwMzIldTAzQzEldTI1NjQldTAzQzRuRSV1MjU1NyV1MDM5NiVCMSUyNCV1MDE0NiVBNlAldTAzQjM5JUFDbyV1MDM5OCV1MjAzMiU2MCV1MjU1MUYldTIxOTIldTI1ODglMjMldTI1QjJ4cCV1MDE0NlJlJXUyNTE0JXUwM0M5JXUwM0I3JXUwM0I3JXUwMUE4JXUyMDE4) A simple dictionary compession with the problem that no word that starts with X was in SOGLs dictionary, so I compensated with xenotropic - tropic was in the dictionary. And I needed to add the starting quote because otherwise the parser thought that `[` started a loop :/ [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 84 bytes ``` UOχ²⁶”m⌈⎚∧³δ¤↶””|↖⧴=P“⪪šl¢‘υKBSAD ⁶⁸ςz↧\–~⎇V▷–ê"℅ ž⟲‹‹⮌0Bff5Y⪪E?Þ¹@)⟦£δT⪪⌕↙]\RZ_Q‹″” ``` [Try it online!](https://tio.run/##FY47CsIAEESvInZ2NpaC2Np4AEVEEAtFsLSKolEwCCIGFE3wG0ihmMRPZNOsvbnDXGCPEBOYaob3mEar3mt06@0oEnoI3cIJOxg8oew60KaYbzC12P15fIKatHEk2ELVYXn5Mi9h27xp84EX4bhUFHKF9kKnVOIYvMNhH6pVYV0CA/OJ0BP6i/WvncZonGIDpsMzKD6uWrbYbOaE/FgodBYyvwb7hQzMCx9/npAXD9BWUNfVipAj9KkJ3RNWceNTUfQH "Charcoal – Try It Online") Uses @HermanLauenstein's wordlist, but I saved one byte because I can miss out the `f`. For once, somewhat competitive even in in verbose mode, which is only 166 bytes. [Try it online!](https://tio.run/##FYwxFoJADESv4tsKChoLr6EHSBPWCJFlgruAyuXXWGRekpn5ceQcjVOt1z4ZhiaezpdTeNihkFKkhPaWFWsTOI6E3kCIhDtBuJAfA8@EkQkaJ8LTXCYRN5L/Zh@Y54yw6EJ4bRwnyUrI7Jjiy6oO24ZE2Fm99@ZM@AjMyW5/xWbGv3EwQltr7fbalfQD "Charcoal – Try It Online") ``` Oblong(c 26 "fozinesses")Print("ach\nbon\nc\nd\neas\n\ngam\nha\nick\njok\nkeen\nla\nma\nnos\no\npip\nquackeri\nrac\nsi\ntid\nugl\nvain\nwar\nxenogami\nyeomanri\nzan") ``` ]
[Question] [ # Background The *parity of a permutation*, [as defined by wikipedia](https://en.wikipedia.org/wiki/Parity_of_a_permutation), is as follows: > > The sign or signature of a permutation σ is denoted sgn(σ) and defined as +1 if σ is even and −1 if σ is odd. > > > The sign of a permutation can be explicitly expressed as > > > sgn(σ) = (−1)^N(σ) > > > where N(σ) is the number of inversions in σ. > > > Alternatively, the sign of a permutation σ can be defined from its decomposition into the product of transpositions as > > > sgn(σ) = (−1)^m > > > where m is the number of transpositions in the decomposition. > > > For those of you who are not fond of Greek alphabet soup in their math, I'll try and simplify the definition a bit with an example (also stolen from wikipedia). ### Example Consider the input array `{1, 2, 3, 4, 5}`, and a permutation of it, let's say, `{3, 4, 5, 2, 1}`. In order to get from the original array to its permutation, you must swap indices `0` and `2`, `1` and `3`, then `2` and `4`. Although this is not a unique solution, the parity is well-defined so this works for all cases. Since it requires 3 swaps, we label this permutation with an `odd` parity. As you might expect, a permutation that requires an even amount of swaps is said to have an `even` parity. # Challenge Your challenge is to write a program in as few bytes as possible to determine the parity of a permutation. Your program or function must: * Accept as arguments, two input arrays (or strings) representing a set before and after a permutation. * Return or print the character `e` for even or `o` for odd, given the permutation. * Should assume that all indices in the arrays or strings have unique values. ### Test Cases Assuming you declared a function named `f`: ``` f([10], [10]) == "e" f([10, 30, 20], [30, 20, 10]) == "e" f([10, 30, 20, 40], [30, 20, 40, 10]) == "o" ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest program in bytes wins! [Answer] # Jelly, ~~13~~ 12 bytes ``` żṗ2</€⁺Sị“oe ``` [Try it online!](http://jelly.tryitonline.net/#code=xbzhuZcyPC_igqzigbpT4buL4oCcb2U&input=&args=WzEsIDIsIDMsIDQsIDVd+WzMsIDQsIDUsIDIsIDFd) ### How it works ``` żṗ2</€⁺Sị“oe Main link. Arguments: A, B (lists) ż Zip A with B. Yields an array of pairs [x, σ(x)]. ṗ2 Generate all pairs [[x, σ(x)], [y, σ(y)]]. </€ Reduce each pair by </€. This maps [[x, σ(x)], [y, σ(y)]] to [x < y, σ(x) < σ(y)]. ⁺ Repeat the previous link, i.e., execute </€ once more. This maps [x < y, σ(x) < σ(y)] to ((x < y) < (σ(x) < σ(y))), which is true if and only if x > y and σ(x) < σ(y). S Sum. This counts the number of inversions. ị“oe Retrieve the letter at the corresponding index. Indexing is 1-based and modular, so an odd sum retrieves the first letter, an even sum the second. ``` [Answer] # [MATL](https://esolangs.org/wiki/MATL), ~~17~~ 16 bytes *1 byte removed thanks to a suggestion by Dennis* ``` 2$St!<Rz2\'oe'w) ``` This works in [current version (15.0.0)](https://github.com/lmendo/MATL/releases/tag/15.0.0) of the language. [**Try it online**!](http://matl.tryitonline.net/#code=MiRTdCE8UnoyXCdvZSd3KQ&input=WzEgMiAzIDQgNV0KWzMgNCA1IDIgMV0) ### Explanation This uses the definition of parity in terms of inversions. An inversion is a pair of elements in the second array that are in the "wrong" order compared with the first array. Since the first array need not be sorted, we first sort it and the same rearrangement needed for that sorting is applied to the second array. Then an inversion corresponds to a pair of elements that is not increasing in the second array. Note also that the two input arrays can be swapped and the result is the same. So it's not important which array is considered to be the "original" and which the "permuted". ``` 2$S % implicitly take two row vectors. Sort second and apply the indices % of that sorting to the first t! % duplicate. Transpose into column vector < % true for elements of the column vector that exceed those of the % row vector. Gives a 2D array with all pairs of comparisons R % keep only upper triangular part of that array z % number of nonzero elements. This is the number of inversions 2\ % parity of that number: gives 0 or 1 'oe'w % push string 'eo' below the top of the stack ) % apply index to produce 'e' or 'o'. An index 1 refers to the first % element, whereas 0 refers to the last. Implicitly display ``` [Answer] # Octave, ~~56~~ 52 bytes It seems nobody is using this approach so far: Basically I'm just using the determinants of the corresponding permutation matrices. The expression `det(eye(nnz(a))(a,:))` returns the determinant of the permutation matrix defined by the vector `a`. Then it is just a matter of extracting the right character from the string, depending on the result. ``` p=@(v)eye(nnz(v))(v,:);@(a,b)'ole'(det(p(a)*p(b))+2) ``` [Answer] ## Haskell, 58 bytes ``` k%l|m<-zip k l=cycle"eo"!!sum[1|(a,b)<-m,(c,d)<-m,a<c,b>d] ``` Usage: ``` *Main> [8,3,5]%[5,3,8] 'o' ``` Same method as [my Python answer](https://codegolf.stackexchange.com/a/75856/20260). proud haskeller saved a byte with `cycle`. Alternative from Wheat Wizard for 58 bytes (56 by modern convention of removing `f=`): ``` g m=cycle"eo"!!sum[0|(a,b)<-m,(c,d)<-m,a<c,b>d] f=(g.).zip ``` [Answer] ## Python 2, 68 bytes ``` lambda*M:"eo"[sum(a<b<M>A>B for a,A in zip(*M)for b,B in zip(*M))%2] ``` Usage: ``` >>> f=lambda*M:"eo"[sum(a<b<M>A>B for a,A in zip(*M)for b,B in zip(*M))%2] >>> f([8,3,5],[5,3,8]) 'o' ``` Counts the number of inversion pairs of two zipped lists, i,e. values `(a,A)` and `(b,B)` from each list at the same index with `a<b` and `A>B`. These comparisons are combines as `a<b<M>A>B`, using the property that the list `M` is greater than any number. The sum is then taken modulo 2 and turned into `e` or `o`. [Answer] ## JavaScript (ES6), 73 bytes ``` (a,b)=>"eo"[r=0,g=a=>a.map((e,i)=>a.slice(i).map(d=>r^=d<e)),g(a),g(b),r] ``` Since we're only interested in the parity, any duplicate transpositions simply cancel out. Conveniently JavaScript's array subscripts are not multidimensional. [Answer] # Mathematica, 77 bytes ``` If[Mod[Plus@@Length/@(Join[{0},#]&)/@PermutationCycles[#][[1]],2]==0,"e","o"]& ``` I agree! [Answer] # Mathematica, 31 bytes ``` If[Tr[Signature/@{##}]==0,o,e]& ``` > > Signature[list] > gives the signature of the permutation needed to place the elements of list in canonical order > > > We can reorder one list to the other, by first reordering one list to any order (in this case the canonical order) and reorder this list to the final list. The sign of the overall permutation is even, iff the signs of the two sub-permutations are equal. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 13 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` øDδ›Æ0›˜O„eoè ``` [Try it online](https://tio.run/##yy9OTMpM/f//8A6Xc1seNew63GYAJE/P8X/UMC81//CK//@jDXWMdIx1THRMY7miwTSQbxgLAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWXC/8M7XM5tedSw63CbAZA8Pcf/UcO81PzDK/7r/I@OjjY0iNUBEbE6CiCOjrGBjhFICEzroEvomCDkTJCkdYx0jHVMdExBkiAayDeMjY0FAA). Or alternatively: ``` øãε`›`›}O„eoè ``` [Try it online](https://tio.run/##yy9OTMpM/f//8I7Di89tTXjUsAuEa/0fNcxLzT@84v//aEMdIx1jHRMd01iuaDAN5BvGAgA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWXC/8M7Di8@tzXhUcMuEK71f9QwLzX/8Ir/Ov@jo6MNDWJ1QESsjgKIo2NsoGMEEgLTOugSOiYIORMkaR0jHWMdEx1TkCSIBvINY2NjAQ). Both ports of [*@Dennis*' Jelly answer](https://codegolf.stackexchange.com/a/75869/52210), so make sure to upvote him as well! **Explanation:** ``` ø # Zip to pair the values in the two (implicit) input-lists together D # Duplicate this list of pairs δ # Apply double-vectorized with the two lists: › # > check # (e.g. [a,b] and [c,d] → [a>c,b>d] Æ # Reduce each inner-most pair by subtracting: [a>c,b>d] → (a>c)-(b>d) 0› # Check if it's positive: (a>c)-(b>d)>0 O # Sum these checks together è # Modular 0-based index it into „eo # string "eo" # (which is output implicitly as result) ø # Same as above ã # Cartesian product with itself to create pairs of pairs ε # Map over each pair of pairs: ` # Pop and push both pairs to the stack › # [a,b] and [c,d] → [a>c,b>d] ` # Pop these values to the check again › # (a>c) and (b>d) → (a>c)>(b>d) } # Close the map O„eoè # Same as above, including implicit output ``` Minor note: Jelly uses 1-based indexing and 05AB1E uses 0-based, which is why his string is `"oe"` and mine is `"eo"`. ]
[Question] [ This problem is from [Five programming problems every Software Engineer should be able to solve in less than 1 hour](https://blog.svpino.com/2015/05/07/five-programming-problems-every-software-engineer-should-be-able-to-solve-in-less-than-1-hour) which itself is an interesting read. The first few problems are trivial, but the fourth one can be a bit more interesting. > > Given a list of integers separated by a single space on standard input, print out the largest and smallest values that can be obtained by concatenating the integers together on their own line. > > > For example: Input: ``` 5 56 50 ``` Output: ``` 50556 56550 ``` Various points of order: * The order of the results are smallest then largest. * *Only* the smallest and largest values may be printed out (iterating over all the variations and printing them out isn't valid). * There will always be two or more integers in the list. * It is possible for the largest and smallest results to be the same. In the case of input `5 55`, the number `555` should be printed twice. * The integers are not necessarily distinct. `5 5` is valid input. * Leading `0`s on integers are ***not*** valid input. You will ***not*** need to account for `05 55`. As this is code golf, shortest entry wins. [Answer] # CJam, ~~14~~ 13 bytes ``` qS/e!:s$(N@W= ``` Pretty straight forward. This is how it works: ``` qS/ e# Split the input on spaces e! e# Get all permutations of the input numbers :s e# Join each permutation order into a single string $ e# Sort them. This sorts the strings based on each digit's value (N@W= e# Choose the first and the last out of the array separated by '\n' ``` [Try it online here](http://cjam.aditsu.net/#code=qS%2Fe!%3As%24(N%40W%3D&input=5%2056%2050) [Answer] # Pyth, 14 13 bytes ``` hJSmsd.pcz)eJ ``` Generates all permutations and sorts them, printing the first and last element. [Answer] # Python 2, ~~104~~ 99 bytes Yep. ``` from itertools import*;z=[''.join(x)for x in permutations(raw_input().split())];print min(z),max(z) ``` Edit: thanks to xnor for -5 bytes! [Answer] # Mathematica, ~~64~~ 58 bytes ``` Print/@Sort[""<>#&/@Permutations@StringSplit@#][[{1,-1}]]& ``` This defines an unnamed function taking a string and printing the two lines. It's pretty straightforward as the others: get all permutations, join them together, sort them and print the first and last result. Six bytes saved thanks to alephalpha. [Answer] # JavaScript (ES6) ~~54 72~~ 85 ~~That's easier than it seems. Just sort them lexicographically. The good news is: that's exactly how plain javascript sort works.~~Well ... no, that's wrong ... still a (more convoluted) lexicograph compare can do the job. Note: having a and b numeric, a+[b] is a shortcut for a+''+b, as we need a string concatenation and not a sum. Note 2: the newline inside `` is significant and must be counted **Edit** Don't argue with a moderator (...just kidding) **Edit2** Fixed I/O format using popups (see [Default for Code Golf: Input/Output methods](http://meta.codegolf.stackexchange.com/a/2459/21348)) ``` // Complete program with I/O // The sorting function is shorter as input are strings alert((l=prompt().split(' ')).sort((a,b)=>a+b>b+a).join('')+` `+l.reverse().join('')) // Testable function (67 chars) // With an integer array parameter, the sorting function must convert to string F=l=>(l.sort((a,b)=>a+[b]>b+[a]).join('')+` `+l.reverse().join('')) ``` **Test** In Firefox / FireBug console ``` F([50, 2, 1, 9]) F([5,56,50]) F([52,36,526]) F([52,36,525]) F([52,36,524] ``` > > 12509 > > 95021 > > > 50556 > > 56550 > > > 3652526 > > 5265236 > > > 3652525 > > 5255236 > > > 3652452 > > 5252436 > > > [Answer] ## J, 34 ~~36~~, ~~42~~ bytes simple brute force: ``` h=:3 :'0 _1{/:~;"1":&.>y A.~i.!#y' h 5 50 56 50556 56550 h 50 2 1 9 12509 95021 ``` [Answer] # Haskell, 98 bytes ``` import Data.List g=sort.map concat.permutations.words h i=unlines[g i!!0,last$g i] main=interact h ``` Split input string at spaces, concatenate every permutation and sort. Print first and last element. [Answer] # Julia, 77 bytes ``` v->(Q=extrema([int(join(x)) for x in permutations(v)]);print(Q[1],"\n",Q[2])) ``` This creates an unnamed function that accepts a vector as input and prints the minimum and maximum of the permutations of the joined elements. To call it, give it a name, e.g. `f=v->...`. Ungolfed + explanation: ``` function f(v) # Create an integer vector of the joined permutations using comprehension, # then get the minimum and maximum as a tuple using extrema(). Q = extrema([int(join(x)) for x in permutations(v)]) # Print the minimum and the maximum, separated by a newline. print(Q[1], "\n", Q[2]) end ``` Suggestions are welcome! [Answer] # Javascript (*ES6*) 134 Sadly, there's no built-in permutation function in JS :( ``` f=(o,y,i,a)=>y?o.concat(a[1]?a.filter((k,j)=>j^i).reduce(f,[]).map(z=>y+z):y):(q=o.split(' ').reduce(f,[])).sort().shift()+` `+q.pop() ``` ``` <!-- Snippet Demo (Firefox only) --> <input id="input" value="5 56 50" /> <input type="button" onclick="output.innerHTML=f(input.value)" value="Run" /> <pre id="output"></pre> ``` [Answer] ## R, 59 bytes ``` write(range(combinat:::permn(scan(),paste,collapse="")),"") ``` [Answer] # Ruby 75 Not my 'native' language, but one I thought I'd give a try at... thus this could (possibly) use some golfing tips. Still, not a bad entrant. ``` puts STDIN.read.split(" ").permutation.map{|x|x.join}.sort.values_at(0,-1) ``` I wouldn't say it is *elegant* other that everything is built in to the language. It should be fairly obvious exactly how this works. [Answer] # Perl, ~~79~~ 70B (68+2) `use Math::Combinatorics;say for(sort map{join'',@$_}permute@F)[0,-1]` Call with `echo 13 42 532 3 6|perl -M5.10.0 -an scratch.pl`. There's a +2 byte penalty for `-an`. Shame about the length of the module name... [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` #œJ{¬sθ» ``` [Try it online.](https://tio.run/##yy9OTMpM/f9f@ehkr@pDa4rP7Ti0@/9/UwVTMwVTAwA) **Explanation:** ``` # # Split the (implicit) input by spaces œ # Get all permutations of this list J # Join each permutation together to a single string { # Sort this list ¬ # Push the first item (without popping the list) s # Swap to get the list again θ # Pop and push its last item » # And join all (both) values on the stack by newlines # (after which the result is output implicitly) ``` [Answer] # [Scala](http://www.scala-lang.org/), 90 bytes ``` val x=Console.in.readLine.split(" ").permutations.map(_.mkString).toSeq print(x.min,x.max) ``` [Try it online!](https://tio.run/##DYrLCsIwEADvfsXSUwqy4NsePEiv3voBsjZrieZls0pA/PYYBgYGJo1kqYTbg0eBPmiegr0DZ2GvE5xjhG/5kIV86oNPwTIajzOTvhjPmKI1ohpoWow8u7eQmLqho6iu6J6DzMZPLUoY@LWINURldMYvqym35Vc6WG@2sIIdHI6wr3R/ "Scala – Try It Online") [Answer] # JavaScript (ES6), 85 bytes ``` F=a=>(c=a.split(" ").sort((b,a)=>b+a-(a+b)),`${c.join("")} ${c.reverse().join("")}`) ``` **usage:** ``` F("50 2 1 9") /* 12509 95021 */ ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), 11 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ú∙n90≤╣*.vâ ``` [Run and debug it](https://staxlang.xyz/#c=L%7CT%7B%24mc%7CmP%7CMp&i=5+56+50) Link is to unpacked version of code. ## Explanation ``` L|T{$mc|MP|mp implicit input L put all inputs in a list |T get the unique orders of the list of inputs {$m convert each list to string c duplicate the array of strings |mP print the minimum element |mp print the maximum element ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes ``` Œ!VṢ.ị ``` [Try it online!](https://tio.run/##y0rNyan8///oJMWwhzsX6T3c3f3/cPujpjX//0eb6iiYmgGxQawOAA "Jelly – Try It Online") Input and output as lists of integers. [+3 bytes](https://tio.run/##ASkA1v9qZWxsef//4biyxZIhVlbhuaIu4buLWf/Dh@KCrP//IjUgNTYgNTAiLA) to input with spaces and output with newlines ## How it works ``` Œ!VṢ.ị - Main link. Takes a list L on the left e.g. [5, 56, 50] Œ! - All permutations of L [[5, 56, 50], [5, 50, 56], [56, 5, 50], [56, 50, 5], [50, 5, 56], [50, 56, 5]] V - Concatenate each into numbers [55650, 55056, 56550, 56505, 50556, 50565] Ṣ - Sort [50556, 50565, 55056, 55650, 56505, 56550] .ị - Take the first and last elements [56550, 50556] ``` ]
[Question] [ A Spirograph is a toy that draws hypotrochoids and epitrochoids. For this challenge, we'll just focus on the hypotrochoids. From [Wikipedia](http://en.wikipedia.org/wiki/Hypotrochoid): > > A hypotrochoid is a roulette traced by a point attached to a circle of radius **r** rolling around the inside of a fixed circle of radius **R**, where the point is a distance **d** from the center of the interior circle. > > > The parametric equations for them can be defined as: ![enter image description here](https://i.stack.imgur.com/hH2sM.png) ![enter image description here](https://i.stack.imgur.com/D7HS8.png) Where *θ* is the angle formed by the horizontal and the center of the rolling circle. --- Your task is to write a program that will draw the path traced by the point defined above. As input, you'll be given **R**, **r**, and **d**, all integers between 1 and 200 inclusive. You can receive this input from stdin, arguments, or user input, but it cannot be hardcoded into the program. You can accept it in whatever form is most convenient for you; as strings, integers, etc. Assume: * Input units are given in pixels. * **R** >= **r** --- Output should be a graphical representation of the hypotrochoid defined by the input. No ASCII- or other text-based output is allowed. This image can be saved to a file or displayed on screen. Include a screenshot or image of the output for an input of your choosing. You can choose any colors you like for the path/background, subject to a contrast restriction. The two colors must have HSV 'Value' component at least half the scale apart. For instance, if you're measuring HSV from `[0...1]`, there should be at least `0.5` difference. Between `[0...255]` there should be a minimum `128` difference. --- This is a code golf, minimum size of source code in bytes wins. [Answer] ## Mathematica, 120 bytes ``` f[R_,r_,d_]:=ParametricPlot[p#@t+#[-p*t/r]d&/@{Cos,Sin},{t,0,2r/GCD[p=R-r,r]Pi},PlotRange->400,ImageSize->800,Axes->0>1] ``` Ungolfed code and example output: ![enter image description here](https://i.stack.imgur.com/ZanXi.png) If I may include the axes in the plot, I can save another 9 characters. [Answer] # JavaScript (ECMAScript 6) - ~~312~~ 314 Characters ``` document.body.appendChild(e=document.createElement("canvas")) v=e.getContext("2d") n=(e.width=e.height=800)/2 M=Math P=2*M.PI t=0 p=prompt r=p('r') R=p('R')-r d=p('d') X=x=>n+R*M.cos(t)+d*M.cos(R/r*t) Y=x=>n+R*M.sin(t)-d*M.sin(R/r*t) v.beginPath() v.moveTo(X(),Y()) for(;t<R*P;v.lineTo(X(),Y()))t+=P/2e4 v.stroke() ``` [JSFIDDLE](http://jsfiddle.net/73Gk8/3/) **Example Output** r=1,R=200,d=30 ![enter image description here](https://i.stack.imgur.com/VbrK2.png) [Answer] # Python: 579 ## Summary This is not competitive at all given the Mathematica answer, but I decided to post it anyway because the pictures are pretty and it may inspire someone or be useful to someone. Because it is so much bigger, I left it basically ungolfed. The program expects command-line input of R,r,d. ## Screenshot Here are two examples, one for (5,3,5) and one for (10,1,7) ![example 5-3-5](https://i.stack.imgur.com/psUuw.png) ![example 10-1-7](https://i.stack.imgur.com/PaU4G.png) ## Code ``` import math import matplotlib.pyplot as P from matplotlib.path import Path as H import matplotlib.patches as S import sys a=sys.argv (R,r,d)=int(a[1]),int(a[2]),int(a[3]) v=[] c=[] c.append(H.MOVETO) t=0 while(len(v)<3 or v.count(v[-1])+v.count(v[-2])<3): p=t*math.pi/1000 t+=1 z=(R-r)*p/r v.append((round((R-r)*math.cos(p)+d*math.cos(z),3),round((R-r)*math.sin(p)-d*math.sin(z),3))) c.append(H.LINETO) c.pop() v.append((0,0)) c.append(H.CLOSEPOLY) f=P.figure() x=f.add_subplot(111) x.add_patch(S.PathPatch(H(v,c))) l=R+d-r x.set_xlim(-l-1,l+1) x.set_ylim(-l-1,l+1) P.show() ``` [Answer] ## Perl/Tk - 239 227 ``` use Tk;($R,$r,$d)=@ARGV;$R-=$r;$s=$R+$d;$c=tkinit->Canvas(-width=>2*$s,-height=>2*$s)->pack;map{$a=$x;$b=$y;$x=$s+$R*cos($_/=100)+$d*cos$_*$R/$r;$y=$s+$R*sin($_)-$d*sin$_*$R/$r;$c->createLine($a,$b,$x,$y)if$a}0..628*$s;MainLoop ``` **R=120, r=20, d=40:** ![R=120, r=20, d=40](https://i.stack.imgur.com/3HkTl.png) **R=128, r=90, d=128:** ![R=128, r=90, d=128](https://i.stack.imgur.com/Uwxpy.png) **R=179, r=86, d=98:** ![R=179, r=86, d=98](https://i.stack.imgur.com/FUkHv.png) [Answer] # Processing, 270 ``` import java.util.Scanner; void setup(){size(500, 500);} Scanner s=new Scanner(System.in); int R=s.nextInt(),r=s.nextInt(),d=s.nextInt(); void draw(){ int t=width/2,q=(R-r); for(float i=0;i<R*PI;i+=PI/2e4) point(q*sin(i)-d*sin(i*q/r)+t,q*cos(i)+d*cos(i*q/r)+t); } ``` The input is entered via console, one number per line. Screenshot for R=65, r=15, d=24: ![enter image description here](https://i.stack.imgur.com/gtm2d.png) [Answer] # shell script + gnuplot (153) Most of the effort is to remove the axes and tics, set the size and range, and increase the precision. Thankfully, gnuplot is natural for golfing, so most of the commands can be abbreviated. To save characters, the output must be redirected to an image file manually. ``` gnuplot<<E se t pngc si 800,800 se pa se sa 1e4 uns bor uns tic a=$1-$2 b=400 p[0:2*pi][-b:b][-b:b]a*cos($2*t)+$3*cos(a*t),a*sin($2*t)-$3*sin(a*t) not E ``` Calling the script with `spiro.sh 175 35 25>i.png` gives ![enter image description here](https://i.stack.imgur.com/EvqlL.png) [Answer] ## GeoGebra, 87 **That is, if you consider GeoGebra a valid language.** ``` R=2 r=1 d=1 D=R-r Curve[D*cos(t)+d*cos(D*t/r),D*sin(t)-d*sin(D*t/r),t,0,2π*r/GCD[D,r]] ``` Accepts input from the GeoGebra input bar, in the format `<variable>=<value>`, e.g. `R=1000`. Note that you may need to manually change the zoom size to view the whole image. ![screenshot](https://i.stack.imgur.com/B5Vnr.png) *(The thing at the bottom of the window is the input bar that I was talking about)* Try it online [here](https://tube.geogebra.org/material/simple/id/kDQXO84k). [Answer] # HTML + Javascript 256 ~~286 303~~ **Edit** Removed 1st call to moveTo, it works anyway. Could save more cutting beginPath, but then it works only the first time **Edit2** 30 bytes saved thx @ӍѲꝆΛҐӍΛПҒЦꝆ ``` <canvas id=c></canvas>R,r,d:<input oninput="n=400;c.width=c.height=t=n+n;v=c.getContext('2d');s=this.value.split(',');r=s[1],d=s[2],R=s[0]-r;v.beginPath();for(C=Math.cos,S=Math.sin;t>0;v.lineTo(n+R*C(t)+d*C(R/r*t),n+R*S(t)-d*S(R/r*t)),t-=.02);v.stroke()"> ``` **Test** Put input in the text box (comma separated) then press tab ``` R,r,d:<input onchange="n=400;c.width=c.height=t=n+n;v=c.getContext('2d');s=this.value.split(',');r=s[1],d=s[2],R=s[0]-r;v.beginPath();for(C=Math.cos,S=Math.sin;t>0;v.lineTo(n+R*C(t)+d*C(R/r*t),n+R*S(t)-d*S(R/r*t)),t-=.02);v.stroke()"><canvas id=c></canvas> ``` [Answer] # R, 80 bytes ``` f=function(R,r,d){a=0:1e5/1e2;D=R-r;z=D*exp(1i*a)+d*exp(-1i*D/r*a);plot(z,,'l')} ``` However, if one wants 'clean' figures (no axes, no labels etc), then the code will have to be slightly longer (88 characters): ``` f=function(R,r,d)plot((D=R-r)*exp(1i*(a=0:1e5/1e2))+d*exp(-1i*D/r*a),,'l',,,,,,'','',,F) ``` One code example using the longer version of f: ``` f(R<-179,r<-86,d<-98);title(paste("R=",R,", r=",r," d=",d,sep="")) ``` Some example outputs: ![enter image description here](https://i.stack.imgur.com/I8KbO.jpg) ![enter image description here](https://i.stack.imgur.com/tVgKO.jpg) ![enter image description here](https://i.stack.imgur.com/ZTUrK.jpg) [Answer] ## C# 813, was 999 Needs some work to reduce byte count. I managed to reduce it a little. It accepts three space separated integers from the Console. ``` using System; using System.Collections.Generic; using System.Drawing; using System.Windows.Forms; class P:Form { int R,r,d; P(int x,int y,int z) {R=x;r=y;d=z;} protected override void OnPaint(PaintEventArgs e) { if(r==0)return; Graphics g=e.Graphics; g.Clear(Color.Black); int w=(int)this.Width/2; int h=(int)this.Height/2; List<PointF> z= new List<PointF>(); PointF pt; double t,x,y; double pi=Math.PI; for (t=0;t<2*pi;t+=0.001F) { x=w+(R-r)*Math.Cos(t)+d*Math.Cos(((R-r)/r)*t); y=h+(R-r)*Math.Sin(t)-d*Math.Sin(((R-r)/r)*t); pt=new PointF((float)x,(float)y); z.Add(pt); } g.DrawPolygon(Pens.Yellow,z.ToArray()); } static void Main() { char[] d={' '}; string[] e = Console.ReadLine().Split(d); Application.Run(new P(Int32.Parse(e[0]),Int32.Parse(e[1]),Int32.Parse(e[2]))); } } ``` Output sample: ![Spirograph](https://i.stack.imgur.com/qUYVx.png) [Answer] ## R, 169 characters ``` f=function(R,r,d){png(w=2*R,h=2*R);par(mar=rep(0,4));t=seq(0,R*pi,.01);a=R-r;x=a*cos(t)+d*cos(t*a/r);y=a*sin(t)-d*sin(t*a/r);plot(x,y,t="l",xaxs="i",yaxs="i");dev.off()} ``` Indented: ``` f=function(R,r,d){ png(w=2*R,h=2*R) #Creates a png device of 2*R pixels by 2*R pixels par(mar=rep(0,4)) #Get rid of default blank margin t=seq(0,R*pi,.01) #theta a=R-r x=a*cos(t)+d*cos(t*a/r) y=a*sin(t)-d*sin(t*a/r) plot(x,y,t="l",xaxs="i",yaxs="i") #Plot spirograph is a plot that fits tightly to it (i. e. 2*R by 2*R) dev.off() #Close the png device. } ``` Examples: ``` > f(65,15,24) ``` ![enter image description here](https://i.stack.imgur.com/bIdOP.png) ``` > f(120,20,40) ``` ![enter image description here](https://i.stack.imgur.com/Ub7lv.png) ``` > f(175,35,25) ``` ![enter image description here](https://i.stack.imgur.com/5aqJR.png) [Answer] # SmileBASIC, 96 bytes ``` INPUT R,Q,D M=R+MAX(Q,D) S=R-Q@L GPSET M+S*COS(I)+D*COS(S/Q*I),M+S*SIN(I)-D*SIN(S/Q*I)I=I+1GOTO@L ``` ### Input: 50,30,50: [![enter image description here](https://i.stack.imgur.com/rh09b.jpg)](https://i.stack.imgur.com/rh09b.jpg) [Answer] # Befunge-98, 113 bytes ``` &&:00p-10p&20p"PXIF"4(10g'd:*:I10v>H40gF1+:"}`"3**`>jvI@ 1(4"TURT"p04/d'*g02I/g00*p03/d'*g<^-\0/g00*g01:Fg03H:<0P ``` This code relies on the [Fixed Point Maths (FIXP)](http://rcfunge98.com/rcsfingers.html#FIXP) fingerprint for some trigonometric calculations, and the [Turtle Graphics (TURT)](https://github.com/catseye/Funge-98/blob/master/library/TURT.markdown) fingerprint for drawing the path of the spirograph. The Turtle Graphics in Befunge are very similar in behaviour to the graphics in the [Logo programming language](https://en.wikipedia.org/wiki/Turtle_graphics). You draw with a 'turtle' (serving as your pen), which you steer around the output surface. This entails orienting the turtle in a particular direction, and then instructing it to move forward a certain distance. In order to work with this system, I needed to adjust the original spirograph equations into something a little more turtle friendly. I'm not sure if this is the best approach, but the algorithm I came up with works something like this: ``` ratio = (R-r)/r distance1 = sin(1°) * (R-r) distance2 = sin(1° * ratio) * d foreach angle in 0° .. 36000°: heading(angle) forward(distance1) heading(-ratio*angle) forward(distance2) ``` Note that this actually draws the path with a kind of zig-zag pattern, but you don't really notice unless you zoom in closely on the image. Here's an example using the parameters R = 73, r = 51, d = 45. ![enter image description here](https://i.stack.imgur.com/fOXzV.png) I've tested the code with [CCBI](https://deewiant.iki.fi/projects/ccbi/) and [cfunge](https://github.com/VorpalBlade/cfunge), both of which produce output in the form of an SVG image. Since this is a scalable vector format, the resulting image doesn't have a pixel size as such - it just scales to fit the screen size (at least when viewed in a browser). The example above is a screen capture that has been manually cropped and scaled. In theory the code could also work on [Rc/Funge](http://www.rcfunge98.com/v2.html), but in that case you'd need to be running on a system with XWindows, since it'll try to render the output in a window. [Answer] ## [wxMaxima](http://andrejv.github.io/wxmaxima/): 110 ``` f(R,r,d):=plot2d([parametric,(p:R-r)*cos(t)+d*cos(t*(p)/r),(p)*sin(t)-d*sin(t*(p)/r),[t,0,2*%pi*r/gcd(p,r)]]); ``` This is called in the interactive session via `f(#,#,#)`. As a sample, consider `f(3,2,1)`: ![enter image description here](https://i.stack.imgur.com/M6npn.png) [Answer] ## Racket ``` #lang racket/gui (require 2htdp/image) (define frame (new frame% [label "Spirograph"] [width 300] [height 300])) (define-values (R r d) (values 50 30 10)) ; these values can be adjusted; (new canvas% [parent frame] [paint-callback (lambda (canvas dc) (send dc set-scale 3 3) (for ((t (in-range 0 (* 10(* R pi)) 1))) (define tr (degrees->radians t)) (define a (- R r)) (define x (+ (* a (cos tr)) (* d (cos (* tr (/ a r)))))) (define y (- (* a (sin tr)) (* d (sin (* tr (/ a r)))))) (send dc draw-ellipse (+ x 50) (+ y 50) 1 1)))]) (send frame show #t) ``` Output: [![enter image description here](https://i.stack.imgur.com/XYnYi.png)](https://i.stack.imgur.com/XYnYi.png) ]
[Question] [ **Closed**. This question needs to be more [focused](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Update the question so it focuses on one problem only by [editing this post](/posts/6798/edit). Closed 6 years ago. [Improve this question](/posts/6798/edit) **Write a non-trivial regex that matches itself.** For example, `#.*$` will match a comment outside of a string in python until the end-of-line, and also matches itself in perl regex syntax. **Rules**: * The regular expression must do something useful or practical. * Tell what regex syntax you are using (e.g. perl or POSIX). * Winner is the highest voted compliant answer. * Be creative! [Answer] ``` /(^|[^/])\/(?!\/)(\[.+?]|\\.|[^/\r\n])+\/[gim]{0,3}(?=\s*($|[\r\n,.;})]))/g ``` Stolen from <https://github.com/LeaVerou/prism/blob/gh-pages/components/prism-javascript.js>. This should match (in JavaScript) all JavaScript regular expressions. [Answer] ## PYTHON Below is a self-matching regex generator. You provide two lists, one contains training data that the regex should match (in addition to matching itself), the other contains training data the the regex should *NOT* match: ``` from random import choice, randrange import re from itertools import zip_longest, chain, islice from operator import itemgetter CHAR_SET = [chr(i) for i in range(128)] + [r"\\", r"\d", r"\D", r"\w", r"\W", r"\s", r"\S", r"?:", r"\1", r"\2", r"\A", r"\b", r"\B", r"\Z", r"\.", r"\[", r"\]", r"\(", r"\)", r"\{", r"\}", r"\+", r"\|", r"\?", r"\*"] CHAR_SAMPLE = [] BREAKPOINT = re.compile( r""" \(.*?\)| \[.*?\]| \{.*?\}| \w+(?=[\(\[\{])?| \S+?| \.\*\??| \.\+\??| \.\?\??| \\.| .*? """, re.VERBOSE) MATCH_BRACKETS = {'(': ')', '[': ']', '{': '}'} CLOSE_BRACKETS = {')', ']', '}'} REGEX_SEEDER = [ r".*?", r"(?:.*?)", r"\w|\s", r"(?<.*?)", r"(?=.*?)", r"(?!.*?)", r"(?<=.*?)", r"(?<!.*?)", ] LEN_LIMIT = 100 def distribute(distribution): global CHAR_SAMPLE for item in CHAR_SET: if item in distribution: CHAR_SAMPLE.extend([item] * distribution[item]) else: CHAR_SAMPLE.append(item) def rand_index(seq, stop=None): if stop is None: stop = len(seq) try: return randrange(0, stop) except ValueError: return 0 def rand_slice(seq): try: start = randrange(0, len(seq)) stop = randrange(start, len(seq)) return slice(start, stop) except ValueError: return slice(0, 0) #Mutation Functions def replace(seq): seq[rand_index(seq)] = choice(CHAR_SAMPLE) def delete(seq): del seq[rand_index(seq)] def insert(seq): seq.insert(rand_index(seq, len(seq) + 1), choice(CHAR_SAMPLE)) def duplicate(seq): source = rand_slice(seq) seq[source.stop: source.stop] = seq[source] def swap(seq): if len(seq) < 2: return a = rand_index(seq, len(seq) - 1) seq[a], seq[a + 1] = seq[a + 1], seq[a] dummy = lambda seq: None MUTATE = ( replace, delete, insert, duplicate, swap, dummy, dummy, ) def repair_brackets(seq): """Attempts to lower the percentage of invalid regexes by matching orphaned brackets""" p_stack, new_seq = [], [] for item in seq: if item in MATCH_BRACKETS: p_stack.append(item) elif item in CLOSE_BRACKETS: while p_stack and MATCH_BRACKETS[p_stack[-1]] != item: new_seq.append(MATCH_BRACKETS[p_stack[-1]]) p_stack.pop() if not p_stack: continue else: p_stack.pop() new_seq.append(item) while p_stack: new_seq.append(MATCH_BRACKETS[p_stack.pop()]) return new_seq def compress(seq): new_seq = [seq[0]] last_match = seq[0] repeat = 1 for item in islice(seq, 1, len(seq)): if item == last_match: repeat += 1 else: if repeat > 1: new_seq.extend(list("{{{0}}}".format(repeat))) new_seq.append(item) last_match = item repeat = 1 else: if repeat > 1: new_seq.extend(list("{{{0}}}".format(repeat))) return new_seq def mutate(seq): """Random in-place mutation of sequence""" if len(seq) > LEN_LIMIT: seq[:] = seq[:LEN_LIMIT] c = choice(MUTATE) c(seq) def crossover(seqA, seqB): """Recombination of two sequences at optimal breakpoints along each regex strand""" bpA = [item.start() for item in BREAKPOINT.finditer(''.join(seqA))] bpB = [item.start() for item in BREAKPOINT.finditer(''.join(seqA))] slObjA = (slice(*item) for item in zip(bpA, bpA[1:])) slObjB = (slice(*item) for item in zip(bpB, bpB[1:])) slices = zip_longest( (seqA[item] for item in slObjA), (seqB[item] for item in slObjB), fillvalue=[] ) recombinant = (choice(item) for item in slices) return list(chain.from_iterable(recombinant)) #Fitness testing def match_percentage(match): """Calculates the percentage a text actually matched by a regular expression""" if match and match.endpos: return (match.end() - match.start()) / match.endpos else: return 0.001 def fitness_test(seq, pos_matches, neg_matches): """Scoring algorithm to determine regex fitness""" try: self_str = ''.join(seq) regex = re.compile(self_str) except (re.error, IndexError): seq[:] = repair_brackets(seq) try: self_str = ''.join(seq) regex = re.compile(self_str) except (re.error, IndexError): return 0.001 pos_score = sum(match_percentage(regex.search(item)) for item in pos_matches) / len(pos_matches) / 3 neg_score = (1 - sum(match_percentage(regex.search(item)) for item in neg_matches) / len(neg_matches)) / 3 self_score = match_percentage(regex.search(self_str)) / 3 return pos_score + self_score + neg_score #Population Management def generate_pop(pos_matches, neg_matches, pop_size): sources = (pos_matches, REGEX_SEEDER) return [crossover( choice(choice(sources)), choice(choice(sources)) ) for i in range(pop_size)] def glean_pop(population, cutoff, fit_test, ft_args=()): scores = (fit_test(bug, *ft_args) for bug in population) ranked = sorted(zip(population, scores), key=itemgetter(1), reverse=True) maxItem = ranked[0] new_pop = next(zip(*ranked))[:cutoff] return maxItem, new_pop def repopulate(population, pop_size): cutoff = len(population) for i in range(pop_size // cutoff): population.extend([crossover(choice(population), choice(population)) for i in range(cutoff)]) population.extend([population[i][:] for i in range(pop_size - len(population))]) #Simulator def simulate(pos_matches, neg_matches, pop_size=50, cutoff=10, threshold=1.0): population = generate_pop(pos_matches, neg_matches, pop_size) while True: for bug in population: mutate(bug) #Scoring step max_item, population = glean_pop( population, cutoff, fitness_test, (pos_matches, neg_matches) ) #Exit condition: max_regex, max_score = max_item if max_score >= threshold: return max_score, max_regex """ print(max_score, ''.join(max_regex)) input("next?")""" #Repopulation Step: population = list(population) repopulate(population, pop_size) ``` [Answer] JavaScript regular expression that matches stuff like it. ``` /^\/\^\\\/\\\^[\\\[\]\/\^\${},\dd]{34}$/ ``` You can test it like so: ``` (function test() { var re =/^\/\^\\\/\\\^[\\\[\]\/\^\${},\dd]{34}$/; var m =/=([^;]+)/.exec(test)[1]; return re.exec(m); })(); ``` ]
[Question] [ Given an alphabet represented as a nonempty set of positive integers, and a word made up of symbols from that alphabet, find that word's position in the lexicographically ordered set of all words, assuming words can't contain duplicate symbols. ## Example Consider the alphabet `{1, 2, 3}` and the word `[2, 3, 1]`. The set of all possible words, ordered via lexicographic order is ``` { [1], [1, 2], [1, 2, 3], [1, 3], [1, 3, 2], [2], [2, 1], [2, 1, 3], [2, 3], [2, 3, 1], [3], [3, 1], [3, 1, 2], [3, 2], [3, 2, 1] } ``` `[2, 3, 1]` is the tenth element in the set, so the answer is 10 (9 if you use zero indexing). ## Input/Output Input can be taken in any reasonable format, including taking the alphabet as a sorted list, or taking the alphabet/word as a string. Output can be zero or one indexed, please say which one you choose in your answer. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer wins. ## Testcases One indexed: ``` alphabet, word -> location (1 indexed) {1, 2, 3} , [] -> undefined {1, 2, 3}, [1] -> 1 {1, 2, 3}, [3] -> 11 {1, 2, 3}, [2, 3, 1] -> 10 {1, 2, 3}, [3, 2, 1] -> 15 {1, 3, 4, 6}, [3, 1, 4] -> 19 {1, 3, 4, 6}, [3, 1, 6, 4] -> 22 {1,3, 4, 16, 23, 37, 43, 57}, [37, 43, 16, 3] -> 79332 {41, 57, 60, 61, 71, 80, 113, 125, 131, 139, 141, 184, 197, 200, 201, 214, 215, 216, 223, 236, 238, 240, 244, 252, 264, 279, 300, 335, 340, 393, 410, 414, 421, 436, 441, 447, 461, 466, 483, 490, 525, 537, 540, 543, 547, 551, 552, 557, 569, 583, 584, 591, 593, 595, 596, 607, 610, 613, 614, 620, 621, 634, 637, 643, 652, 683, 691, 713, 726, 733, 738, 750, 757, 767, 777, 789, 803, 812, 813, 817, 844, 850, 856, 878, 901, 910, 926, 947, 949, 951, 953, 958, 962, 969, 982, 995}, [252, 300, 969, 844, 856, 713, 60, 621, 393, 637, 634, 441, 817, 264, 551, 757, 926, 240, 461, 421, 767, 726, 223, 610, 547, 141, 593, 184, 200, 643, 583, 614, 958, 540, 201, 214, 584, 591, 525, 652, 466, 414, 995, 125, 813, 951, 901, 215, 947, 410, 113, 279, 238, 57, 750, 607, 61, 131, 216, 340, 569, 803, 557, 878, 691, 80, 850, 483, 71, 613, 41, 244, 789, 595, 447, 596, 812, 543, 953, 620, 962, 436, 537, 733, 738, 197, 949, 982, 139, 683, 910, 236, 552, 490, 777, 335] -> 653513463887666116337968717018588523734749776398084200209718028326146195147009645472571018754197481757464478858415475671625444580437153140577102475638 ``` Zero indexed: ``` alphabet, word -> location (0 indexed) {1, 2, 3} , [] -> undefined {1, 2, 3}, [1] -> 0 {1, 2, 3}, [3] -> 10 {1, 2, 3}, [2, 3, 1] -> 9 {1, 2, 3}, [3, 2, 1] -> 14 {1, 3, 4, 6}, [3, 1, 4] -> 18 {1, 3, 4, 6}, [3, 1, 6, 4] -> 21 {1,3, 4, 16, 23, 37, 43, 57}, [37, 43, 16, 3] -> 79331 {41, 57, 60, 61, 71, 80, 113, 125, 131, 139, 141, 184, 197, 200, 201, 214, 215, 216, 223, 236, 238, 240, 244, 252, 264, 279, 300, 335, 340, 393, 410, 414, 421, 436, 441, 447, 461, 466, 483, 490, 525, 537, 540, 543, 547, 551, 552, 557, 569, 583, 584, 591, 593, 595, 596, 607, 610, 613, 614, 620, 621, 634, 637, 643, 652, 683, 691, 713, 726, 733, 738, 750, 757, 767, 777, 789, 803, 812, 813, 817, 844, 850, 856, 878, 901, 910, 926, 947, 949, 951, 953, 958, 962, 969, 982, 995}, [252, 300, 969, 844, 856, 713, 60, 621, 393, 637, 634, 441, 817, 264, 551, 757, 926, 240, 461, 421, 767, 726, 223, 610, 547, 141, 593, 184, 200, 643, 583, 614, 958, 540, 201, 214, 584, 591, 525, 652, 466, 414, 995, 125, 813, 951, 901, 215, 947, 410, 113, 279, 238, 57, 750, 607, 61, 131, 216, 340, 569, 803, 557, 878, 691, 80, 850, 483, 71, 613, 41, 244, 789, 595, 447, 596, 812, 543, 953, 620, 962, 436, 537, 733, 738, 197, 949, 982, 139, 683, 910, 236, 552, 490, 777, 335] -> 653513463887666116337968717018588523734749776398084200209718028326146195147009645472571018754197481757464478858415475671625444580437153140577102475637 ``` Note: This challenge is loosely based upon an old weekly challenge on [replit.](https://replit.com) [Answer] # [Python 3.8](https://docs.python.org/3.8/), 93 bytes ``` lambda a,w:sum(sum(map(e.__gt__,a:=a-{e}))*h(len(a))+1for e in w) h=lambda n:n<1or 1+n*h(n-1) ``` An unamed function that accepts the alphabet, `a`, as a `set` and the word, `w`, as an `Iterable` and returns the 1-indexed index of the word (an empty word will give `0`). **[Try it online!](https://tio.run/##hVTbTttAEH3nK/bRLqbyXmYvEfmStoqMSBqkxLHSoKhCfHs653gRtIUWyZOx57Iz55xl@nnaHkafp@Nls/x62Q37u/vBDN158eNx3@DZD1Oz/rxafT@tVt2wWA43T@vntv20bXbrsRna9tpuDkezNg@jObdX22XtMS7GW6sBez1q7nhj2wvyht20He7Wp86cD8d7FDVXpv41T7YzrjP@uTNfvrXd@wH7YcR/GMFvZ/5RSffvuH4PnYk1RT@E/6fEd7LmJKshp65P@qq/klhV3xD9Y4NgkaQte33UT/pk9a1FvhM13sIUNUi2GccULXF9D4MdbYARGAyACZznKFlNQF5AiigELsJL2s@jgfda5pHiC3awPYymBAcw0CXg3BCwBEYMEd8ykosmC4YUrCjoIlwbySLYDUcKNpSoRwrKBCtIQRRHSkGDEgECkLCEwsMAdodXzBI9XnFQxBkRnSP6xULg1EtOuyQPD5sn6WG0IkWYBJMLENaUbB0MPQ1kIJRRkUW75KQNCtAtGKigc8FaJWiDgt2KeBjkRQeDQIZXhJLEhASZoXpArLPGl72I@7wXNiTanIhMEUXuwBFI5kwDaue93AvpxI7gUyuEl4KhVggbGSCynJycvYroDTWglRjPfLMCTFGUhG0GYa6Vig71Q/FSYhQgCQCwld@qaWqVyqM0yAmVQuhJau4rJZQb7gaFgd0oaJJJ/VCeFBFppQrJD/VDfqhlCvVVIbxIM6MgjteMmiLpvENUMJVO/eh9eXuD2wXd6fgwnppN8/v/vra9/AI "Python 3.8 (pre-release) – Try It Online")** ### How? We calculate the number of "blocks" in the set of valid words that we need to pass for each character in the word and multiply by the size of said "blocks", moving forward one more for each character. The size of the block at each step is the number of words that may be formed from the alphabet once we've removed the current character and any previously processed characters. This is [OEIS: A000522](https://oeis.org/A000522) and is calculated with the recursive helper function, `h`. The number of blocks to pass at each step is the number of characters that come before the current character in the alphabet once we've removed any previously processed characters and is calculated with `sum(map(e.__gt__,a:=a-{e}))` which deals with removing the word character from the alphabet. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 5 bytes ``` Þxs?ḟ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLDnnhzP+G4nyIsIiIsIlsxLCAzLCA0LCA2XVxuWzMsIDEsIDRdIl0=) **Explanation**: ``` Þxs?ḟ Þx All possible combinations of the set (without replacements) s Sort ?ḟ Output index of the word ``` [Answer] # JavaScript (ES6), 73 bytes Expects `(word)(alphabet)`. The result is 1-indexed. ``` b=>g=(a,w=k=0)=>w==b||a.some((v,i)=>g(a.filter(_=>i--),w?w+[,v]:v),k++)*k ``` [Try it online!](https://tio.run/##jdC9boMwEADgnae48VwOEuwkKK2OTn0KC1WGAqXQuIIIlrw7NSgd2qhJPPh@7M8n@cMMps@7@usYHOxbMZU8ZZxUjIZGbngtOBmZs9PJhL39LBAHql2vQhOWdXssOnzlpA4CQePz6Gsa0sdBUOP74qGZnrQHoHVEIAlUSqCj1O231moF0V@o7oUXco4ENwbPcn0xc0nvkNsf6cSGYHfGrrG5gme5h3/p7op2VMrfMnL3pUtV7EoXt/Hy1LmaT90XLjLeKyW91AtL272Y/B1RG4IsFcAJ5PbQ27YIW1thiZlAI4SYvgE "JavaScript (Node.js) – Try It Online") ### Commented ``` b => // outer function taking the word array b[] g = ( // inner recursive function taking: a, // the alphabet array a[] w = k = 0 // the current word w and the corresponding index k ) => // w == b || // stop if w is equal to b (implicit string coercion) a.some((v, i) => // otherwise, for each value v at position i in a[]: g( // do a recursive call: a.filter(_ => // pass a copy of a[] with ... i-- // ... the i-th entry removed ), // w ? // if w is already initialized: w + [, v] // append a comma followed by v to w : // otherwise: v // set w to v ), // end of recursive call k++ // before some() is actually processed: increment k ) * k // end of some(); return k ``` [Answer] # [Factor](https://factorcode.org/) + `math.combinatorics`, 64 bytes ``` [ all-subsets [ <permutations> ] map concat natural-sort index ] ``` [Try it online!](https://tio.run/##fZDBCsIwEETv/Yr5AYW22oJKr@LFi3gqPcQYNdAmNdmCUvrtdaviRdqEwOy8WQhzEZKs64@H3X67gvDeSo9K0G0ubXXSRjDVbHl1b5SRipV1pM0VtVNEz9ppQ1gHQRuAT8u34xciQsyq@7nhiB@P@MM8vhNNsBCLL4tZJX80meIpFpxJft8aIjxG8Rct03e@C/ocoixnvjl5RR45NrVyVUOCtDU@Q8Et1pDWSEHgGhsnOM3dQZuzeqDoL5@6syE3718 "Factor – Try It Online") 1-indexed. Takes input as `word alphabet`. * `all-subsets` get all subsets of the alphabet * `[ <permutations> ] map concat` get each permutation of each set and flatten it to a list * `natural-sort` sort * `index` find the index of the word [Answer] # [Python](https://www.python.org), 101 bytes ``` f=lambda a,w:w>[]and sorted(a).index(w[0])*g(len(a))+f(a-{w[0]},w[1:])+1 g=lambda n:n and~-n*g(n-1)+1 ``` [Attempt This Online!](https://ato.pxeger.com/run?1=bVTLbhNBEDxx8VeMctol62hePQ-j5MRfWD4Y2Q6WnLWVGAyKwo9wyQX-Cb6Grto1IRIHd2b7Nd1VNfn-8_D1-HHfPz__-HTcTMuv9eZ6t7z7sFqaZXeanW7mi2W_Mg_7--N61Szbq22_Wn9pTnO7aN_eNrt1r872ctMsp49wPnWnuZst2ks3uT036me90Sbfpr1W9FOnwfGy95v9vdmZbW_2B-1k29nEbLu9uTZ3y0Oz_rzcdburh8Nue2wuzPTGXLTtxBzut_2x0bRu07zdtu3Q6_n3m3ePrjO-M-HJdGa-QIGd_PWpy9HnXvnC4HvtxN_OjOmvewQex5AwpK7YmTRG1RGHaDX_D6dzhvdIGOJOvV6PIeun_pXMgvEL0WHSXEPQsuiQor2s_vSc9Vf07ByyvagJDqaqQbIruKRqibcWBju5CCMwuB73-8BBipqIvIgU0ZV9wilrv4AGIWhZQEqo2MBZGE2JHgigS8S9MWIFjBgTfAXJVZMFQwoWFHQRLo1kEeyGKwUbStIrBWWCFaQiiiulokFNAAFIOEIRYIC3xydmSQGfuCjhjoTOCf1SJXB6yl675IATNs9iYbQiJ5gMUyoQ1pTiPAxPGihAqKCiiHYpWRtUoFsxUEXnirVq1AYVu1UJMMhLHgaBglMVqg8TEmSGxgvSOGs670Xch72wIdHmRGSKKHIHjkAyBxpQO-zlz6QTO4JPrRBeCoZaIWxkgMhycnL2IqJ_qAGtxHjgmxVgiqIkbAMIQ62M6FA_FC8lRgGSAAA78jtqmlql8igNckKlEHqSWuxICeWGt0FhYDcKmmRSP5QnRURaqULyQ_2QH2qZQn1RCB_SwCiI4zOjpkg63xAVTKVTP_pe-H6TBHEhplBKTik5l0LINZXssnVFShEfcog51pxTqMWWqCR4W7Mr1pfglYPkFMKYra0pKmtestPaLFHHiioByTHpYtqrRKcJkrJLXmKMUmwM2Ulw0UrWMo9oKJPhn-gf) Does actually calculate the index. 1-based, 0 for undefined. [Answer] # [Ruby](https://www.ruby-lang.org/), ~~62~~ 57 bytes ``` ->a,w{a.product(*a.map{a}).map(&:uniq).sort.uniq.index w} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y5Rp7w6Ua@gKD@lNLlEQytRLzexoDqxVhNEa6hZleZlFmrqFecXleiBmHqZeSmpFQrltf8LFNKiow11FIx1FEx0FMxidRSigUyggBlQIDb2PwA "Ruby – Try It Online") Thanks Jordan for the hint that saved 5 bytes. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 30 bytes ``` ≔⟦υ⟧ζFζF⁻θι⊞ζ⁺ι⟦κ⟧W⁻ζυ⊞υ⌊ιI⌕υη ``` [Try it online!](https://tio.run/##NY49CwIxDEB3f0XGFOIgHi5OIrgJt5cO5fxosNfD9qLQP19zwk0J771AhuDzMPnY2qkUfia04giqOW4eUwasBv7zykkKvgnYGOilBKwEfVTGBPbljB58A8f7mqqWNRUChTzKiLyEfeY049mXGS@cbosPRkVr1u4I9gQdwUHfsLoq6Jxr20/8AQ "Charcoal – Try It Online") Link is to verbose version of code. 1(!)-indexed. Explanation: ``` ≔⟦υ⟧ζFζ ``` Start a breadth-first search for words with the empty word (this consumes index 0, which is why the output becomes 1-indexed.) ``` F⁻θι⊞ζ⁺ι⟦κ⟧ ``` For each word, create new words by suffixing all symbols not already used. ``` W⁻ζυ⊞υ⌊ι ``` Sort the words lexicographically. ``` I⌕υη ``` Output the desired word's position. [Answer] # [Python 3](https://docs.python.org/3/), 107 bytes ``` lambda a,b:sorted([[*p]for i in range(len(a))for p in permutations(a,i+1)]).index(b) from itertools import* ``` [Try it online!](https://tio.run/##TYzNCsIwEITvfYo9JjUINbWFgk8Sc0hpogvND9sI@vQxVQ@edubbmUmvfI9BFne5ltX4eTFgxDxtkbJdmFJt0i4SIGAAMuFm2WoDM5zvNO00WfKPbDLGsDEj8NBxzY8YFvtkM28cRQ@YLeUY1w3QpzrdlkQYMnNMdQKkgF7AoAWoKivoNefNX@Ib6AYBpyrlWG295/HT@Ln9K2uvvAE "Python 3 – Try It Online") Get permutations of all sizes, sort them and return index of required word. [Answer] # [PARI/GP](https://pari.math.u-bordeaux.fr), 67 bytes ``` f(a,w)=sum(l=1,#w,sum(i=0,k=#a=a[^1+n=#[1|b<-a,b<w[l]]],k!/i!)*n+1) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=dVTLbhNBELzwIZv44iVjsfPoeUhZLnzGyqANkpGVxVqFRBYSf8IlF8Sdv4Gvoat2LEcyHNzumenpR1XNfv85jw_7D5_m5-cfT4-7Tf79brcezbHtvzx9Xk-9NaujgbvvO3Pfr8Z-HN7bm0O_Guy3u9vNaO5uj8O03W7N_dWb_VX7-nBj2yXVn1e_xnmevq7HZvO2mR_2h0d1r7G4bj6O07TemWZsW9MMw2BN40zjt7rYwrzcsBc7_mIH_6b5RyTd876ug2liPdKN8P-jeHlqdc-p65Mu9V8Sw-sKp7W1YHGoOTr9qZ_0l9W3FnFO1HgLU9Qg2GakL3rFdR0MhrABRmBQGJWdZwtZTUBcQIjojC7CS5rPI4H3es0jxBf0bjsYDQkOUyNLQN0Q0DxaDBF7GcFFgwVNCkYTZBGOi2ARzIaSggklaknBNcEIUnCKklKQoESAACQsofAwwNlhiV6ixxKFImpEZI7IFwuBUy85zZI8PEyepIPRGynCJJhcgLCGZOtg6OlBBkIZN7Jolpw0QQG6BQ0VZC4YqwRNUDBbEQ-DuOhgcJDhFaHW0CFB5lEtEGuv8TQXcV_mwoREmx2RKaLIGdgCyVxowN1lLncindgRfGqF8FIw1AphIwNElp2Ts7OIXlADWonxwjdvgCmKkrAtICx3paJD_VC8lBgFSAIAbOW3appapfIoDXJCpRB6kpq7SgnlhrdBYWA2CppkUj-UJ0VEWqlC8kP9kB9qmUI9K4QPaWEUxPGZUVMknW-ICqbSqR99L_oVq5-u09fwLw) Takes the alphabet as a sorted list. 1-indexed. A port of [Jonathan Allan's Python answer](https://codegolf.stackexchange.com/a/252670/9288), but using the formula \$a(n)=\sum\_{i=0}^n k!/i!\$ for OEIS A000522. [Answer] # [Pyth](https://github.com/isaacg1/pyth), 8 bytes ``` xSs.pMyE ``` [Test suite](https://pythtemp.herokuapp.com/?code=xSs.pMyE&test_suite=1&test_suite_input=%5B%5D%0A%5B1%2C2%2C3%5D%0A%5B1%5D%0A%5B1%2C2%2C3%5D%0A%5B3%5D%0A%5B1%2C2%2C3%5D%0A%5B2%2C3%2C1%5D%0A%5B1%2C2%2C3%5D%0A%5B3%2C2%2C1%5D%0A%5B1%2C2%2C3%5D%0A%5B3%2C1%2C4%5D%0A%5B1%2C3%2C4%2C6%5D%0A%5B3%2C1%2C6%2C4%5D%0A%5B1%2C3%2C4%2C6%5D%0A%5B37%2C43%2C16%2C3%5D%0A%5B1%2C3%2C4%2C16%2C23%2C37%2C43%2C57%5D%0A%5B252%2C300%2C969%2C844%2C856%2C713%2C60%2C621%2C393%2C637%2C634%2C441%2C817%2C264%2C551%2C757%2C926%2C240%2C461%2C421%2C767%2C726%2C223%2C610%2C547%2C141%2C593%2C184%2C200%2C643%2C583%2C614%2C958%2C540%2C201%2C214%2C584%2C591%2C525%2C652%2C466%2C414%2C995%2C125%2C813%2C951%2C901%2C215%2C947%2C410%2C113%2C279%2C238%2C57%2C750%2C607%2C61%2C131%2C216%2C340%2C569%2C803%2C557%2C878%2C691%2C80%2C850%2C483%2C71%2C613%2C41%2C244%2C789%2C595%2C447%2C596%2C812%2C543%2C953%2C620%2C962%2C436%2C537%2C733%2C738%2C197%2C949%2C982%2C139%2C683%2C910%2C236%2C552%2C490%2C777%2C335%5D%0A%5B41%2C57%2C60%2C61%2C71%2C80%2C113%2C125%2C131%2C139%2C141%2C184%2C197%2C200%2C201%2C214%2C215%2C216%2C223%2C236%2C238%2C240%2C244%2C252%2C264%2C279%2C300%2C335%2C340%2C393%2C410%2C414%2C421%2C436%2C441%2C447%2C461%2C466%2C483%2C490%2C525%2C537%2C540%2C543%2C547%2C551%2C552%2C557%2C569%2C583%2C584%2C591%2C593%2C595%2C596%2C607%2C610%2C613%2C614%2C620%2C621%2C634%2C637%2C643%2C652%2C683%2C691%2C713%2C726%2C733%2C738%2C750%2C757%2C767%2C777%2C789%2C803%2C812%2C813%2C817%2C844%2C850%2C856%2C878%2C901%2C910%2C926%2C947%2C949%2C951%2C953%2C958%2C962%2C969%2C982%2C995%5D&debug=0&input_size=2) Takes the word as a list as the first input and the alphabet as a list as the second input, outputs the 1-index of the word. Unfortunately hits a MemoryError / times out for that last one, but I can't think of a reason it shouldn't work in theory. #### Explanation: ``` xSs.pMyE | Full code xSs.pMyEQ | with implicit variables ----------+----------------------------------------- yE | Generate all subsets of alphabet .pM | Generate all permutations of each subset s | Flatten the list S | Sort the list x Q | Find the index of the word ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~10~~ 8 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` à cá ÍbV ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=4CBj4SDNYlY&input=ImIzZWExY2Q0IgoiY2RhMyI) 1-indexed output. Takes the alphabet as a sorted string with each symbol represented by a unique byte, then the word as another string. ``` à cá ÍbV à # Get all substrings of the alphabet á # Get all the permutations of each substring c # Flatten to a single array Í # Sort lexicographically by the alphabet bV # Find the index of the word ``` The last test case runs slow enough that I haven't been able to check its output, but alphabets of that length should be supported. [Answer] # [Nibbles](http://golfscript.com/nibbles/index.html), ~~9~~ 8 bytes (16 nibbles) ``` ?`<+.`_0$``p$ ``` ``` ?`<>>+.`_0$``p$ `_0$ # get all subsequences of arg1 . # and map over this ``p$ # getting all permutations of each list, + # and flatten this list-of-list-of-lists, >> # remove the first element (the empty list), `< # and sort the list-of-lists, ? # finally, get the index of arg2. ``` [![enter image description here](https://i.stack.imgur.com/wYz7A.png)](https://i.stack.imgur.com/wYz7A.png) [Answer] # [Haskell](https://www.haskell.org/), ~~60~~ 58 bytes ``` f l=do y<-l;(y:)<$>[]:f[x|x<-l,x/=y] a!w=sum[1|x<-f a,w>x] ``` [Try it online!](https://tio.run/##hY/LCoMwEEX3fsUILlqItEl8oDX@SMgiYKXSqKW2GKH/nsZGFy6kq9y552RgbnK4X5UypgbFqh6mIlSXw5Qfi6DkIq@5/mhbIX1ik/CkP7Lh3XI8lzVINJZamFY2HTCoeg8ez6Z7QQAcIyAIqADfZgFhCHiHUkf38BwQLCvOezt@eZHirWRZhCBZPdtEzsvgn5isLiEb1ZnYYmIjTe1o3zh1X5dxxu62NKOUmC8 "Haskell – Try It Online") Thanks to @Laikoni for saving 2 Bytes using *do* notation. * 0 indexed *f l* generates vocabulary of set *l* *a!w* counts words less than *w* [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` œ€æ€`êÅΔQ ``` 1-based indexing (or actually 0-based indexing, by also handling `[]` at index `0`). [Try it online](https://tio.run/##yy9OTMpM/f//6ORHTWsOLwMSCYdXHW49NyXw//9oQx0jHeNYrmggqWMYCwA) or [verify (almost) all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWVC6P@jkx81rTm8DEgkHF51uPXclIjA/7U6/6Ojow11jHSMY3WiY2N1FBA8Q1SuMSoXSOqgqwDScCFjHRMdM7CgoY4JNkEzkHAsAA) (the last two test cases are omitted, because they time-out on TIO). **Explanation:** ``` œ # Get the powerset of the (implicit) input-list, including empty list €æ # Get all permutations of each sublist €` # Flatten it one level down ê # Sorted-uniquify the inner lists lexicographically ÅΔ # Get the first (0-based) index which is truthy for: Q # Is it equal to the second (implicit) input-list? # (which is output implicitly as result) ``` ]
[Question] [ This puzzle is derived from [CodinGame](https://www.codingame.com) SamSi's "Heart of the City" puzzle. ## Description You decide to take a walk in an `n` \* `n` tile city and go to the center tile. All of the buildings are infinitely small, but you have super vision and can see everything close up and far away. ## Constraints `n` is always odd You can see any building that is not directly obstructed by another one ## Task Mark each building visible with `*`. The building is visible iff it is not blocked by another building on the exact same line of vision. In other words, if `@` is the origin, the building is visible iff the x-coordinate and the y-coordinate are co-prime to each other. ## Example input and output Input: ``` 7 ``` Output: ``` ** ** * * * * ******* *@* ******* * * * * ** ** ``` `*` is a visible building, is an invisible building, and `@` is where you are. # Scoring Remember, this is **[code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'")**, so the answer with the least bytes wins. ``` var QUESTION_ID=91394,OVERRIDE_USER=59057;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i; ``` ``` body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}*{font-family:"Helvetica",sans-serif} ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> ``` [Answer] # Excel-VBA, (47\*n^2) bytes and 121 bytes **Instruction:** Excel turns out to be very handy for this challenge and there are combination of Excel formulas to get the exact pattern as the OP's shown for a given input. Luckily enough for me, Excel has a GCD function - a built-in formula to return greatest common divisor of positive integers so I don't have to create one using [Euclidean algorithm](https://en.wikipedia.org/wiki/Euclidean_algorithm). Why do I need a GCD function here? **It's because two numbers are called coprime, if their greatest common divisor equals 1**. The numbers here is the coordinate of the position, `x` and `y`, relative to the origin, `@`. Here is the Excel formula ``` =IF(GCD(ABS(COLUMN()-m),ABS(m-ROW()))=1,"*","") ``` where `m` is the name of a reference cell and it's equal to the smallest integer greater than or equal to `n/2`, ceiling(`n/2`), where `n` is the name of a reference cell for the input. Paste this formula in cell A1, then drag all over range with the size `n x n`. The length of the formula is 47 bytes but you have to replicate it `n x n` times, so it's equal to (47\*n^2) bytes. To automate the process and to reduce the use of characters, we can use VBA since it's integrated with Excel. First thing first, set a worksheet Excel like the following: [![enter image description here](https://i.stack.imgur.com/WLMhD.png)](https://i.stack.imgur.com/WLMhD.png) Then put the following code in the Immediate Window ``` n=[A1]:m=Int(n/2)+1:Range("A1",Cells(n,n))="=IF(GCD(ABS(COLUMN()-"&m &"),ABS("&m &"-ROW()))=1,""*"","""")":Cells(m,m)="@" ``` **Ungolfed the code:** ``` Sub A() n = [A1] m = Int(n / 2) + 1 Range("A1", Cells(n, n)) = "=IF(GCD(ABS(COLUMN()-" & m & "),ABS(" & m & "-ROW()))=1,""*"" ,"""")" Cells(m, m) = "@" End Sub ``` **Explanation:** 1. `n = [A1]` : Set n as the input and assign the value of cell A1 to n. 2. `m = Int(n / 2) + 1` : Custom way to return the same output as the ceiling function for argument `n/2`. 3. `Range("A1", Cells(n, n)) = "=IF(GCD(ABS(COLUMN()-" & m & "),ABS(" & m & "-ROW()))=1,""*"" ,"""")"` : Paste the formula above to every cell in the range with size `n x n` start from cell A1. 4. `Cells(m, m) = "@"` : Assign the center of the range with a character `@`. **Output:** Figure below is the example output for the input `n = 11` [![enter image description here](https://i.stack.imgur.com/PJ9hz.png)](https://i.stack.imgur.com/PJ9hz.png) I set the font color to red to make it look more attractive. Even better [![enter image description here](https://i.stack.imgur.com/EiIZe.png)](https://i.stack.imgur.com/EiIZe.png) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 16 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` :2ạḶgþ`«2ị“* @”Y ``` [Try it online!](http://jelly.tryitonline.net/#code=OjLhuqHhuLZnw75gwqsy4buL4oCcKiBA4oCdWQ&input=&args=Nw) ### How it works ``` :2ạḶgþ`«2ị“* @”Y Main link. Argument: 2n + 1 :2 Perform integer division by 2, yielding n. Ḷ Yield [0, ..., 2n]. ạ Take the absolute difference of the result to both sides. This yields A := [n, ... 0, ... n]. ` Call the quicklink to the left with left and right argument A. þ Table; call the link to the left for all x in A and all y in A. g Yield the GCD of x and y. «2 Truncate the GCD at 2, leaving 0 for the origin, 1 for coprime coordinates, and 2 otherwise. ị“* @” Index into that string, mapping [1, 2, 0] to ['*', ' ', '@']. Y Join, separating by linefeeds. ``` [Answer] # J, 24 bytes ``` '@* '{~2<.[:+./~<.@-:-i. ``` A port of [Dennis' answer in Jelly](https://codegolf.stackexchange.com/a/91398/48934). [Answer] # [Perl 6](http://perl6.org/), 77 or 74 bytes Full program *(77 bytes)*: ``` my \h=Int(get/2);say |map {$_|$^j??2>$j gcd$_??'*'!!' '!!'@'},-h..h for -h..h ``` ([try it online](https://glot.io/snippets/ehwt4srqs4)) If it is acceptable to return the output from a lambda as a list of lists of 1-character strings *(74 bytes)*: ``` {my \h=$_ div 2;map {map {$^i|$_??2>$i gcd$_??'*'!!' '!!'@'},-h..h},-h..h} ``` ([try it online](https://glot.io/snippets/ehwt28xbst)) [Answer] # [S.I.L.O.S](http://github.com/rjhunjhunwala/S.I.L.O.S), 236 bytes ``` GOTO s funcg if q p r=p return lblp t=p t%q p=q q=t GOSUB g return lbls readIO m=i m/2 a=i lbla a-1 a-m b=i lblb b-1 b-m p=a p| q=b q| GOSUB g r-1 A=r A| r/A r*-1 r+1 p=r r*r r*6 p*4 r+p r+32 printChar r b+m if b b printLine a+m if a a ``` [Try it online!](http://silos.tryitonline.net/#code=R09UTyBzCmZ1bmNnCmlmIHEgcApyPXAKcmV0dXJuCmxibHAKdD1wCnQlcQpwPXEKcT10CkdPU1VCIGcKcmV0dXJuCmxibHMKcmVhZElPCm09aQptLzIKYT1pCmxibGEKYS0xCmEtbQpiPWkKbGJsYgpiLTEKYi1tCnA9YQpwfApxPWIKcXwKR09TVUIgZwpyLTEKQT1yCkF8CnIvQQpyKi0xCnIrMQpwPXIKcipyCnIqNgpwKjQKcitwCnIrMzIKcHJpbnRDaGFyIHIKYittCmlmIGIgYgpwcmludExpbmUgCmErbQppZiBhIGE&input=&args=MTU) Port of [my answer in C](https://codegolf.stackexchange.com/a/91396/48934). [Answer] # C, ~~147~~ ~~145~~ ~~135~~ 133 bytes **2 bytes thanks to Dennis.** **10 bytes thanks to Arnauld.** **2 bytes thanks to H Walters.** ``` r,m,i,j;g(a,b){r=b?g(b,a%b):a;}main(n){scanf("%d",&n);for(m=n/2,i=-m;i<=m;putchar(r?r*r-1?32:42:64),i+=++j%n<1&&puts(""))g(i,j%n-m);} ``` [Ideone it!](http://ideone.com/YLwCxz) Golfing advice welcome as always. [Answer] ## Javascript (ES6), ~~114~~ ~~113~~ 105 bytes This started as a port of [Leaky Nun's C version](https://codegolf.stackexchange.com/questions/91394/visible-buildings/91396#91396) and was then further optimized. Most optimizations are specific to JS. ``` n=>(r=j=>i<n?('*@*'[1+(g=(i,j)=>j?g(j,i%j):i)(i-m,j-m)]||' ')+(++j<n?'':(i++,` `))+r(j%n):'')(i=0,m=n>>1) ``` Example: ``` let f = n=>(r=j=>i<n?('*@*'[1+(g=(i,j)=>j?g(j,i%j):i)(i-m,j-m)]||' ')+(++j<n?'':(i++,` `))+r(j%n):'')(i=0,m=n>>1) console.log(f(7)) ``` [Answer] # Pyth, 40 bytes ``` L@"@* "hS[b2)jsMcQyM.aMiM*.**2[r_/Q2h/Q2 ``` I'm very new to Pyth, so this can likely be golfed further. [Try it online](https://pyth.herokuapp.com/?code=L%40%22%40%2a+%22hS%5Bb2%29jsMcQyM.aMiM%2a.%2a%2a2%5Br_%2FQ2h%2FQ2&input=7&debug=0) **How it works** ``` L@"@* "hS[b2)jsMcQyM.aMiM*.**2[r_/Q2h/Q2 L@"@* "hS[b2) Lambda y. Input: b L Declare lambda [b2) List [b, 2] S Sort ascending h Head. Yield first element a, clamping to max 2 "@* " String literal "@* " @ Index into string with a, yielding string[a] jsMcQyM.aMiM*.**2[r_/Q2h/Q2 Program. Input: Q _/Q2 /Q2 -Q//2 and Q//2 h Head. Q//2+1 r Range [-Q//2, Q//2+1] [ List *2 Duplicate .* Splat. Unpack * Cartesian product. Yield all coordinate pairs iM Map GCD over above .aM Map absolute value over above yM Map y over above, yielding required characters cQ Chunk. Split above into Q pieces sM Map concatenate over above j Join on newlines Implicitly print ``` [Answer] ## GolfScript, ~~98~~ 83 bytes ``` ~:l.2/~):o:i;{o{.abs i abs.!!{{.@\%.}do}*;1={'*'}{' '}if\.i|!{\;'@'\}*)}l*;i):i;n}* ``` [Try it online!](http://golfscript.tryitonline.net/#code=fjpsLjIvfik6bzppO3tvey5hYnMgaSBhYnMuISF7ey5AXCUufWRvfSo7MT17JyonfXsnICd9aWZcLml8IXtcOydAJ1x9Kil9bCo7aSk6aTtufSo&input=MTE) ***Input = 11*** ``` **** **** * * * * * * ** ** ** ** * * * * * * *********** *@* *********** * * * * * * ** ** ** ** * * * * * * **** **** ``` [Answer] # [APL (Dyalog Classic)](https://www.dyalog.com/), 23 bytes ``` '@ * '[3⌊∨/|↑(⊖-⌽)⍳2⍴⎕] ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob2pm/qO2CQZcjzra0/6rOyhoKahHGz/q6XrUsUK/5lHbRI1HXdN0H/Xs1XzUu9noUe8WoI7Y/0DF/9O4zLnU1bnSuIwNAQ "APL (Dyalog Classic) – Try It Online") ]
[Question] [ # Task Given a list of space-delimited integers as input, output all unique non-empty subsets of these numbers that each subset sums to 0. --- ## Test Case Input: `8 −7 5 −3 −2` Output: `-3 -2 5` --- ## Winning Criterion This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins! [Answer] # [Brachylog](https://github.com/JCumin/Brachylog) (2), 9 characters ``` {⊇.+0∧}ᵘb ``` [Try it online!](https://tio.run/nexus/brachylog2#@1/9qKtdT9vgUcfy2odbZyT9/x9toRNvrmOqE2@sE2@kYxL7PwoA "Brachylog – TIO Nexus") ``` {⊇.+0∧}ᵘb ⊇ subset +0 that sums to 0 . ∧ output the subset { }ᵘ take all unique solutions b except the first (which is the empty solution) ``` [Answer] ### GolfScript, 41 characters ``` ~][[]]\{`{1$+$}+%}%;(;.&{{+}*!},{" "*}%n* ``` If you do not care about the specific output format you can shorten the code to 33 characters. ``` ~][[]]\{`{1$+$}+%}%;(;.&{{+}*!},` ``` Example (see [online](http://golfscript.apphb.com/?c=OyI4IC03IDUgLTMgLTIgNCIKCn5dW1tdXVx7YHsxJCskfSslfSU7KDsuJnt7K30qIX0seyIgIip9JW4qCgpwcmludA%3D%3D)): ``` > 8 -7 5 -3 -2 4 -3 -2 5 -7 -2 4 5 -7 -3 -2 4 8 ``` [Answer] ## Python, 119 chars ``` def S(C,L): if L:S(C,L[1:]);S(C+[L[0]],L[1:]) elif sum(map(int,C))==0and C:print' '.join(C) S([],raw_input().split()) ``` Enumerates all 2^n subsets recursively and checks each one. [Answer] ## Python, 120 I'm a character worse than Keith's solution. But... this is too close to not post. One of my favorite features of code-golf is how dissimilar similar-length solutions can be. ``` l=raw_input().split() print[c for c in[[int(j)for t,j in enumerate(l)if 2**t&i]for i in range(1,2**len(l))]if sum(c)==0] ``` [Answer] ## Python (~~128 137~~ 136) Damn you, `itertools.permutations`, for having such a long name! Brute force solution. I'm surprised it's not the shortest: but I guess `itertools` ruins the solution. Ungolfed: ``` import itertools initial_set=map(int, input().split()) ans=[] for length in range(1, len(x)+1): for subset in itertools.permutations(initial_set, length): if sum(subset)==0: ans+=str(sorted(subset)) print set(ans) ``` Golfed (ugly output): ``` from itertools import* x=map(int,input().split()) print set(`sorted(j)`for a in range(1,len(x)+1)for j in permutations(x,a)if sum(j)==0) ``` Golfed (pretty output) (183): ``` from itertools import* x=map(int,input().split()) print `set(`sorted(j)`[1:-1]for a in range(1,len(x)+1)for j in permutations(x,a)if sum(j)==0)`[5:-2].replace("'","\n").replace(",","") ``` `import itertools as i`: importing the itertools module and calling it `i` `x=map(int,input().split())`: seperates the input by spaces, then turns the resulting lists' items into integers (`2 3 -5` -> `[2, 3, -5]`) set(`sorted(j)`for a in range(1,len(x)+1)for j in i.permutations(x,a)if sum(j)==0): Returns a list of all subsets in `x`, sorted, where the sum is 0, and then gets only the unique items (`set(...)`) The graves (`) around `sorted(j)` is Python shorthand for `repr(sorted(j))`. The reason why this is here is because sets in Python cannot handle lists, so the next best thing is to use strings with a list as the text. [Answer] ## C# – 384 characters OK, functional-style programming in C# is not that *short*, but I *love* it! (Using just a brute-force enumeration, nothing better.) ``` using System;using System.Linq;class C{static void Main(){var d=Console.ReadLine().Split(' ').Select(s=>Int32.Parse(s)).ToArray();foreach(var s in Enumerable.Range(1,(1<<d.Length)-1).Select(p=>Enumerable.Range(0,d.Length).Where(i=>(p&1<<i)!=0)).Where(p=>d.Where((x,i)=>p.Contains(i)).Sum()==0).Select(p=>String.Join(" ",p.Select(i=>d[i].ToString()).ToArray())))Console.WriteLine(s);}} ``` Formatted and commented for more readability: ``` using System; using System.Linq; class C { static void Main() { // read the data from stdin, split by spaces, and convert to integers, nothing fancy var d = Console.ReadLine().Split(' ').Select(s => Int32.Parse(s)).ToArray(); // loop through all solutions generated by the following LINQ expression foreach (var s in // first, generate all possible subsets; well, first just their numbers Enumerable.Range(1, (1 << d.Length) - 1) // convert the numbers to the real subsets of the indices in the original data (using the number as a bit mask) .Select(p => Enumerable.Range(0, d.Length).Where(i => (p & 1 << i) != 0)) // and now filter those subsets only to those which sum to zero .Where(p => d.Where((x, i) => p.Contains(i)).Sum() == 0) // we have the list of solutions here! just convert them to space-delimited strings .Select(p => String.Join(" ", p.Select(i => d[i].ToString()).ToArray())) ) // and print them! Console.WriteLine(s); } } ``` [Answer] # **SWI-Prolog** 84 This version prints the list, instead of trying to find an appropriate binding for a term in a predicate. ``` s([],O):-O=[_|_],sum_list(O,0),print(O). s([H|T],P):-s(T,[H|P]). s([_|T],O):-s(T,O). ``` ### Input method ``` s([8,-7,5,-3,-2,4],[]). ``` --- For the record, this is the version that finds a binding to satisfy the predicate: ``` s(L,O):-s(L,0,O),O=[_|_]. s([],0,[]). s([H|T],S,[H|P]):-R is H+S,s(T,R,P). s([_|T],S,O):-s(T,S,O). ``` ### Input method ``` s([8,-7,5,-3,-2,4],O). ``` Previous revision contains an incomplete solution that didn't manage to remove empty set. [Answer] # Mathematica 62 57 38 **Code** Input entered as integers in an array, `x`. ``` x ``` ![input](https://i.stack.imgur.com/4YuJs.png) ``` Grid@Select[Subsets@x[[1, 1]], Tr@# == 0 &] ``` --- **Output** ![output](https://i.stack.imgur.com/mB2cn.png) --- [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes ``` ŒPḊSÐḟ ``` [Try it online!](https://tio.run/##y0rNyan8///opICHO7qCD094uGP@////LXR0zXVMdXSNdXSNAA "Jelly – Try It Online") Just for completeness. Similar to Brachylog, Jelly also postdates the challenge, but by now, newer languages compete normally. ``` ŒP Power set. Ḋ Dequeue, remove the first element (empty set). Ðḟ Filter out the subsets with truthy (nonzero)... S sum. ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 5 bytes ``` æ¦ʒO> ``` [Try it online!](https://tio.run/##MzBNTDJM/f//8LJDy05N8rf7/z/aQkfXXMdUR9dYR9coFgA "05AB1E – Try It Online") --- If input must be space delimited, prepending `#` to this answer is the only change required. [Answer] ## J, 57 53 51 49 characters ``` >a:-.~(#:@i.@(2&^)@#<@":@(#~0=+/)@#"1 _])".1!:1[1 ``` Usage: ``` >a:-.~(#:@i.@(2&^)@#<@":@(#~0=+/)@#"1 _])".1!:1[1 8 _7 5 _3 _2 4 5 _3 _2 _7 5 _2 4 8 _7 _3 _2 4 ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), 8 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)CP437 ``` â±3╒yΣ╓à ``` [Run and debug online!](https://staxlang.xyz/#c=%C3%A2%C2%B13%E2%95%92y%CE%A3%E2%95%93%C3%A0&i=8+-7+5+-3+-2&a=1) ## Explanation Uses the unpacked version (9 bytes) to explain. ``` LS{|+!fmJ L Convert to list S Powerset { f Filter with block |+! Sum is zero mJ Print each subset, joined by spaces ``` [Answer] # [J](http://jsoftware.com/), 34 bytes ``` (a:-.~](<@#~0=+/)@#~[:#:@i.2^#)@". ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/NRKtdPXqYjVsHJTrDGy19TWBdLSVspVDpp5RnLKmg5Lef02u1OSMfAUNG1OFeGOFeCNNBVuFNAV1C4V4cwWokDpUCZBrag0TtFawADNMwQxzoIiCGZCnqaBrha4fLKH@HwA "J – Try It Online") ## how `".` converts the input to a list. then: ``` a: -.~ ] (<@#~ (0 = +/))@#~ [: #:@i. 2 ^ # i. NB. ints from 0 to... 2 ^ # NB. 2 to the input len [: #:@ NB. converted to binary masks ] ( ) #~ NB. filter the input using NB. using those masks, giving NB. us all subsets ( )@ NB. and to each one... ( #~ (0 = +/)) NB. return it if its sum is NB. 0, otherwise make it NB. the empty list. (<@ ) NB. and box the result. NB. now we have our answers NB. and a bunch of empty NB. boxes, or aces (a:). a: -.~ NB. remove the aces. ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 51 bytes ``` *.words.combinations.skip.grep(!*.sum)>>.Bag.unique ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwX0uvPL8opVgvOT83KTMvsSQzP69Yrzg7s0AvvSi1QENRS6@4NFfTzk7PKTFdrzQvs7A09b81V3FipUKahpKFgq65gqmCrrGCrpGCiZImXMIYJAYigGL/AQ "Perl 6 – Try It Online") Returns a list of unique Bags that sum to 0. A Bag is a weighted Set. ### Explanation: ``` *.words # Split by whitespace .combinations # Get the powerset .skip # Skip the empty list .grep(!*.sum) # Select the ones that sum to 0 >>.Bag # Map each to a weighted Set .unique # And get the unique sets ``` [Answer] # Ruby, 110 bytes ``` a=gets.split.map &:to_i;b=[];(1...a.length).each{|c|a.permutation(c){|d|d.sum==0?b<<d:0}};p b.map(&:sort).uniq ``` Will add TIO link later. Takes input from stdin as a list of numbers, e.g. `8 −7 5 −3 −2` How it works: It converts the input into an array of numbers. Gets all the permutations of the lengths from 1 to the array's length. It adds them to the output array if they sum to 0. It outputs the array without duplicates. Output for the sample input: `[[-3, -2, 5]]` ]