text
stringlengths
180
608k
[Question] [ Given an integer 2n, find the number of possible ways in which 2n^2 black pawns and 2n^2 white pawns can be arranged on a 2n by 2n chess board such that no pawn attack another. * A black pawn can attack only a white pawn, and vice versa. * The usual chess rules of attacking follow, i.e, white pawns attack squares immediately diagonally in front, and the black pawns attack squares immediately diagonally backward (as seen by the white observer). * All rotation, reflections count as distinct. --- The program that can output all possible configurations for the highest value of 2n in 120 seconds wins. (All programs are welcome, though) For example, Alice's program can deal with upto n=16 within 120 seconds while Bob's can deal with upto n=20 within the same time. Bob wins. Platform: Linux 2.7GHz @ 4 CPUs [Answer] # Java, n=87 on my machine The result for n=87 is ``` 62688341832480765224168252369740581641682638216282495398959252035334029997073369148728772291668336432168 ``` ``` import java.math.BigInteger; public class NonattackingPawns { static BigInteger count(int n) { BigInteger[][] a0 = new BigInteger[n+1][n*n+1], a1 = new BigInteger[n+1][n*n+1], tm; for(int h = 0; h <= n; h++) a0[h][0] = h%2==0? BigInteger.ONE: BigInteger.ZERO; for(int c = 1; c <= 2*n; c++) { int minp = 0; for(int h = 0; h <= n; h++) { java.util.Arrays.fill(a1[h], BigInteger.ZERO); if(h>0) minp += c >= 2*h-c%2 ? 2*h - c%2 : c; int maxp = Math.min(n*(c-1)+h, n*n); for(int p = minp; p <= maxp; p++) { BigInteger sum = a0[h][p-h]; if(c%2==1 && h>0) sum = sum.add(a0[h-1][p-h]); else if(c%2==0 && h<n) sum = sum.add(a0[h+1][p-h]); a1[h][p] = sum; } } tm=a0; a0=a1; a1=tm; } BigInteger[] s = new BigInteger[n*n+1]; for(int p = 0; p <= n*n; p++) { BigInteger sum = BigInteger.ZERO; for(int h = 0; h <= n; h++) sum = sum.add(a0[h][p]); s[p] = sum; } BigInteger ans = BigInteger.ZERO; for(int p = 0; p < n*n; p++) ans = ans.add(s[p].multiply(s[p])); return ans.shiftLeft(1).add(s[n*n].multiply(s[n*n])); } public static void main(String[] args) { for(int n = 0;; n++) { System.out.println(n + " " + count(n)); } } } ``` This currently uses a dynamic programming scheme taking O(n^4) operations to calculate the ways to place `p` pawns on the squares of one color for `0 <= p <= n^2`. I think it should be possible to do this much more efficiently. [Check out the results here.](http://ideone.com/uFx1s2) ### Explanation In a valid solution, the lowermost white pawns in each column must form a zigzagging line like this: ![pawn line](https://i.stack.imgur.com/dwbdc.png) That is, the height of the line in column *c* must be +/- 1 from its position in column *c - 1*. The line can also go onto two imaginary rows above the top of the board. We can use dynamic programming to find the number of ways to draw a line on the first *c* columns that includes *p* pawns on those columns, is at height *h* on the *c*th column, using the results for column *c - 1*, heights *h +/- 1*, and number of pawns *p - h*. [Answer] # Java Currently, my code is very long and tedious, I'm working on making it faster. I use a recursive method in order to find the values. It computes the first 5 within 2 or 3 seconds, but it gets much slower afterwards. Also, I'm not sure yet if the numbers are right, but the first few seem to line up with the comments. Any suggestions are welcome. **Output** ``` 2x2: 3 4x4: 30 6x6: 410 8x8: 6148 10x10: 96120 ``` **Explanation** The basic idea is recursion. Essentially you start with an empty board, a board with all zeros. The recursive method just checks to see if it can put a black or white pawn in the next position, if it can only put one color, it puts it there and calls itself. If it can put both colors it calls itself twice, one with each color. Each time it calls itself it decreases the squares left and the appropriate color left. When it has filled the entire board it returns the the current count + 1. If it finds out that there is no way to put a black or white pawn in the next position, it returns 0, which means it's a dead path. **Code** ``` public class Chess { public static void main(String[] args){ System.out.println(solve(1)); System.out.println(solve(2)); System.out.println(solve(3)); System.out.println(solve(4)); System.out.println(solve(5)); } static int solve(int n){ int m =2*n; int[][] b = new int[m][m]; for(int i = 0; i < m; i++){ for(int j = 0; j < m; j++){ b[i][j]=0; } } return count(m,m*m,m*m/2,m*m/2,0,b); } static int count(int n,int sqLeft, int bLeft, int wLeft, int count, int[][] b){ if(sqLeft == 0){ /*for(int i = 0; i < n; i++){ for(int j = 0; j < n; j++){ System.out.print(b[i][j]); } System.out.println(); } System.out.println();*/ return count+1; } int x=(sqLeft-1)%n; int y=(sqLeft-1)/n; if(wLeft==0){ if(y!=0){ if ((x==0?true:b[x-1][y-1]!=1)&&(x==n-1?true:b[x+1][y-1]!= 1)) { b[x][y] = 2; return count(n, sqLeft-1, bLeft-1, wLeft, count, b); } else { return 0; } } else { b[x][y]=2; return count(n,sqLeft-1,bLeft-1,wLeft,count,b); } } else if(bLeft==0){ if(y!=n-1){ if((x==0?true:b[x-1][y+1]!=2)&&(x==n-1?true:b[x+1][y+1]!=2)){ b[x][y]=1; return count(n,sqLeft-1,bLeft,wLeft-1,count,b); } else { return 0; } } else { b[x][y]=1; return count(n,sqLeft-1,bLeft,wLeft-1,count,b); } } else{ if(y==0){ if((x==0?true:b[x-1][y+1]!=2)&&(x==n-1?true:b[x+1][y+1]!=2)){ int[][] c=new int[n][n]; for(int i = 0; i < n; i++){ System.arraycopy(b[i], 0, c[i], 0, n); } b[x][y]=2; c[x][y]=1; return count(n,sqLeft-1,bLeft,wLeft-1,count,c)+count(n,sqLeft-1,bLeft-1,wLeft,count,b); } else { b[x][y]=2; return count(n,sqLeft-1,bLeft-1,wLeft,count,b); } }else if(y==n-1){ if((x==0?true:b[x-1][y-1]!=1)&&(x==n-1?true:b[x+1][y-1]!=1)){ int[][] c=new int[n][n]; for(int i = 0; i < n; i++){ System.arraycopy(b[i], 0, c[i], 0, n); } b[x][y]=2; c[x][y]=1; return count(n,sqLeft-1,bLeft,wLeft-1,count,c)+count(n,sqLeft-1,bLeft-1,wLeft,count,b); } else { b[x][y]=1; return count(n,sqLeft-1,bLeft,wLeft-1,count,b); } }else{ if(((x==0?true:b[x-1][y-1]!=1)&&(x==n-1?true:b[x+1][y-1]!=1))&&((x==0?true:b[x-1][y+1]!=2)&&(x==n-1?true:b[x+1][y+1]!=2))){ int[][] c=new int[n][n]; for(int i = 0; i < n; i++){ System.arraycopy(b[i], 0, c[i], 0, n); } b[x][y]=2; c[x][y]=1; return count(n,sqLeft-1,bLeft,wLeft-1,count,c)+count(n,sqLeft-1,bLeft-1,wLeft,count,b); } else if ((x==0?true:b[x-1][y-1]!=1)&&(x==n-1?true:b[x+1][y-1]!=1)){ b[x][y]=2; return count(n,sqLeft-1,bLeft-1,wLeft,count,b); } else if ((x==0?true:b[x-1][y+1]!=2)&&(x==n-1?true:b[x+1][y+1]!=2)){ b[x][y]=1; return count(n,sqLeft-1,bLeft,wLeft-1,count,b); } else { return 0; } } } } } ``` [Try it here](http://ideone.com/CH26vk) *(Doesn't run fast enough for Ideone so the last value doesn't print, looks like my solution isn't very good!)* [Answer] # C++ with pthreads, n = ~~147~~ 156 The latest result is from running the same code as before on a beefier machine. This was now run on a desktop with a quad-core i7 (Core i7-4770), which got to n=156 in 120 seconds. The result is: > > 7858103688882482349696225090648142317093426691269441606893544257091315906431773702676266198643058148987365151560565922891852481847049321541347582728793175114543840164406674137410614843200 > > > This is using a dynamic programming algorithm. I initially pondered approaches where the result would be built row by row, but I could never come up with a way to expand the solution without tracking a ton of state. The key insights that enabled a reasonably efficient solution were: * Since pawns on black squares can only attack pawns on other black squares, and the same is true for white squares, the black and white squares are independent, and can be processed separately. And since they are equivalent, we only need to process one of the two. * The problem gets much easier when processing the board diagonal by diagonal. If you look at one diagonal of a valid configuration, it always consists of a sequence of black pawns followed by a sequence of white pawns (where either sequence can also be empty). In other words, each diagonal can be fully characterized by its number of black pawns. Therefore, the state tracked for each diagonal is the number of valid pawn configurations for each combination of: * Number of black pawns in the row (or in other words, the position within the diagonal that separates the black pawns from the white pawns). * Total count of black pawns used. We need to track the whole thing per pawn count because we only need the equal number of black pawns and white pawns at the very end. While processing the diagonals, the counts can be different, and still result in valid solutions in the end. When stepping from one diagonal to the next one, there is another constraint to build valid solutions: The position that separates black pawns from white pawns can not increase. So the number of valid configurations is calculated as the sum of the valid configurations of the previous diagonal for positions that are equal or larger. The basic DP step is then very simple. Each value in a diagonal is just a sum of values from the previous diagonal. The only somewhat painful part is calculating the indices and loop ranges correctly. Since we're working on diagonals, the length increases during the first half of the calculation, and decreases for the second half, which makes the calculation of the loop ranges more cumbersome. There's also some considerations for the values at the boundary of the board, since they only have diagonal neighbors on one side when stepping from diagonal to diagonal. The amount of memory used is O(n^3). I keep two copies of the state data, and ping pong between them. I believe it would be possible to operate with a single instance of the state data. But you would have to be very careful that no values are updated before the old values are fully consumed. Also, it would not work well for the parallel processing I introduced. Runtime complexity is... polynomial. There are 4 nested loops in the algorithm, so at first sight it would look like O(n^4). But you obviously need bigints at these sizes, and the numbers themselves also get longer at larger sizes. The number of digits in the result seems to increase roughly proportionally to n, which would make the whole thing O(n^5). On the other hand, I found some performance improvements, which avoids going through the full range of all loops. So while this is still a fairly expensive algorithm, it gets much farther than the algorithms that enumerate solutions, which are all exponential. Some notes on the implementation: * While there can be up to 2\*n^2 black pawns on the black squares, I only calculate the configuration numbers up to n^2 black pawns. Since there's a symmetry between black and white pawns, the configuration count for k and 2\*n^2-k are the same. * The number of solutions is calculated at the end from the configuration counts on the black squares based on a similar symmetry. The total number of solutions (which need to have 2\*n^2 pawns of each color) is the number of configurations for k black pawns on one color of squares multiplied by the number of configurations for 2\*n^2-k black pawns on the other color of squares, summed over all k. * In addition to just storing the configuration counts per diagonal position and pawn count, I also store the range of pawn counts that have valid configurations per position. This allows cutting down the range of the inner loop substantially. Without this, I found that a lot of zeros were being added. I got a very substantial performance improvement from this. * The algorithm parallelizes fairly well, particularly at large sizes. The diagonals have to be processes sequentially, so there is a barrier at the end of each diagonal. But the positions within the diagonal can be processed in parallel. * Profiling shows that the bottleneck is clearly in adding bigint values. I played around with some variations of the code, but it's not heavily optimized. I suspect that there could be a significant improvement from inline assembly to use 64-bit additions with carry. Main algorithm code. `THREADS` controls the number of threads used, where the number of CPU cores should be a reasonable starting point: ``` #ifndef THREADS #define THREADS 2 #endif #if THREADS > 1 #include <pthread.h> #endif #include <vector> #include <iostream> #include <sstream> #include "BigUint.h" typedef std::vector<BigUint> BigUintVec; typedef std::vector<int> IntVec; static int N; static int NPawn; static int NPos; static BigUintVec PawnC[2]; static IntVec PawnMinC[2]; static IntVec PawnMaxC[2]; #if THREADS > 1 static pthread_mutex_t ThreadMutex; static pthread_cond_t ThreadCond; static int BarrierCount; #endif #if THREADS > 1 static void ThreadBarrier() { pthread_mutex_lock(&ThreadMutex); --BarrierCount; if (BarrierCount) { pthread_cond_wait(&ThreadCond, &ThreadMutex); } else { pthread_cond_broadcast(&ThreadCond); BarrierCount = THREADS; } pthread_mutex_unlock(&ThreadMutex); } #endif static void* countThread(void* pData) { int* pThreadIdx = static_cast<int*>(pData); int threadIdx = *pThreadIdx; int prevDiagMin = N - 1; int prevDiagMax = N; for (int iDiag = 1; iDiag < 2 * N; ++iDiag) { BigUintVec& rSrcC = PawnC[1 - iDiag % 2]; BigUintVec& rDstC = PawnC[iDiag % 2]; IntVec& rSrcMinC = PawnMinC[1 - iDiag % 2]; IntVec& rDstMinC = PawnMinC[iDiag % 2]; IntVec& rSrcMaxC = PawnMaxC[1 - iDiag % 2]; IntVec& rDstMaxC = PawnMaxC[iDiag % 2]; int diagMin = prevDiagMin; int diagMax = prevDiagMax;; if (iDiag < N) { --diagMin; ++diagMax; } else if (iDiag > N) { ++diagMin; --diagMax; } int iLastPos = diagMax; if (prevDiagMax < diagMax) { iLastPos = prevDiagMax; } for (int iPos = diagMin + threadIdx; iPos <= iLastPos; iPos += THREADS) { int nAdd = iPos - diagMin; for (int iPawn = nAdd; iPawn < NPawn; ++iPawn) { rDstC[iPos * NPawn + iPawn] = 0; } rDstMinC[iPos] = NPawn; rDstMaxC[iPos] = -1; int iFirstPrevPos = iPos; if (!nAdd) { iFirstPrevPos = prevDiagMin; } for (int iPrevPos = iFirstPrevPos; iPrevPos <= prevDiagMax; ++iPrevPos) { int iLastPawn = rSrcMaxC[iPrevPos]; if (iLastPawn + nAdd >= NPawn) { iLastPawn = NPawn - 1 - nAdd; } if (rSrcMinC[iPrevPos] > iLastPawn) { continue; } if (rSrcMinC[iPrevPos] < rDstMinC[iPos]) { rDstMinC[iPos] = rSrcMinC[iPrevPos]; } if (iLastPawn > rDstMaxC[iPos]) { rDstMaxC[iPos] = iLastPawn; } for (int iPawn = rSrcMinC[iPrevPos]; iPawn <= iLastPawn; ++iPawn) { rDstC[iPos * NPawn + iPawn + nAdd] += rSrcC[iPrevPos * NPawn + iPawn]; } } if (rDstMinC[iPos] <= rDstMaxC[iPos]) { rDstMinC[iPos] += nAdd; rDstMaxC[iPos] += nAdd; } } if (threadIdx == THREADS - 1 && diagMax > prevDiagMax) { int pawnFull = (iDiag + 1) * (iDiag + 1); rDstC[diagMax * NPawn + pawnFull] = 1; rDstMinC[diagMax] = pawnFull; rDstMaxC[diagMax] = pawnFull; } prevDiagMin = diagMin; prevDiagMax = diagMax; #if THREADS > 1 ThreadBarrier(); #endif } return 0; } static void countPawns(BigUint& rRes) { NPawn = N * N + 1; NPos = 2 * N; PawnC[0].resize(NPos * NPawn); PawnC[1].resize(NPos * NPawn); PawnMinC[0].assign(NPos, NPawn); PawnMinC[1].assign(NPos, NPawn); PawnMaxC[0].assign(NPos, -1); PawnMaxC[1].assign(NPos, -1); PawnC[0][(N - 1) * NPawn + 0] = 1; PawnMinC[0][N - 1] = 0; PawnMaxC[0][N - 1] = 0; PawnC[0][N * NPawn + 1] = 1; PawnMinC[0][N] = 1; PawnMaxC[0][N] = 1; #if THREADS > 1 pthread_mutex_init(&ThreadMutex, 0); pthread_cond_init(&ThreadCond, 0); BarrierCount = THREADS; int threadIdxA[THREADS] = {0}; pthread_t threadA[THREADS] = {0}; for (int iThread = 0; iThread < THREADS; ++iThread) { threadIdxA[iThread] = iThread; pthread_create(threadA + iThread, 0, countThread, threadIdxA + iThread); } for (int iThread = 0; iThread < THREADS; ++iThread) { pthread_join(threadA[iThread], 0); } pthread_cond_destroy(&ThreadCond); pthread_mutex_destroy(&ThreadMutex); #else int threadIdx = 0; countThread(&threadIdx); #endif BigUint solCount; BigUintVec& rResC = PawnC[1]; for (int iPawn = 0; iPawn < NPawn; ++iPawn) { BigUint nComb = rResC[(N - 1) * NPawn + iPawn]; nComb *= nComb; if (iPawn < NPawn - 1) { nComb *= 2; } solCount += nComb; } std::string solStr; solCount.toDecString(solStr); std::cout << solStr << std::endl; } int main(int argc, char* argv[]) { std::istringstream strm(argv[1]); strm >> N; BigUint res; countPawns(res); return 0; } ``` This also needs a bigint class that I wrote for this purpose. Note that this is not a general purpose bigint class. It does just enough to support the operations used by this specific algorithm: ``` #ifndef BIG_UINT_H #define BIG_UINT_H #include <cstdint> #include <string> #include <vector> class BigUint { public: BigUint() : m_size(1), m_cap(MIN_CAP), m_valA(m_fixedValA) { m_valA[0] = 0; } BigUint(uint32_t val) : m_size(1), m_cap(MIN_CAP), m_valA(m_fixedValA) { m_valA[0] = val; } BigUint(const BigUint& rhs) : m_size(rhs.m_size), m_cap(MIN_CAP), m_valA(m_fixedValA) { if (m_size > MIN_CAP) { m_cap = m_size; m_valA = new uint32_t[m_cap]; } for (int iVal = 0; iVal < m_size; ++iVal) { m_valA[iVal] = rhs.m_valA[iVal]; } } ~BigUint() { if (m_cap > MIN_CAP) { delete[] m_valA; } } BigUint& operator=(uint32_t val) { m_size = 1; m_valA[0] = val; return *this; } BigUint& operator=(const BigUint& rhs) { if (rhs.m_size > m_cap) { if (m_cap > MIN_CAP) { delete[] m_valA; } m_cap = rhs.m_size; m_valA = new uint32_t[m_cap]; } m_size = rhs.m_size; for (int iVal = 0; iVal < m_size; ++iVal) { m_valA[iVal] = rhs.m_valA[iVal]; } return *this; } BigUint& operator+=(const BigUint& rhs) { if (rhs.m_size > m_size) { resize(rhs.m_size); } uint64_t sum = 0; for (int iVal = 0; iVal < m_size; ++iVal) { sum += m_valA[iVal]; if (iVal < rhs.m_size) { sum += rhs.m_valA[iVal]; } m_valA[iVal] = sum; sum >>= 32u; } if (sum) { resize(m_size + 1); m_valA[m_size - 1] = sum; } return *this; } BigUint& operator*=(const BigUint& rhs) { int resSize = m_size + rhs.m_size - 1; uint32_t* resValA = new uint32_t[resSize]; uint64_t sum = 0; for (int iResVal = 0; iResVal < resSize; ++iResVal) { uint64_t carry = 0; for (int iLhsVal = 0; iLhsVal <= iResVal && iLhsVal < m_size; ++iLhsVal) { int iRhsVal = iResVal - iLhsVal; if (iRhsVal < rhs.m_size) { uint64_t prod = m_valA[iLhsVal]; prod *= rhs.m_valA[iRhsVal]; uint64_t newSum = sum + prod; if (newSum < sum) { ++carry; } sum = newSum; } } resValA[iResVal] = sum & UINT64_C(0xFFFFFFFF); sum >>= 32u; sum += carry << 32u; } if (resSize > m_cap) { if (m_cap > MIN_CAP) { delete[] m_valA; } m_cap = resSize; m_valA = resValA; } else { for (int iVal = 0; iVal < resSize; ++iVal) { m_valA[iVal] = resValA[iVal]; } delete[] resValA; } m_size = resSize; if (sum) { resize(m_size + 1); m_valA[m_size - 1] = sum; } return *this; } void divMod(uint32_t rhs, uint32_t& rMod) { uint64_t div = 0; for (int iVal = m_size - 1; iVal >= 0; --iVal) { div <<= 32u; div += m_valA[iVal]; uint64_t val = div / rhs; div -= val * rhs; if (val || iVal == 0 || iVal < m_size - 1) { m_valA[iVal] = val; } else { --m_size; } } rMod = div; } void toDecString(std::string& rStr) const { std::vector<char> digits; BigUint rem(*this); while (rem.m_size > 1 || rem.m_valA[0]) { uint32_t digit = 0; rem.divMod(10, digit); digits.push_back(digit); } if (digits.empty()) { rStr = "0"; } else { rStr.clear(); rStr.reserve(digits.size()); for (int iDigit = digits.size() - 1; iDigit >= 0; --iDigit) { rStr.append(1, '0' + digits[iDigit]); } } } private: static const int MIN_CAP = 8; void resize(int newSize) { if (newSize > m_cap) { uint32_t* newValA = new uint32_t[newSize]; for (int iVal = 0; iVal < m_size; ++iVal) { newValA[iVal] = m_valA[iVal]; } if (m_cap > MIN_CAP) { delete[] m_valA; } m_cap = newSize; m_valA = newValA; } for (int iVal = m_size; iVal < newSize; ++iVal) { m_valA[iVal] = 0; } m_size = newSize; } int m_size; int m_cap; uint32_t* m_valA; uint32_t m_fixedValA[MIN_CAP]; }; #endif // BIG_UINT_H ``` [Answer] ## [Fantom](http://fantom.org/) Here's an initial post that sets up the framework. I think the procedure is a relatively good one, but the implementation right now kind of sucks. I need to probably try to minimize the number of calculations I'm doing, and instead just pass more constants. # Strategy Basically, each white pawn must be attacking other white pawns. So I start by placing a white pawn, placing pawns in each place it attacks, and essentially filling in the board with all the places a white pawn HAS to go. I stop if I've added too many white pawns already. If, at the end of this, I have exactly 2n^2 pawns, it's a solution. If less than that, add another white pawn somewhere, fill out all his required places, and count again. I recursively split every time a fill with less than 2n^2 is found, and calculate number of solutions with and without the last pawn I added. # Code ``` class main { public Void main(){ echo(calculate(1)) echo(calculate(2)) echo(calculate(3)) echo(calculate(4)) echo(calculate(5)) } public static Int calculate(Int n){ n *= 2 //Initialize the array - Definitely a weakpoint, but only runs once Bool[][] white := [,] n.times{ row := [,] n.times{ row.add(false) } white.add(row) } return recurse(white, -1, 0, n, n*n/2) } private static Int recurse(Bool[][] white, Int lastPlacement, Int numWhites, Int n, Int totalWhite){ if(totalWhite - numWhites > n*n - 1 - lastPlacement) return 0 lastPlacement++ Int row := lastPlacement / n Int col := lastPlacement % n if(white[row][col]){ return recurse(white, lastPlacement, numWhites, n, totalWhite)} Bool[][] whiteCopy := copy(white) whiteCopy[row][col] = true Int result := fillIn(whiteCopy, numWhites + 1, totalWhite) if(result == -1){ return recurse(white, lastPlacement, numWhites,n, totalWhite); } else if(result == totalWhite){ //echo("Found solution") //echo("WhiteCopy = $whiteCopy") return recurse(white, lastPlacement, numWhites,n, totalWhite) + 1; } else return recurse(whiteCopy, lastPlacement, result,n, totalWhite) + recurse(white, lastPlacement, numWhites,n, totalWhite) } //Every white must be attacking other whites, so fill in the grid with all necessary points //Stop if number of whites used goes too high private static Int fillIn(Bool[][] white, Int count, Int n){ white[0..-2].eachWhile |Bool[] row, Int rowIndex -> Bool?| { return row.eachWhile |Bool isWhite, Int colIndex -> Bool?|{ if(isWhite){ //Catching index out of bounds is faster than checking index every time try{ if(colIndex > 0 && !white[rowIndex + 1][colIndex - 1]){ white[rowIndex + 1][colIndex - 1] = true count++ } if(!white[rowIndex + 1][colIndex + 1]){ white[rowIndex + 1][colIndex + 1] = true count++ } } catch {} } if(count > n){ count = -1; return true} return null }//End row.each }//End white.each return count } private static Bool[][] copy(Bool[][] orig){ Bool[][] copy := [,] orig.each{ copy.add(it.dup) } return copy } } ``` # Output Only makes it to 5 right now, but I think most of the issue is in implementation. ``` 3 30 410 6148 96120 ``` # [Test](http://www.fanzy.net/) ]
[Question] [ **Note:** This isn't as much a golfing challenge; it is more so asking for golfing suggestions. Recently I had a Python assignment for my web development class, in order to check whether we could code. Since I already feel comfortable in Python, I decided to try and golf it, and I was wondering if people could point out things that I missed. I already know that there are extra spaces in some places, but I'm more interested in conceptual things, like using `while r:` when r is a variable, and then waiting for it to "run out"! [The assignment](http://cs.nyu.edu/courses/spring15/CSCI-UA.0061-001/assign1.html) ``` import random from collections import Counter s=l='' c=['yellow','blue','white','green','Black', 'purple', 'silver', 'cyan', 'magenta', 'red'] n=[10,15,1,10,6,15,10,25,1,12,5,10,4,6,5,12,0,10,1,1] o=i=0 for y in c:l+=y[0]*(random.randint(n[o],n[o+1]));o+=2 l=list(l) print("Welcome to the CIMS Gumball Machine Simulator\nYou are starting with the following gumballs:") for b in c:print(str(l.count(b[0])) + " "+b);random.shuffle(l) print("Here are your random purchases:") while 'r' in l: random.shuffle(l); r=l.pop(); s+=r for j in c: if j[0] == r:print(j.capitalize()) print("You purchased %i gumballs, for a total of $%.2f \nMost common gumball(s):" % (len(s),len(s)*25/100)) a=Counter(s).most_common() m=[x[1] for x in a] while m[0] == m[i]: for j in c: if j[0] == a[i][0]:print(j.capitalize(), end=" ") if(i<(len(m)-1)):i+=1 else:break ``` Also: I'm sorry if this isn't an appropriate question for the code golf page, since it is not a challenge and will remove it on request. [Answer] Here's a whole bunch of micro-optimisations you can do: **Use `.split()` to create a long list (-17 bytes):** ``` c=['yellow','blue','white','green','Black', 'purple', 'silver', 'cyan', 'magenta', 'red'] c='yellow blue white green Black purple silver cyan magenta red'.split() ``` **Remove extraneous brackets (-2 bytes):** ``` l+=y[0]*(random.randint(n[o],n[o+1])) l+=y[0]*random.randint(n[o],n[o+1]) ``` **Use splat (-2 bytes):** ``` random.randint(n[o],n[o+1]) random.randint(*n[o:o+2]) ``` **Use extended iterable unpacking to turn something into a list (-4 bytes):** ``` l=list(l) *l,=l ``` **Import all the things (-15 bytes):** ``` import random;random.randint;random.shuffle;random.shuffle from random import*;randint;shuffle;shuffle ``` **Use other functions that can do the same job here (-5 \* 2 = -10 bytes):** ``` j.capitalize() j.title() ``` **`print` separates by space by default (-11 bytes):** ``` print(str(l.count(b[0])) + " "+b) print(l.count(b[0]),b) ``` **More unpacking (-3 bytes):** ``` r=l.pop() *l,r=l ``` **Abuse side-effects (-1 byte, plus indents):** ``` if j[0]==r:print(j.capitalize()) r!=j[0]or print(j.capitalize()) ``` **Anything reused and over 5 chars might be worth saving as a variable (-1 byte):** ``` len(s);len(s) L=len(s);L;L ``` **Simplify fractions (-5 bytes):** ``` len(s)*25/100 len(s)/4 ``` **Unary abuse (-4 bytes):** ``` if(i<(len(m)-1)):i+=1 if~-len(m)>i:i+=1 ``` Or the biggest one of all... ## Look at your algorithm, and see if it needs changing altogether ``` from random import* *s,P,S=print,shuffle P("Welcome to the CIMS Gumball Machine Simulator\nYou are starting with the following gumballs:") *l,c,C='yellow blue white green Black purple silver cyan magenta red'.split(),s.count for x,y,z in zip(c,[10,1,6,10,1,5,4,5,0,1],[15,10,15,25,12,10,6,12,10,1]):n=randint(y,z);l+=[x]*n;P(n,x) S(l) P("Here are your random purchases:") while'red'in l:S(l);*l,r=l;s+=r,;P(r.title()) L=len(s) P("You purchased %i gumballs, for a total of $%.2f\nMost common gumball(s):"%(L,L/4)) for x in c:C(x)!=max(map(C,c))or P(x.title()) ``` (If you ever find yourself importing `Counter` in a code-golf, you're probably doing something very wrong...) ]
[Question] [ **Create a function or program that makes a grid as close to an square as possible** * You will be given an integer *N* as input, whole numbers (1,2,3,25, etc) * The output must be a perfect rectangular grid of *N* letters as close to a square as possible * The (wannabe)square must consist of one of the the letters O or X as specified by user **Points**: * Hardcoded to only O or X: +1 * A param(0/1, true/false, something similar) to rotate output (like with 5 or 8): -10 * Design the square (use both O and X in some sort of pattern): -5 A pattern is considered valid if it contains both types of characters (where x/y-axis >= 3) and the pattern stays the same when flipped horizontally or vertically (exchanging Xs with Os is allowed) **Examples** ``` INPUT: 4 INPUT: 5 INPUT: 8 INPUT: 9 OO OOOOO XXXX XOX OO XXXX OXO or rotated 90deg XOX ``` **Examples which aren't allowed (not same length row or columns)** ``` BAD RESULT: 5a BAD RESULT: 5b BAD RESULT: 8 OOO OO OOO OO OO OOO O OO ``` If possible please provide an online example. [Answer] ## CJam, 16 (31 - 10 - 5) This takes two integers are input, first one being `0` or `1` for direction and second one being the number of `O` or `X` in the grid. It prints an alternate `O` and `X`. ``` :X"OX"*X<\Xmqi){(_X\%}g_X\/?/N* ``` This is just the function body, to try it out add `l~` in front of the code like: ``` l~:X"OX"*X<\Xmqi){(_X\%}g_X\/?/N* ``` and give input like ``` 0 10 ``` to get output like ``` OXOXO XOXOX ``` or input like ``` 1 10 ``` for ``` OX OX OX OX OX ``` [Try it online here](http://cjam.aditsu.net/) --- How it works: ``` l~ "Put the two input integers to stack"; :X "Assign the number of cells to X"; "OX"* "Take string "OX" and repeat it X times"; X< "Slice it to take only first X characters"; \ "Swap top two stack elements, now string is at bottom"; Xmqi) "Take square root of X, ceil it and put on stack"; {(_X\%}g "Keep decrementing until it is perfectly divisible by X"; _X\/ "Copy it, divide X by that and put it on stack"; ? "Based on first input integer, take either of numbers"; / "Divide the XOXO string that many times"; N* "Join the string parts with a new line"; ``` Example run: ``` l~ed:X"OX"*edX<ed\edXmqi)ed{(_X\%}ged_edXed\ed/ed?ed/edN*ed #INPUT: 1 10 #OUTPUT: Stack: [1 10] Stack: [1 "OXOXOXOXOXOXOXOXOXOX"] Stack: [1 "OXOXOXOXOX"] Stack: ["OXOXOXOXOX" 1] Stack: ["OXOXOXOXOX" 1 4] Stack: ["OXOXOXOXOX" 1 2] Stack: ["OXOXOXOXOX" 1 2 2] Stack: ["OXOXOXOXOX" 1 2 2 10] Stack: ["OXOXOXOXOX" 1 2 10 2] Stack: ["OXOXOXOXOX" 1 2 5] Stack: ["OXOXOXOXOX" 2] Stack: [["OX" "OX" "OX" "OX" "OX"]] Stack: ["OX OX OX OX OX"] OX OX OX OX OX ``` [Answer] # APL (36 - 5 - 10 = 21) ``` {'OX'⍴⍨⍺⌽⊃∆/⍨⍵=×/¨∆←∆[⍋|-/¨∆←,⍳2/⍵]} ``` The left argument is rotation, the right argument is the size. It also uses a simple pattern (it just alternates 'X' and 'O'). ``` 0{'OX'⍴⍨⍺⌽⊃∆/⍨⍵=×/¨∆←∆[⍋|-/¨∆←,⍳2/⍵]}¨4 5 8 9 OX OXOXO OXOX OXO OX OXOX XOX OXO 1{'OX'⍴⍨⍺⌽⊃∆/⍨⍵=×/¨∆←∆[⍋|-/¨∆←,⍳2/⍵]}¨4 5 8 9 OX O OX OXO OX X OX XOX O OX OXO X OX O ``` Explanation: * `∆←,⍳2/⍵`: generate all possible pairs of numbers from `1` to `⍵` and store in `∆`. * `∆←∆[⍋|-/¨∆`...`]`: sort `∆` ascending in the absolute difference of the two numbers in each pair, and store the result back in `∆`. * `⊃∆/⍨⍵=×/¨∆`: for each pair, multiply the numbers together. Select only those pairs that multiply to `⍵`, and take the first one that matches (which is the 'most square' because of the sort). * `⍺⌽`: rotate the list of lengths (which has 2 elements) by `⍺`. * `'OX'⍴⍨`: create a matrix of that size, and fill it with alternating `O` and `X`. [Answer] ### Haskell, 59 characters ``` r=replicate f n=[r x$r y '0'|x<-[1..n],y<-[1..x],x*y==n]!!0 ``` [Answer] # CJam, ~~25~~ ~~22~~ 21 (31 - 10) This is a function body. If you want a complete program, add `riri` to the front. If you want to use it as a code block, surround it in `{}`. Test it on [cjam.aditsu.net](http://cjam.aditsu.net). It takes input as two integer arguments: the switch for whether the rectangle is vertical (any non-zero value) or horizontal (zero), and the number of `O`s to use. ``` :Xmqi){(_X\%}g_X\/@{\}{}?'O*N+* ``` ## Explanation ``` :X "Assign the top item on the stack (the second input) to variable X"; mq "Take its square root"; i "Convert to integer (round)"; ) "Increment it"; { "Start code block"; ( "Decrement"; _X "Duplicate top item on stack; push X to the stack"; \% "Swap top 2 items and take division remainder"; }g "Loop until top item on stack is 0; pop condition after checking it"; _X "Duplicate top item on stack; push X to the stack"; \/ "Swap top 2 items and divide"; "OMIT THIS BIT TO GET A 25-CHAR FUNCTION WITHOUT THE 10PT BONUS"; @ "Rotate top 3 items on stack"; {\}"Code block 1: swap top two items"; {} "Code block 2: do nothing"; ? "If top item of stack is 0, run code block 1, otherwise run code block 2"; 'O "Push the character O to the stack"; * "Repeat it N times, where N is the second item from the top of the stack (O is first)"; N+ "Push a new line and concatenate it with the string on the top of the stack"; * "Repeat the string N times"; ``` [Answer] # JavaScript (E6) 84 (83+1) or 101 (116-10-5) Pattern + rotation (parameter f, 0 or 1) - bonus 15 ``` F=(n,f)=>{ for(r=x=0;y=n/++x|0,x<=y;)x*y-n?0:z=f?x:y; for(o='';n;)o+=(n--%z?'':(r^=1,c='\n'))+'OX'[r^(c^=1)]; alert(o) } ``` No pattern, no rotation - penalty 1 ``` F=n=>{ for(x=0;y=n/++x|0,x<=y;)x*y-n?0:z=y; alert(('O'.repeat(z)+'\n').repeat(n/z)); } ``` **Test** In FireFox/FireBug console ``` F(30,0) OXOXOX XOXOXO OXOXOX XOXOXO OXOXOX F(30,1) OXOXO XOXOX OXOXO XOXOX OXOXO XOXOX ``` [Answer] # Python, 79 75 (no bonuses) The bonuses seem tricky, so here is a pretty simple Python function: ``` def f(N):c=max(x*((x*x<=N)>N%x)for x in range(1,N+1));print(N/c*'O'+'\n')*c ``` [Answer] # Ruby, 74 ``` f=->n{w=(1..n).min_by{|z|n%z>0?n:(n/z-n/(n/z))**2};$><<("X"*w+"\n")*(n/w)} ``` ## Explanation * Input is taken as arguments to a lambda. It expects an `Integer`. * Check if `n` (the input) is divisible by every integer from 1 to `n`. + If it is, calculate the difference between the length and width. + If it is not, return a large number (`n`). * Take the smallest of length-width differences to best resemble a square. * Use (the overly concise) `String#*` method to "draw" the square. [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 30 - 15 = 15 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set") Anonymous infix lambda. Takes *N* as right argument and param as left argument. Rectangles will either have stripes of X and O or be chequered. ``` {⍉⍣⍺⍴∘'XO'⊃∘c⌈.5×≢c←⍸⍵=∘.×⍨⍳⍵} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///v/pRb@ej3sWPenc96t3yqGOGeoS/@qOuZiAr@VFPh57p4emPOhclP2qb8Kh3x6PerbZACT2gWO@KR72bgfza/2lgub5HfVM9/YEaD603ftQ2EcgLDnIGkiEensH/DRTSFCy4dHV1uQzhLJCYJZxlCAA "APL (Dyalog Unicode) – Try It Online") `{`…`}` "dfn"; `⍺` is left argument (param), `⍵` is right argument (*N*):  `⍳⍵` **ɩ**ndices 1…N  `∘.×⍨` multiplication table of that  `⍵=` mask where *N* is equal to that  `⍸` **ɩ**ndices of true values in the mask  `c←` store that in `c` (for **c**andidates)  `≢` tally the candidates  `.5×` one half multiplied by that  `⌈` ceiling (round up)  `⊃∘c` pick that element from `c`  `⍴∘'XO'` use that to cyclically reshape "XO"  `⍉⍣⍺` transpose if param   [Answer] # [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/wiki/Commands), score: 7 (22 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) - 15 bonus) ``` „OXI∍¹tï[D¹sÖ#<}äIiø}» ``` [Try it online](https://tio.run/##AS4A0f8wNWFiMWX//@KAnk9YSeKIjcK5dMOvW0TCuXPDliM8fcOkSWnDuH3Cu///OAox) or [verify some more test cases](https://tio.run/##MzBNTDJM/V@m5JlXUFpipaBkX6mj5F9aAuHoVCaEhv1/1DDPPyLyUUdvZMnh9dEukcWHpynb1B5eEpF5eEftod3/dQ5ts/8fHW2iYxCrowCkDEGUKYRnCuFZQHgWEJ4lhGcJ4RkawGmwsKEZnAaLG0HFjUDqYgE). Takes the inputs `N` first, then the boolean (`0`/`1`) whether it should rotate or not. Uses the Python legacy version of 05AB1E since zip with a string-list implicitly flattens and joins the characters, unlike the newer Elixir rewrite version of 05AB1E. **Explanation:** ``` „OX # Push string "OX" I∍ # Extend it to a size equal to the first input # i.e. 9 → "OXOXOXOXO" # i.e. 10 → "OXOXOXOXOX" ¹t # Take the first input again, and square-root it # i.e. 9 → 3.0 # i.e. 10 → 3.1622776601683795 ï # Then cast it to an integer, removing any decimal digits # i.e. 3.0 → 3 # i.e. 3.1622776601683795 → 3 [ # Start an infinite loop: D # Duplicate the integer ¹sÖ # Check if the first input is evenly divisible by that integer # i.e. 9 and 3 → 1 (truthy) # i.e. 10 and 3 → 0 (falsey) # # And if it is: stop the infinite loop < # If not: decrease the integer by 1 # i.e. 3 → 2 } # After the infinite loop: ä # Divide the string into that amount of equal sized parts # i.e. "OXOXOXOXO" and 3 → ["OXO","XOX","OXO"] # i.e. "OXOXOXOXOX" and 2 → ["OXOXO","XOXOX"] Ii } # If the second input is truthy: ø # Zip/transpose; swapping rows/columns of the strings # i.e. ["OXOXO","XOXOX"] → ["OX","XO","OX","XO","OX"] » # And finally join the strings in the array by newlines # i.e. ["OXO","XOX","OXO"] → "OXO\nXOX\nOXO" # i.e. ["OX","XO","OX","XO","OX"] → "OX\nXO\nOX\nXO\nOX" # (and output the result implicitly) ``` [Answer] ## GolfScript 26 (41 - 10 - 5) ``` :x),1>{x\%!},.,2/=.x\/@{\}*'X'*n+*1>'O'\+ ``` Expects two parameters to be on the stack: * `0` for normal or `1` for transposed * the `n` value The pattern is that the board is full of `X`s and the top left corner is an `O`. Needless to say, this pattern is maintained when transposing the board. Demo: [regular](http://golfscript.apphb.com/?c=OwowCjI0Cgo6eCksMT57eFwlIX0sLiwyLz0ueFwvQHtcfSonWCcqbisqMT4nTydcKw%3D%3D&run=true), [transposed](http://golfscript.apphb.com/?c=OwoxCjI0Cgo6eCksMT57eFwlIX0sLiwyLz0ueFwvQHtcfSonWCcqbisqMT4nTydcKw%3D%3D&run=true) [Answer] # Mathematica, 71 chars ``` f@n_:=#<>"\n"&/@Array["O"&,{#,n/#}&[#[[⌊Length@#/2⌋]]&@Divisors@n]]<>"" ``` [Answer] # Petit Computer BASIC, 72 bytes ``` INPUT N,S$FOR I=1TO SQR(N)IF N%I<1THEN M=I NEXT ?(S$*M+" "*(32-M))*(N/M) ``` [Answer] # [J](http://jsoftware.com/), 32 bytes - 15 = 17 bytes ``` 'XO'$~[|.](%,])i.@]{~0 i:~i.@]|] ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/1SP81VXqomv0YjVUdWI1M/UcYqvrDBQyrepAzJrY/5pcqckZ@UAdaQomEKa6OkLIElXIEChkjpA1x9RggVBo8R8A "J – Try It Online") The rotation is controlled by a 0/1 flag taken as the left argument [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 66 bytes + 1 byte penalty = 67 ``` .+ $*X ((^|\3)(X(?(3)\3)))+(\3)*$ $3 $3$#4$*X X(?=X* (X+))| X+ $1¶ ``` [Try it online!](https://tio.run/##K0otycxL/P9fT5tLRSuCS0MjribGWFMjQsNew1gTyNLU1NYAUloqXCrGCirGKsomIGVAadsILQWNCG1NzRqFCKBew0Pb/v83MwAA "Retina 0.8.2 – Try It Online") Explanation: ``` .+ $*X ``` Convert the input to a string of `X`s. ``` ((^|\3)(X(?(3)\3)))+(\3)*$ ``` The first pass of the outer capture matches the start of the string while on subsequent passes the previous value of the inner capture is matched. The inner capture is then incremented and matched. The upshot of this is that the amount of string consumed by the outer capture is the square of the inner capture, which therefore cannot exceed the square root of the input. Meanwhile the subsequent repetition ensures that the inner capture is a factor of the length of the string. ``` $3 $3$#4$*X ``` Save the discovered factor and calculate the other divisor by adding on the number of subsequent repetitions. ``` X(?=X* (X+))| X+ $1¶ ``` Rearrange the factors into a rectangle. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 33 bytes - 10 - 5 = 18 ``` Nθ≔⌊Φ⊕θ¬∨‹×ιιθ﹪θιηE÷θη⭆η§XO⁺ιλ¿N⟲ ``` [Try it online!](https://tio.run/##Tc49C8IwEIDhvb8iOF0hgi4unQQRCraKOrjW9jQH@ajJRfz3MXHyxnuOlxvV4Ec36JRaO0fuo7mjh1fdVNsQ6GmhI0smGtiT5iytHT0atIxTvpKidwxHDwcMAa5kMABJQRkKdm6K2sGrbMpIoXL45MkydMOcY7yjN01YTlTmC2d7FlJSbLm1E35gcTsupDjp@GvrX6mp6CHg/@W6FmfHAyPUTUqbVbVOy7f@Ag "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` Nθ ``` Input `N`. ``` ≔⌊Φ⊕θ¬∨‹×ιιθ﹪θιη ``` Take the range `0`..`N`, keep only the numbers whose squares are not less than `N` and divide `N`, and take the minimum of those numbers. ``` E÷θη⭆η§XO⁺ιλ ``` Use the discovered factor to output a rectangle of the appropriate width and height using a chequerboard pattern. (This should be `UOη÷θηXO¶OX` for a 1-byte saving but that's buggy right now.) ``` ¿N⟲ ``` If the second input is nonzero then rotate the output. (If requiring the second input to be `0` or `2` is acceptable, then this could be `⟲N` for a 1-byte saving.) ]
[Question] [ In mathematics, tetration is the next hyper operator after exponentiation, and is defined as iterated exponentiation. **Addition** (***a*** succeeded ***n*** times) ![](https://i.stack.imgur.com/reccr.png) **Multiplication** (***a*** added to itself, ***n*** times) ![](https://i.stack.imgur.com/INMDP.png) **Exponentiation** (***a*** multiplied by itself, ***n*** times) ![](https://i.stack.imgur.com/NFoYJ.png) **Tetration** (***a*** exponentiated by itself, ***n*** times) ![](https://i.stack.imgur.com/Z1cm0.png) The inverse relations of tetration are called the super-root, and the super-logarithm. Your task is to write a program that, given A and B, prints out the Bnd-order super-root of A. For example: * if A = `65,536` and B = `4` it prints `2` * if A = `7,625,597,484,987` and B = `3` it prints `3` A and B are positive integers and the result must be floating point number with a precision of 5 digits after the decimal point. The result belongs to the real domain. *Be careful, super-roots may have many solutions.* [Answer] # C — aiming for clarity, didn't attempt to squeeze the code Considering input: ``` A: A ∈ ℝ, A ≥ 1.0 B: B ∈ ℕ, B ≥ 1 ``` Then there should usually be only one solution in ℝ, which simplifies the problem considerably. Code is: ``` #include <stdlib.h> #include <stdio.h> #include <math.h> #define TOLERANCE 1.0e-09 double tetrate(double, int); int main(int argc, char **argv) { double target, max, min, mid, working; int levels; if (argc == 3) { target = atof(argv[1]); // A levels = atoi(argv[2]); // B // Shortcut if B == 1 if (levels == 1) { printf("%f\n", target); return 0; } // Get a first approximation max = 2.0; while (tetrate(max, levels) < target) max *= 2.0; min = max / 2.0; // printf("Answer is between %g and %g\n", min, max); // Use bisection to get a closer approximation do { mid = (min + max) / 2.0; working = tetrate(mid, levels); if (working > target) max = mid; else if (working < target) min = mid; else break; } while (max - min > TOLERANCE); // printf("%g: %f = %f tetrate %d\n", target, tetrate(mid, levels), mid, levels); printf("%f\n", mid); } return 0; } double tetrate(double d, int i) { double result = d; // If the result is already infinite, don't tetrate any more while (--i && isfinite(result)) result = pow(d, result); return result; } ``` To compile: ``` gcc -o tet_root tet_root.c -lm ``` To run: ``` ./tet_root A B ``` E.g.: 42 ``` $ ./tet_root 65536 4 2.000000 ``` 33 ``` $ ./tet_root 7625597484987 3 3.000000 ``` 3π ``` $ ./tet_root 1.340164183e18 3 3.141593 ``` n(2½) ➙ 2 as n ➙ ∞ ? (well known limit) ``` $ ./tet_root 2 10 1.416190 $ ./tet_root 2 100 1.414214 $ ./tet_root 2 1000 1.414214 ``` Yes! n(e1/e) ➙ ∞ as n ➙ ∞ ? (upper bounds) ``` $ ./tet_root 9.999999999e199 100 1.445700 $ ./tet_root 9.999999999e199 1000 1.444678 $ ./tet_root 9.999999999e199 10000 1.444668 $ ./tet_root 9.999999999e199 100000 1.444668 ``` Cool! (e1/e ≅ 1.44466786101...) [Answer] ## Python, 87 chars ``` E=lambda x,n:x**E(x,n-1)if n else 1 def S(A,B): x=1. while E(x,B)<A:x+=1e-5 return x ``` A simple linear search for the answer. Off-topic, but what the \*#$(@! is up with the python `**` operator? ``` >>> 1e200*1e200 inf >>> 1e200**2 Traceback (most recent call last): File "<stdin>", line 1, in <module> OverflowError: (34, 'Numerical result out of range') ``` [Answer] ## Mathematica, ~~35~~ 40 ``` n /. Solve[Nest[#^(1/n) &, a, b] == n]~N~5 ``` Generates a list of all solutions, with 5 digit precision. ``` n /. Last@Solve[Nest[#^(1/n) &, a, b] == n]~N~5 ``` 5 more characters to get only the real solution, which the updated rules demand. [Answer] When did this become a code golf? I thought it was a code challenge to come up with the best algorithm! --- [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") # APL, 33 chars ``` {r←⍵⋄⍺{1≥⍵⍟⍣⍺⊢r:⍵⋄⍺∇⍵+i}1+i←1e¯6} ``` This is a simple linear search, starting from C = 1 + 10-6 and incrementing it by 10-6 until     logC logC logC ⋯ A ≤ 1 where the logC function is applied recursively B times. **Examples** ``` 4 {r←⍵⋄⍺{1≥⍵⍟⍣⍺⊢r:⍵⋄⍺∇⍵+i}1+i←1e¯6} 65536 2.0000009999177335 3 {r←⍵⋄⍺{1≥⍵⍟⍣⍺⊢r:⍵⋄⍺∇⍵+i}1+i←1e¯6} 7625597484987 3.0000000000575113 ``` This code is very slow, but for small bases such as 2 or 3 it completes in a few seconds. See below for a better thing. --- [code-challenge](/questions/tagged/code-challenge "show questions tagged 'code-challenge'") # APL, logarithmic complexity Actually linear complexity on the root order, logarithmic on the result size and precision:     time = O(B × log(C) + B × log(D)) where B is the root order, C is the tetration base being asked for, and D is the number of digits of precision asked. This complexity is my intuitive understanding, I have not produced a formal proof. This algorithm does not require big integers, it only uses the log function on regular floating point numbers, therefore it's quite efficient on very large numbers, up to the limit of the floating point implementation (either double precision, or arbitrary large FP numbers on the APL implementations that offer them.) The precision of the result can be controlled by setting `⎕CT` (comparison tolerance) to the desired acceptable error (on my system it defaults to 1e¯14, roughly 14 decimal digits) ``` sroot←{ ⍝ Compute the ⍺-th order super-root of ⍵: n←⍺ ⋄ r←⍵ ⍝ n is the order, r is the result of the tetration. u←{ ⍝ Compute u, the upper bound, a base ≥ the expected result: 1≥⍵⍟⍣n⊢r:⍵ ⍝ apply ⍵⍟ (log base ⍵) n times; if ≤1 then upper bound found ∇2×⍵ ⍝ otherwise double the base and recurse }2 ⍝ start the search with ⍵=2 as a first guess. (u÷2){ ⍝ Perform a binary search (bisection) to refine the base: b←(⍺+⍵)÷2 ⍝ b is the middle point between ⍺ and ⍵ t←b⍟⍣n⊢r ⍝ t is the result of applying b⍟ n times, starting with r; t=1:b ⍝ if t=1 (under ⎕CT), then b is the super-root wanted; t<1:⍺∇b ⍝ if t<1, recurse between ⍺ and b b∇⍵ ⍝ otherwise (t>1) returse between b and ⍵ }u ⍝ begin the search between u as found earlier and its half. } ``` I'm not sure whether `1≥⍵⍟⍣n` above could fail with a Domain Error (because the log of a negative argument could either fail immediately, or give a complex result, which would not be in the domain of `≥`) but I haven't been able to find a case that fails. **Examples** ``` 4 sroot 65536 1.9999999999999964 4 sroot 65537 2.000000185530773 3 sroot 7625597484987 3 3 sroot 7625597400000 2.999999999843567 3 sroot 7625597500000 3.000000000027626 ``` '3' comes out as an exact value because it happens to be one of the values directly hit by the binary search (starting from 2, doubled to 4, bisect to 3). In the general case that does not happen, so the result will approximate the root value with a ⎕CT error (more precisely, the logarithmic test of every candidate base is performed with ⎕CT tolerance.) [Answer] # Julia ``` julia> t(a,b)=(c=a;for j=1:b-1;c=a^c;end;c) julia> s(c,b)=(i=1;while t(i,b)!=c;i+=1;end;i) julia> s(65536,4) 2 julia> s(7625597484987,3) 3 ``` Ignored floating point instruction since the the question only defines behavior for integers. [Answer] ## Ruby, 79 bytes ``` ->a,b{x=y=1.0;z=a;eval"y=(x+z)/2;x,z=a<eval('y**'*~-b+?y)?[x,y]:[y,z];"*99;p y} ``` This is the same as the below program, but less accurate since it only runs 99 loops. ## Ruby, 87 bytes ``` ->a,b{x=y=1.0;z=a;(y=(x+z)/2;x,z=a<eval("y**"*~-b+?y)?[x,y]:[y,z])while y!=(x+z)/2;p y} ``` [Try it online](https://tio.run/##KypNqvyv8V/XLlEnqbrCttLWUM/Auso20Vqj0lajQrtKU9/IukIHKGCTWpaYo6FUqaWlpFWnm6RtX6lpH12hUxlrFV2pUxWrWZ6RmZOqUKkI11WgUFn7XzPa3MzI1NTS3MTCxNLCXMc49j8A) This is simply bisection. Ungolfed: ``` -> a, b { # y^^b by evaluating the string "y ** y ** ..." tetration =-> y {eval "y ** " * (b-1) + ?y} lower = middle = 1.0 upper = a while middle != (lower + upper) / 2 do middle = (lower + upper) / 2 if tetration[middle] > a upper = middle else lower = middle end end print middle } ``` [Answer] # k [52 chars] ``` {{{((%x)*(z*x-1)+y%z xexp x-1)}[x;y]/[2]}[y]/[y<;x]} ``` A modified version of my own post [nth root](http://qkdb.wordpress.com/2012/10/06/nth-root/) Example: ``` {{{((%x)*(z*x-1)+y%z xexp x-1)}[x;y]/[2]}[y]/[y<;x]}[7625597484987;3] 3f {{{((%x)*(z*x-1)+y%z xexp x-1)}[x;y]/[2]}[y]/[y<;x]}[65536;4] 2f ``` [Answer] ## Haskell Simple linear search, returns first, smallest match found. ``` {- The value of a is the result of exponentiating b some number of times. This function computes that number. -} superRoot a b = head [x | x<-[2..a], tetrate x b == a] {- compute b^b^...^b repeated n times -} tetrate b 1 = b tetrate b n = b^(tetrate b (n-1)) ``` Example ``` *Main> superRoot 65536 4 2 *Main> superRoot 7625597484987 3 3 ``` [Answer] ## Mathematica, 41 bytes without optimization Mathematica was basically invented to solve problems like this. One easy solution is to construct the problem as a nested power series and pass it to the built-in `Reduce` function, which seeks analytical solutions to equations. As a result, the following, in addition to being unusually concise code, is also not brute force. ``` Reduce[Nest[Power[#, 1/x] &, a, b] == x, x, Reals] ``` You can remove the restriction to provide only Real number solutions if you're patient and want to save six bytes. You can also express some of the nested functions in abbreviated form to save a few more bytes. As given, it returns thusly ![enter image description here](https://i.stack.imgur.com/suGMf.png) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 16 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` 1[ÐU²FXm}¹@#5(°+ ``` Port of [*@KeithRandall*'s Python answer](https://codegolf.stackexchange.com/a/20321/52210). [Try it online.](https://tio.run/##yy9OTMpM/f/fMPrwhNBDm9wicmsP7XRQNtU4tEH7/39zMyNTU0tzEwsTSwtzLmMA) **Explanation:** ``` 1 # Push a 1 [ # Start an infinite loop: Ð # Triplicate the top value on the stack U # Pop and store one in variable `X` ²F # Inner loop the second input amount of times: Xm # And take the top value to the power `X` } # After the inner loop: ¹@ # If the resulting value is larger than or equal to the first input: # # Stop the infinite loop # (after which the top of the stack is output implicitly as result) 5(°+ # If not: increase the top value by 10^-5 ``` `ÐU²FXm}` could also be `D²>и.»m` for the same byte-count: ``` D # Duplicate the top value on the stack ²> # Push the second input + 1 и # Repeat the top value that many times as list .» # Reduce it by: m # Taking the power ``` ]
[Question] [ [In fairness, this is based on a StackExchange question - but its a good question.](https://stackoverflow.com/questions/21152424/finding-the-largest-prime-number-within-a-number) The challenge is fairly simple: 1. Take a string of numerals 2. Find and print the largest contiguous prime number in the string Scoring: * Lowest number of characters wins. * Victor will likely be a golfscript entry but we won't hold that against them, cause we all have fun and learn things, right. * Winner we be awarded when I notice that I haven't actually ticked the green button. Assumptions: * The string is only numbers + If the string contains letters, you may have undefined behaviour * The string contains at least 1 prime + If the string does not contains 1 valid prime number, you may have undefined behaviour * Speed is not a constraint + Use a shorter prime algorithm over a faster one. + If your entry eventually finishes, thats ok, just make sure it will provable happen before the heat death of the universe. * *The length of the string can be assumed less than 15 characters long* For example: ``` >> Input: 3571 << Output: 3571 >> Input: 123 << Output: 23 >> Input: 1236503 << Output: 236503 >> Input: 46462 << Output: 2 >> Input: 4684 << Output: ValueError: max() arg is an empty sequence >> Input: 460 << Output: 0 # Note, zero is not a prime, but the above string has no valid prime >> Input: 4601 << Output: 601 >> Input: "12 monkeys is a pretty good movie, but not as good as se7en" << Output: ValueError: Fight Club was also good, I find Brad Pitt to be a consistantly good actor. ``` ## Possible implementations: 1. Find all substrings of the input, check if they are prime. - [Legostormtroopr (original)](https://codegolf.stackexchange.com/a/18593/8777) 2. Find all integers less than input, check if they are in the input then check if it is prime - [Ben Reich](https://codegolf.stackexchange.com/a/18596/8777) 3. Take a list of all primes less than the input, check if it is in the input - [daniero](https://codegolf.stackexchange.com/a/18626/8777) [Answer] ## GolfScript ~~40~~ 37 ``` .{`\`?)}+\~),\,{.,(;\{\%!}+,,1=},)\; ``` This looks at all numbers less than or equal to the the input, filters down to the ones that are substrings of the input, and then filters further down to the primes. Then, it takes the largest such element (which is obviously guaranteed to have the most digits). Let's break it down into two main sections: ``` .{`\`?)}+\~,\, ``` This part of the code filters down to all integers string contained in the input. It uses grave accent to turn numbers into strings, and then `?` to determine the index of the substring. Since `?` returns `-1` in the case of no containment, increment using `)` so that the output is `0` for non-substrings, which will behave nicely with the `,` filtering. ``` {.,(;\{\%!}+,,1=}, ``` This part of the code filters down to the primes by counting the number of factors less than the given number (an integer is a factor only if `number factor %!` is 1. A prime number will have exactly 1 factor strictly less than itself, so do `1=`. Since the numbers are in order, take the last one and clear the stack using `)\;` This obviously isn't as efficient as possible (since it somewhat unnecessarily iterates over all integers less than the input), but it still terminates with big input like `1236503` relatively quickly on my computer (1 minute). [Answer] ## Python 2.7 - 84 Here is a reference implementation to beat, I used it for the example output in the question, so its gauranteed to work \* Not an actual guarantee **Shameless improvement** based on [Ben Reich](https://codegolf.stackexchange.com/a/18596/8777)'s much better solution than my original one. With major assistance from **Volatility** ``` N=input() print max(x for x in range(N+1)if(`x`in`N`)&all(x%i for i in range(2,x))) ``` Prior incantations of the second line include: ``` print max(x for x in range(N+1)if`x`in`N`and 0 not in(x%i for i in range(2,x))) print max(x for x in range(N+1)if`x`in`N`and sum(x%i<1 for i in range(2,x))<1) ``` --- **The original version - 143** ``` N=`input()` p=lambda n:[n%i for i in range(2,n)if n%i==0] print max(int(N[j:i])for i in range(len(N)+1)for j in range(i)if not p(int(N[j:i]))) ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `G`, 4 bytes ``` ǎ⌊~æ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJBRyIsIlMiLCLHjuKMin7DpiIsIiIsIjM1NzFcbjEyM1xuMTIzNjUwM1xuNDY0NjIiXQ==) Link includes test cases. Input as a string. Add the `Ṡ` flag if you want input as a number. #### Explanation ``` ǎ⌊~æ # Implicit input ǎ # Substrings ⌊ # Cast to integer ~ # Filtered by æ # Is prime # G flag gets maximum # Implicit output ``` [Answer] # Ruby 61 Take all primes up to N and see if they are in the string ``` require'prime' p Prime.each(gets.to_i).select{|i|~/#{i}/}.max ``` I think this only works on Ruby 1.9 and newer, but I'm not sure. [Answer] # Scala (83 chars) I wasn't sure how to provide inputs to the program so I considered `n` is the input. Here's the actual solution (based on which the solution length is evaluated). Below that is an executable form of the solution (which isn't golfed yet) for execution along with the output (for the samples give OP has). **Solution:** ``` n.inits.flatMap(_.tails.toList.init.map(BigInt(_))).filter(_ isProbablePrime 1).max ``` **Executable solution:** ``` object A { def main(x:Array[String])=List("3571","123","23","1236503","46462","4684","460","4601","12 monkeys..").foreach(e=>println(e+" => "+q(e))) private def p(n: String)=n.inits.flatMap(_.tails.toList.init.map(BigInt(_))).filter(_ isProbablePrime 1).max private def q(n: String)=try p(n)catch{case e=>e.toString} } ``` **Sample output:** ``` 3571 => 3571 123 => 23 23 => 23 1236503 => 236503 46462 => 2 4684 => java.lang.UnsupportedOperationException: empty.max 460 => java.lang.UnsupportedOperationException: empty.max 4601 => 601 12 monkeys.. => java.lang.NumberFormatException: For input string: "12 " ``` **Explanation:** Steps are pretty straight forward. input -> Find all substrings -> filter non primes -> find longest value * `main(Array[String])`: Method provides sample input and executes method `q(String)` for each input * `q(String)`: Wraps actual program logic from `p(String)` so any exceptions are appropriately reported. Helps in formatting the output better because invalid inputs are going to get `NumberFormatException`s where as the lack of a prime will throw an `UnsupportedOperationException` * `p(String)`: Actual logic of the program. Let's split the explanation for this into parts + `n.inits`: Creates an `Iterator` to iterate over the String input (`n`) + `flatMap(f)`: Applies an operation on the `Iterator` and pushes the result into a `List` - `_.tails.toList.init.map(BigInt(_))`: Splits the `String` and removes empty `String`s from the resultant `List`. Finally converts the `String` to a `BigInt` which is an equivalent of `java.math.BigInteger`. For golfing reasons, `BigInt` is selected (shorter name). + `filter(f)`: if `f` returns `false`, the value is removed from the resultant `List` - `_ isProbablePrime 1`: This line could have been written as `_.isProbablePrime(1)` but the representation used saves 1 byte. This line actually checks if the value is a prime (probabilistically; since `certainty` is set to `1`, execution time goes up but the system makes certain (more or less) that the number is a prime. + `max`: Finds the maximum value (not `String` based length. Actual max value) [Answer] ## J (~~24~~ 22) Reading from the keyboard is actually shorter than defining a function. ``` >./(*1&p:);".\.\1!:1[1 ``` Test: ``` >./(*1&p:);".\.\1!:1[1 3571 3571 >./(*1&p:);".\.\1!:1[1 46462 2 >./(*1&p:);".\.\1!:1[1 1236503 236503 >./(*1&p:);".\.\1!:1[1 4684 0 >./(*1&p:);".\.\1!:1[1 4680 0 >./(*1&p:);".\.\1!:1[1 twelve monkeys is a pretty good movie __ ``` Explanation: * `1!:1[1`: read a line of text from the keyboard * `".\.\`: the evaluation (`".`) of each suffix (`\.`) of each prefix (`\`) of the string. * `;`: flatten the matrix * `*1&p:`: multiply each value by whether it is a prime or not (so all nonprimes will be zero) * `>./`: get the largest value in the list [Answer] # Haskell, 94 `main=getLine>>=print.maximum.filter(\x->and$map((0/=).mod x)[2..x-1]).map read.init.scanr(:)[]` [Answer] ## Perl 6 (40 characters, 41 bytes) ``` $_=get;say max grep &is-prime,+«m:ex/.+/ ``` First `get` input into `$_`, this makes the regex match call shorter. `:ex` gives exhaustive matching for regex, it will give all possibilities. The hyper op `+«` (or `+<<` works too) will make numbers out of the Match objects, those are passed to `grep` with `&is-prime` sub as selector. Finally take the maximum of the remaining list and output it. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes ``` DẆḌẒƇṀ ``` [Try it online!](https://tio.run/##y0rNyan8/9/l4a62hzt6Hu6adKz94c6G/4fbHzWt@f/f2NTcUEfB0MgYTJiZGgAZJmYmZkYgysIERBqACUMA "Jelly – Try It Online") Takes input as an integer. If input must be a string, then [7 bytes](https://tio.run/##y0rNyan8/z/sUdOah7vaHu7oebhr0rH2hzsb/h9uB4r9/69kbGpuqKSjoGRoZAylzEwNwEwTMxMzIwjDwgRCG0ApQyUA). Returns `0` for numbers with no primes in them. ## How it works ``` DẆḌẒƇṀ - Main link. Takes n on the left Ƈ - Find... Ṁ - ...the largest... Ẇ - ...contiguous... ḌẒ - ...prime... D - ...in a string ``` or, alternatively, ``` DẆḌẒƇṀ - Main link. Takes n on the left D - Convert n to digits Ẇ - Get all contiguous sublists Ḍ - Convert each back from digits Ƈ - Filter keep: Ẓ - Primes Ṁ - Yield the maximum ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 5 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` Œʒp}Z ``` [Try it online!](https://tio.run/##yy9OTMpM/f//6KRTkwpqo/7/NzQyNjM1MAYA "05AB1E – Try It Online") #### Explanation ``` Œʒp}Z # Implicit input Œ # Substrings ʒ } # Filtered by p # Is prime Z # Maximum # Implicit output ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 170 bytes I'm sure there is a better way of doing this... ``` $v.count..1|%{ $d=$_ 0..(-$d+$v.count)|%{ $n=$v[$_..($_+$d-1)]-join"" $a=@() 1..[math]::sqrt($n)|%{$a+=$_,($n/$_)*!($n%$_)} if($a.count-eq2){$b+=$n} } } $b[0] ``` [Try it online!](https://tio.run/##NY7hCoJAEIR/e09hxwqe5qVWVILQe4jImZaGnamXEeqz21b0b3a/nZm918@87Yq8qmbo9VAH0V660dCV9SKQ4uJoMiT8VD@k4twbjYFokIWQEM3l3HQgs/@YfaEGMoQ@ggQpJDZkjsdi51qXktIPFSFGovA4j25CFXEQdE2rTJAfPwgbs5c4rSBh1gKFgWJCQ3k2QfyanLzx2QAp3kpEE5kIfhu58TzP9LDfbbaev6Zv "PowerShell – Try It Online") [Answer] # Mathematica ~~67~~ 47 ``` StringCases[#,a__/;PrimeQ@ToExpression@a]〚1〛& ``` **Explanation** The code is a pure function. It has no name. In it, `#` represents the full input string. `StringCases` takes the input, #, and checks for substrings, `a`, of one character or more (that's why \_\_ was used instead of \_) that are primes; PrimeQ must return True for the substring. All the favorable cases, i.e. the substrings that are primes, are by default returned in a list. `〚1〛`, or `[[1]]` takes the first part, that is, the first element of that list of primes. `element[[1]]` is shorthand for `Part[element, 1]`. If there is more than one prime, the first one will be the longest prime (`StringCases` checks the longest substrings first). **Examples** ``` StringCases[#,a__/;PrimeQ@ToExpression@a]〚1〛&["1236503"] ``` > > "236503" > > > ``` StringCases[#,a__/;PrimeQ@ToExpression@a]〚1〛&/@ {"1236503", "123", "46462", "4684", "460", "4601", "12 monkeys is a pretty good movie, but not as good as se7en"} ``` > > {"236503", "23", "2", {}[[1]], {}[[1]], "601", "2"} > > > [Answer] # Perl 6 (50 characters, 51 bytes) ``` say max +«get.match(/(.+)<?{(+$0).is-prime}>/,:ex) ``` `+«` maps strings to numbers, `max` gets the biggest number, `get` receives a line. `/(.+)<?{(+$0).is-prime}>/` is a regular expression that gets all primes `<?{}>` is a code assertion. `is-prime` is `Int` class method which checks if number is a prime. I need to cast value to number by using `+`, because it's `Str` by default. `:ex` means that it tries to find **ALL** matches (including those where overlap others). Because of Rakudo Perl bug, it's currently impossible to use `m//` here. This works for any number, and if you remove `max` (or replace it with `sort`) you will get list of all primes in the number, for extra bonus (not that this gives points, or anything). For example (with `sort` in this case): ``` 1234567890 2 3 5 7 23 67 89 4567 23456789 ``` [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-h`](https://codegolf.meta.stackexchange.com/a/14339/), 6 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` ã f_°j ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWg&code=4yBmX7Bq&input=IjM1NzEi) [Answer] # [Husk](https://github.com/barbuz/Husk), 6 bytes ``` →fṗmrQ ``` [Try it online!](https://tio.run/##yygtzv7//1HbpLSHO6fnFgX@//9fydjU3FAJAA "Husk – Try It Online") [Answer] # [Arturo](https://arturo-lang.io), 50 bytes ``` $[s][last select..1do s'x->∧prime? x in?~"|x|"s] ``` [Try it](http://arturo-lang.io/playground?woNbmh) [Answer] # [PARI/GP](http://pari.math.u-bordeaux.fr/), 212 bytes [Try it online!](https://tio.run/##RVDbioMwEH33K4JCSWgs2lpb6GY/Y1/Eh6ybyrQaxUkF2fbb3UltWQicM2fmzCW9HiCu@3lG5CitbIWqOltpx79MxVEUdrOx6zZOSxHAaElRv@3ER0VpbHXTkCJO527goFIZoYQzHwsoP7Lj/e7J5/4gB@Nug@WJoNL0EUCP7z6NivDf3kjPLsRAUhKdem51kc06jYHM1Py5hBOrFWA/QGu4GXXjFfEe4znVhuFjRjeArZEpVoTpdpfvk10omacesjzLtws5ZgsmL0hDSVWs7ezVTMgAmWY99XcTq7vuhxIjGMm@b47ZzjGNi0yI5mBsWJ4Cbf3c0VSObopem0gG9Pz9S0wfJERAh1jHySDmPw) ``` ss(s,n,m)=concat(Vec(s)[n..n+m-1]) ivn(s)={my(v=Vecsmall(s));for(i=1,#s,if(v[i]<48||v[i]>57,return(0)));1} ips(s)={my(l=#s);for(i=1,l,for(j=1,i,my(st=ss(s,j,l+1-i));if(ivn(st)&&isprime(eval(st)),return(st))));""} ```           Ungolfed version ``` substring(s,n,m)=concat(Vec(s)[n..n+m-1]) is_valid_number(s) = { my(vec_s = Vecsmall(s)); for (i = 1, #s, if (vec_s[i] < 48 || vec_s[i] > 57, return(0))); return(1); } is_prime_string(s) = { my(len = #s); for (i = 1, len, for (j = 1, i, my(substr = substring(s, j, len+1-i)); if (is_valid_number(substr) && isprime(eval(substr)), return(substr)); ) ); return(""); } strings = ["1236503", "123", "46462", "4684", "460", "4601","12 monkeys is a pretty good movie, but not as good as se7en"]; ans = vector(#strings, i, is_prime_string(strings[i])) print(ans) ``` ]
[Question] [ **Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/16826/edit). Closed 2 years ago. [Improve this question](/posts/16826/edit) I saw [this question](https://mathematica.stackexchange.com/questions/39361/how-to-generate-a-random-snowflake) on <https://mathematica.stackexchange.com/> and I think it's pretty cool. Let's make the snowflake with other programming languages. This is a quote from the original question: > > 'Tis the season... And it's about time I posed my first question on Mathematica Stack Exchange. So, here's an holiday quest for you Graphics (and P-Chem?) gurus. > > > What is your best code for generating a (random) snowflake? By random I mean with different shapes that will mimic the diversity exhibited by real snowflakes. Here's a link to have an idea: <http://www.its.caltech.edu/~atomic/snowcrystals/> , more specifically here are the different types of snowflakes: <http://www.its.caltech.edu/~atomic/snowcrystals/class/class.htm> . > Here we are trying to generate a single snowflake (possibly with different parameters to tune its shape), the more realistic, the better. Three dimensional renderings, for adding translucency and colors are also welcome. Unleash your fantasy, go beyond the usual fractals! > > > Rules: * Generate a random single snowflake. * The flake should be six-fold radial symmetry. * It doesn't need to be realistic. (But prefer) * Single character answers, like \*, ⚹, ❅, ❄, ❆ are not allowed. * Most upvotes wins! [Answer] # Bash and ImageMagick ``` #!/bin/bash third=() x=90 y=90 while (( x>10 )); do (( dx=RANDOM%10 )) while :; do (( dy=RANDOM%21-10 )); (( y-dy<95 )) && (( y-dy>(x-dx)/2 )) && break; done third+=( -draw "line $x,$y $(( x-dx )),$(( y-dy ))" -draw "line $x,$(( 200-y )) $(( x-dx )),$(( 200-y+dy ))" -draw "line $(( 200-x )),$y $(( 200-x+dx )),$(( y-dy ))" -draw "line $(( 200-x )),$(( 200-y )) $(( 200-x+dx )),$(( 200-y+dy ))" ) (( x-=dx )) (( y-=dy )) done third+=( -draw "line 90,90 90,110" -draw "line $x,$y 15,100" -draw "line $x,$(( 200-y )) 15,100" -draw "line 110,90 110,110" -draw "line $(( 200-x )),$y 185,100" -draw "line $(( 200-x )),$(( 200-y )) 185,100" -draw 'color 20,100 filltoborder' -draw 'color 180,100 filltoborder' ) convert \ -size '200x200' \ xc:skyblue \ -background skyblue \ -stroke 'white' \ -strokewidth 1 \ -fill 'white' \ -bordercolor 'white' \ -fuzz 10% \ "${third[@]}" \ -rotate 120 \ -crop '200x200' \ "${third[@]}" \ -rotate 120 \ -crop '200x200' \ "${third[@]}" \ -draw 'ellipse 100,100 15,15 0,360' \ x: ``` Sample run: ``` bash-4.1$ for i in {1..30}; do ./showflake.sh "showflake-$i.png"; done bash-4.1$ montage showflake-*.png x: ``` ![snowflake montage](https://i.stack.imgur.com/iO7Pz.png) [Answer] # Javascript [Fiddle located here](http://jsfiddle.net/XGundam05/Lh3f5/) [More fancy Fiddle located here](http://jsfiddle.net/XGundam05/Cb2XC/) It's not golfed, not by a long shot. Also required are the Perlin Noise function and seeded Random (both included in Fiddle, seeded random needed for Perlin). Fiddle also displays the current seed for keeping track of favorites ;) ``` function DoFlake(canvas){ var width = canvas.width; var height = canvas.height; var ctx = canvas.getContext('2d'); var thing = document.createElement('canvas'); thing.width = 128; thing.height = 32; var thingctx = thing.getContext('2d'); var noise = new ImprovedPerlin((new Date()).getTime()); var wDiv = 1/64; var y = 7/32; var z = 2/11; for(var x = 0; x < 128; x++){ var h = 32 - (x * 32 / 128); h += 16 * noise.Noise(4 * x * wDiv, y, z); h += 8 * noise.Noise(8 * x * wDiv, y, z); h += 4 * noise.Noise(16 * x * wDiv, y, z); h += 2 * noise.Noise(32 * x * wDiv, y, z); h += 1 * noise.Noise(64 * x * wDiv, y, z); thingctx.fillRect(x, 0, 1, h); } ctx.translate(128,128); var angle = Math.PI / 3; for(var i = 0; i < 6; i++){ ctx.rotate(angle); ctx.drawImage(thing, 0, 0); ctx.scale(1, -1) ctx.drawImage(thing, 0, 0); ctx.scale(1, -1); } } ``` [Answer] ## ZXSpectrum Basic, 21 Well, I Can't do the 6 fold symmetry, but I can get all sorts of randomness using the ZX Spectrum: Emulator [Here](http://torinak.com/qaop) Remember that keywords are a single character in the ZX Spectrum ``` OVER 1 PLOT 40,40 DRAW 40,40,RND*5000 ``` To enter these commands on the emulator: `TAB` `,1` `ENTER` q 40,40 `ENTER` w 40,40,`TAB` `t``CTRL`+`B`5000`ENTER` (Don't you just love the spectrum keyboard) ]
[Question] [ ## Background In Western music, every single music note has an assigned name. Within each octave, there are twelve unique notes in the following order: "C C#/Db D D#/Eb E F F#/Gb G G#/Ab A A#/Bb B C", where the final C is one octave above the first. To tell the difference between notes of different octaves, a number (for this challenge restricted to a single digit) is appended to the end of the note name. Thus, C5 is the note that is one octave above C4. Bb6 is above B5. An important fact is that B5 and C6 are notes that are right next to each other, and that C0 and B9 are the lowest and highest notes. Between any two notes, there is a distance which is the number of semitones between them. Bb4 is one semitone below B4, which is itself one semitone below C5. There are twelve semitones in an octave, so Bb4 is a distance of 12 from A#3 since it is an octave above it (notice how a single note can have up to two names). ## The Challenge Your challenge is to write the shortest possible program that can take a list of music notes from STDIN and print the list of interval changes to STDOUT. Input will be a space-separated list of music notes. Each note will consist of an uppercase letter A-G, an optional b or # sign, and a single digit number. You will not have to deal with E#/Fb or B#/Cb. Example input: ``` C4 D4 E4 F4 G4 A4 B4 C5 C4 ``` Output will be a space-separated list of integers which represent the distance between each successive note, always prefixed with an + or - to show whether the note was ascending or descending relative to the one before it. There will always be one less number outputted than notes inputted. Example output for the above input: ``` +2 +2 +1 +2 +2 +2 +1 -12 ``` Some more example inputs: ``` E5 D#5 E5 B4 E5 F#5 E5 B4 C0 B0 Bb1 A2 G#3 G4 F#5 F6 G4 Ab4 Gb4 A4 F4 A#4 ``` And their corresponding outputs: ``` -1 +1 -5 +5 +2 -2 -5 +11 +11 +11 +11 +11 +11 +11 +1 -2 +3 -4 +5 ``` ## Rules and Restrictions 1. The winner is determined by the number of characters in the source code 2. Your program should consist of only printable ASCII characters 3. You are not allowed to use any sort of built-in function that is related to music or sound 4. Other than that, standard code golf rules apply [Answer] ### GolfScript, 61 ``` " "/{)12*\{"bC#D EF G A B"?(+}/}%(\{.@-.`\0>{"+"\+}*\}/;]" "* ``` [Answer] ## Haskell, 161 characters ``` f(c:r)=maybe(12*read[c])(+f r).lookup c$zip"bC#D.EF.G.A.B"[-1..] g n|n<0=show n|1<3='+':show n h x=zipWith(-)(tail x)x main=interact$unwords.map g.h.map f.words ``` [Answer] # Perl, 103 ``` #!/usr/bin/perl -an /.((b)|(\D))?/,(($~,$,)=($,,12*$'+ord()%20%7*2+(ord()%7>3)-$-[2]+$-[3]))[0]&&printf'%+d ',$,-$~for@F ``` [Answer] ## C, 123 characters Based on leftaroundabout's solution, with some improvements. ``` main(c,b,d) char*b; { while(d=c,~scanf("%s",b)?c=-~*b*1.6,c%=12,c+=b[~b[1]&16?c+=1-b[1]/40,2:1]*12:0) d>1&&printf("%+d ",c-d); } ``` Some tricks that I think are worth mention: 1. `argv[0]` (here called `b`) is a pointer to the program name, but used here as a scratch buffer. We only need 4 bytes (e.g. `C#2\0`), so we have enough. 2. `c` is the number of arguments, so it starts as 1 (when run without arguments). We use it to prevent printing on the first round. Possible problem - `c+=b[..c+=..]` is kind-of strange. I don't think it's undefined behavior, because `?:` is a sequence point, but maybe I'm wrong. [Answer] ## C, ~~241~~ ~~229~~ 183 ``` F(c){c-=65;return c*1.6+sin(c/5.+.3)+9;} #define r if(scanf("%s",b)>0){c=F(*b)%12;c+=b[b[1]<36&&++c||b[1]>97&&c--?2:1]*12 main(e,c,d){char b[4];r;}s:d=c;r;printf("%+d ",c-d);goto s;}} ``` [Answer] ## Factor, 303 characters ``` USING: combinators formatting io kernel math regexp sequences ; f contents R/ [#-b]+/ all-matching-slices [ 0 swap [ { { [ dup 48 < ] [ drop 1 ] } { [ dup 65 < ] [ 48 - 12 * ] } { [ dup 98 < ] [ "C-D-EF-G-A-B" index ] } [ drop -1 ] } cond + ] each swap [ over [ - "%+d " printf ] dip ] when* ] each drop ``` With comments, ``` ! combinators => cond ! formatting => printf ! io => contents ! kernel => swap dup drop over dip when* ! math => < - * + ! regexp => R/ all-matching-slices ! sequences => each USING: combinators formatting io kernel math regexp sequences ; f ! Push false, no previous note value. ! Find notes (as string slices) in standard input. The golfed regexp ! R/ [#-b]+/ matches all notes and no whitespace. contents R/ [#-b]+/ all-matching-slices ! For each string slice: [ 0 ! Push 0, initial note value. swap ! Move note slice to top of stack, above note value. ! For each Unicode codepoint in note: [ ! Convert the Unicode codepoint to its value in semitones. ! For golf, [ 48 ] is shorter than [ CHAR: A ]. { ! Sharp # {35} has 1 semitone. { [ dup 48 < ] [ drop 1 ] } ! 0-9 {48-57} has 0 to 9 octaves (1 octave = 12 semitones). { [ dup 65 < ] [ 48 - 12 * ] } ! A-G {65-71} has 0 to 11 semitones. { [ dup 98 < ] [ "C-D-EF-G-A-B" index ] } ! Flat b {98} has -1 semitone. [ drop -1 ] } cond + ! Add semitones to cumulative note value. ] each swap ! Move previous note value to top of stack. ! When there is a previous note value: [ ! Keep current note on stack. over [ ! Compute and print interval. - "%+d " printf ] dip ] when* ! Current note replaces previous note at top of stack. ] each drop ! Drop previous note, so stack is empty. ``` For this script, a "space-separated list" can have 1 or more spaces between elements, and 0 or more spaces at the beginning or end. This script does print an extra space at end of output, but it also accepts an extra space (or newline) at end of input. If I would adopt a stricter definition, where a "space-separated list" has exactly 1 space between elements, and 0 spaces at the beginning or end, then I can shorten `contents R/ [#-b]+/ all-matching-slices` to `contents " " split` (using `splitting`, not `regexp`). However, I would need to add more code to prevent the extra space at end of output. If I use the deprecated word `dupd`, I can shorten `over [ - "%+d " printf ] dip` to `dupd - "%+d " printf`, saving 8 characters. I am not using deprecated words because they "are intended to be removed soon." ]
[Question] [ # Objective Given the distance between two keys in an octave, identify its name. But there's a caveat. In this challenge, there are [22](https://en.xen.wiki/w/22edo) keys in an octave, not usual 12. Here, a [porcupine[7] scale](https://en.xen.wiki/w/Porcupine) will be assumed. # Mapping White keys are marked **bold**. | Distance | Name | | --- | --- | | **0** | `Unison` | | 1 | `Augmented Unison` or `Diminished Second` | | 2 | `Minor Second` | | **3** | `Major Second` | | 4 | `Augmented Second` | | 5 | `Diminished Third` | | **6** | `Minor Third` | | 7 | `Major Third` | | 8 | `Augmented Third` or `Diminished Fourth` | | **9** | `Perfect Fourth` | | 10 | `Major Fourth` | | 11 | `Augmented Fourth` or `Diminished Fifth` | | 12 | `Minor Fifth` | | **13** | `Perfect Fifth` | | 14 | `Augmented Fifth` or `Diminished Sixth` | | 15 | `Minor Sixth` | | **16** | `Major Sixth` | | 17 | `Augmented Sixth` | | 18 | `Diminished Seventh` | | **19** | `Minor Seventh` | | 20 | `Major Seventh` | | 21 | `Augmented Seventh` or `Diminished Octave` | | *(others)* | *(don't care)* | # Rule You can freely mix cases in output. Trailing whitespaces are permitted. [Answer] # JavaScript (ES6), 153 bytes ``` n=>n?(a="AugmentedDiminishedMinorMajorPerfectSecondThirdFourthFifthSixthSeventh".match(/.[a-z]+/g))["51324"[n-9]^n%13%4]+' '+a[n+3*(n>11)+19>>2]:'Unison' ``` [Try it online!](https://tio.run/##ZZLRatswFIbv8xQHQ5E0Jy5Ouos22GWw9a5skO7KeCBsOVZxjoqshNGyNxjsZpfbe/R5@gJ7hEyxQhzLN7L1/Tr/OTpHj3zH20LLJzNDVYp9lewxSfGW8iT4sF1vBBpRfpQbibKtRXkvUel7/qj0F6ErUZiVKBSWD7XU5Z3aalPfycrUK/ndLmJno@sg2nBT1PQyyvjsOQ8v14xlwft4Mb8KMpxd59/wIl5cXOUhARLyDMPFO4ppHLMwvk7TeX5DvtrkCsl@mU0AMgjcPoB86vanQuGoTCHoawZXY3@8u8SYHm41or21r5wl6K7v@/uws/dg7@6EYd2uof3pY8tH3Fn7tPc@Kp75YU5@zR48JRziM@dO8Lp9mP2o2R50vR7Cs1YPhcEo3ZsazdLHx2F6@HyaThrW/rkwfCfs@Uk@iSqlP3H7cKm0EXrHmykggySFF2vWCANatJBARZEtLbGvo1WNiBq1phgZtTJa4pqy6ImXK8O1oXMGIZAbIPZziLWb7v@UIJJYNNtStNTKDG6B/Hv99fbnt10J2Li3vz8Js8l@sOX@Pw "JavaScript (Node.js) – Try It Online") ### How? The case \$n=0\$ is processed separately. We use the repeating sequence ***Diminished** / **Minor** / **Major** / **Augmented*** for \$1\le n\le 8\$ and for \$14\le n\le 21\$. The corresponding indices in the lookup array are \$[1,2,3,0]\$. This is done by reducing \$n\$ modulo \$13\$ and then modulo \$4\$. We actually use the same calculation for \$9\le n\le 13\$, but we apply a bitwise XOR to get the correct indices \$[4,3,0,2,4]\$, corresponding to ***Perfect** (Fourth) / **Major** (Fourth) / **Augmented** (Fourth) / **Minor** (Fifth) / **Perfect** (Fifth)*. This gives: ``` "51324"[n - 9] ^ n % 13 % 4 ``` We then need to append ***Second*** to ***Seventh*** with indices \$5\$ to \$10\$ in the lookup array. The expected sequence is: ``` n | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 -------+--------------------------------------------------------------- index | 5 5 5 5 6 6 6 6 7 7 7 8 8 9 9 9 9 10 10 10 10 ``` Basically, each index is repeated 4 times but 3 indices are omitted between \$n=11\$ and \$n=12\$. This can be obtained with: ``` n + 3 * (n > 11) + 19 >> 2 ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 54 bytes ``` 6ɾ›∆o`diø¤Ṁ§ ↑ṙ €ǐ ÷¨ «ø⟑ƒ₄ḭ`⌈vMƒJRvṄ»9Tr⌈»bTİ`Ẏ↲½Ŀ`pi ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIyMihu4oC5OuKCtGAgPT4gYOKCtCIsIjbJvuKAuuKIhm9gZGnDuMKk4bmAwqcg4oaR4bmZIOKCrMeQIMO3wqggwqvDuOKfkcaS4oKE4bitYOKMiHZNxpJKUnbhuYTCuzlUcuKMiMK7YlTEsGDhuo7ihrLCvcS/YHBpIiwiLCIsIiJd) ### How? Get the list `["second", "third", ... , "seventh"]`: ``` 6ɾ›∆o ``` Get the list `["diminished", "minor", "perfect", "major", "augumented"]`: ``` `diø¤Ṁ§ ↑ṙ €ǐ ÷¨ «ø⟑ƒ₄ḭ`⌈ ``` Get all pairs in the correct order and join them by space: ``` vMƒJRvṄ ``` Only keep the some of the pairs: ``` »9Tr⌈»bTİ ``` Prepend `"unison"` and index into the list: ``` `Ẏ↲½Ŀ`pi ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~95~~ 94 bytes ``` ⪫E§⪪”$&⊞ςq×P5μ·⸿§▷"↑W4⪪9Qλς”²⊖N§⪪”↶⌈∨S⎚χ]¹↶E´üêB⭆↓HηW◧⁻◨~,⦄Zi≦r⊗Þπ↖Z):⊕À´Aeδ∨8:≧#$/VMχ)A” ⌕αι ``` [Try it online!](https://tio.run/##XY7NTsUgEEZfZdIVTWpi3LqCcumfGhOfAGEqY1poKNzct0eu7tycTObLnG@M09EEvZXyHsknNgfy7FUfjKfJW7yxj2OjxBquhOqVVHwQQz/I4TL2oxzFdJn4LOZ@ljNfxNIvcnlpOnhqO5BoIu7oE1o2@SOnt7x/YmRtW8N/dks7eTodWqhDiLDr70qdv/4EcGBc0SQ40QRvITmKFtaQY3Kw0lp50u1OvNYDB7nagq@fNNDUOkXeMt0B/Zbfd@1zKY/l4br9AA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ”...” Compressed lookup table ⪪ ² Split into substrings of length `2` § Index by N Input integer ⊖ Decremented E Map over letters ⪪”...” List of words § Indexed by ⌕αι Uppercase letter index ⪫ Join with spaces Implicitly print ``` Note that the lookup table is `43` letters long so that the last entry only has one letter; this is the one that is then selected for an input of `0`. Previous 95-byte solution: ``` Nθ∧θ§⪪”↶↧*y³↨Cⅈ~➙…⟧⊖⁺¡κY⁸⁴Σ1|R6;” §”)⊞⮌i›‽”θM→§⪪”↶⌈∨l⟲Eχ⁼⁰θ℅BNμ↨%),ρ℅«◨ THY¬O⬤ε” §”)➙:⌊B/M⁷ê\`”θ ``` [Try it online!](https://tio.run/##ZY7BasMwDIbvfQrhkwMdJHG2w3LqsYeN0j5BFiu1SmInjhz69q4KgzL2gX6EhPjUuy72oRtzPvo58XeafjDqpWh3p0ie9cFbvezhwEdv8a4v80islaWJPK0OLUgTIkzdTbJL1wk9y3TGOGDPag8KVPG6V01Z1eZZTW0qWS@F0O6@wob680xXxy/1X2cSYfCwYh@8BXYULQwhRXYw0CC50v2ZuMkL7r@5rIRaMMY0zbvwIfy@0OZc5rdtfAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` Nθ ``` Input the distance. ``` ∧θ§⪪”...” §”...”θ ``` If it's not zero, cyclically index into the compressed table `4012301234231` to find the index into the compressed list of words `diminished minor major augmented perfect`. ``` M→ ``` Leave a space between the two words. ``` §⪪”...” §”...”θ ``` Index into the compressed table `0111122223334455556666` to find the index into the compressed list of words `unison second third fourth fifth sixth seventh`. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~71~~ 70 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` .•10°ÝΣËðw¶\ƵUʒ•…‡®¢ÑíÀ«#•”Öζт'µ•5вè“…Þ‰ª¦ƒ³äÇïÖµ“#•γ¤æ•ÅΓø.•I¢#€•šÅв» ``` Outputs in lowercase. [Try it online](https://tio.run/##yy9OTMpM/f9f71HDIkODQxsOzz23@HD34Q3lh7bFHNsaemoSUPxRw7JHDQsPrTu06PDEw2sPNxxarQwWnXt42rltF5vUD20Fck0vbDq84lHDHKDiw/MeNWw4tOrQsmOTDm0@vORw@@H1h6eBFM0B6Tu3@dCSw0ADFx1uPTf58A6QxZ6HFik/aloDZB1deLj1wqZDu///NzIEAA) or [verify all test cases](https://tio.run/##yy9OTMpM/W9keGySn72SwqO2SQpK9n7/9R41LDI0OLTh8Nxziw93H95QfmhbzLGtoacmAcUfNSx71LDw0LpDiw5PPLz2cMOh1cpg0bmHp53bdrFJ/dBWINf0wqbDKx41zAEqPjzvUcOGQ6sOLTs26dDmw0sOtx9ef3gaSNEckL5zmw8tOQw0cNHh1nOTD@8AWex5aJHyo6Y1QNbRhYdbL2w6tPu/zn8A). **Explanation:** ``` .•10°ÝΣËðw¶\ƵUʒ• # Push compressed string "augmented diminished " …‡®¢ÑíÀ # Push dictionary string "major minor perfect" « # Append them together # # Split this string on spaces: # ["augmented","diminished","major","minor","perfect"] •”Öζт'µ• '# Push compressed integer 160475945053335 5в # Convert it to base-5 as list: # [1,3,2,0,1,3,2,1,4,2,1,3,4,1,3,2,0,1,3,2,0] è # 0-based index each into the previous list of strings “…Þ‰ª¦ƒ³äÇïÖµ“ # Push dictionary string "second third fourth fifth sixth seventh" # # Split it by spaces as well •γ¤æ• # Push compressed integer 4333444 ÅΓ # Run-length decode the list of strings and digits of this integer ø # Create pairs of the two list of strings .•I¢#€• # Push compressed string "unison" š # Prepend it to the list of pairs Åв # Convert the (implicit) input-integer to this custom base as list » # Join each inner pair by spaces, and then the strings by newlines, # which simply pushes the only string in the list in this case # (after which it is output implicitly as result) ``` [See this 05AB1E tip of mine (all four sections)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `.•10°ÝΣËðw¶\ƵUʒ•` is `"augmented diminished "`; `…‡®¢ÑíÀ` is `"major minor perfect"`; `•”Öζт'µ•` is `160475945053335`; `•”Öζт'µ•5в` is `[1,3,2,0,1,3,2,1,4,2,1,3,4,1,3,2,0,1,3,2,0]`; `“…Þ‰ª¦ƒ³äÇïÖµ“` is `"second third fourth fifth sixth seventh"`; `•γ¤æ•` is `4333444`; and `.•I¢#€•` is `"unison"`. ]
[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. --- [You successfully route the laser into the sensor](https://codegolf.stackexchange.com/q/255405/78410), but nothing happens. "What?" Frustrated, you flip the note from Santa. There's some more text: > > Calculate the number of ways to complete the laser puzzle, and enter it into the number pad on the back side of the package. > > > Wow, now it's a hard problem. The time is ticking and it's got so many G's, so a simple brute force (`O(3^G)`) won't cut it. For the example problem below, ``` +-+-+-+-+-+-+-+ laser --> |G|G|R|\|G|G|G| +-+-+-+-+-+-+-+ |\|R|/|G|R|G|\| --> sensor +-+-+-+-+-+-+-+ ``` the answer is 3. The G at the 5th cell on the top row can be anything (`./\`); the others are fixed. ## Task In this task, the positions of the laser and the sensor are fixed, and the height of the grid is always 2. Given the state of the lock as a 2-by-N grid, output the number of its solutions. The input grid is given as a 2D string like ``` GGR\GGG \R/GRG\ ``` but the following variations (and combinations thereof) are allowed: * an array of rows / a matrix / a flattened string or array * charcodes instead of characters * transposed grid (in other words, columns instead of rows) * lowercase instead of uppercase No other alternative I/O formats are allowed. **This is a [restricted-complexity](/questions/tagged/restricted-complexity "show questions tagged 'restricted-complexity'") challenge.** The time complexity must be at most polynomial in the length of the grid N. Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins. ## Test cases ``` G G -> 1 GG GG -> 6 G\GGGGGRGGGGG GGG/G\GG/GGGR -> 64512 RR RR -> 0 R\ \R -> 0 /GGG GGGG -> 0 ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 117 bytes ``` f=(a,p=1,q=0,h=r=>!!a.match('^'+r))=>a?f(a.slice(2),h`\\w`*3**h`.g`*p+h`[g/]{2}`*q,h`.\\w`*3**h`g`*q+h`[S-g]{2}`*p):q ``` [Try it online!](https://tio.run/##RZBNb4MwDIbv/Ap6IoFgSvdx2BR2mDYuO61HYErEAqSiJJCoRZr221nopDaOrDfvY9mKD/zETT1JbeNBfYvlnS4NRZxompKRbklHJ5ptNhyO3NYdCr6CaMKYZvylQRxML2uBdph0rCzPLLwLw45By0Iddaxok@pn98vC0WG4cYfHFe/j9p9r/DQuVhhbcyOMT/29neTQwsTPzMtdxJmfel6er9fpR6fLfD2fl@zsPFmdZLUuFfcP6c5jnnftClZ9qLOYXt0DYTC6lxYl5VAOCXZ/02im2Qxu7vFKg3II8BUW0Qxa6Rv1A1ykFSkAYC62VXUpRCci3XZO0exYISsMByUHFATYyUZNb9wtERWCOESzWg1G9QJ61SJBaYMkJmvC@Hn5Aw "JavaScript (Node.js) – Try It Online") Input transposed, flatten, lowercase grid. ``` f=( a, // the input grid, transposed flatten lowercase p=1,q=0, // number of solutions where laser reach the first / second row h=r=>!!a.match('^'+r) // test if input "a" matches given regex // or in the other word, test if the first column match given pattern )=>a? // whenever there are remaining columns f(a.slice(2), // recursively call function with first column removed h`\\w`*3**h`.g`*p+ // pattern "g?", "r?" (where "?" is whatever) allow laser from row 1 to row 1 h`[g/]{2}`*q, // pattern "//" allow laser from row 2 to row 1 h`.\\w`*3**h`g`*q+ // pattern "?g", "?r" allow laser from row 2 to row 2 h`[S-g]{2}`*p // pattern "\\" allow laser from row 1 to row 2 // as /[g\\]/ need to be written as "[g\\\\\\\\]" // we use "[S-g]" to avoid leaning toothpick syndrome ):q ``` For any grid with \$2\times N\$ cells, the algorithm took \$O(N^2)\$ time to compute the result. [Answer] # [Python](https://www.python.org), 97 bytes (@Arnauld) ``` def f(a,t=1,b=0): for T,B in a:t,b=B*3%5*t*(T&8<1)+T*B%2*b,T*3%5*b*(B&8<1)+t*(T*B%7<2) return b ``` [Attempt This Online!](https://ato.pxeger.com/run?1=NY_PCoJAEMbv-xSDYOxs2z8jEtGLl-7hzTy46NKCqGzjoV6lS5d6p94m12pgZuD3DXzf3F_9lc5d-3g8B9KL8F1WtQbNS0nJRqpkjRED3VnIZAqmhTKikaZi6-8ECZ7NwniD80ykfiCUzCauBE-_3F2M0j4OkIGtabAtqJ-RIkjA87zD6eDqOE029sqRlUOjurz0jSGOzF3neWcr3qB0y2IxBWukdcFupueCsGC9NS1xzQnx6_R_7QM) ### [Python](https://www.python.org), 127 bytes ``` def f(a,t=1,b=0): for T,B in a:t,b=t*(T>"a")*3**(B=='g')+b*({T,B}<={*"/g"}),b*(B>"a")*3**(T=="g")+t*({T,B}<={*"\g"}) return b ``` [Attempt This Online!](https://ato.pxeger.com/run?1=TY_BbsIwDIbveQrLF-w0o5u4TIhw6IU76g02qRVNqVS1VTCaNoR4EC5c4J32NkvYpi2Sffj8Wf5zvg3vsu27y-W6F_fw_HnaVA4cFUbskyntI08VuN5DbjJoOiimEqhoyudYIOuJ1pRZO6pHnJSaDkE7zuxBY1rjkU1A2Z-YW4s1ciL_xXUUFfhK9r6D8ifGq4AFRFysF_Et712FSiNJIwrTcdu_VZ54vBvaRohV3Fq1ib9Hbo2PkT-agbTwixp80wk5EubvK7-f_gI) Using small letters saves a few bytes. ### [Python](https://www.python.org), 134 bytes ``` def f(a,t=1,b=0): for T,B in a:t,b=t*(T in"RG")*3**(B=='G')+b*({T,B}<={*"/G"}),b*(B in"RG")*3**(T=="G")+t*({T,B}<={*"\\G"}) return b ``` [Attempt This Online!](https://ato.pxeger.com/run?1=VY-_CsIwEMb3PMWRpUkareIixSxdspfiYh0sGiyUtsTroKWrL-Hiou_k25j4B_TgjrvvfhzfXe7tEfdNfb3eOjSj-eO83RkwbCNRTWWhJjwmYBoLmUygrGETo1NRsMxNNNWUi5kQLFEq0AEPC8F6Rw4L1QsaaTpw6aTkj82Uoq4P8ZfNcw8TsDvsbA3Fx80SQQGlVOfaR_qqxGXklchLbjs-tFWJjBNPr6rQvhxX0nrHp7JlAvmatLaskRmGnL-vf39-Ag) Takes the transpose, i.e. a list of 2-strings. Note: this is linear in the grid length. ### How? The key insight here would be that there are no nasty interdependencies. Any partial path that leaves column n in the top row, say, can be combined with any partial path that enters column n+1 in the top row. This allows for many counting methods. A particularly simple one - used here - is to advance column by column keeping track of the numbers of paths that leave the current column at the top or the bottom. [Answer] # JavaScript (ES6), 86 bytes This is a port of [loopy walt's answer](https://codegolf.stackexchange.com/a/255443/58563) with an extra layer of ASCII code trickery. Expects a transposed matrix of ASCII codes, using upper case. ``` m=>m.map(([T,B])=>[t,b]=[B*3%5*t*!(T&8)+T*B%2*b,T*3%5*b*!(B&8)+t*(T*B%7<2)],t=1,b=0)|b ``` [Try it online!](https://tio.run/##RdBdT8MgFAbge34FLpnjVGRzxmiiLLFGue96R3vRMrrV9GMCmi1uv71CNZEQTnh4OSG8F1@FVabeu@uu3@ih4kPLVy1riz0hMqVxDnwlHS1zLuPodnoXueiCpJcPcJVG8XQZlTQdufQcB3YRCSf3T0vIqeM3tOQLOJWD0R@ftdFkVtkZMKOLzVvd6PWxU2QBzPVrZ@puS4DZfVM7Msm6rJsAq3rzWqgdsZiv8DfCuNEOt5hjmT/6nf2P@/D4akvxEUJaMsZs/ouK4sOIpJWH3F8fy@nk24A8BlBM7Qrz4j/h2REACN1V39m@0azpt6QibcAzDAIJhIQIE4lMhJGMqxcxDzIPhFCShImSDGW@zP8S4gc "JavaScript (Node.js) – Try It Online") ### Expressions * `X * 3 % 5` evaluates to \$3\$ if \$X=71\$ (`G`) or \$1\$ otherwise * `!(X & 8)` evaluates to \$1\$ (true) if \$X\in\{71,82\}\$ (`G` or `R`) or \$0\$ (false) otherwise * `T * B % 2` evaluates to \$1\$ if \$T,B\in\{47,71\}\$ (`/` or `G`) or \$0\$ otherwise * `T * B % 7 < 2` evaluates to \$1\$ (true) if \$T,B\in\{71,92\}\$ (`G` or `\`) or \$0\$ (false) otherwise [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 52 bytes ``` F²⊞υ¬ιFEθ⁺ι§ηκUMυ⁺××κ№α§ιλX³⁼§ι¬λG×§υ¬λ⬤ι№⁺§/\λGμI⊟υ ``` [Try it online!](https://tio.run/##TY9PC4MwDMXvforgKUKHsB13Ehmyw4aMHb0UdSi21n/d9u27pCIz0Bxefi95LRs5lUYq515mAjxGkNu5QSvgbhZso@gc@MFNDjgKyJWdsRWQLNe@qr/YCOgiKqB5arSWfcVejz1bXW@9E5Aa2y8o/15ao8hKtPnUE54EXEYr1Yw7gEMoZsIs9Oy6biPsjkiUYsd6xgfYqDAuipCPrWsEaI5MP8unlthUzmQwA1oWncuKjOvhe0AvZiVmyR3e6gc "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Port of @loopywalt's Python answer. ``` F²⊞υ¬ι ``` Start with one possible beam on the top row and none on the bottom row. ``` FEθ⁺ι§ηκ ``` Loop through the columns. ``` UMυ⁺××κ№α§ιλX³⁼§ι¬λG×§υ¬λ⬤ι№⁺§/\λGμ ``` Update each row, keeping the count for `R` and `G` with no `G` in the other row or trebling it with `G` in the other row, plus the count of the other row if the column is or can be changed to `//` or `\\` as appropriate. ``` I⊟υ ``` Output the final count for the bottom row. (As with my answer to the linked question, six bytes could be saved by taking the input in transposed format.) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 54 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` 1¾‚Iv©y`'GQ3smsa*y„/G2ãQà‚*y„\G2ãQày`as'GQ3sm*‚®*R‚O}θ ``` Port of [*@tsh*'s JavaScript answer](https://codegolf.stackexchange.com/a/255442/52210), so make sure to upvote him/her as well! Unlike his/her answer, *I think* my answer is \$O(38N)\$ for a grid of dimensions \$2\times N\$. Input is transposed and as a list of 2-char strings. [Try it online](https://tio.run/##yy9OTMpM/f/f8NC@Rw2zPMsOraxMUHcPNC7OLU7UqnzUME/f3ejw4sDDC4CyYH4MlF@ZkFgMUagFlDq0TisISPnXntvx/3@0kntMjJKOknsQkAjSBxIxMe4wvjuYBZSPBQA) or [verify all test cases](https://tio.run/##yy9OTMpM/V@mFFCUWlJSqVtQlJlXkpqikJlXUFpipaCkU6nDpeSYXFKamAMXs68MPrTt0MLDO7xsw/4bHtr3qGFWZNmhlZUJ6u6BxsW5xYlalY8a5um7Gx1eHHh4AVAWzI@B8isTEoshCrWAUofWaQUBKf/aczv@K/mXlkBt0Dm0zf5/tJK7e1BMjLu7e0xeTEyQvnuQe0yMko6CEpDvDqZBDAgLrAyoHEyCRN31wWL6IEGlWAA). **Explanation:** ``` 1¾‚ # † Push 1 and 0, and pair them together Iv # Loop `y` over the input-list: © # Store the current pair in variable `®` (without popping) y # Push the current string-pair `y` ` # Pop and push them separated to the stack 'GQ '# Check if the second/top is equal to "G" 3sm # Take 3 to the power this y[1]=="G" check s # Swap so the first character is at the top a # Check whether it's a letter ("R" or "G"): isLetter(y[0]) * # Multiply the checks together: (3**(y[1]=="G"))*isLetter(y[0]) y # Push the current pair `y` again „/G # Push string "/G" 2ã # Cartesian power of 2: ["//","/G","G/","GG"] Q # Check for each whether it's equal to `y` à # Check if any is truthy by taking the maximum ‚ # Pair the two together * # Multiply the values in the two pairs together y„\G2ãQà # Same as above for ["\\","\G","G\","GG"] y`as'GQ3sm* '# Same as above for isLetter(y[1])*(3**(y[0]=="G")) ‚ # Pair the two together ®* # Multiply the values with pair `®` as well R # Then revert it ‚ # Pair these two pairs together O # Sum each inner pair }θ # After the loop: leave last element of the resulting pair # (which is output implicitly as result) ``` † This could have been `0L` instead for -1 byte, but it would change the complexity to \$O(38N+2)\$. ***Why I think it's \$O(38N)\$:*** Looping with `Iv` is the \$N\$ complexity. Within its body, the following add to the complexity: * ``` (2x): pop and dumping both characters to the stack: \$2\times2=4\$ * `„/G2ã` and `„\G2ã`: cartesian power of 2 on a 2-char string: \$2\times2^2=8\$ * `Q` (2x): equals check on all four values in a quadruplet list: \$2\times4=8\$ * `à` (2x): maximum on a quadruplet list: \$2\times4=8\$ * `‚*` and `‚®*`: multiply the values in two pairs together: \$2\times2=4\$ * `R`: reversing a pair: \$2\$ * `‚O`: summing the inner pairs of a pair of pairs: \$2^2=4\$ All summed together: \$4+8+8+8+4+2+4=38\$ [Answer] # [PARI/GP](https://pari.math.u-bordeaux.fr), 84 bytes ``` a->l=[1,0];[l*=[if(u%15%2,v*3%5),u*v%7<2;u*v%2,if(v%15%2,u*3%5)]|t<-a,[u,v]=t~];l[2] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=NY_BSsQwEIbv-xRDoJCUlLqVRaHtXjzk5KWIlyRIELsUstmQJgVh2RfxUhDxMXwO38amceeQ-fN__wzMx7dVbng52Pmzh_Yr-L64_31SxV63fEtvZM113vKhxyHb7rKKTvlttiM05FN211R17BVd8JRwWLE8-6ZQlAc6ydZfZK15Jf93_xywItDCo_KYw8NJ4-e31_GotMaOEDiDg6aA0bvR6sFjRQEJgwhIctlslLX6HSso9mDdYBYc6fJD0OO4mKQ0BY6YMAwt0yyKpIRgsbr1jS4rV6-MZkx0nTBdUkIII8Sqy2uaIUnSGfOc-h8) Takes a matrix of ASCII codes. A port of [@Arnauld's JavaScript answer](https://codegolf.stackexchange.com/a/255455/9288). Uses `X % 15 % 2` instead of `!(X & 8)` because PARI/GP doesn't have a bitand operator. ]
[Question] [ In the game [Pickomino](https://www.boardgamegeek.com/boardgame/15818/pickomino), there are several tiles lying in the middle of the table, each with a different positive integer on them. Each turn, the players roll dices in a certain way and get a score, which is a nonnegative integer. Now the player takes the tile with the highest number that is still lower or equal to their score, removing the tile from the middle and adding it to their stack. If this is not possible because all numbers in the middle are higher than the player's score, the player loses the topmost tile from their stack (which was added latest), which is returned to the middle. If the player has no tiles left, nothing happens. ## The challenge Simulate a player playing the game against themselves. You get a list of the tiles in the middle and a list of the scores that the player got. Return a list of the tiles of the player after all turns have been evaluated. ## Challenge rules * You can assume that the list with the tiles is ordered and doesn't contain any integer twice. * You can take both lists of input in any order you want * The output has to keep the order of the tiles on the stack, but you can decide whether the list is sorted from top to bottom or from bottom to top. ## 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 with [default I/O rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/), so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. * [Default Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. * If possible, please add a link with a test for your code (i.e. [TIO](https://tio.run/#)). * Adding an explanation for you answer is recommended. ## Example (taken from the 6th testcase) ``` Tiles: [21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36] Scores: [22, 22, 22, 23, 21, 24, 0, 22] ``` First score is 22, so take the highest tile in the middle <= 22, which is 22 itself. ``` Middle: [21, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36] Stack: [22] Remaining scores: [22, 22, 23, 21, 24, 0, 22] ``` Next score is 22, so take the highest tile in the middle <= 22. Because 22 is already taken, the player has to take 21. ``` Middle: [23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36] Stack: [22, 21] Remaining scores: [22, 23, 21, 24, 0, 22] ``` Next score is 22, but all numbers <= 22 are already taken. Therefore, the player loses the topmost tile on the stack (21), which is returned into the middle. ``` Middle: [21, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36] Stack: [22] Remaining scores: [23, 21, 24, 0, 22] ``` Next scores are 23, 21 and 24, so the player takes these tiles from the middle. ``` Middle: [25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36] Stack: [22, 23, 21, 24] Remaining scores: [0, 22] ``` The player busts and scores zero. Therefore, the tile with the number 24 (topmost on the stack) is returned into the middle. ``` Middle: [24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36] Stack: [22, 23, 21] Remaining scores: [22] ``` The last score is 22, but all tiles <= 22 are already taken, so the player loses the topmost tile on the stack (21). ``` Middle: [21, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36] Final Stack and Output: [22, 23] ``` ## Test cases (with the topmost tile last in the output list) ``` Tiles: [21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36] Scores: [26, 30, 21] Output: [26, 30, 21] Tiles: [21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36] Scores: [35, 35, 36, 36] Output: [35, 34, 36, 33] Tiles: [21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36] Scores: [22, 17, 23, 19, 23] Output: [23] Tiles: [21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36] Scores: [] Output: [] Tiles: [21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36] Scores: [22, 17, 23, 19, 23, 0] Output: [] Tiles: [21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36] Scores: [22, 22, 22, 23, 21, 24, 0, 22] Output: [22, 23] Tiles: [1, 5, 9, 13, 17, 21, 26] Scores: [6, 10, 23, 23, 23, 1, 0, 15] Output: [5, 9, 21, 17, 13, 1] Tiles: [] Scores: [4, 6, 1, 6] Output: [] ``` --- [Sandbox](https://codegolf.meta.stackexchange.com/questions/2140/sandbox-for-proposed-challenges/17352#17352) [Answer] # [Haskell](https://www.haskell.org/), ~~119~~ ~~111~~ ~~104~~ 103 bytes *1 byte saved thanks to Ørjan Johansen* ``` (#)=span.(<) (a%(b:c))d|(g,e:h)<-b#d=(e:a)%c$g++h|g:h<-a,(i,j)<-g#d=h%c$i++g:j|1>0=a%c$d (a%b)c=a ([]%) ``` [Try it online!](https://tio.run/##JYzNCoMwEITvfQpBhV0SS/WihKQvEnJYf0hibZDao@@eJhZmYGY@GEfHa9m2GKFEdewU7iDxBlTDKCbE@QTLF@FQNmM5K1gEYT1VljF3WuFkQxw8XxO2CbuEPGNWrGf7fChKdc5fI06K4pt8UPvHh2@lTa27jhftpZyu9l8GU@kukyG550Vv4g8 "Haskell – Try It Online") Assumes the tiles are sorted in descending order. Not much fancy going on here. The first argument is the players pile, the second their scores and the third is the pile in the middle. [Answer] # Japt, 24 bytes Oof! That didn't work out as well as I thought it would! Takes input in reverse order. ``` ®=Va§Z)Ì?NpVjZ:VpNo)nÃN¤ ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=rj1WYadaKcw/TnBWalo6VnBObyluw06k&input=WzYsIDEwLCAyMywgMjMsIDIzLCAxLCAwLCAxNV0KWzEsIDUsIDksIDEzLCAxNywgMjEsIDI2XQ==) or [run all test cases on TIO](https://tio.run/##rZE9CsJAEEb7PcW2gRUyO@ZPEG9gIZJAQopUQkCTwhvYegzBTjzD5mDrt7vBRssUX3ayvHnDJH03Xu3@ZN5HEZ56sOa1LTvzrKPpvqvGsq835VgN0WW6VeZhbS4anSrJsZKaWiUbTag0wsgaSRAQOkNypAg0g2NwDI7BMThOW9H4wr/4iyWUrpmyIKDCnYtoveRX/W@ekvFim3zjJBRE7vPrRSaApXjun0PeT4nzowYJCfG8oxvoGiFJPev/WStW58MH) ``` ®=Va§Z)Ì?NpVjZ:VpNo)nÃN¤ :Implicit input of N=[U=scores, V=tiles] ® :Map each Z in U = : Reassign to Z Va : 0-based index of last element in V (-1 if not found) §Z : Less than or equal to Z ) : End reassignment Ì : Sign of difference with -1 (1 if found, 0 if not) ? : If truthy (not zero) Np : Push to N VjZ : Remove and return the element at index Z in V : : Else Vp : Push to V No : Pop the last element of N ) : End Push n : Sort V à :End map N¤ :Slice the first 2 elements (the original inputs) off N ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 89 bytes ``` {my@x;@^a;@^b>>.&{@x=|@x,|(keys(@a∖@x).grep($_>=*).sort(-*)[0]//(try [[email protected]](/cdn-cgi/l/email-protection)&&()))};@x} ``` [Try it online!](https://tio.run/##vZLBToMwHMbP8hQNWUi7dEDpxpwLpB68mXjQeNnQADKzuAkBTCDbPPsEPqAvgv8CWRrPbocvkK9ff9@/TbMk37jNtkbGCnmo2W1rUc3FUwiKfN80dqLy9qKie/yW1AUW4c/Xt6iI@ZonGR48@96QmEWal3g0JAs7sCxc5jX6FJWZpZlhYELIYS6qQ7NKc7RZvycFUON0G2FruTCHy8AiYNw8Xt@ikY9ESEVERUwHL56uo512UYQ1WkEt3YuIUF2GdPiPtUPzsN4kxRVaOIwixwFx0Bg0AbmgKegSNKOI2yDIcchxyHHIcchxN9Du4zTvQG4XdFig3X2U2Uf5x9T@vbI1WrNbONa25rhf4KeolhA27UBsJr/qqU9SqRSc50QU2WfoPErCWAeUL8ZRL9Tpbvg4AeSABTWM91PLnSoaxmF2T@3FWjCbKOAOIjdLSAtTWhQcDOW2BPWZBb8 "Perl 6 – Try It Online") I think there's a few more bytes to be golfed off this... [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), ~~159~~ ~~158~~ 154 bytes Called as `f(tiles)(scores)` ``` n=>m=>{var s=new Stack<int>();m.Add(0);n.ForEach(k=>{var a=m.Except(s).Where(x=>x<=k).Max();if(a<1)m.Add(s.Count<1?0:s.Pop());else s.Push(a);});return s;} ``` If only `System.Void` is actually a return type and not just a placeholder for reflection. I would be able to replace `if(a<1)m.Add(s.Count<1?0:s.Pop());else s.Push(a);` with `var t=a>1?m.Add(s.Count<1?0:s.Pop()):s.Push(a);`, saving two bytes. [Try it online!](https://tio.run/##xY/BSsQwEIbv@xQ5JlBD02jXNU1EZPeksODBc8imtNSmS5NqYemz12krCvsA9fCRTObP/88Yf2N8OR46Z7KX0oesdEFFV@Vb0Kaar0rlcnRS1VJdPnWLvHT2C/31MRE1fTqdcEyEo4em3WtT4OpHrWVN972x54A9oe@FbS3upeozWRH6qnv4XeZYZ4wsJp4@N50LGXuMHzw9NmdMiLAf3iKoOl9gTcRARGtD1zrkxTCKzbGFOXCOp7l@N7gkLEJJAnDgFrgDUmAL3AO7CPEYAB0HHQcdBx0HHU8Hcm2XLvKEDTDRZp3Q@XluLe3Vgicrtl3s2G46Vwz/1z0jFE/54zc "C# (Visual C# Interactive Compiler) – Try It Online") ``` //Function taking in a list and returning //another function that takes in another list and returns a stack n=>m=>{ //Initialize the stack var s=new Stack<int>(); //Add a zero to the tiles, to ensure no exceptions appear due to accessing //non-existent elements in an empty collection later //when we try to filter it later and getting the biggest element m.Add(0); //Iterate through our scores n.ForEach(k=>{ //Create a variable called a, which we will use later var a= //Get all the elements in the middle that haven't appeared in our stack m.Except(s). //And throw away all elements that are bigger than our current score Where(x=>x<=k). //And get the biggest element there, and that is now the value of a //Without the m.Add(0), we would get an exception here Max(); //Self-explanatory, if a is less than 1 aka if a equals 0 //Checks if all elements in the middle are bigger than our score //Except for our self added 0, of course if(a<1) //Add 0 to the middle if the stack is empty //Remember, zeros don't affect the list m.Add(s.Count<1?0: //Else pop the stack and add that to the middle s.Pop()); //If a isn't 0, add a to the stack else s.Push(a);}); //Afterwards, return the stack return s;} ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 77 bytes ``` ->t,s,r=[]{s.map{|i|(x=(t-[p]).reject{|j|j>i}.max)?(t-=[x];r<<x):t<<r.pop};r} ``` [Try it online!](https://tio.run/##vZJBboMwEEX3nMLLIDkI44QkgNMjdNHuLC9SRFRQq1jGSFTA2enYRhGwJ4svo/Gf98cjVPP1N97ZuL9qXGPFuOjq4Pcmu77sdy3b6T2Xwg9UURW57vqqr67lAIbWf4M7xluRqixr/URnmQrkQw6pGkbeeZ/lT1EniEcEoygCUdABdATFoBPoDLpgREMQ@Cj4KPgo@Cj4aCyw95E/lCPFzhkRqL43WjZ6XR2wt0WyrdjqdPNMt9XDdEO3m8BQyMmRyMWcix1smDzPeeX7MApfF/2UoRFHNP9UtNhyNO19MQi4AQlphE5PMP2LBBiLhBN8ErF8cpzzHca0G4zFrcPmVBgxtqB4vScRFLf8u@t1r9ida57YdoERfLp2IVKJFEaKMai5ZjGM/w "Ruby – Try It Online") [Answer] # [JavaScript (Node.js)](https://nodejs.org), 80 bytes Same logic as the ES6 version, but takes the tiles as a BigInt bitmask and the scores as an array of BigInts. ``` m=>s=>s.map(g=x=>!x||m>>x&1n?m^=1n<<(x?r.push(x)&&x:r.pop()||~x):g(--x),r=[])&&r ``` [Try it online!](https://tio.run/##vZLfboIwFMbvfYqzG9ImoJQqTkMx2YXJrvYAhiXEKXNKIfxZekH26uy0Jcsmt9OEj9Ker7/vlPQj/UzrfXUqG08Wb4f@KPpcxDU@0zwtSSaUiB9U1@VxrBwmN/mrYDKKiNpU07Kt34mijqPWOClKQrvuS9F1RjxPUbcSuwSLVb8FAQ2IGGr9OpLGoJWenKETwCREETydsmfZIM/FVQG@pOA4cKbEdmLLlE4m@0LWxeUwvRQZ2ZJdwFwIAhRHzVELVIhaoh5RKxe4j0IfRx9HH0cfRx8PE4qE0DoCllAKsxm8tE3ZNmv4Xfn/WPNlZnblb7SpzIcqv0G83s2WlsBWehyd/hax1yF3OZkL/p1yf6QpzJL0BQpGP9eYRl3gFuRhFOPDITTE4LEX5g/kQczA2eIabhF6q0YY1ChJI7G50FBG1y/pvwE "JavaScript (Node.js) – Try It Online") --- # JavaScript (ES6), ~~100 98 94~~ 87 bytes Takes input as `(tiles)(scores)`. The tiles can be passed in any order. ``` t=>s=>s.map(g=x=>m[x]?m[x?r.push(x)&&x:r.pop()]^=1:g(x-1),t.map(x=>m[x]=1,m=[r=[]]))&&r ``` [Try it online!](https://tio.run/##vZJdboMwEITfewo/RbbkEBYnpEFycoQeALkSShPaKsSIn4rb07GNqja8NpEYwHj2m13kz@KraI/NR90tr/btNJ712Ol9iyuqipqXetD7Kh/MAbdDE9V9@84HsVgMGRa25sK8aspKPixJyM7XTBWaZKXzRufGCBQ049FeW3s5RRdb8jPPE5IsSSAFraENlEJb6BnaSaZiCD4Fn4JPwafgU6kRIKTBkRAS2GrFXvqu7ruM/d55@vdY/@ZX4cvfaL@znnbVHeJdNW0DgXbuOZv@HrG3IQ@ZTLL4Qbk/chQKJHeAktnP9aZZFygBD1GkpiEcxOPRC8UTeRJ5OG1u4QHhSh3Co2ZJDonmUk@ZHT8zfgM "JavaScript (Node.js) – Try It Online") ### Commented ``` t => s => // t[] = tiles; s[] = scores s.map(g = x => // for each score x in s[]: m[x] ? // if m[x] is set: m[ // update the 'middle': x ? // if x is not equal to 0: r.push(x) && x // push x in the stack r[] and yield x : // else: r.pop() // pop the last value from the stack // (may be undefined if the stack is empty) ] ^= 1 // toggle the corresponding flag in m[] : // else: g(x - 1), // try again with x - 1 t.map(x => // initialization of the 'middle': for each value x in t[]: m[x] = 1, // set m[x] m = [r = []] // the stack r[] is stored as the first entry of m[], // which ensures that g will always stop when x = 0 ) // end of initialization ) && r // end of main loop; return r[] ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 35 bytes ``` Fη«≔⌈Φ講κιι¿ι«≔Φθ⁻κιθ⊞υι»¿υ⊞θ⊟υ»Iυ ``` [Try it online!](https://tio.run/##TYxfC4IwFEef9VPcxwkLzPWXniKoJ8N38WGE5cg0NxdB9NnXb1bU4DDuds49VFIfWlk7d2w1sSqiRxisjVGnhqXyri72wraq7kvNOk77tmc7XUo/njmpCMdfqzBQR2JqqL/5L0tVY80n4NR5PcisqZj9xM8wKGtTkl9iIxr@0GXtFSOEZ5hp1fRsI00/vDiX58mYU5IAASZgCmZgDhZgyUnEAJ6AJ@AJeAKemBWc8qFO/raM35ti/1QUbnSrXw "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` Fη« ``` Loop over the scores. ``` ≔⌈Φ講κιι ``` Look for the highest available tile. ``` ¿ι« ``` If it exists then... ``` ≔Φθ⁻κιθ ``` ... remove the tile from the middle... ``` ⊞υι ``` ... and add it to the stack. ``` »¿υ ``` Otherwise, if the stack is not empty... ``` ⊞θ⊟υ ``` Remove the latest tile from the stack and return it to the middle. ``` »Iυ ``` Print the resulting stack from oldest to newest. [Answer] # [Python 2](https://docs.python.org/2/), 120 bytes ``` m,s=input() t=[] for n in s: i=[v for v in m if v<=n] if i:v=max(i);t+=[v];m.remove(v) else:m+=t and[t.pop()] print t ``` [Try it online!](https://tio.run/##tZFBboMwEEX3PsWIbqBBEbYTkpB61XbdAyAvotRRLRWDwLXS09MZG1Xqni6@7Bn//8bg4dt/9E7Mz28vryrLsrkrJ2Xd8OXzgnnVanbrR3BgHUwNA6vaANQJ1OnA3iA8KacZ7WwTVHe557Y4@w0a9bnbjqbrg8lDwcB8TqbpNsrDxb23fjv0Q15oNozWefAzDmfM3M0V6C6Px7kVvAQhUBK1Q@1RNeqAOqJOJcgKhT6JPok@iT6JPlnrElpyk0NwDQ9/SrYCPe5iFTs0IZa7pSVXmUJpfkgEfqI1fcs69Mj6p3uWUK2L/xVReCLRc4r0R@IJDsMTjCGRy@VK5I0UHMmrBbCIRwbfR0bKkZ9yMY9ASuKoOprTQ@sf "Python 2 – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~27~~ 22 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` vÐy>‹ÏDgĀià©K®së\sª])¨ ``` [Try it online](https://tio.run/##yy9OTMpM/f@/7PCESrtHDTsP97scWn@4K/PwgkMrvQ@tKz68Oqb40KpYzUMr/v@PNjLSUYBjYyA2BGITHQUDkFAsVzSYD5MDihuZArEZEJsDsQUQW@ooGAMVGwPVGQPVGQPVGQPVGQPVGZvFAgA) or [verify all test cases](https://tio.run/##yy9OTMpM/W/hpuSZV1BaYqXAFZycX5RabKWgZO/poqMUkpkD5xT/Lzs8odLuUcPOw/0uh9Yf7so8vODQSu9D64oPr44pPrSqtlbz0Ir/Slz@pSVgo5TsdQ5t0/kfbWSmo2BsoKNgZBjLFW1kCGQYAbExEJsAsSkQAxUYmQOxBRBbQhQbA9UZA9UZA9UZA9UZA9UZmwENADPAHKgAxSaCNBuaQwwwtATR1DCVNi7TUTCglsFwDDLEEGIQKJaMqGEBUK2hAVQ/FBuCjTc0BcoCmUCFQDMMjaEeBNkH0gc0wwysFByEAA). **Explanation:** ``` v # Loop `y` over the (implicit) input-list of scores: Ð # Triplicate the tiles list (takes it as implicit input in the first iteration) y>‹ # Check for each if `y` <= the value in the tiles list Ï # Only leave the values at the truthy indices D # Duplicate the remaining tiles ¯Êi # If this list is not empty: à # Pop the list, and push its maximum © # Store it in the register, without popping K # Remove it from the tiles list ® # Push the maximum again s # Swap the maximum and tiles-list on the stack ë # Else: \ # Remove the duplicated empty tiles-list from the stack sª # Add the last tile to the tiles-list ] # Close the if-else and loop ) # Wrap everything on the stack into a list ¨ # Remove the last item (the tiles-list) # (and output the result implicitly) ``` [Answer] # Pyth, 32 bytes ``` VE ?JeS+0f!>TNQ=-QeaYJaQ.)|Y]0;Y ``` Try it online [here](https://pyth.herokuapp.com/?code=VE%20%3FJeS%2B0f%21%3ETNQ%3D-QeaYJaQ.%29%7CY%5D0%3BY&input=%5B21%2C%2022%2C%2023%2C%2024%2C%2025%2C%2026%2C%2027%2C%2028%2C%2029%2C%2030%2C%2031%2C%2032%2C%2033%2C%2034%2C%2035%2C%2036%5D%0A%5B22%2C%2022%2C%2022%2C%2023%2C%2021%2C%2024%2C%200%2C%2022%5D&debug=0), or verify all the test cases at once [here](https://pyth.herokuapp.com/?code=VE%20%3FJeS%2B0f%21%3ETNQ%3D-QeaYJaQ.%29%7CY%5D0%3BY&test_suite=1&test_suite_input=%5B21%2C%2022%2C%2023%2C%2024%2C%2025%2C%2026%2C%2027%2C%2028%2C%2029%2C%2030%2C%2031%2C%2032%2C%2033%2C%2034%2C%2035%2C%2036%5D%0A%5B26%2C%2030%2C%2021%5D%0A%5B21%2C%2022%2C%2023%2C%2024%2C%2025%2C%2026%2C%2027%2C%2028%2C%2029%2C%2030%2C%2031%2C%2032%2C%2033%2C%2034%2C%2035%2C%2036%5D%0A%5B35%2C%2035%2C%2036%2C%2036%5D%0A%5B21%2C%2022%2C%2023%2C%2024%2C%2025%2C%2026%2C%2027%2C%2028%2C%2029%2C%2030%2C%2031%2C%2032%2C%2033%2C%2034%2C%2035%2C%2036%5D%0A%5B22%2C%2017%2C%2023%2C%2019%2C%2023%5D%0A%5B21%2C%2022%2C%2023%2C%2024%2C%2025%2C%2026%2C%2027%2C%2028%2C%2029%2C%2030%2C%2031%2C%2032%2C%2033%2C%2034%2C%2035%2C%2036%5D%0A%5B%5D%0A%5B21%2C%2022%2C%2023%2C%2024%2C%2025%2C%2026%2C%2027%2C%2028%2C%2029%2C%2030%2C%2031%2C%2032%2C%2033%2C%2034%2C%2035%2C%2036%5D%0A%5B22%2C%2017%2C%2023%2C%2019%2C%2023%2C%200%5D%0A%5B21%2C%2022%2C%2023%2C%2024%2C%2025%2C%2026%2C%2027%2C%2028%2C%2029%2C%2030%2C%2031%2C%2032%2C%2033%2C%2034%2C%2035%2C%2036%5D%0A%5B22%2C%2022%2C%2022%2C%2023%2C%2021%2C%2024%2C%200%2C%2022%5D%0A%5B1%2C%205%2C%209%2C%2013%2C%2017%2C%2021%2C%2026%5D%0A%5B6%2C%2010%2C%2023%2C%2023%2C%2023%2C%201%2C%200%2C%2015%5D%0A%5B%5D%0A%5B4%2C%206%2C%201%2C%206%5D&debug=0&input_size=2). There must be room for improvement here somewhere - any suggestions would be much appreciated! ``` VE ?JeS+0f!>TNQ=-QeaYJaQ.)|Y]0;Y Implicit: Q=input 1 (middle), E=input 2 (scores), Y=[] VE ; For each score, as N, in the second input: f Q Filter Q, keeping elements T where: !>TN T is not greater than N (less than or equal is the only standard inequality without a token in Pyth, grrr) +0 Prepend 0 to the filtered list eS Take the largest of the above (_e_nd of _S_orted list) J Store the above in J ? If the above is truthy: aYJ Append J to Y e Take last element of Y (i.e. J) =-Q Remove that element from Q and assign the result back to Q Else: |Y]0 Yield Y, or [0] if Y is empty .) Pop the last element from the above (mutates Y) aQ Append the popped value to Q Y Print Y ``` [Answer] # Perl 5 `-apl -MList:Util=max`, 97 bytes ``` $_=$".<>;for$i(@F){(($m=max grep$_<=$i,/\d+/g)&&s/ $m\b//?$s:$s=~s/ \d+$//?$_:$G).=$&}$_=$s;s/ // ``` [TIO](https://tio.run/##rVLBSsQwEL33Kx4ylBbdTZM0Xdtu1JNe9Ohtoeyy6xJobWl6UEQ/3ZhUf2BVGIY3b968hGGGw9gq172SrR01ms6W66v6qR/JJDe36VuSUKe77QuO42GgZq3JXLDN/pwd0zi2DNRtdoxdk63I6g9P@B4FoqnoLl1qit@Dq619izHnhMBPSAgOkSPzVRTgN5dDKIgCYgVxCVFCZpAcUkBKyBxSQRZRyAEEfOqsF/NV0PPS55PH//gest8Y/MfOCvBsls/BvQlXEYdCCS7nL3rD4rMfJtM/W7fYDq1bPNwbO1XV42TacAZf) reads scores and tiles on next line and prints output. How * `-apl` : `-p` to loop over lines and print, `-a` autosplit, `-l` to chomp from input and add newline character to output * `$_=$".<>` : to read next line (tiles) and prepend a space into default var `$_` * `for$i(@F){` ... `}` loop `$i` over `@F` fields of current line (scores) * `(` .. `?` .. `:` .. `).=$&` append previous match to ternary l-value * `($m=max grep$_<=$i,/\d+/g)&&s/ $m\b//?$s` in case max value found and removed from tiles (`$_`) l-value is scores (`$s`) * `$s=~s/ \d+$//?$_` otherwise if last number could be removed from scores it's tiles * `:$G` finally it's garbage because can't occur * `$_=$s;s/ //` to set scores to default var, and remove leading space ]
[Question] [ A little known fact is that if you turn on enough language extensions (ghc) Haskell becomes a dynamically typed interpreted language! For example the following program implements addition. ``` {-# Language MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances, UndecidableInstances #-} data Zero data Succ a class Add a b c | a b -> c instance Add Zero a a instance (Add a b c) => Add (Succ a) b (Succ c) ``` This doesn't really look like Haskell any more. For one instead of operating over objects, we operate over types. Each number is it's own type. Instead of functions we have type classes. The functional dependencies allows us to use them as functions between types. So how do we invoke our code? We use another class ``` class Test a | -> a where test :: a instance (Add (Succ (Succ (Succ (Succ Zero)))) (Succ (Succ (Succ Zero))) a) => Test a ``` This sets the type of `test` to the type 4 + 3. If we open this up in ghci we will find that `test` is indeed of type 7: ``` Ok, one module loaded. *Main> :t test test :: Succ (Succ (Succ (Succ (Succ (Succ (Succ Zero)))))) ``` --- ## Task I want you to implement a class that multiplies two Peano numerals (non-negative integers). The Peano numerals will be constructed using the same data types in the example above: ``` data Zero data Succ a ``` And your class will be evaluated in the same way as above as well. You may name your class whatever you wish. You may use any ghc language extensions you want at no cost to bytes. ## Test Cases These test cases assume your class is named `M`, you can name it something else if you would like. ``` class Test1 a| ->a where test1::a instance (M (Succ (Succ (Succ (Succ Zero)))) (Succ (Succ (Succ Zero))) a)=>Test1 a class Test2 a| ->a where test2::a instance (M Zero (Succ (Succ Zero)) a)=>Test2 a class Test3 a| ->a where test3::a instance (M (Succ (Succ (Succ (Succ Zero)))) (Succ Zero) a)=>Test3 a class Test4 a| ->a where test4::a instance (M (Succ (Succ (Succ (Succ (Succ (Succ Zero)))))) (Succ (Succ (Succ Zero))) a)=>Test4 a ``` --- ## Results ``` *Main> :t test1 test1 :: Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ Zero))))))))))) *Main> :t test2 test2 :: Zero *Main> :t test3 test3 :: Succ (Succ (Succ (Succ Zero))) *Main> :t test4 test4 :: Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ Zero))))))))))))))))) ``` *Draws inspiration from [Typing the technical interview](https://aphyr.com/posts/342-typing-the-technical-interview)* [Answer] # ~~130~~ 121 bytes -9 bytes thanks to Ørjan Johansen ``` type family a+b where s a+b=a+s b;z+b=b type family a*b where s a*b=a*b+b;z*b=z class(a#b)c|a b->c instance a*b~c=>(a#b)c ``` [Try it online!](https://tio.run/##nZNRa8IwFIXf@ysu9KFWl8GqT04L4lTG5hxMGYy93KbRBtpUmsimc/vrLmlLp9OBrA/h5N7D@XLbNEAZ7Sgq8IHjZSSh03EGk6FjfRAb7nsPo1lvNIDxKlb8ETNMpusl68coJZMXMFwJqngqML5hSyZCJijP6zF750HMboVUKKgpzXSX8hAPqyZtsmQZqjTT236qWxlyoe64CMv@EBMe61iwyacVokJ4YVlaqKcVpYA7pW0wN741YCOAt4hlDKTRXWxICK43WgXWga@@56trXz1oaJ9WG4uaAWtoBy7dIgTEpxYvD228X7TrF92CPAZtAgpdqNluoa0iA6ZMqivALRAfS5wypXYbfyJrY6jlkxyvZlRXP3@3AN2uX2L2qd4x1ftNNREnMqtI7zCyeRzZ/Ocg@bbiNA85rWNO61zOKeZZr69lzqBvvmUxGqVAGDhtVXysV1Eqr1LNSrUc2MIiohzIs0iJ5Mky5nNuLjrJRyK0utWy8CRcSi4WJGEqSkNZ/Hi7bw "Bash – Try It Online") This defines closed type families for addition `(+)` and multiplication `(*)`. Then a type class `(#)` is defined that uses the `(*)` type family along with an equality constraint to convert from the world of type familes to the world of typeclass prolog. [Answer] # 139 bytes ``` class(a+b)c|a b->c;instance(Zero+a)a;instance(a+b)c=>(s a+b)(s c) class(a*b)c|a b->c;instance(Zero*a)Zero;instance((a*b)c,(b+c)d)=>(s a*b)d ``` [Try it online!](https://tio.run/##nZNRT8IwEMff9yku4YENqInbnhBICAIxipgIMTG@3LrKmoxuWUvUiJ99thsOcZAQ97Be/738/nfbNUAZ5RQVDIDjRSSh12uO55Om9UkacDe8ny6H0zHMNrHiD5jhevGRslGMUjLZgclGUMUTgfE1S5kImaC80GP2zoOY3QipUFAjLfUp5SEeqoY2T1mGKsn0dpToowy5ULdchBIa5MsKUSE8sywpo8cNpYA5NSXY2A4cukUIyIBe8R3WNsltdHCvFHn9gS3BRHqhjrUjtE4RWuiYZS@WuR07aFMndEqaVsJc6SZgBhoCFPpgt5wytkoPWDCpLgG3QAYIbxHLGCgjdbto/dDBnoFd9FZ/mzIc/Zw@AtT17Gx@u7p1V/evq0EcYVZI9xDp1ZHePxsptpWPd@jj1338c32OeZ71@XxTg55@y2I0SoAwaHZV@bNexC5yq8irIr8JW1hFlAN5EgmRfJ3G/JWbYSdFS4RWky3LnDWXkosVWTMVJXrUi8uXfwM "Bash – Try It Online") Defines a type operator `*`. Equivalent to the Prolog program: ``` plus(0, A, A). plus(s(A), B, s(C)) :- plus(A, B, C). mult(0, _, 0). mult(s(A), B, D) :- mult(A, B, C), plus(B, C, D). ``` Potato44 and Hat Wizard saved 9 bytes each. Thanks! [Answer] # Family-Version, 115 bytes ``` type family(a%b)c where(a%b)(s c)=s((a%b)c);(s a%b)z=(a%b)b;(z%b)z=z class(a#b)c|a b->c instance(a%b)Zero~c=>(a#b)c ``` [Try it online!](https://tio.run/##nZNRa8IwFIXf@ysuyGgLy2DVJ7UFcSpjcw6mDMZebtNoA20qTWTTuf11lzRS5nQg86Gce@/hfLltjFGmO4oKIuB4lUrodt3BZOg6H6QB972H0aw3GsB4lSn@iCXm0/WS9TOUkslLGK4EVbwQmN2wJRMJE5RX/Yy98zhjt0IqFNS0ZnpKeYKHXZM2WbISVVHqsl/oUYlcqDsukv18iDnPdCw0yKeToEJ4YWVh1dOKUsCd0jaYG9/aw4vYp/CWspJV2pNA/VB6duB3dG3UJqwaccfbVNXGoWYrDxvatUWISUQdvj9pZTXULxpG1mKZY9BOoBCC1/CtdmwQTJlU14BbIBHa44AyrXYb61zwxuBVOxw/Dc7Xv79HgH4Y7TE/qcExNfhNNREnMuvI4DCyeRzZ/OciVVlzmoec1jGndS7nFPOs19cyZ9B33nEYTQsgDNy2sh/rVexVUKtmrVoubGGRUg7kWRRE8nyZ8Tk3V5xUKxFa32dpPTmXkosFyZlKi0Tav9zuGw "Bash – Try It Online") This is uses a closed type family like [potato44's](https://codegolf.stackexchange.com/a/166607/56656). Except unlike the other answer I use only 1 type family. ``` type family(a%b)c where -- If the accumulator is Succ c: -- the answer is Succ of the answer if the accumulator were c (a%b)(s c)=s((a%b)c) -- If the left hand argument is Succ a, and the right hand is b -- the result is the result if the left were a and the accumulator were b (s a%b)z=(a%b)b -- If the left hand argument is zero -- the result is zero (z%b)z=z ``` This defines an operator on three types. It essentially implements `(a*b)+c`. Whenever we want to add our right hand argument to the total we instead put it in the accumulator. This prevents us from needing to define `(+)` at all. Technically you can use this family to implement addition by doing ``` class Add a b c | a b -> c instance (Succ Zero % a) b ~ c => Add a b c ``` # Class-Version, 137 bytes ``` class(a#b)c d|a b c->d instance(a#b)c d=>(a#b)(f c)(f d) instance(a#b)b d=>(f a#b)Zero d instance(Zero#a)Zero Zero type(a*b)c=(a#b)Zero c ``` [Try it online!](https://tio.run/##nZNRS8MwEMff@ykO@rBWjOC2p7EWxtyG6JzghiC@XNNsDbTpaDKcOD97TdJZVqsw7EP43@X6/921SYQyKSkqCIHjVSJhOOxMFtOO80FcuB89zFaj2QTmu1TxRywwW75v2ThFKZm8hOlOUMVzgekN2zIRM0G5zadsz6OU3QqpUNDT1DgXiu2Vzqx0PeUxNuuM/2LLClR5oUNdLlWBXKg7LuLj/hQznmoQuOTTiVEhvLAir9TTjlLAkpoWPXQjn0J8QIiAkjB2@BH0vROEVnlroGaJ/WZFZCvWYLRBwImDiV2s0havdGceXmjfwKtfoKVJwxxsCxCAd@FX2nFsj7BkUl0DHoCECG8JKxgokxoMsIaBNwfPTtZeDcbXz99bgH4QHjGn1G6b2v1JtUO0PWvLbtOy17bs/XMQG9acXpPTb3P653J@Y571@fqmB303HIfRJAfCoDNQ1c96FUfVrVWvVv0OHGCTUA7kWeRE8myb8jU3B5/YkQitT7msajIuJRcbkjGV5LGsrmb5BQ "Bash – Try It Online") This class version loses some ground to the family version, however it is still shorter than the shortest class version here. It uses the same approach as my family version. ]
[Question] [ Yes is a stack-based ~~language~~ that has a few space-separated instructions: ``` yes: Push 1 to the stack no: Push 0 to the stack what: Push the input to the stack (input is taken at the start of program execution and is the same for the whole execution) sure: Increment the last item in the stack nah: Decrement the last item in the stack really: If the last stack item is a number, replace it with its Unicode character. If it is a letter, replace it with its Unicode char code. oh: convert the stack to strings and concatenate it, and push that to the stack. nope: remove the first stack item yep: remove the last stack item ``` The stack's last element is always outputted at program end. All non-alphanumeric and non-space characters are ignored. All code is lowercase. Example programs: ``` yes sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure really yes sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure really yes sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure really yes sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure really yes sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure really yes sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure really yes sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure really yes sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure really yes sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure really yes sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure really yes sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure really yes sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure really yes sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure really oh ``` prints `Hello, World!`. ``` what ``` prints the input (`cat` program.) ``` no nah ``` prints `-1`. ``` no really ``` prints the `NUL` character (`U+0000`) ``` what yes sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure really oh ``` prints the input and an underscore. ``` yes no nope ``` prints `0` ``` yes no yep ``` prints `1`. You must write an interpreter in as few bytes as possible. Here's a JS implementation (not well golfed!): ``` function yes(code, input){ var stack = []; var functions = { "yes": "stack.push(1)", "no": "stack.push(0)", "what": "stack.push(input)", "sure": "stack[stack.length - 1] ++", "nah": "stack[stack.length - 1] --", "really": "stack[stack.length - 1] = (typeof lastItem === 'number' ? String.fromCharCode(lastItem) : lastItem.charCodeAt())", "oh": "stack.push(stack.reduce((x, y)=>''+x+y))", "nope": "stack.shift()", "yep": "stack.pop()" }; code.replace(/[^a-z ]/g, "").split(" ").map(x=>(lastItem = stack[stack.length - 1],eval(functions[x]))); return stack[stack.length - 1]; } ``` ``` textarea{ display: block; } ``` ``` Code: <textarea id = "code"></textarea> Input: <textarea id = "input"></textarea> <button onclick = "output.value = yes(code.value, input.value)">Run</button> <textarea id = "output"></textarea> ``` See also [my JS answer](https://codegolf.stackexchange.com/a/119254/58826) below. You may assume that all integers involved will be less than or equal to 126, that `really` will never be run with a multi-char string on top of the stack, and that the stack will never be longer than 100 elements. # Edge cases * `yes yes oh` prints `11`. * Intput may be a string or number. * The code can contain any chars. Ones not matching `[a-z ]` should be ignored. [Answer] ## JavaScript (ES6), ~~218~~ ~~215~~ ~~204~~ 203 bytes Takes the program string `s` and the input `i` in currying syntax `(s)(i)`. ``` s=>i=>s.replace(/\w+/g,S=>(c=eval("[P()];P()+1;[s.shift()];1;0;s=[s.join``];P()-1;i;P()[0]?k.charCodeAt():String.fromCharCode(k)".split`;`[parseInt(S,35)%156%9])).map||s.push(c),s=[],P=_=>k=s.pop())&&P() ``` ### How? We use the perfect hash function `parseInt(S, 35) % 156 % 9` to convert the instruction ***S*** into an index in ***0…8*** and use this index to select the JS code to be executed: ``` instruction | base 35 -> dec. | % 156 | % 9 | JS code ------------+-----------------+-------+-----+--------------------------------------------- "yes" | 42168 | 48 | 3 | 1 "no" | 829 | 49 | 4 | 0 "what" | 1393204 | 124 | 7 | i "sure" | 1238209 | 37 | 1 | P()+1 "nah" | 28542 | 150 | 6 | P()-1 "really" | 1439554619 | 35 | 8 | P()[0]?k.charCodeAt():String.fromCharCode(k) "oh" | 857 | 77 | 5 | s=[s.join``] "nope" | 1016414 | 74 | 2 | [s.shift()] "yep" | 42165 | 45 | 0 | [P()] ``` The ***P*** function pops the last item off the stack ***s*** and loads it into ***k***. We prevent the result of some instructions from being pushed back onto the stack by testing if the *.map()* method is defined, that is, if the result is an array. The code for ***oh*** is returning an array by design and we force ***nope*** and ***yep*** to return arrays as well. Hence the syntax: ``` (c = eval("[code0];code1;...".split`;`[index])).map || s.push(c) ``` ### Test cases ``` let f = s=>i=>s.replace(/\w+/g,S=>(c=eval("[P()];P()+1;[s.shift()];1;0;s=[s.join``];P()-1;i;P()[0]?k.charCodeAt():String.fromCharCode(k)".split`;`[parseInt(S,35)%156%9])).map||s.push(c),s=[],P=_=>k=s.pop())&&P() console.log(f(`yes sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure really yes sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure really yes sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure really yes sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure really yes sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure really yes sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure really yes sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure really yes sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure really yes sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure really yes sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure really yes sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure really yes sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure really yes sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure really oh`)()) console.log(f(`what`)(1234)) console.log(JSON.stringify(f(`no really`)())) console.log(f(`what yes sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure really oh`)('code golf')) console.log(f(`yes no nope`)()) console.log(f(`yes no yep`)()) ``` [Answer] # [Röda](https://github.com/fergusq/roda), 256 bytes ``` f c,n{s=[];(c/`\W|_`)()|{|m|s+=#m-2 if[m=~"yes|no"];s[-1]+=#m*2-7 if[m=~"sure|nah"];s+=n if[m="what"];s=s[#m%3:#s-#m%2]if[m=~"nope|yep"];{s+=""s()|s[-1].=_}if[m="oh"];{t=s[-1]y=t..""a=t+0;a=a..""{s[-1]=ord(s)}if[#a>#y]else{s[-1]=chr(t)}}if[#m=6]}_;[s[-1]]} ``` [Try it online!](https://tio.run/nexus/roda#NZDRTsQgEEXf@xUEYtJaW7VGTWzG3/ABSUu6bLqJwKZTYxrAX6/Ark@TuWfuHZj9SKY74xC46Mvpfvz88MNYlZV3XnusgemmI6cj1/BLN4XeWCp65M2jSOy2a17/KX4vyhs5J16Ducj0Z5ZrUgA50zdPbwybWDtxNRl7Vn5T5zjiootSjKtzfAtDuETYFOlWyPIGa9tSKmGtH3oJMjUuE7DLocQqmZh8Z5tQX6iuaJqXcq1CZhpeRBh6nokIu5Yn4wpi4LkgE4zxk8RYEt80FiQfpwj7Hw "Röda – TIO Nexus") ### Explanation `#variable` returns the length of `variable` (if it is a string or an array). ``` f c,n{ /*declare a function f with arguments c and n*/ s=[]; /*initialise the stack*/ (c/`\W|_`) /*split the code on anything not [a-zA-Z0-9]*/ ()| /*and push each of its values to the stream*/ {|m|...}_ /*for each element m in the stream, do:*/ s+=#m-2 if[m=~"yes|no"]; /* add 1 or 0 to the stack if m is "yes" or "no"*/ s[-1]+=#m*2-7if[m=~"sure|nah"];/* increment or decrement the top element if m is "sure" or "nah"*/ s+=n if[m="what"]; /* push input if m is "what"*/ s=s[#m%3:#s-#m%2] /* remove the first or last element of the stack if[m=~"nope|yep"]; /* if m is "nope" or "yep" */ { }if[m="oh"]; /* if m is "oh" do:*/ s+="" /* add an element to the stack*/ s()|s[-1].=_ /* for each element in s, concatenate that amount to the last element of the stack*/ { }if[#m=6] /* if m is "really" (it's length is 6) do:*/ t=s[-1]y=t.."" /* get the last element of the stack*/ a=t+0;a=a.."" /* add 0 to it, if a is a number, this does nothing, otherwise this makes a longer by 1 character*/ {s[-1]=ord(s)}if[#a>#y] /* if a is longer than t (the last element is a char/string) replace it with its code point*/ else{s[-1]=chr(t)} /* otherwise, replace the last element with the char it represents*/ [s[-1]] /*finally output the top of the stack*/ ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~77~~ ~~67~~ ~~63~~ 61 bytes ``` Að«Ã#vyÇO§}ðý•9ǝ×н}ÀÀÙ™Íð•650в"X ¾ I > < DdiçëÇ} J r\r \"#:.V ``` Assumes the program is on the top of the stack. [Try it online!](https://tio.run/nexus/05ab1e#UyrPSCxR4KpMLVYoLi1KHSWGG1GUmpiTU6nAlZ@h9N/x8IZDqw83K5dVHm73P7S89vCGw3sfNSyyPD738PQLe2sPNwDhzEctiw73Ht4AFDczNbiwSSlC4dA@BU8FOwUbBZeUzMPLD68@3F6r4KVQFFOkEKOkbKUX9v9/Uk4iBAEA) [Answer] # [Pyth](https://github.com/isaacg1/pyth), 69 bytes ``` Vczd=Y.v@c"+YsY X_1Y1 +Yw +Y0 X_1Y_1 PY +Y1 tY +PYCeY"d%CN23;eY ``` [Try it online!](http://pyth.herokuapp.com/?code=Vczd%3DY.v%40c%22%2BYsY+X_1Y1+%2BYw+0+%2BY0+X_1Y_1+0+0+0+PY+0+0+%2BY1+tY+%2BPYCeY%22%29%25CN23%3BeY&input=yes+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+really+yes+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+really+yes+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+really+yes+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+really+yes+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+really+yes+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+sure+really+oh&debug=0) [Answer] # JS (ES6), ~~361~~ 340 bytes ``` c=>i=>(s=[],r="s[s.length-1]",c.replace(/[^a-z ]/g,"").split` `.map(x=>(eval({"yes":"s.push(1)","no":"s.push(0)","what":"s.push(i)","sure":"~++","nah":"~--","really":"~=((typeof ~)[0]<'o'?String.fromCharCode(~):lastItem.charCodeAt())","oh":"s.push(s.reduce((x,y)=>''+x+y))","nope":"s.shift()","yep":"s.pop()"}[x].replace(/~/g,r)))),eval(r)) ``` Takes code and input through currying. ``` var yes = c=>i=>(s=[],r="s[s.length-1]",c.replace(/[^a-z ]/g,"").split` `.map(x=>(eval({"yes":"s.push(1)","no":"s.push(0)","what":"s.push(i)","sure":"~++","nah":"~--","really":"~=((typeof ~)[0]<'o'?String.fromCharCode(~):lastItem.charCodeAt())","oh":"s.push(s.reduce((x,y)=>''+x+y))","nope":"s.shift()","yep":"s.pop()"}[x].replace(/~/g,r)))),eval(r)) ``` ``` textarea{ display: block; } ``` ``` Code: <textarea id = "code"></textarea> Input: <textarea id = "input"></textarea> <button onclick = "output.value = yes(code.value)(input.value)">Run</button> <textarea id = "output"></textarea> ``` [Answer] ## JavaScript (ES6), ~~220~~ 216 bytes ``` c=>i=>c.replace(/\w+/g,x=>a=a.concat(eval("Q,[] (b=Q)[0]?b.charCodeAt():String.fromCharCode(b) 1 [a.join``,a=[]][0] Q+1 a.shift(),[] i Q-1".split`Q`.join`a.pop()`.split` `[parseInt(x,36)%19]||0)),a=[])&&a.pop() ``` A function that takes input with currying syntax, like `f(code)(input)`. [Answer] # [Python 2](https://docs.python.org/2/), 258 bytes ``` s=[] m=-1 i,p=input() for c in p.split(' '): k=c<"o" if c in"yesnowhat":s+=[i if"w"==c[0]else-k+1] if c in"surenah":s[m]+=[1,m][k] if"p"in c:s.pop(k-1) if"oh"==c:s+=[''.join(map(str,s))] if"y"==c[m]:s[m]="'"in`s[m]`and ord(s[m])or chr(s[m]) print(s[m]) ``` [Try it online!](https://tio.run/nexus/python2#RY/BCsMgEETvfoXsRaVJaK6hfokIDaklNlUXtZR8farm0Nvszuwb9khSaeJkPxLbobQeP5kL8gyRLtR6ikPCt82cUSYmQje53CAAofbZfNhN8uG7zhmmdJHKFgO@IOWirtq8k@m3y6j/8fSJxs9rCSunS37snFZbCwBC6VumNGBAvvWjaNuwVlqDMza8gvXczchTjl0S4rzcW6HTjSqBFdC9yvvsHzTEB6@DqC@t8dQEo/X51Mdx7eof1Ae6G4Qf "Python 2 – TIO Nexus") --- -3 bytes thanks to @Wondercricket [Answer] # [Perl 6](https://perl6.org), ~~233~~ 225 bytes ``` {my @s;{yes=>{@s.push(1)},no=>{@s.push(0)},what=>{@s.push: once slurp},sure=>{[[email protected]](/cdn-cgi/l/email-protection)},nah=>{[[email protected]](/cdn-cgi/l/email-protection)},really=>{($/:[[email protected]](/cdn-cgi/l/email-protection))~~Int??$/.=chr!!$/.=ord},oh=>{@s.=join},nope=>{@s.shift},yep=>{@s.pop},}{.words}.map:{.()};@s.tail.print} ``` Try it [Hello World](https://tio.run/nexus/perl6#7ZNLasMwEIb3PoUCodjEkdtNFzZqskmgq1DoBYSjVCqOJCS5wRjl6u64dh8X6Cqz@RD/MMzrV@sF@XikdZWcO3JXm6MgbOjhvfVV3wnPnvqtp7b1Mn3IYq7NH@EehIvk4VcqidG1IL5pnY25b52A2GoF0cBVA@lcgrBe/whO8KbpQEuXRclmObten3XYbJYFZbV0i8X4MO4YcyOnWuzdKD12Y8UkeKlOIeadsHMzBurHnl4gzUd65rbsaZrFai5BrVM6xOFr4JcymGJ32BdVAhOTsW3Ev2I6O8F14/1xHwi0CAItgkDH3MyI@HfRYAh0DAKBBkKgRRA3cPrvXo1Mdof98Cp8UPrtEw "Perl 6 – TIO Nexus") [cat](https://tio.run/nexus/perl6#TY/BasMwEETv/goFQrCJI6eXHmzU5JJAT6WQHxDOtlJxJKGVE4xQft1dN6btbXjDMDM9Ars@87bJLgNbtfYMTIyR9B6bOACKl7hH7npU@VORSmP/gS2Bm5LhD9XMmhYYdr13qcTeA3nrNblB6o7iUhHYbH6BB9l1A7F8WdVixsX9/mrCbresuGiVXywmYf05lVY9usSX1WZa4@ABUOmPkMoB3DzGUn@K/EYxTPwiXR15XqRmruDOaxPS@HP4vQ62Orwdqyab7mQkxxNg0ObzGw "Perl 6 – TIO Nexus") [-1](https://tio.run/nexus/perl6#TY/BTsMwEETv@QpXqlCipg5cOCQy7QUkTgiJH7DSBRulXsvrUEWW@@thSyPgNvtGo5kdCcTXvey74jiJmx4PINScWO@pSxOQekh7kn4kU95VuXb4D9wyOBkd/1Ar0PUgaBiDzzWNAdjbbNiN2g4c14bBdvsLAuhhmJiV66ZVC67O52cXd7t1I1Vvwmp1ERgOuUZz7VKfaN1ljYcrIGPfY64n8MsY5P6c5IljlOVR@zbJssrdUiF9sC7m@efh1zZi8/jy1HSFQ8EbCz7mN6Bo3cc3 "Perl 6 – TIO Nexus") [nul](https://tio.run/nexus/perl6#TY/BasMwEETv/goFQrCJI6eXHmzU5JJAT6WQHxDOtlJxJKGVE4xQft3d1KbtbfYNw8z2COz6zNsmuwxs1dozMDFG0nts4gAoXuIeuetR5U9FKo39B7YEbkqGP1Qza1pg2PXepRJ7D@St1@QGqTuKS0Vgs/kFHmTXDcTyZVWLGRf3@6sJu92y4qJVfrF4COvPqbRq6hJfVpvHGgcTQKU/QioHcPMYS/0p8hvFMPGLdHXkeZGauYI7r01I48/D73Ww1eHtWDWZsWyalNE9ngCDNp/f "Perl 6 – TIO Nexus") [cat\_](https://tio.run/nexus/perl6#7ZJBasMwEEX3OoUCIdjEkdNNFzZqskmgq1LIBYSjViqOJDRyghHK1d1xbdqeoXQzDG8Y/v/MdCDp9ZE1Nbn0dNXYs6R8iNjvoY69BP4U98BcByp7yFNh7C@wRXBTIvygilrTSApt510qoPMSZ@s1ToPQLa4LhWCz@QZeirbtkWXLsuIzzu/3ZxN2u2XJeKP8YjE21p9TYdWkxT@sNqMbJycASr@FVPTSzWYs6qfIbrgGiV2EqyLL8lTPEsx5bUIavgK/VsGWh5djWZMxDiWYm47m/8tfK9O/UWIVwYMPJwlBm/dP "Perl 6 – TIO Nexus") [0](https://tio.run/nexus/perl6#Tc/BasMwDAbge57ChVISmjrdZYcEr720sNMY9AVM6s0eqWUspyUY99UzZQ3bbuIT0i/1qNj1mbdNdhnYqoWzYmKMVO@xiYNC8RL3yF2POn8qUmnhH2wJblqGP6oZ2FYx7HrvUom9V9Rbr6kbpOloXGqCzeYXvJJdN5Dly6oWMxf3@6sNu92y4qLVfrGYCvDnVIJ@ZIkvMHa6xqkHoDYfIZWDcvMxQPkp8huNYeIX6erI8yI1cwR33tiQxp@H3@sA1eHtWDUZfcwssGlxRjKeFAZjP78B "Perl 6 – TIO Nexus") [1](https://tio.run/nexus/perl6#Tc/BTsMwDAbge58ikybUal0KFw6twnYBiRNC4gWizpCgLo7ilKmKslcvHquAm/VZ9m@PBOLrXvZdcZzETY8HEGpOXO@pSxOQekh7kn4kU95VuXb4D24ZTkbHP2oFuh4EDWPwuaYxAPc2G@5GbQce14Zhu/2FAHoYJrZy3bRq4ep8fnZxt1s3UvUmrFaXAsMh12iuWeoTrbtc4@EKZOx7zPUEfjkGOT8neeIxyvKofZtkWeVuiZA@WBfz/PPwaxuxeXx5arqCPxYOBe8pGOY3oGjdxzc "Perl 6 – TIO Nexus") ``` {my @s;{es=>{@s.push(1)},no=>{@s.push(0)},at=>{@s.push: once slurp},re=>{[[email protected]](/cdn-cgi/l/email-protection)},ah=>{[[email protected]](/cdn-cgi/l/email-protection)},ly=>->{($_:[[email protected]](/cdn-cgi/l/email-protection))~~Int??.=chr!!.=ord},oh=>{@s.=join},pe=>{@s.shift},ep=>{@s.pop},}{.comb(/..»/)}.map:{.()};@s.tail.print} ``` Works the same except it only grabs the last two characters from each command, and uses `$_` instead of `$/` for `really`. [Try it (Hello World)](https://tio.run/nexus/perl6#7ZO9asMwFIV3P4UCIdjEltulg42cLAl0CoXuxXVuKxdbEpJcMEJ5sW59MVc0bpsX6JS7fOgeCe7f0WCAvN/Rpoz6kawaeQTCJhfOW1M6MKxyW0PVYHh8m/hUyAvhJgi1/RMKIkUDxHSDVj7VEG7W63Bn67YLL3mIs@w37kZWZZWLl08Fm8XkdLoXdrOhrOF6saBM6qNPJT@nYG@yFT5VcA4Nb1@sT0HNBciQ0zvayP45zin9/MgTT/taFY7GiS/nFFTpVlg/fTf6UFiZ7w77vIxGMMQMGhD/Cg11140Ex437x3kg0CIItAgCHXM1LeLfRYMh0DEIBBoIgRZBXMHqf2qVPNod9tMjGNuK1y8 "Perl 6 – TIO Nexus") ## Expanded: ``` { my @s; # stack { # Associative array yes => {@s.push(1)}, no => {@s.push(0)}, what => {@s.push: once slurp}, # read everything from $*IN sure => {[[email protected]](/cdn-cgi/l/email-protection)}, nah => {[[email protected]](/cdn-cgi/l/email-protection)}, really => { ( $/ := @s.tail ) # bind $/ to the last value in the stack ~~ Int # if that is an Int ?? $/.=chr # replace it with that character !! $/.=ord # otherwise replace it with its ordinal }, oh => {@s.=join}, nope => {@s.shift}, yep => {@s.pop}, }\ { .words } # index by the words in the program .map: {.()}; # call each of the lambdas in order @s.tail.print # print the last value on the stack } ``` [Answer] # PHP, ~~315~~ 305 bytes second draft, not tested yet ``` foreach($argv as$k=>$v)if($k>1)eval((strstr($c=preg_replace('#[^a-z ]#','',$v),p)?'':'$s[]=').[yes=>1,no=>0,what=>'$argv[1]',sure=>'array_pop($s)+1',nah:'array_pop($s)-1',really=>'is_int($x=array_pop($s))?chr($x):ord($x)',oh=>'join($s)',nope=>'array_shift($s)',yep=>'array_pop($s)'][$c].';');echo end($s); ``` Run with `php -nr '<php-code>' <input> <yes-code>`. **breakdown** ``` foreach($argv as$k=>$v)if($k>1) # loop through commands eval( # 3. interprete (strstr( # 2. if no 'p' in command, prepend '$s[]=' # 1. ignore all non-code characters $c=preg_replace('#[^a-z ]#','',$v),p)?'':'$s[]='). [yes=>1, # yes: append 1 no=>0, # no: append 0 what=>'$argv[1]', # what: append input sure=>'array_pop($s)+1', # sure: remove end, increment, append nah:'array_pop($s)-1', # nah: remove end, decrement, append # really: convert between ascii and ordinal really=>'is_int($x=array_pop($s))?chr($x):ord($x)', oh=>'join($s)', # oh: concatenate elements, append nope=>'array_shift($s)', # nope: remove first element yep=>'array_pop($s)'] # yep: remove last element [$c] .';'); echo end($s); # print last element (if exists) ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 286 bytes ``` $s=@() $k-split"\s"|%{ switch($_){ "yes"{$s+=1} "no"{$s+=0} "what"{$s+=(read-host)} "sure"{$s[-1]+=1} "nah"{$s[-1]-=1} "really"{if($s[-1]-is[int]){[char]($s[-1])}else{[int][char]($s[-1])}} "oh"{$s+=($s-join'')} "nope"{$s=($s[1..($s.Length-1)])} "yep"{$s=($s[0..($s.Length-2)])}}} $s[-1] ``` [Try it online!](https://tio.run/##XY/RDoIgFIbvfYrGaMoaLrt36wF6A3PN1SlIBsxDc458dgO1i7ri8J2P8x@s6aFDAUpNtC3JALjRZjOAJRPF8pixhLYcrZKOnJG8tz7BXrqryOiF@ST6xFPclcWYEG2Weh/qXjRuuWUdNDcuDDoWOL46iLziRb2@asQX8BkEX6mBeHnPViyxktrVzFdX0XT1itkICsHPrb9GmGLEGk@RP43UacrmFe0cH3FV5Hk48hPohxO8YHU04te/wv5HOEQhjF5CpukD "PowerShell – Try It Online") The input is defined as `$k` in header of TIO. An empty array `$s` initialized. Splits the input on whitespace using a regex. Then for each switch it does ``` yes: Push 1 to the stack (read stack as array and push as append, += operator used, which adds an item at the end of arrays (here)) no: Push 0 to the stack what: Push the input to the stack sure: Increment the last item in the stack (indexing and += used) nah: Decrement the last item in the stack really: If the last stack item is a number, replace it with its Unicode character. If it is a letter, replace it with its Unicode char code. (used [char] and [int][char] type casting) oh: convert the stack to strings and concatenate it, and push that to the stack. (Just join the array with '') nope: remove the first stack item (Using indexing) yep: remove the last stack item (Using indexing) ``` At last output last item in array. ]
[Question] [ [April 5th](http://www.nationaldaycalendar.com/national-deep-dish-pizza-day-april-5/) is National Deep DIsh Pizza Day, the theme of this challenge. Given a positive integer `n` (`n` is greater than 0), create an ASCII deep dish pizza. Actual deep dish pizza shown: [![A Pizza!](https://i.stack.imgur.com/Ntrau.jpg)](https://i.stack.imgur.com/Ntrau.jpg) As you can see, there is a layer of crust on the bottom and surrounding the rest of the pizza. **How to make the pizza** The crust is made of two layers. The first layer will be `n` tall and `n*3` long. Length is the number of characters (including spaces) in the highest line. So given `n` is 1, the first layer would look like this: ``` \_/ 1 character tall 3 characters long ``` If `n` is two: ``` \ / 2 characters tall \__/ 6 characters long ``` Now for the second layer of the crust. It will go *outside* the first, inner crust so therefore, it will be `n+2` characters tall and `(n*3)+6)` characters long. Given `n` is one: ``` \ / 3 characters tall \ / \___/ 9 characters long (3 underscores, 3 slashes on either side) ``` If `n` is two: ``` \ / 4 characters high \ / \ / \____/ 12 characters long ``` You would then match up the two highest pairs of `\/` with each other for the inner and outer crust. In `n` is 1: ``` \ \ / / \ \_/ / \___/ ``` If done correctly, it would look like a V without the tops with a one character difference between each layer. Speaking of tops, the crust will be joined together by a pair of `/\`, separated by a line of underscores `(n*3)+2` long to complete the crust and pizza. **Examples** If `n` is 1: ``` /\_____/\ \ \ / / \ \_/ / \___/ ``` `n` is 2: ``` /\________/\ \ \ / / \ \ / / \ \__/ / \____/ ``` `n` is 3: ``` /\___________/\ \ \ / / \ \ / / \ \ / / \ \___/ / \_____/ ``` **Winning Criterion** This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins! [Answer] ## JavaScript (ES6), 136 bytes ``` f= n=>"/\\"+(r=s=>s[0][0].repeat(n-1)+s)`_`+r`_`+r`___/\\ `+r` `.replace(/ /g,"$`\\ \\$` $'$'$'/ /\n")+r` \\ \\`+r`_/ / `+r` \\`+r`___/` ``` ``` <input type=number min=1 oninput=o.textContent=f(this.value)><pre id=o> ``` The whole pizza is very repetitious so the `r` function (designed as a tagged template literal) repeats the first character of its input `n` times. This handles the top and bottom two lines of the pizza. The middle is repeated by replacing a string of blanks; the `$`` and `$'` subsitutions automatically correspond to increasing and decreasing numbers of blanks thus positioning the `\ \` and `/ /` appropriately. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 35 bytes ``` Nθ←_←×_θ↖θ↖²M→/P×_⁺²×²θ↘θ↘¹\×_θ‖BOθ ``` [Try it online!](https://tio.run/##ZZDBCoJAEIbvPYV4WsGI9mi36BJkidRNCJMxF0Zd11mjp9/UqDW7fv/wfzOTFanK6hSN2VdS01GXN1Cs8TaLSImKWHCAnHzHvbpzdBYltKwPfKfxbHiR77j5R7xHYd0BC2JxL@g74K6G8lAjCTmCSXWEumX8Y@Oja2Lb1Y9qLPsRTujaWpLE3jBfPoYcIaOtJgKV4/PUgcJUDo8whptlhy8 "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` Nθ ``` Input the size of the pizza. ``` ←_←×_θ ``` Print part of the outer crust base. ``` ↖θ↖² ``` Print the outer crust left side. ``` M→/P×_⁺²×²θ ``` Print part of the top crust. ``` ↘θ↘¹\ ``` Print the inner crust left side. ``` ×_θ ``` Print part of the inner crust base. ``` ‖BOθ ``` Reflect to complete the pizza. Note that modern additions to Charcoal shrink the size down to 31 bytes: ``` Nθ←×_⊕θ↖θ↖²M→/P×_⊗⊕θ↘⊕θ\×_θ‖BOθ ``` [Try it online!](https://tio.run/##ZY/BCoJAEIbvPYXsaQUj8Gi38CJkhdRNCN3GXFh3123W6Ok3NVDJ4/zz8f0zrC4MU4VwLpHa4sk2JRja@vvNxXCJNDpChYF35Q28KLmTwEskM9CARHj0nD@TN/1j23UU9lGqOqBRxp81TgDZkWFjBXI9BoueWNlS9B3/fbM9Vm85@lZHTf48J9OwcI9IBpUAhgeLCKYSn3MHRhR6eN650G078QU "Charcoal – Try It Online") Link is to verbose version of code. [Answer] ## Python 2, ~~153~~ 151 bytes [Try it online](https://tio.run/nexus/python2#RYyxCsMwDER3f4XJcolFcNt0C/oTg0hKBi0ilBT6945dU6JFune6y8Zq@@foB7cwPIK5lSF172@1AzElEdAaJqo3nPLNbd/t1TW/RJSQfCoDqrKfgo2PoEMJ@IhZie9z9y/0S/sulc2/cKHywxKR8/ME) ``` n=input() a=' '*n b='_'*n print'/\\__'+b*3+'/\\' i=0 exec"print' '*i+'\ \\\\'+' '*(3*n-2*i)+'/ /';i+=1;"*n print a+'\ \\'+b+'/ /' print a+' \\_'+b+'_/' ``` -2 bytes by substituting repeated values with variables thanks to @KoishoreRoy [Answer] ## MATLAB, 333 bytes (Lazy-ish attempt) ``` function t(n);p=@(q)fprintf(q);s=@(x)p(' ');r=@()p('/ /');l=@()p('\\ \\');f=@()p('/');b=@()p('\\');u=@(x)p('_');h=@()p('/\\');e=@()p('\n');h();arrayfun(u,1:3*n+2);h();e();for i=1:n;arrayfun(s,1:i-1);l();arrayfun(s,1:3*n-2*(i-1));r();e();end;arrayfun(s,1:n);l();arrayfun(u,1:n);r();e();arrayfun(s,1:n+1);b();arrayfun(u,1:n+2);f();e(); ``` ### Formatted: ``` function d(n) p=@(q)fprintf(q); s=@(x)p(' '); r=@()p('/ /'); l=@()p('\\ \\'); f=@()p('/'); b=@()p('\\'); u=@(x)p('_'); h=@()p('/\\'); e=@()p('\n'); h();arrayfun(u,1:3*n+2);h();e(); for i=1:n arrayfun(s,1:i-1); l(); arrayfun(s,1:3*n-2*(i-1)); r();e(); end arrayfun(s,1:n); l(); arrayfun(u,1:n); r();e(); arrayfun(s,1:n+1); b(); arrayfun(u,1:n+2); f();e(); ``` Basic idea is I have function handles to print everything, and then I just pretty much brute-force it. The one for loop is for the `n` layers between the very top and the bottom of the inside layer. The repetition of (spaces) and `_` is done using `arrayfun`, with array inputs. Will try to think of more interesting ways to do this if I get more time later. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~54~~ 52 bytes ``` A⁺N²β↖M↓↙¹M→↘βM↑×_β↗βM←↖¹M↓↙βM↑←×_⁺β±²↖βM↘M→×_⁺×β³±⁴ ``` Explanation: ``` A⁺N²β Assign input + 2 to the variable β ↖ Move up and left one, printing a \ M↓ Move pointer down one ↙¹ Move down and left one, printing a / M→ Move pointer right one ↘β Move down and right β times M↑ Move pointer up ×_β Write underscores β times ↗β Move up and right β times M← Move pointer right one ↖¹ Move up and left one M↓ Move pointer down one ↙β Move down and right β times M↑ Move up one ← Set direction to left ×_⁺β±² Write underscores β - 2 times ↖β Move up and left β times M↘ Move down and right one M→ Move right one ×_⁺×β³±⁴ Write underscores (β * 3) - 4 times ``` My previous answer was in Retina, a language I haven't posted an answer to before. Now, you have an answer in Charcoal, which I haven't posted an answer to before. [Try it online!](https://tio.run/nexus/charcoal#@/9@z8JHjbve71l3aNO5TY/apr3fs/ZR2@RHbTMP7QQzJz1qm3FuE5g58fD0eJCa6VD@BKByqCqQBpgqoARQIdDQc5sObTwEMhMqMwNiIETyMNCUQ5sPbXzUuOX/fyMA "Charcoal – TIO Nexus") [Answer] # PHP, ~~209 200 137~~ 135 bytes finally beating JS :) ``` echo($f=str_pad)("/\\",1+3*$x=$n=1+$argn,_),"/\\ ";for(;$n;)echo$f("\\ \\",2*$n+$x," _"[!--$n]),"/ / ",$p.=" ";echo$f("\\",2+$x,_),"/"; ``` Takes input from STDIN; run with `-nR` or [order a family pizza](http://sandbox.onlinephpfunctions.com/code/46dda86004c64ff7e68cd974fd2a03c4e43925cd). **breakdown** ``` // print top echo($f=str_pad)("/\\",1+3*$x=$n=1+$argn,_),"/\\\n"; // loop N+1 times for(;$n;) // print current line and left padding for next line echo$f("\\ \\",2*$n+$x," _"[!--$n]),"/ /\n",$p.=" "; // print bottom echo$f("\\",2+$x,_),"/"; ``` [Answer] # JavaScript (ES6), 205 bytes --- This is my first [ascii-art](/questions/tagged/ascii-art "show questions tagged 'ascii-art'") post! Add a `f=` at the beginning and invoke like `f(arg)`. ``` n=>{a=[];w=" ";u="_";t=`/\\${u.repeat(n*3+2)}/\\ `;for(i=0;i<n+1;i++){c=i==n?u:w;a.push(`${w.repeat(i)}\\ \\${c.repeat((n+1-i*2)+n+(n-1))}/ / `)};return [t,...a,`${w.repeat(i)}\\${u.repeat(n+2)}/`].join``} ``` **Note:** *All line breaks are necessary!* --- ``` f=n=>{a=[];w=" ";u="_";t=`/\\${u.repeat(n*3+2)}/\\ `;for(i=0;i<n+1;i++){c=i==n?u:w;a.push(`${w.repeat(i)}\\ \\${c.repeat((n+1-i*2)+n+(n-1))}/ / `)};return [t,...a,`${w.repeat(i)}\\${u.repeat(n+2)}/`].join``} document.querySelector("#elem").innerHTML = f(+prompt("Enter a Number")); ``` ``` <pre id="elem"> ``` --- [Answer] ## Batch, 200 bytes ``` @set l=@for /l %%i in (1,1,%1)do @call @set t= @set s= %l%set s=___%%s%% @echo /\_%s%_/\ %l%echo %%t%%\ \%%s:_= %%/ /&call set t= %%t%%&call set s=%%s:~2%% @echo %t%\ \%s%/ / @echo %t% \_%s%_/ ``` `t` contains the left indent while `s` contains the inside; its `_`s are subsituted with spaces on the middle rows. `l` just exists to avoid some repetition. [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal), 59 bytes ``` k/₴3*⇧\_*k/+,›(n`\ \\`꘍₴nεd+n⁰=` _`$i*₴`/ /`,)›\\꘍₴⇧\_*\/+, ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=k%2F%E2%82%B43*%E2%87%A7%5C_*k%2F%2B%2C%E2%80%BA%28n%60%5C%20%5C%5C%60%EA%98%8D%E2%82%B4n%CE%B5d%2Bn%E2%81%B0%3D%60%20_%60%24i*%E2%82%B4%60%2F%20%2F%60%2C%29%E2%80%BA%5C%5C%EA%98%8D%E2%82%B4%E2%87%A7%5C_*%5C%2F%2B%2C&inputs=5&header=&footer=) [Answer] # [V](https://github.com/DJMcMayhem/V), 57 bytes ``` i\ \´ / /ÙãxX2r_>>Ù>>lxxE2r_À­ñHãyêP>GÄXã2é ñHÄÒ_R/\$h. ``` [Try it online!](https://tio.run/nexus/v#@58ZoxBzaIuCvoK@9OGZhxdXRBgVxdvZHZ5pZ5dTUeEK5BxuOLT28EaPw4srD68KsHM/3BJxeLHR4ZUKILGWw5Pig/RjpFUy9P7//28EAA "V – TIO Nexus") Since, (as usual) this contains lots of nasty non-ASCII characters and unprintables, here is a hexdump: ``` 00000000: 695c 205c b420 2f20 2f1b d9e3 7858 3272 i\ \. / /...xX2r 00000010: 5f3e 3ed9 3e3e 6c78 7845 3272 5fc0 adf1 _>>.>>lxxE2r_... 00000020: 48e3 79ea 503e 47c4 58e3 32e9 20f1 48c4 H.y.P>G.X.2. .H. 00000030: d25f 522f 5c1b 2468 2e ._R/\.$h. ``` I'll post a more detailed explanation soon, but here is a high level overview: ``` i\ \´ / /ÙãxX2r_>>Ù>>lxxE2r_ "Create "\ \ / / " \ \__/ / " \____/ "This can probably be compressed a lot more À­ñHãyêP>GÄXã2é ñ "*arg1 times*, expand the pizza slice HÄÒ_R/\$h. "Add the crust ``` [Answer] # [C (clang)](http://clang.llvm.org/), ~~211~~ 215 bytes ``` i,l;f(n){l=n*3+6;char u[l];for(i=0;i<l;)u[i++]='_';u[l-1]=i=0;printf("/\\%.*s/\\\n",l-4,u);for(;i<n;i++)printf("%*s\\ \\%*.s/ /\n",i,"",n*3-(2*i),"");printf("%*.s\\ \\%.*s/ /\n%*.s\\%.*s/\n",i,"",n,u,i+1,"",n+2,u);} ``` [Try it online!](https://tio.run/nexus/c-clang#RY/PboMwDMbvfQoLCTX/gNGtu7h5hWn3Bk0IldVSllYwdmjFY@/MHFo6H5LP8e@L7YmMx1YEefU2qGf9is2x7mDY@wrbUyfIPiHtPMphT1pXdv2xRi5mZWVj6dxR@G5FUjiX5qrny4XE@OzFDHL2szkgO@VCpqp3DhhXeV9AEXEySWK4eSY2iiQnEv/p/I7H3yN@e7k1e3jNYEiXs9Sb2Hqc2A9fNQURRd19NgbiZkqx/pFwXQFHrBHOkocF3rZEoJ3d8skz36kYy0CWA97pcqnhzaYEMZ/nkPhgW7Fk42qcfsMpa@rmePgD "C (clang) – TIO Nexus") ## Pretty Code: ``` i,l; f(n) { l = n*3+6; char u[l]; // Initialize u[] with a full line of underscores, for (i=0;i<l;) u[i++] = '_'; // Make sure the string ends in a valid way u[l] = i = 0; /* Print the crust 'top' * l-4 dashes are needed because '/\/\' * %.*s notation to pad (l-4) bytes of the underscore string */ printf("/\\%.*s/\\\n", l-4,u); /* Print n rows of just 'walls' \ \ / / * each row has i=0++ leading spaces, * and each row has n*3-(2i) center spaces */ for(; i<n; i++) printf("%*s\\ \\%*.s/ /\n", i,"", n*3-(2*i), ""); /* Print i spaces, '\ \', n underlines, '/ /' * then i+1 spaces, '\', n+2 underlines, and '/' */ printf("%*.s\\ \\%.*s/ /\n%*.s\\%.*s/\n",i,"",n,u,i+1,"",n+2,u); } ``` ## Edits: * removed s[l] and associated by switching from %.*s notation to %*.s * added function wrapper for compliance & try it online [Answer] ## CJam, 74 Bytes *Way* too long. I'm going to try another approach. ``` "/\\"ri:M3*:A2+'_*1$NL{"\ \\"AS*"/ /"3$S+A((:A;N\}M*4$A'_*4$N4$S'\A2+'_*'/ ``` Builds the string line-by line. Nothing too crazy. [Answer] ## CJam, 89 bytes Well, this is actually longer than my other solution at the moment, but I think it's more golfable: ``` ri{:T)_S*a*ee_{~'\t}%TS*aTU+*'_f+@{~'/t}%W%++z}:K~2S*f{\+}T1:U+K..e>"/\\"'_T3*(*1$++a\+N* ``` Stack trace: ``` "2" ; r 2 ; i 2 {:T)_S*a*ee_{~'\t}%TS*aTU+*'_f+@{~'/t}%W%++z} ; {} 2 {:T)_S*a*ee_{~'\t}%TS*aTU+*'_f+@{~'/t}%W%++z} ; :K 2 ; ~ 2 ; :T 3 ; ) 3 3 ; _ 3 3 " " ; S 3 " " ; * 3 [" "] ; a [" " " " " "] * [[0 " "] [1 " "] [2 " "]] ; ee [[0 " "] [1 " "] [2 " "]] [[0 " "] [1 " "] [2 " "]] ; _ [[0 " "] [1 " "] [2 " "]] ["\ " " \ " " \\"] ; {~'\t}% [[0 " "] [1 " "] [2 " "]] ["\ " " \ " " \\"] 2 ; T [[0 " "] [1 " "] [2 " "]] ["\ " " \ " " \\"] 2 " " ; S [[0 " "] [1 " "] [2 " "]] ["\ " " \ " " \\"] " " ; * [[0 " "] [1 " "] [2 " "]] ["\ " " \ " " \\"] [" "] ; a [[0 " "] [1 " "] [2 " "]] ["\ " " \ " " \\"] [" "] 2 ; T [[0 " "] [1 " "] [2 " "]] ["\ " " \ " " \\"] [" "] 2 0 ; U [[0 " "] [1 " "] [2 " "]] ["\ " " \ " " \\"] [" "] 2 ; + [[0 " "] [1 " "] [2 " "]] ["\ " " \ " " \\"] [" " " "] ; * [[0 " "] [1 " "] [2 " "]] ["\ " " \ " " \\"] [" " " "] '_ ; '_ [[0 " "] [1 " "] [2 " "]] ["\ " " \ " " \\"] [" _" " _"] ; f+ ["\ " " \ " " \\"] [" _" " _"] [[0 " "] [1 " "] [2 " "]] ; @ ["\ " " \ " " \\"] [" _" " _"] ["/ " " / " " /"] ; {~'/t}% ["\ " " \ " " \\"] [" _" " _"] [" /" " / " "/ "] ; W% ["\ " " \ " " \\" " _" " _" " /" " / " "/ "] ; ++ ["\ /" " \ / " " \__/ "] ; z ["\ /" " \ / " " \__/ "] " " ; 2S* [" \ /" " \ / " " \__/ "] ; f{\+} [" \ /" " \ / " " \__/ "] 2 ; T [" \ /" " \ / " " \__/ "] 2 1 ; 1 [" \ /" " \ / " " \__/ "] 2 1 ; :U [" \ /" " \ / " " \__/ "] 3 ; + [" \ /" " \ / " " \__/ "] ["\ /" " \ / " " \ / " " \____/ "] ; K ["\ \ / /" " \ \ / / " " \ \__/ / " " \____/ "] ; ..e> ["\ \ / /" " \ \ / / " " \ \__/ / " " \____/ "] "/\\" ; "/\\" ["\ \ / /" " \ \ / / " " \ \__/ / " " \____/ "] "/\\" '_ ; '_ ["\ \ / /" " \ \ / / " " \ \__/ / " " \____/ "] "/\\" '_ 3 ; T ["\ \ / /" " \ \ / / " " \ \__/ / " " \____/ "] "/\\" '_ 9 ; 3* ["\ \ / /" " \ \ / / " " \ \__/ / " " \____/ "] "/\\" '_ 8 ; ( ["\ \ / /" " \ \ / / " " \ \__/ / " " \____/ "] "/\\" "________" ; * ["\ \ / /" " \ \ / / " " \ \__/ / " " \____/ "] "/\\" "________" "/\\" ; 1$ ["\ \ / /" " \ \ / / " " \ \__/ / " " \____/ "] "/\________/\\" ; ++ ["\ \ / /" " \ \ / / " " \ \__/ / " " \____/ "] ["/\________/\\"] ; a ["/\________/\\" "\ \ / /" " \ \ / / " " \ \__/ / " " \____/ "] ; \+ "/\________/\ \ \ / / \ \ / / \ \__/ / \____/ " ; N* ; [implicit output] ``` ]
[Question] [ ## Goal Generate (`N`) random line segments of uniform length (`l`), check if they cross the equidistant (`t`) parallel lines. ## Simulation **What are we simulating?** [Buffon's needle](https://en.wikipedia.org/wiki/Buffon's_needle). Smooth out the sand in your sandbox, draw a set of equally spaced parallel lines (call the distance in between `t`). Take a straight stick of length `l` and drop it `N` times into the sandbox. Let the number of times it crossed a line be `c`. Then `Pi = (2 * l * n) / (t * c)`! **How are we simulating this?** * Take input `N,t,l` * With `N, t, l` all being positive integers * Do the following `N` times: + Generate a uniformly random integer coordinate `x,y` + With `1 <= x, y <= 10^6` + `x,y` is the center of a line segment of length `l` + Generate a uniformly random integer `a` + With `1 <= a <= 180` + Let `P` be the point where the line segment would cross the x-axis + Then `a` is the angle `(x,y), P, (inf,0)` * Count the number, `c`, of line segments that cross the line `x = i*t` for any integer `i` * Return `(2 * l * N) / (t * c)` [![enter image description here](https://i.stack.imgur.com/lfQxF.png)](https://i.stack.imgur.com/lfQxF.png) [![enter image description here](https://i.stack.imgur.com/xbiqa.jpg)](https://i.stack.imgur.com/xbiqa.jpg) ## Specification * **Input** + Flexible, take input in any of the standard ways (eg function parameter,STDIN) and in any standard format (eg String, Binary) * **Output** + Flexible, give output in any of the standard ways (eg return, print) + White space, trailing and leading white space is acceptable + Accuracy, please provide at least 4 decimal places of accuracy (ie `3.1416`) * **Scoring** + Shortest code wins! ## Test Cases Your output may not line up with these, because of random chance. But on average, you should get about this much accuracy for the given value of `N, t, l`. ``` Input (N,t,l) -> Output ----------- ------ 10,10,5 -> ?.???? 10,100,50 -> ?.???? 1000,1000,600 -> 3.???? 10000,1000,700 -> 3.1??? 100000,1000,700 -> 3.14?? ``` ### TL;DR These challenges are simulations of algorithms that only require nature and your brain (and maybe some re-usable resources) to approximate Pi. If you really need Pi during the zombie apocalypse, these methods don't [waste ammo](https://medium.com/the-physics-arxiv-blog/how-mathematicians-used-a-pump-action-shotgun-to-estimate-pi-c1eb776193ef#.eld2u7w76)! There are [nine challenges](http://meta.codegolf.stackexchange.com/a/10035/43214) total. [Answer] # R, ~~113~~ ~~100~~ ~~75~~ ~~70~~ ~~68~~ ~~67~~ ~~65~~ ~~59~~ ~~63~~ 57 bytes As a statistical, functional programming language, it's not surprising that R is fairly well-suited to this kind of task. The fact that most functions can take vectorized input is really helpful for this problem, as rather than looping over `N` iterations, we just pass around vectors of size `N`. Thanks to @Billywob for some suggestions that lead to cutting off 4 bytes. Many thanks to @Primo for patiently explaining to me how my code wasn't working for cases where `t > l`, which is now fixed. ``` pryr::f(2*l*N/t/sum(floor(runif(N)+sinpi(runif(N))*l/t))) ``` [Try it online!](https://tio.run/##XclBCoAgFEXReSvxW6AFFQhuwWUIgql8ddDqLaPCmjy452HRsgTcUQhNJmqpYonFvBFtvUeC2RlNFPTRuGDeBGpZAoByhhz5kOpYOUPXwCX8IX5j1YU33Pj68d9RDg "R – Try It Online") Sample output: ``` N=1000, t=1000, l=500 3.037975 N=10000, t=1000, l=700 3.11943 N=100000, t=1000, l=700 3.140351 ``` ## Explanation The problem boils down to determining whether the two `x` values of the needle are on either side of a parallel line. This has some important consequences: 1. `y`-values are irrelevant 2. The absolute location on the `x`-axis is irrelevant, only the position relative to the closest parallel lines. Essentially this is a task in a 1-dimensional space, where we generate a line with length in [0, `l`] (the angle `a` determines this length), and then we check to see how many times this length exceeds `t`. The rough algorithm is then: 1. Sample `x1` values from [0, 1000000]. Since parallel lines occur at every `t`th point along the `x`-axis, the relative `x`-position is `x` modulo `t`. 2. Sample an angle `a`. 3. Calculate the `x2` position based on `a`. 4. Check how many times `x1+x2` fits into `t`, i.e. take the floor of `(x1+x2)/t`. Sampling `N` numbers in [0, 1e6] modulo `t` is equivalent to simply sampling `N` numbers in [0, `t`]. Since `(x1+x2)/t` is equivalent to `x1/t + x2/t`, the first step becomes sampling from [0, `t`]/`t`, i.e. [0, 1]. Lucky for us, that is the default range for R's `runif` function, which returns `N` real numbers from 0 to 1 from a uniform distribution. ``` runif(N) ``` We repeat this step to generate `a`, the angle of the needle. ``` runif(N) ``` These numbers are is interpreted as a half-turn (i.e. `.5` is 90 degrees). (The OP asks for degrees from 1 to 180, but in comments it's clarified that any method is allowed if it is as or more precise.) For an angle `θ`, `sin(θ)` gives us the x-axis distance between the ends of the needle. (Normally you'd use the cosine for something like this; but in our case, we are considering the angle `θ` as being relative to the y-axis, not the x-axis (that is, a value of 0 degrees goes *up*, not *right*), and therefore we use the sine, which basically phase-shifts the numbers.) Multiplied by `l` this gives us the `x` location of the end of the needle. ``` sinpi(runif(N))*l ``` Now we divide by `t` and add the `x1` value. This yields `(x1+x2)/t`, which is how far the needle protrudes from `x1`, in terms of number of parallel lines. To get the integer of how many lines were crossed, we take the `floor`. ``` floor(runif(N)+sinpi(runif(N))*l/t) ``` We calculate the sum, giving us the count `c` of how many lines are crossed by needles. ``` sum(floor(runif(N)+sinpi(runif(N))*l/t)) ``` The rest of the code is just implementing the formula for approximating pi, that is, `(2*l*N)/(t*c)`. We save some bytes on parentheses by taking advantage of the fact that `(2*l*N)/(t*c) == 2*l*N/t/c`: ``` 2*l*N/t/sum(floor(runif(N)+sinpi(runif(N))*l/t)) ``` And the whole thing is wrapped into an anonymous function: ``` pryr::f(2*l*N/t/sum(floor(runif(N)+sinpi(runif(N))*l/t))) ``` [Answer] # Perl, 97 bytes ``` #!perl -p / \d+/;$_*=2*$'/$&/map{($x=(1+~~rand 1e6)/$&)-$a..$x+($a=$'/$&/2*sin~~rand(180)*71/4068)-1}1..$_ ``` Counting the shebang as one, input is taken from stdin, space separated. If non-integer random values were allowed, this could be somewhat shorter. I have taken one liberty, approximating *π/180* as *71/4068*, which is accurate within *1.48·10-9*. **Sample Usage** ``` $ echo 1000000 1000 70000 | perl pi-sand.pl 3.14115345174061 ``` --- **More-or-less mathematically equivalent substitutions** Assuming the x-coordinate represents the left-most point of the needle, rather than its middle, as specified in the problem description: **89 bytes** ``` #!perl -p / \d+/;$_*=2*$'/$&/map{($x=(1+~~rand 1e6)/$&)..$x+($'/$&*sin~~rand(180)*71/4068)-1}1..$_ ``` The problem specifies that `x` is to be sampled as a random integer. If we project the line spacing to a gap of one, this will leave us with values of the form `n/t` with `0 <= n < t`, not necessarily uniform, if `t` does not evenly divide `1e6`. Assuming that a uniform distribution is nonetheless acceptable: **76 bytes** ``` #!perl -p / \d+/;$_*=2*$'/$&/map{($x=rand)..$x+($'/$&*sin~~rand(180)*71/4068)-1}1..$_ ``` Note that since `rand` will always be less than one (and therefore truncated to zero), it is not necessary at the start of the range: **70 bytes** ``` #!perl -p / \d+/;$_*=2*$'/$&/map{1..(rand)+($'/$&*sin~~rand(180)*71/4068)}1..$_ ``` Assuming that the angle of the needle need not be an integer degree, but only uniformly random: **59 bytes** ``` #!perl -p / \d+/;$_*=2*$'/$&/map{1..(rand)+abs$'/$&*sin rand$`}1..$_ ``` Assuming that the angle may be any uniform distribution: **52 bytes** ``` #!perl -p / \d+/;$_*=2*$'/$&/map{1..(rand)+abs$'/$&*sin}1..$_ ``` The above is a mathematically correct simulation of Buffon's Needle. However, at this point I think most people would agree that this isn't actually what the question asked for. --- **Really pushin' it** We could just throw away half of the test cases, whenever the second endpoint is to the left of the first (rather than swapping them): **47 bytes** ``` #!perl -p / \d+/;$_*=$'/$&/map{1..(rand)+$'/$&*sin}1..$_ ``` Note that the values of `t` and `l` are inconsequential to the results of the experiment. We could just ignore them (implicitly assuming them to be equal): **28 bytes** ``` #!perl -p $_/=map{1..(rand)+sin}1..$_ ``` Obviously non-competing, but you have to admit, it does have a certain elegance to it. [Answer] # Python 2, 141 bytes shameless port of rtumbull, already skipping `y` because totally not needed. ``` from math import* from random import* lambda N,t,l:(2.*l*N)/(t*sum(randint(1,1e6)%t+abs(cos(randint(1,180)*pi/180))*l>t for _ in range(N))) ``` Problem is only, that pi is already known in the program. Here it is (golfable) with unknown pi and no trigonometric functions ``` def g(N,t,l): c=0 for _ in range(N): x,y=gauss(0,1),gauss(0,1);c+=randint(1,1e6)%t+abs(x/sqrt(x*x+y*y))*l>t return(2.*l*N)/(t*c) ``` `x,y` in `g` is only for the direction. ]
[Question] [ The [Chinese Remainder Theorem](https://en.wikipedia.org/wiki/Chinese_remainder_theorem) can be quite useful in modular arithmetic. For example, consider the following set of congruence relations: [![Set of congruence](https://i.stack.imgur.com/qHvYd.gif)](https://i.stack.imgur.com/qHvYd.gif) For sets of congruence relations like this, where all the bases (`3, 5, 7` in this example) are [co-prime](https://en.wikipedia.org/wiki/Coprime_integers) with each other, there will be one and only one integer `n` between `1` and the product of the bases (`3*5*7 = 105` in this example) inclusive that satisfies the relations. In this example, the number would be `14`, generated by this formula: [![formula](https://i.stack.imgur.com/TBiLq.gif)](https://i.stack.imgur.com/TBiLq.gif) where `2, 4, and 0` are given from the above example. `70, 21, 15` are the **coefficients** of the formula and they are dependent on the bases, `3, 5, 7`. To calculate the coefficients of the formula (`70, 21, 15` in our example) for a set of bases, we use the following procedure. For each number `a` in a set of bases: 1. Find the product of all of the other bases, denoted as `P`. 2. Find the first multiple of `P` that leaves a remainder of `1` when divided by `a`. This is the coefficient of `a`. For example, to calculate the coefficient that corresponds to the base `3`, we find the product of all the other bases (i.e. `5*7 = 35`) and then find the first multiple of that product that leaves a remainder of `1` when divided by the base. In this case, `35` leaves a remainder of `2` when divided by `3`, but `35*2 = 70` leaves a remainder of `1` when divided by `3`, so `70` is the corresponding coefficient for `3`. Similarly, `3*7 = 21` leaves a remainder of `1` when divided by `5` and `3*5 = 15` leaves a remainder of `1` when divided by `7`. # In a nutshell For each number `a` in a set of numbers: 1. Find the product of all of the other numbers, denoted as `P`. 2. Find the first multiple of `P` that leaves a remainder of `1` when divided by `a`. This is the coefficient of `a`. # The challenge * The challenge is, for a set of two or more bases, to find the set of corresponding coefficients. * The set of bases are guaranteed to be pairwise co-prime and each base is guaranteed to be larger than 1. * Your input is a list of integers as input `[3,4,5]` or space-separated string `"3 4 5"` or however your inputs work. * Your output should either be a list of integers or space-separated string that denotes the set of coefficients. # Test cases ``` input output [3,5,7] [70,21,15] [2,3,5] [15,10,6] [3,4,5] [40,45,36] [3,4] [4,9] [2,3,5,7] [105,70,126,120] [40,27,11] [9801,7480,6480] [100,27,31] [61101,49600,56700] [16,27,25,49,11] [363825,2371600,2794176,5583600,529200] ``` Many thanks to Leaky Nun for his help in writing this challenge. As always, if the problem is unclear, please let me know. Good luck and good golfing! [Answer] ## Haskell, ~~61~~ ~~55~~ 53 bytes ``` f x=[[p|p<-[0,product x`div`n..],p`mod`n==1]!!0|n<-x] ``` Defines a function `f` that takes input and gives output as a list of integers. ``` f x=[ |n<-x] (1) product x (2) `div`n (3) ``` First we loop over all integers in the input (1). Then we take the product of all of the integers (2) and divide by n to get just the product of the non-`n` integers, which is `P` (3). ``` [0, ..] (4) [p|p<- ,p`mod`n==1] (5) !!0 (6) ``` Then we use the result (`P`) as the step value for a range starting at zero (4). We take the result, `[0, P, 2P, 3P, ...]`, and filter it on values for which the result of a mod-n operation is one (5). Finally, we take the first element, which works thanks to lazy evaluation (6). Thanks to [@xnor](https://codegolf.stackexchange.com/users/20260/xnor) for 2 bytes! [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~11~~ 7 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` P:*ÆṪ%P ``` [Try it online!](http://jelly.tryitonline.net/#code=UDoqw4bhuaolUA&input=&args=WzE2LDI3LDI1LDQ5LDExXQ) or [verify all test cases](http://jelly.tryitonline.net/#code=UDoqw4bhuaolUArDh-KCrEc&input=&args=WzMsIDUsIDddLCBbMiwgMywgNV0sIFszLCA0LCA1XSwgWzMsIDRdLCBbMiwgMywgNSwgN10sIFs0MCwgMjcsIDExXSwgWzEwMCwgMjcsIDMxXSwgWzE2LDI3LDI1LDQ5LDExXQ). ### Background Let **P** and **a** be strictly positive, *coprime* integers. The two-step process in the question – finding a multiple of **P** that leaves a remainder of **1** when divided by **a** – can be described by the following congruence equation. ![linear congruence equation](https://i.stack.imgur.com/mEzmg.png "linear congruence equation") By the [Euler-Fermat theorem](https://en.wikipedia.org/wiki/Euler%27s_theorem "Euler-Fermat theorem"), we have ![Euler-Fermat theorem](https://i.stack.imgur.com/RMgkb.png "Euler-Fermat theorem") where **φ** denotes [Euler's totient function](https://en.wikipedia.org/wiki/Euler%27s_totient_function "Euler's totient function"). From this result, we deduce the following. ![formula for linear congruence equation](https://i.stack.imgur.com/uYXR8.png "formula for linear congruence equation") Finally, since the challenge requires us to compute **Px**, we observe that ![formula for final result](https://i.stack.imgur.com/kuqgM.png "formula for final result") where **Pa** can be computed as the product of all moduli. ### How it works ``` P:*ÆṪ%P Main link. Argument: A (list of moduli) P Yield the product of all moduli. : Divide the product by each modulus in A. ÆṪ Apply Euler's totient function to each modulus. * Raise each quotient to the totient of its denominator. %P Compute the remainder of the powers and the product of all moduli. ``` [Answer] # J, 13 bytes ``` */|5&p:^~*/%] ``` Based on @Dennis' amazing [answer](https://codegolf.stackexchange.com/a/88974/6710). ## Usage Some test cases will need the input as extended integers which have a suffix `x`. ``` f =: */|5&p:^~*/%] f 3 5 7 70 21 15 f 40x 27 11 9801 7480 6480 f 16x 27 25 49 11 363825 2371600 2794176 5583600 529200 ``` ## Explanation ``` */|5&p:^~*/%] Input: list B */ Reduce B using multiplication to get the product of the values ] Identity function, get B % Divide the product by each value in B, call the result M 5&p: Apply the totient function to each value in B, call the result P ^~ Raise each value in M to the power of its corresponding value in P */ The product of the values in B | Compute each power modulo the product and return ``` [Try it here.](http://tryj.tk/) [Answer] # Mathematica, 27 bytes ``` PowerMod[a=LCM@@#/#,-1,#]a& ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 14 bytes ``` mhfq1%Td*R/*FQ ``` [Test suite.](http://pyth.herokuapp.com/?code=mhfq1%25Td%2aR%2F%2aFQ&test_suite=1&test_suite_input=%5B3%2C5%2C7%5D%0A%5B2%2C3%2C5%5D%0A%5B3%2C4%2C5%5D%0A%5B40%2C27%2C11%5D%0A%5B100%2C27%2C31%5D&debug=0) Naive implementation of the algorithm. [Answer] # Jelly, ~~14~~ 13 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` P:×"Ḷð%"’¬æ.ḷ ``` Saved a byte thanks to @[Dennis](https://codegolf.stackexchange.com/users/12012/dennis)! Uses the process described in the challenge spec. The input is a list of bases and the output is a list of coefficients. [Try it online](http://jelly.tryitonline.net/#code=UDrDlyLhuLbDsCUi4oCZwqzDpi7huLc&input=&args=WzMsIDUsIDdd) or [Verify all test cases](http://jelly.tryitonline.net/#code=UDrDlyLhuLbDsCUi4oCZwqzDpi7huLcKw4figqxH&input=&args=W1szLCA1LCA3XSwgWzIsIDMsIDVdLCBbMywgNCwgNV0sIFszLCA0XSwgWzIsIDMsIDUsIDddLCBbNDAsIDI3LCAxMV0sIFsxMDAsIDI3LCAzMV0sIFsxNiwgMjcsIDI1LCA0OSwgMTFdXQ). ## Explanation ``` P:×"Ḷð%"’¬æ.ḷ Input: a list B P Get the product of the list : Divide it by each value in the B, call it M Ḷ Get a range from 0 to k for k in B ×" Vectorized multiply, find the multiples of each M ð Start a new dyadic chain. Input: multiples of M and B %" Vectorized modulo, find the remainders of each multiple by B ’ Decrement every value If the remainder was 1, decrementing would make it 0 ¬ Logical NOT, zeros become one and everything else becomes 0 ḷ Get the multiples of M æ. Find the dot product between the modified remainders and the multiples Return ``` [Answer] ## JavaScript (ES6), 80 bytes ``` a.map(e=>[...Array(e).keys()].find(i=>p*i/e%e==1)*p/e,p=a.reduce((i,j)=>i*j)) ``` I tried the extended Euclidean algorithm but it takes 98 bytes: ``` a=>a.map(e=>(r(e,p/e)+e)%e*p/e,p=a.reduce((i,j)=>i*j),r=(a,b,o=0,l=1)=>b?r(b,a%b,t,o-l*(a/b|0)):o) ``` If the values are all prime, ES7 can do it in 56 bytes: ``` a=>a.map(e=>(p/e%e)**(e-2)%e*p/e,p=a.reduce((i,j)=>i*j)) ``` [Answer] # Python + SymPy, 71 bytes ``` from sympy import* lambda x:[(prod(x)/n)**totient(n)%prod(x)for n in x] ``` This uses the algorithm from [my Jelly answer](https://codegolf.stackexchange.com/a/88974/12012). I/O is in form of lists of SymPy numbers. [Answer] # Python 2, ~~87~~ 84 bytes A simple implementation of the algorithm. Golfing suggestions welcome. ``` a=input();p=1 for i in a:p*=i print[p/i*j for i in a for j in range(i)if p/i*j%i==1] ``` [Answer] # [Cheddar](http://cheddar.vihan.org/), 64 bytes ``` n->n.map(i->(|>i).map(j->(k->k%i>1?0:k)(n.reduce((*))/i*j)).sum) ``` [Answer] ## [GAP](http://gap-system.org), 51 bytes GAP has a function that can compute the motivating example with `ChineseRem([2,5,7],[2,4,0])`, but that still doesn't make it that easy to get the coefficients. We can get the n-th coefficient by using the list with a one in the n-th position and zeroes at the other positions as second argument. So we need to create these lists and apply the function to all of them: ``` l->List(Basis(Integers^Size(l)),b->ChineseRem(l,b)) ``` [Answer] ## Batch, 148 bytes ``` @set p=%* @set/ap=%p: =*% @for %%e in (%*)do @for /l %%i in (1,1,%%e)do @call:l %%e %%i @exit/b :l @set/an=p/%1*%2,r=n%%%1 @if %r%==1 echo %n% ``` [Answer] # Actually, 14 bytes This uses the algorithm in [Dennis's Jelly answer](https://codegolf.stackexchange.com/a/88974/47581). Another answer based on my Python answer is forthcoming. Golfing suggestions welcome. [Try it online!](http://actually.tryitonline.net/#code=O8-AOynimYBcO-KZguKWkkDimYDigb_imYAl&input=WzEwMCwyNywzMV0) ``` ;π;)♀\;♂▒@♀ⁿ♀% ``` **How it works** ``` Implicit input a. ; Duplicate a. π;) Take product() of a, duplicate and rotate to bottom. ♀\ Integer divide the product by each element of a. Call this list b. ;♂▒ Take that list, duplicate, and get the totient of each element. @♀ⁿ Swap and take pow(<item in b>, <corresponding totient>) ♀% Modulo each item by the remaining duplicate product on the stack. Implicit return. ``` Another answer based on my Python answer at 22 bytes. Golfing suggestions welcome. [Try it online!](http://actually.tryitonline.net/#code=O8-A4pWWYOKVneKVm-KVnFzilZtyKiLilZtAJTE9IsKj4paRYE0&input=WzEwMCwyNywzMV0) ``` ;π╖`╝╛╜\╛r*"╛@%1="£░`M ``` **How it works** ``` Implicit input a. ;π╖ Duplicate, take product of a, and save to register 0. `...`M Map over a. ╝ Save the item, b, in register 1. ╛╜\ product(a) // b. Call it P. ╛r Take the range [0...b]. * Multiply even item in the range by P. Call this list x. "..."£░ Turn a string into a function f. Push values of [b] where f returns a truthy value. ╛@% Push b, swap, and push <item in x> % b. 1= Does <item> % b == 1? Implicit return. ``` ]
[Question] [ This challenge is very simple. You are given as input a square matrix, represented in any sane way, and you have to output the dot product of the diagonals of the matrix. The diagonals in specific are the diagonal running from top-left to bottom-right and from top-right to bottom-left. # Test Cases ``` [[-1, 1], [-2, 1]] -> -3 [[824, -65], [-814, -741]] -> 549614 [[-1, -8, 4], [4, 0, -5], [-3, 5, 2]] -> -10 [[0, -1, 0], [1, 0, 2], [1, 0, 1]] -> 1 ``` [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), ~~8~~ 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ×UŒDḢS ``` [Try it online!](http://jelly.tryitonline.net/#code=w5dVxZJE4biiUw&input=&args=W1stMSwgLTgsIDRdLCBbNCwgMCwgLTVdLCBbLTMsIDUsIDJdXQ) or [verify all test cases](http://jelly.tryitonline.net/#code=w5dVxZJE4biiUwrDh-KCrA&input=&args=W1stMSwgMV0sIFstMiwgMV1dLCBbWzgyNCwgLTY1XSwgWy04MTQsIC03NDFdXSwgW1stMSwgLTgsIDRdLCBbNCwgMCwgLTVdLCBbLTMsIDUsIDJdXSwgW1swLCAtMSwgMF0sIFsxLCAwLCAyXSwgWzEsIDAsIDFdXQ) ### How it works ``` ×UŒDḢS Main link. Argument: M (matrix) U Upend M, i.e., reverse each row. , Pair M and upended M. ŒD Yield all diagonals. Ḣ Head; extract the first, main diagonal. S Reduce by sum. ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 8 bytes ``` t!P!*Xds ``` Input format is ``` [-1, -8, 4; 4, 0 -5; -3, 5, 2] ``` [Try it online!](http://matl.tryitonline.net/#code=dCFQISpYZHM&input=Wy0xLCAtOCwgNDsgNCwgMCAtNTsgLTMsIDUsIDJd) Or [verify all test cases](http://matl.tryitonline.net/#code=YAp0IVAhKlhkcwpEVA&input=Wy0xLCAxOyAtMiwgMV0KWzgyNCwgLTY1OyAtODE0LCAtNzQxXQpbLTEsIC04LCA0OyA0LCAwIC01OyAtMywgNSwgMl0KWzAsIC0xLCAwOyAxLCAwLCAyOyAxLCAwLCAxXQo). ### Explanation ``` t % Take input matrix implicitly. Duplicate !P! % Flip matrix horizontally * % Element-wise product Xd % Extract main diagonal as a column vector s % Sum. Display implicitly ``` [Answer] # Julia, 25 bytes ``` ~=diag !x=~x⋅~rotl90(x) ``` [Try it online!](http://julia.tryitonline.net/#code=fj1kaWFnCiF4PX544ouFfnJvdGw5MCh4KQoKZm9yIHggaW4gKFstMSAxOy0yIDFdLCBbODI0IC02NTstODE0IC03NDFdLCBbLTEgLTggNDs0IDAgLTU7LTMgNSAyXSwgWzAgLTEgMDsxIDAgMjsxIDAgMV0pCiAgICBwcmludGxuKCF4KQplbmQ&input=) [Answer] # Python, 47 bytes ``` lambda x:sum(r[i]*r[~i]for i,r in enumerate(x)) ``` Test it on [Ideone](http://ideone.com/blsF8C). [Answer] # J, ~~21~~ 19 bytes ``` [:+/(<0 1)|:(*|."1) ``` Straight-forward approach. Saved 2 bytes thanks to @[Lynn](https://codegolf.stackexchange.com/users/3852/lynn). ## Usage The input array is shaped using `dimensions $ values`. ``` f =: [:+/(<0 1)|:(*|."1) f (2 2 $ _1 1 _2 1) _3 f (2 2 $ 824 _65 _814 _741) 549614 f (3 3 $ _1 _8 4 4 0 _5 _3 5 2) _10 f (3 3 $ 0 _1 0 1 0 2 1 0 1) 1 ``` ## Explanation ``` [:+/(<0 1)|:(*|."1) Input: matrix M |."1 Reverse each row of M * Multiply element-wise M and the row-reversed M (<0 1)|: Take the diagonal of that matrix [:+/ Sum that diagonal and return it= ``` [Answer] # [APL (Dyalog)](https://www.dyalog.com/), ~~15~~ 9 bytes ``` +/1 1⍉⌽×⊢ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R2wRtfUMFw0e9nY969h6e/qhrEVBUwUjB6FHvlkPrgTIKh9YbKRhywcQsjEyAImamQMLCEMQ0NwFJGisYQzUAxRVMgNAAyAKpMlYwVTCCqwCJGgLlQNgITBoCAA "APL (Dyalog Unicode) – Try It Online") **How?** `+/` - sum `1 1⍉` - diagonal of `⌽×⊢` - element wise multiplication of the matrix with it's reverse [Answer] ## JavaScript (ES6), 45 bytes ``` a=>a.reduce((r,b,i)=>r+b[i]*b.slice(~i)[0],0) a=>a.reduce((r,b,i)=>r+b[i]*b[b.length+~i],0) ``` [Answer] ## R, 26 bytes ``` sum(diag(A*A[,ncol(A):1])) ``` [Answer] # Mathematica, 17 bytes ``` Tr[#~Reverse~2#]& ``` [Answer] ## Clojure, 57 bytes ``` #(apply +(map(fn[i r](*(r i)(nth(reverse r)i)))(range)%)) ``` [Answer] # [Haskell](https://www.haskell.org/), ~~80~~ 48 bytes I liked my previous solution more, but this is much shorter (basically does the same as the Python solution): ``` f m=sum[r!!i*r!!(length m-i-1)|(i,r)<-zip[0..]m] ``` [Try it online!](https://tio.run/##DcZBDoMgEEDRq4w7bWaItpp0Udx4DMKCpKiTAhqgG9O7Uxb/5e8mfaxzpazgZfp6FZuGb5XW2bDlHTwxDd2vZYzdiy4@VS@E9rp4wwEkbDYvR8g25ATzLOGMHDIIWGvRmndRigakJ44a1Yg90lSHHjjhXes/ "Haskell – Try It Online") [Answer] # J, 18 Bytes ``` <:@#{+//.@:(*|."1) ``` ### Explaination: ``` ( ) | Monadic hook * | Argument times... |."1 | The argument mirrored around the y axis +//.@: | Make a list by summing each of the diagonals of the matrix { | Takes element number... <:@# | Calculates the correct index (size of the array - 1) ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 5 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` í*Å\O ``` [Try it online](https://tio.run/##yy9OTMpM/f//8Fqtw60x/v//R0frGuroWuiYxOpEm@gY6OiaAhm6xjqmOkaxsQA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9WeXiCvZLCo7ZJCkr2/w@v1TrcGuP/X@d/dHS0rqGOYaxOtK4RkIrVUYiOtjAy0dE1MwWJWRgCmeYmUAmgSl0LHROghImOgY4uWIWxjqmOEUQaKGSoYwAUBJJAMQgN1BoLAA). **Explanation:** ``` í # Reverse each row of the (implicit) input-matrix # i.e. [[-1,-8,4],[4,0,-5],[-3,5,2]] → [[4,-8,-1],[-5,0,4],[2,5,-3]] * # Multiply it with the (implicit) input-matrix (at the same positions) # i.e. [[-1,-8,4],[4,0,-5],[-3,5,2]] and [[4,-8,-1],[-5,0,4],[2,5,-3]] # → [[-4,64,-4],[-20,0,-20],[-6,25,-6]] Å\ # Get the diagonal-list from the top-left corner towards the bottom-right # i.e. [[-4,64,-4],[-20,0,-20],[-6,25,-6]] → [-4,0,-6] O # Sum it (and output implicitly) # i.e. [-4,0,-6] → -10 ``` [Answer] # [Kamilalisp](https://github.com/kspalaiologos/kamilalisp), 46 bytes ``` $(⌿⊙← +)∘∊∘[* #0 [$(⌼ =) #0 #0]∘⍳∘⍴]∘[* #0 :⌽] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70qOzE3MycxJ7O4YMEyjZTUNIXMpaUlaboWNz1UNB717H_UNfNR2wQFbc1HHTMedXQByWgtBWUDhWiQ7B4FW00QR9kgFiTduxlMbomFq7J61LM3FmqeriaXRma-VXlRZklqTp6CRqaCuoaGoYKpgpGmgoaZgiGYtgTyLTSBAKJpwQIIDQA) ]
[Question] [ This is a code-golf question. Given integers s and n the task is to output all arrays of length n which take values from -s to s. The only twist is that you must output them in the following order. * The all zeros array of length n. * All arrays of length n with elements from -1 to 1 excluding any array you have outputted before. * All arrays of length n with elements from -2 to 2 excluding any array you have outputted before. * And so on until you get to all arrays of length n with elements from -s to s excluding any array you have outputted before. You should output one array per line. They can be space or comma separated. Here is some non-complying python code that outputs the arrays/lists/tuples in the right order. ``` import itertools s = 3 n = 2 oldsofar = set() newsofar = set() for i in xrange(s): for k in itertools.product(range(-i,i+1), repeat = n): newsofar.add(k) print newsofar - oldsofar oldsofar = newsofar.copy() print "***" ``` Extra glory (and an upvote from me) for answers that perform no set subtraction or equivalent. [Answer] # Jelly, 9 bytes ``` NRṗµAṀ€Ụị ``` No list subtraction was used in the making of this post. [Try it online!](http://jelly.tryitonline.net/#code=TlLhuZfCtUHhuYDigqzhu6Thu4s&input=&args=Mw+Mg) ### How it works ``` NRṗµAṀ€Ụị Main link. Arguments: s, n N Negate; yield -s. R Range; yield [-s, ..., s]. ṗ Cartesian power; push all vectors of length n of those elements. µ Begin a new, monadic link. Argument: L (list of vectors) A Compute the absolute values of all vector components. Ṁ€ Get the maximum component of each vector. Ụ Sort the indices of A according to the maximal absolute value of the corresponding vector's components. ị Retrieve the vectors of A at those indices. ``` [Answer] # [MATL](https://esolangs.org/wiki/MATL), 18 bytes ``` _G2$:iZ^t!|X>4#SY) ``` First input is `s`, second is `n` 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=X0cyJDppWl50IXxYPjQjU1kp&input=Mwoy) ### Explanation ``` _ % take input s implicitly. Negate to obtain -s G % push input s again 2$: % inclusive range from -s to s i % take input n Z^ % Cartesian power. Gives 2D array, with each result on a row t! % duplicate and transpose | % absolute value X> % maximum of each column 4#S % sort and push the indices of the sorting Y) % apply as row indices into the 2D array. Display implicitly ``` [Answer] ## Haskell, ~~61~~ 60 bytes ``` n#s=[c|b<-[0..s],c<-mapM id$[-b..b]<$[1..n],any((b==).abs)c] ``` Usage example: `2#2`-> `[[0,0],[-1,-1],[-1,0],[-1,1],[0,-1],[0,1],[1,-1],[1,0],[1,1],[-2,-2],[-2,-1],[-2,0],[-2,1],[-2,2],[-1,-2],[-1,2],[0,-2],[0,2],[1,-2],[1,2],[2,-2],[2,-1],[2,0],[2,1],[2,2]]`. How it works: ``` b<-[0..s] -- loop b through 0 .. s c<-mapM id$[-b..b]<$[1..n] -- loop c through all lists of length n -- made out of the numbers -b .. b -- ("[-b..b]<$[1..n]" is "replicate n [-b..b]"; -- "mapM id" is "sequence") [c| ,any((b==).abs)c] -- keep c if it contains b or -b ``` Edit: @xnor pointed out that `mapM id` is `sequence`. [Answer] # Mathematica, 83 bytes ``` Print/@Select[Range[-#,b=#]~Tuples~a,Abs@#~MemberQ~b&]&/@Range[0,a=Input[];Input[]] ``` To use, put in a script and input `n` then `s` on separate lines. Prints each array as a curly-bracketed, comma-delimited list (e.g., `{-1, 0, 1}`). It works by taking every list of length `n` with numbers between `[-cur..cur]`, and and printing those which include either `-cur` or `cur`. It then repeats this for all `cur` in `[0..s]`. (This post contains 19 ` characters!) [Answer] ## JavaScript (SpiderMonkey 30+), 134 bytes ``` (s,n)=>n?[for(a of f(s,n-1))for(i of Array(s*2+1).keys())[i-n,...a]].sort((a,b)=>g(a)-g(b),g=a=>Math.max(...a,-Math.min(...a))):[[]] ``` Uses the cartesian-power-and-sort approach, which I thought of separately, but I was recompiling SpiderMonkey at the time so I unable to answer this before @Dennis. ]
[Question] [ In Skyrim, the player character can use powerful magic shouts (Thu'ums) to achieve their goals. Every shout consists of three words, however, the player can use the first one or two words to achieve the same effect with less power but at a shorter cooldown. Given a lowercase ASCII Thu'um phrase **without punctuation or spaces**, return how many words of power it contains. Example: ``` fusrodah -> 3 dur -> 1 kaandrem -> 2 odah -> 2 vengaarnos -> 3 ``` The input will **always** be a lowercase ASCII string formed by taking one of the shouts below, choosing the first 1, 2, or 3 words from that shout, and concatenating the words in order. ``` dur neh viir faas ru maar feim zii gron fo krah diin fus ro dah gaan lah haas gol hah dov hun kaal zoor iiz slen nus joor zah frul kaan drem ov krii lun aus laas yah nir lok vah koor mid vur shaan mul qah diiv od ah viing raan mir tah rii vaaz zol strun bah qo su grah dun tiid klo ul ven gaar nos wuld nah kest yol toor shul zul mey gut zun haal viik ``` So `fus`, `fusro`, and `fusrodah` are all valid inputs, but `fusroviir` isn't because it uses words from mixed shouts, and `rodah` isn't because it's not a prefix of a shout. You also don't have to handle the empty string input. --- Shortest code in bytes wins. [Answer] ## Retina, ~~78~~ ~~42~~ ~~15~~ 14 bytes ``` ul xo [aeiou]+ ``` [Try it online](http://retina.tryitonline.net/#code=dWwKeG8KW2FlaW91XSs&input=aHVua2FhbHpvb3I&args=) **tiidkloul** is the only word that doesn't have the same amount of vowel sequences as the number supposed to be printed. Therefore we need to match the word to give it an extra vowel sequence. `ou` will only match tiidkl**ou**l and we can then replace **ou** with **oxo** which creates the extra sequence. My initial approach wasn't this simple, but was build around removing all consonants, then removing a few vowel sequences (`ai|ii|aa|...`) and then finally counting the numbers of letters. But thanks to [@Martin Büttner](https://codegolf.stackexchange.com/users/8478/martin-b%C3%BCttner) for thinking of `[aeiou]+` instead. [Answer] ## [Retina](https://github.com/mbuettner/retina/), 313 bytes ``` ah|aus|bah|d(ah|ii[nv]|ov|rem|u[nr])|[fhl]aas|f(eim|o|rul|us)|g(aa[nr]|ol|rah|ron|ut)|haal|hah|hun|iiz|joor|k(aa[ln]|est|lo|oor|rah|rii)|lah|lok|lun|m(aar|ey|i[dr]|ul)|n[ae]h|nir|n[ou]s|od|ov|qah|qo|r(aan|ii|o|u)|s(haan|hul|len|trun|u)|tah|tiid|toor|ul|v(aaz|ah|en|iin?[gkr]|ur)|wuld|yah|yol|z(ah|ii|[ou][ln]|oor) ``` [Try it online!](http://retina.tryitonline.net/#code=YWh8YXVzfGJhaHxkKGFofGlpW252XXxvdnxyZW18dVtucl0pfFtmbF1hYXN8ZihlaW18b3xydWx8dXMpfGcoYWFbbnJdfG9sfHJhaHxyb258dXQpfGhhYVtsc118aGFofGh1bnxpaXp8am9vcnxrKGFhW2xuXXxlc3R8bG98b29yfHJhaHxyaWkpfGxhaHxsb2t8bHVufG0oYWFyfGV5fGlbZHJdfHVsKXxuW2FlXWh8bmlyfG5bb3Vdc3xvZHxvdnxxYWh8cW98cihhYW58aWl8b3x1KXxzKGhhYW58aHVsfGxlbnx0cnVufHUpfHRhaHx0aWlkfHRvb3J8dWx8dihhYXp8YWh8ZW58aWluP1tna3JdfHVyKXx3dWxkfHlhaHx5b2x8eihhaHxpaXxbb3VdW2xuXXxvb3Ip&input=ZnVzcm9kYWg) Based on a few simple observations: * All words are unique, regardless of their position. * No word is a prefix of another word. * The input is guaranteed to be valid. That means we can simply count how many of words appear in the string without overlap. That's exactly what a regex does. I've tried compressing the regex a little beyond just concatenating all the words with `|` (which would be 351 bytes), but I'm sure this is far from optimal. For a start, I've definitely not exploited all common parts optimally. But more importantly, it's possible to compress the string even further by making it match more strings than valid words, as long as those can't accidentally match part of a valid word (because then they'll just never be matched). I'm pretty sure one would have to automate the compressing to really be sure it's optimal. [Answer] # Perl 5, 28 bytes Byte count includes one for `-p`. ``` s/ou/oxo/;$_=()=/[aeiou]+/g ``` Stolen straight from [dev-null](/a/72033). (Thanks, dev-null!) ]
[Question] [ # Intro Consider the process of taking some positive integer *n* in some base *b* and replacing each digit with its representation in the base of the digit to the right. * If the digit to the right is a 0, use base *b*. * If the digit to the right is a 1, use [unary](http://en.wikipedia.org/wiki/Unary_numeral_system) with 0's as tally marks. * If there is no digit to the right (i.e. you are in the ones place), loop around to the most significant digit. As an example let *n* = 160 and *b* = 10. Running the process looks like this: ``` The first digit is 1, the digit to the right is 6, 1 in base 6 is 1. The next digit is 6, the digit to the right is 0, 0 is not a base so use b, 6 in base b is 6. The last digit is 0, the digit to the right (looping around) is 1, 0 in base 1 is the empty string (but that's ok). Concatenating '1', '6', and '' together gives 16, which is read in the original base b = 10. ``` The exact same procedure *but moving left instead of right* can also be done: ``` The first digit is 1, the digit to the left (looping around) is 0, 0 is not a base so use b, 1 in base b is 1. The next digit is 6, the digit to the left is 1, 6 in base 1 is 000000. The last digit is 0, the digit to the left is 6, 0 in base 6 is 0. Concatenating '1', '000000', and '0' together gives 10000000, which is read in the original base b = 10. ``` Thus, we've made two numbers related to 160 (for *b* = 10): 16 and 10000000. *We will define n to be a **crafty number** if it evenly divides at least one of the two numbers generated in this process into 2 or more parts* In the example *n* is crafty because 160 divides 10000000 exactly 62500 times. 203 is NOT crafty because the resulting numbers are 2011 and 203 itself, which 203 cannot fit evenly into 2 or more times. # Challenge (For the rest of the problem we will only consider *b* = 10.) The challenge is to write a program that finds the highest crafty number that is also prime. The first 7 crafty primes (and all that I have found so far) are: ``` 2 5 3449 6287 7589 9397 93557 <-- highest so far (I've searched to 100,000,000+) ``` I am not officially certain whether more exist, but I expect they do. If you can prove that there are (or aren't) finitely many I'll give you +200 bounty rep. The winner will be the person who can provide the highest crafty prime, provided it is apparent that they have been active in the search and are not intentionally taking glory from others. # Rules * You may use any prime finding tools you want. * You may use probabilistic prime testers. * You may reuse other peoples code **with attribution**. This is a communal effort. Cutthroat tactics will not be tolerated. * Your program must actively search for the prime. You may start your search at the highest known crafty prime. * Your program should be able to compute **all** of the known crafty primes within 4 hours of [Amazon EC2 t2.medium instances](http://aws.amazon.com/ec2/instance-types/) (either four at once or one for four hours or something in between). I will not actually be testing it on them and you certainly don't need to. This is just a benchmark. Here is my Python 3 code I used for generating the table above: (runs in a second or two) ``` import pyprimes def toBase(base, digit): a = [ ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], ['', '0', '00', '000', '0000', '00000', '000000', '0000000', '00000000', '000000000' ], ['0', '1', '10', '11', '100', '101', '110', '111', '1000', '1001'], ['0', '1', '2', '10', '11', '12', '20', '21', '22', '100'], ['0', '1', '2', '3', '10', '11', '12', '13', '20', '21'], ['0', '1', '2', '3', '4', '10', '11', '12', '13', '14'], ['0', '1', '2', '3', '4', '5', '10', '11', '12', '13'], ['0', '1', '2', '3', '4', '5', '6', '10', '11', '12'], ['0', '1', '2', '3', '4', '5', '6', '7', '10', '11'], ['0', '1', '2', '3', '4', '5', '6', '7', '8', '10'] ] return a[base][digit] def getCrafty(start=1, stop=100000): for p in pyprimes.primes_above(start): s = str(p) left = right = '' for i in range(len(s)): digit = int(s[i]) left += toBase(int(s[i - 1]), digit) right += toBase(int(s[0 if i + 1 == len(s) else i + 1]), digit) left = int(left) right = int(right) if (left % p == 0 and left // p >= 2) or (right % p == 0 and right // p >= 2): print(p, left, right) if p >= stop: break print('DONE') getCrafty() ``` [Answer] ## Mathematica, finds 93,557 in 0.3s (no further crafty primes below 2\*1010) This is just a naive exhaustive search through all primes. To begin with it checks about 1,000,000 primes every 55 seconds (which is bound to get slower as the primes get larger). I'm using a bunch of helper functions: ``` lookup = { {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, {{}, 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, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0}}, {0, 1, {1, 0}, {1, 1}, {1, 0, 0}, {1, 0, 1}, {1, 1, 0}, {1, 1, 1}, {1, 0, 0, 0}, {1, 0, 0, 1}}, {0, 1, 2, {1, 0}, {1, 1}, {1, 2}, {2, 0}, {2, 1}, {2, 2}, {1, 0, 0}}, {0, 1, 2, 3, {1, 0}, {1, 1}, {1, 2}, {1, 3}, {2, 0}, {2, 1}}, {0, 1, 2, 3, 4, {1, 0}, {1, 1}, {1, 2}, {1, 3}, {1, 4}}, {0, 1, 2, 3, 4, 5, {1, 0}, {1, 1}, {1, 2}, {1, 3}}, {0, 1, 2, 3, 4, 5, 6, {1, 0}, {1, 1}, {1, 2}}, {0, 1, 2, 3, 4, 5, 6, 7, {1, 0}, {1, 1}}, {0, 1, 2, 3, 4, 5, 6, 7, 8, {1, 0}} }; convertBase[d_, b_] := lookup[[b + 1, d + 1]]; related[n_] := ( d = IntegerDigits[n]; {FromDigits[Flatten[convertBase @@@ Transpose[{d, RotateRight@d}]]], FromDigits[Flatten[convertBase @@@ Transpose[{d, RotateLeft@d}]]]} ); crafty[n_] := ( {ql, qr} = related[n]/n; IntegerQ[ql] && ql > 1 || IntegerQ[qr] && qr > 1 ); ``` And then this loop does the actual search: ``` p = 2; start = TimeUsed[]; i = 1; While[True, If[crafty[p], Print@{"CRAFTY PRIME:", p, TimeUsed[] - start}]; p = NextPrime@p; If[Mod[++i, 1000000] == 0, Print[{"Last prime checked:", p, TimeUsed[] - start}] ] ] ``` I'll keep updating the post, if I find any primes or can think of optimisations. It currently checks all primes up to 100,000,000 in about 5.5 minutes. **Edit:** I decided to follow the OP's example and switched to a lookup table for base conversion. That gave roughly a 30% speedup. ## Crafty Numbers in general I'm stopping my search for crafty primes now, since I'd need several days just to catch up with where the Perl answer already got. Instead, I started searching for all crafty numbers. Maybe their distribution helps to find a proof the the number of crafty primes is finite or infinite. I define *right-crafty* numbers those which divide the related number obtained by interpreting the digit to the *right* as the new base, and *left-crafty* numbers accordingly. It will probably help to tackle these individually for a proof. Here are all left-crafty numbers up to 2,210,000,000: ``` {2, 5, 16, 28, 68, 160, 222, 280, 555, 680, 777, 1600, 2605, 2800, 6800, 7589, 7689, 9397, 9777, 16000, 16064, 16122, 22222, 24682, 26050, 28000, 55555, 68000, 75890, 76890, 93557, 160000, 160640, 161220, 247522, 254408, 260500, 280000, 680000, 758900, 768900, 949395, 1600000, 1606400, 1612200, 2222222, 2544080, 2605000, 2709661, 2710271, 2717529, 2800000, 3517736, 5555555, 6800000, 7589000, 7689000, 9754696, 11350875, 16000000, 16064000, 16122000, 25440800, 26050000, 27175290, 28000000, 28028028, 35177360, 52623721, 68000000, 68654516, 75890000, 76890000, 113508750, 129129129, 160000000, 160640000, 161220000, 222222222, 254408000, 260500000, 271752900, 275836752, 280000000, 280280280, 333018547, 351773600, 370938016, 555555555, 680000000, 758900000, 768900000, 777777777, 877827179, 1135087500, 1291291290, 1600000000, 1606400000, 1612200000, 1944919449} ``` And here are all right-crafty numbers in that range: ``` {2, 5, 16, 28, 68, 125, 128, 175, 222, 284, 555, 777, 1575, 1625, 1875, 3449, 5217, 6287, 9375, 14625, 16736, 19968, 22222, 52990, 53145, 55555, 58750, 93750, 127625, 152628, 293750, 529900, 587500, 593750, 683860, 937500, 1034375, 1340625, 1488736, 2158750, 2222222, 2863740, 2937500, 5299000, 5555555, 5875000, 5937500, 6838600, 7577355, 9375000, 12071125, 19325648, 21587500, 28637400, 29375000, 29811250, 42107160, 44888540, 52990000, 58750000, 59375000, 68386000, 71461386, 74709375, 75773550, 93750000, 100540625, 116382104, 164371875, 197313776, 207144127, 215875000, 222222222, 226071269, 227896480, 274106547, 284284284, 286374000, 287222080, 293750000, 298112500, 421071600, 448885400, 529900000, 555555555, 587500000, 593750000, 600481125, 683860000, 714613860, 747093750, 757735500, 769456199, 777777777, 853796995, 937500000, 1371513715, 1512715127, 1656354715, 1728817288, 1944919449, 2158750000} ``` Note that there's an infinite number of left-crafty and right-crafty numbers, because there are several ways to generate them from existing ones: * One can append an arbitrary number of `0`s to any left-crafty number whose least significant digit is greater than its most significant digit to obtain another left-crafty number. * Likewise, one can append an arbitrary number of `0`s to any right-crafty number whose least significant digit in *less* than its most significant digit. This (and the previous statement) is because the `0` will be appended to both the crafty number and its related number, effectively multiplying both of them by 10. * Every odd number of `2`s or `5`s is crafty. * Every odd number of `777`s is crafty. * It appears that an odd number of `28` joined by `0`s, like `28028028` is always left-crafty. Other things to note: * There are at least four 10-digit numbers which consist of two repeated five-digit numbers (which are themselves not crafty, but there might be some pattern here anyway). * There are a lot of right-crafty numbers that are a multiple of `125`. It might be worth investigating those to find another production rule. * I haven't found a left-crafty number that starts with 4 or ends with 3. * Right-crafty numbers can start with any digit but I haven't found a right-crafty number ending in 1 or 3. I suppose this list would be more interesting if I omitted those whose existence is implied by a smaller crafty number, especially since these are never primes by the construction rules discovered so far. So here are all crafty primes that cannot constructed with one of the above rules: ``` Left-crafty: {16, 68, 2605, 7589, 7689, 9397, 9777, 16064, 16122, 24682, 93557, 247522, 254408, 949395, 2709661, 2710271, 2717529, 3517736, 9754696, 11350875, 52623721, 68654516, 129129129, 275836752, 333018547, 370938016, 877827179, 1944919449} Right-crafty: {16, 28, 68, 125, 128, 175, 284, 1575, 1625, 1875, 3449, 5217, 6287, 9375, 14625, 16736, 19968, 52990, 53145, 58750, 127625, 152628, 293750, 593750, 683860, 1034375, 1340625, 1488736, 2158750, 2863740, 7577355, 12071125, 19325648, 29811250, 42107160, 44888540, 71461386, 74709375, 100540625, 116382104, 164371875, 197313776, 207144127, 226071269, 227896480, 274106547, 284284284, 287222080, 600481125, 769456199, 853796995, 1371513715, 1512715127, 1656354715, 1728817288, 1944919449} ``` Note also that there a few *doubly-crafty* numbers (those which appear in both lists and hence divide both related numbers): ``` {2, 5, 16, 28, 68, 222, 555, 777, 22222, 55555, 2222222, 5555555, 1944919449} ``` There exist infinitely many of these as well. ~~But as you can see, except for `16`, `28`, `68` these all consist only of a single (repeated) digit. It would also be interesting prove whether any larger numbers can be doubly crafty without having that property, but that might just drop out as a corollary of a proof for singly crafty numbers.~~ Found the counter-example `1944919449`. [Answer] # Perl (1e5 in 0.03s, 1e8 in 21s). Max 93557 to 1e11. Very similar to the original. Changes include: * transpose the base lookup. Small language-dependent savings. * mod the incremented right shift instead of if. Language dependent micro-opt. * use Math::GMPz because Perl 5 doesn't have auto-magic bigints like Python and Perl 6. * Use 2s <= left instead of int(left/s) >= 2. Native integer shift vs. bigint divide. Does first 1e8 primes in 21 seconds on my fast machine, 3.5 minutes for 1e9, 34 minutes for 1e10. I'm a little surprised it is at all faster than the Python code for small inputs. We could parallelize (Pari/GP's new `parforprime` would be nice for this). Since it is a search we can parallelize by hand I suppose (`forprimes` can take two arguments). `forprimes` is basically like Pari/GP's `forprime` -- it does segmented sieves internally and calls the block with each result. It's convenient, but for this problem I don't think it is a performance area. ``` #!/usr/bin/env perl use warnings; use strict; use Math::Prime::Util qw/forprimes/; use Math::GMPz; my @rbase = ( [ 0,"", 0, 0, 0, 0, 0, 0, 0, 0], [qw/1 0 1 1 1 1 1 1 1 1/], [qw/2 00 10 2 2 2 2 2 2 2/], [qw/3 000 11 10 3 3 3 3 3 3/], [qw/4 0000 100 11 10 4 4 4 4 4/], [qw/5 00000 101 12 11 10 5 5 5 5/], [qw/6 000000 110 20 12 11 10 6 6 6/], [qw/7 0000000 111 21 13 12 11 10 7 7/], [qw/8 00000000 1000 22 20 13 12 11 10 8/], [qw/9 000000000 1001 100 21 14 13 12 11 10/], ); my($s,$left,$right,$slen,$i,$barray); forprimes { ($s,$slen,$left,$right) = ($_,length($_),'',''); foreach $i (0 .. $slen-1) { $barray = $rbase[substr($s,$i,1)]; $left .= $barray->[substr($s,$i-1,1)]; $right .= $barray->[substr($s,($i+1) % $slen,1)]; } $left = Math::GMPz::Rmpz_init_set_str($left,10) if length($left) >= 20; $right = Math::GMPz::Rmpz_init_set_str($right,10) if length($right) >= 20; print "$s $left $right\n" if (($s<<1) <= $left && $left % $s == 0) || (($s<<1) <= $right && $right % $s == 0); } 1e9; ``` [Answer] # C++11, with threads and GMP Timing (on a MacBook Air): * 4 threads + 10^8 in 2.18986s + 10^9 in 21.3829s + 10^10 in 421.392s + 10^11 in 2557.22s * 1 thread + 10^8 in 3.95095s + 10^9 in 37.7009s Requirements: * Needs <https://github.com/kimwalisch/primesieve> and <https://gmplib.org/> * Compile: `g++ crafty.cpp -o crafty --std=c++11 -ffast-math -lprimesieve -O3 -lgmpxx -lgmp -Wall -Wextra` ``` #include <vector> #include <iostream> #include <chrono> #include <cmath> #include <future> #include <mutex> #include <atomic> #include "primesieve.hpp" #include "gmpxx.h" using namespace std; using ull = unsigned long long; mutex cout_mtx; atomic<ull> prime_counter; string ppnum(ull number) { if (number == 0) { return "0 * 10^0"; } else { int l = floor(log10(number)); return to_string(number / pow(10, l)) + " * 10^" + to_string(int(l)); } } inline void bases(int& base, int& digit, mpz_class& sofar) { switch (base) { case 0: sofar *= 10; sofar += digit; break; case 1: sofar *= pow(10, digit); break; case 2: switch (digit) { case 0: sofar *= 10; break; case 1: sofar *= 10; sofar += 1; break; case 2: sofar *= 100; sofar += 10; break; case 3: sofar *= 100; sofar += 11; break; case 4: sofar *= 1000; sofar += 100; break; case 5: sofar *= 1000; sofar += 101; break; case 6: sofar *= 1000; sofar += 110; break; case 7: sofar *= 1000; sofar += 111; break; case 8: sofar *= 10000; sofar += 1000; break; case 9: sofar *= 10000; sofar += 1001; break; } break; case 3: switch (digit) { case 0: sofar *= 10; break; case 1: sofar *= 10; sofar += 1; break; case 2: sofar *= 10; sofar += 2; break; case 3: sofar *= 100; sofar += 10; break; case 4: sofar *= 100; sofar += 11; break; case 5: sofar *= 100; sofar += 12; break; case 6: sofar *= 100; sofar += 20; break; case 7: sofar *= 100; sofar += 21; break; case 8: sofar *= 100; sofar += 22; break; case 9: sofar *= 1000; sofar += 100; break; } break; case 4: switch (digit) { case 0: sofar *= 10; break; case 1: sofar *= 10; sofar += 1; break; case 2: sofar *= 10; sofar += 2; break; case 3: sofar *= 10; sofar += 3; break; case 4: sofar *= 100; sofar += 10; break; case 5: sofar *= 100; sofar += 11; break; case 6: sofar *= 100; sofar += 12; break; case 7: sofar *= 100; sofar += 13; break; case 8: sofar *= 100; sofar += 20; break; case 9: sofar *= 100; sofar += 21; break; } break; case 5: switch (digit) { case 0: sofar *= 10; break; case 1: sofar *= 10; sofar += 1; break; case 2: sofar *= 10; sofar += 2; break; case 3: sofar *= 10; sofar += 3; break; case 4: sofar *= 10; sofar += 4; break; case 5: sofar *= 100; sofar += 10; break; case 6: sofar *= 100; sofar += 11; break; case 7: sofar *= 100; sofar += 12; break; case 8: sofar *= 100; sofar += 13; break; case 9: sofar *= 100; sofar += 14; break; } break; case 6: switch (digit) { case 0: sofar *= 10; break; case 1: sofar *= 10; sofar += 1; break; case 2: sofar *= 10; sofar += 2; break; case 3: sofar *= 10; sofar += 3; break; case 4: sofar *= 10; sofar += 4; break; case 5: sofar *= 10; sofar += 5; break; case 6: sofar *= 100; sofar += 10; break; case 7: sofar *= 100; sofar += 11; break; case 8: sofar *= 100; sofar += 12; break; case 9: sofar *= 100; sofar += 13; break; } break; case 7: switch (digit) { case 0: sofar *= 10; break; case 1: sofar *= 10; sofar += 1; break; case 2: sofar *= 10; sofar += 2; break; case 3: sofar *= 10; sofar += 3; break; case 4: sofar *= 10; sofar += 4; break; case 5: sofar *= 10; sofar += 5; break; case 6: sofar *= 10; sofar += 6; break; case 7: sofar *= 100; sofar += 10; break; case 8: sofar *= 100; sofar += 11; break; case 9: sofar *= 100; sofar += 12; break; } break; case 8: switch (digit) { case 0: sofar *= 10; break; case 1: sofar *= 10; sofar += 1; break; case 2: sofar *= 10; sofar += 2; break; case 3: sofar *= 10; sofar += 3; break; case 4: sofar *= 10; sofar += 4; break; case 5: sofar *= 10; sofar += 5; break; case 6: sofar *= 10; sofar += 6; break; case 7: sofar *= 10; sofar += 7; break; case 8: sofar *= 100; sofar += 10; break; case 9: sofar *= 100; sofar += 11; break; } break; case 9: switch (digit) { case 0: sofar *= 10; break; case 1: sofar *= 10; sofar += 1; break; case 2: sofar *= 10; sofar += 2; break; case 3: sofar *= 10; sofar += 3; break; case 4: sofar *= 10; sofar += 4; break; case 5: sofar *= 10; sofar += 5; break; case 6: sofar *= 10; sofar += 6; break; case 7: sofar *= 10; sofar += 7; break; case 8: sofar *= 10; sofar += 8; break; case 9: sofar *= 100; sofar += 10; break; } break; }; } vector<ull> crafty(ull start, ull stop) { cout_mtx.lock(); cout << "Thread scanning from " << start << " to " << stop << endl; cout_mtx.unlock(); vector<ull> res; auto prime_iter = primesieve::iterator(start); ull num; int prev, curr, next, fprev; int i, size; mpz_class left, right; unsigned long num_cpy; unsigned long* num_ptr; mpz_class num_mpz; while ((num = prime_iter.next_prime()) && num < stop) { ++prime_counter; left = 0; right = 0; size = floor(log10(num)); i = pow(10, size); prev = num % 10; fprev = curr = num / i; if (i != 1) { i /= 10; next = (num / i) % 10; } else { next = prev; } for (size += 1; size; --size) { bases(prev, curr, left); bases(next, curr, right); prev = curr; curr = next; if (i > 1) { i /= 10; next = (num / i) % 10; } else { next = fprev; } } num_cpy = num; if (num != num_cpy) { num_ptr = (unsigned long *) &num; num_mpz = *num_ptr; num_mpz << sizeof(unsigned long) * 8; num_mpz += *(num_ptr + 1); } else { num_mpz = num_cpy; } if ((left % num_mpz == 0 && left / num_mpz >= 2) || (right % num_mpz == 0 && right / num_mpz >= 2)) { res.push_back(num); } } cout_mtx.lock(); cout << "Thread scanning from " << start << " to " << stop << " is done." << endl;; cout << "Found " << res.size() << " crafty primes." << endl; cout_mtx.unlock(); return res; } int main(int argc, char *argv[]) { ull start = 0, stop = 1000000000; int number_of_threads = 4; if (argc > 1) { start = atoll(argv[1]); } if (argc > 2) { stop = atoll(argv[2]); } if (argc > 3) { number_of_threads = atoi(argv[3]); } ull gap = stop - start; cout << "Start: " << ppnum(start) << ", stop: " << ppnum(stop) << endl; cout << "Scanning " << ppnum(gap) << " numbers" << endl; cout << "Number of threads: " << number_of_threads << endl; chrono::time_point<chrono::system_clock> tstart, tend; tstart = chrono::system_clock::now(); cout << "Checking primes..." << endl; using ptask = packaged_task<decltype(crafty)>; using fur = future<vector<ull>>; vector<thread> threads; vector<fur> futures; for (int i = 0; i < number_of_threads; ++i) { auto p = ptask(crafty); futures.push_back(move(p.get_future())); auto tstop = (i + 1 == number_of_threads) ? (stop) : (start + gap / number_of_threads * (i + 1)); threads.push_back(thread(move(p), start + gap / number_of_threads * i, tstop)); } vector<ull> res; for (auto& thread : threads) { thread.join(); } for (auto& fut : futures) { auto v = fut.get(); res.insert(res.end(), v.begin(), v.end()); } cout << "Finished checking primes..." << endl; tend = chrono::system_clock::now(); chrono::duration<double> elapsed_seconds = tend - tstart; cout << "Number of tested primes: " << ppnum(prime_counter) << endl; cout << "Number of found crafty primes: " << res.size() << endl; cout << "Crafty primes are: "; for (auto iter = res.begin(); iter != res.end(); ++iter) { if (iter != res.begin()) cout << ", "; cout << *iter; } cout << endl; cout << "Time taken: " << elapsed_seconds.count() << endl; } ``` Output: ``` Start: 0 * 10^0, stop: 1.000000 * 10^11 Scanning 1.000000 * 10^11 numbers Number of threads: 4 Checking primes... Thread scanning from 25000000000 to 50000000000 Thread scanning from 0 to 25000000000 Thread scanning from 50000000000 to 75000000000 Thread scanning from 75000000000 to 100000000000 Thread scanning from 75000000000 to 100000000000 is done. Found 0 crafty primes. Thread scanning from 50000000000 to 75000000000 is done. Found 0 crafty primes. Thread scanning from 25000000000 to 50000000000 is done. Found 0 crafty primes. Thread scanning from 0 to 25000000000 is done. Found 7 crafty primes. Finished checking primes... Number of tested primes: 4.118055 * 10^9 Number of found crafty primes: 7 Crafty primes are: 2, 5, 3449, 6287, 7589, 9397, 93557 Time taken: 2557.22 ``` [Answer] # C, with GMP, multithreaded (1e8 in 17s for 1 thread) Similar in concept to the rest, with probably a bit of optimizations here and there. Compile: `gcc -I/usr/local/include -Ofast crafty.c -pthread -L/usr/local/lib -lgmp && ./a.out` Please donate your CPU power. I don't have a fast computer. 1e8 in 17 seconds with 1 thread on my macbook air. ``` #include <stdio.h> #include <stdlib.h> #include <sys/time.h> #include <gmp.h> #include <pthread.h> #include <string.h> #define THREAD_COUNT 1 // Number of threads #define MAX_DIGITS 32768 // Maximum digits allocated for the string... some c stuff #define MAX_NUMBER "100000000" // Number in string format #define START_INDEX 1 // Must be an odd number >= 1 #define GET_WRAP_INDEX(index, stringLength) index<0?stringLength+index:index>=stringLength?index-stringLength:index static void huntCraftyPrime(int startIndex) { char lCS [MAX_DIGITS]; char rCS [MAX_DIGITS]; char tPS [MAX_DIGITS]; mpz_t tP, lC, rC, max; mpz_init_set_ui(tP, startIndex); mpz_init(lC); mpz_init(rC); mpz_init_set_str(max, MAX_NUMBER, 10); int increment = THREAD_COUNT*2; if (START_INDEX < 9 && startIndex == START_INDEX) { printf("10 10 2\n\n"); printf("10 10 5\n\n"); } while (mpz_cmp(max, tP) > 0) { mpz_get_str(tPS, 10, tP); int tPSLength = strlen(tPS); int l = 0, r = 0, p = 0; while (p < tPSLength) { char lD = tPS[GET_WRAP_INDEX(p-1, tPSLength)]; char d = tPS[GET_WRAP_INDEX(p , tPSLength)]; char rD = tPS[GET_WRAP_INDEX(p+1, tPSLength)]; if (d == '0') { if (lD != '1') lCS[l++] = '0'; if (rD != '1') rCS[r++] = '0'; } else if (d == '1') { lCS[l++] = (lD != '1') ? '1' : '0'; rCS[r++] = (rD != '1') ? '1' : '0'; } else if (d == '2') { if (lD == '1') { lCS[l++] = '0'; lCS[l++] = '0'; } else if (lD == '2') { lCS[l++] = '1'; lCS[l++] = '0'; } else { lCS[l++] = '2'; } if (rD == '1') { rCS[r++] = '0'; rCS[r++] = '0'; } else if (rD == '2') { rCS[r++] = '1'; rCS[r++] = '0'; } else { rCS[r++] = '2'; } } else if (d == '3') { if (lD == '1') { lCS[l++] = '0'; lCS[l++] = '0'; lCS[l++] = '0'; } else if (lD == '2') { lCS[l++] = '1'; lCS[l++] = '1'; } else if (lD == '3') { lCS[l++] = '1'; lCS[l++] = '0'; } else { lCS[l++] = '3'; } if (rD == '1') { rCS[r++] = '0'; rCS[r++] = '0'; rCS[r++] = '0'; } else if (rD == '2') { rCS[r++] = '1'; rCS[r++] = '1'; } else if (rD == '3') { rCS[r++] = '1'; rCS[r++] = '0'; } else { rCS[r++] = '3'; } } else if (d == '4') { if (lD == '1') { lCS[l++] = '0'; lCS[l++] = '0'; lCS[l++] = '0'; lCS[l++] = '0'; } else if (lD == '2') { lCS[l++] = '1'; lCS[l++] = '0'; lCS[l++] = '0'; } else if (lD == '3') { lCS[l++] = '1'; lCS[l++] = '1'; } else if (lD == '4') { lCS[l++] = '1'; lCS[l++] = '0'; } else { lCS[l++] = '4'; } if (rD == '1') { rCS[r++] = '0'; rCS[r++] = '0'; rCS[r++] = '0'; rCS[r++] = '0'; } else if (rD == '2') { rCS[r++] = '1'; rCS[r++] = '0'; rCS[r++] = '0'; } else if (rD == '3') { rCS[r++] = '1'; rCS[r++] = '1'; } else if (rD == '4') { rCS[r++] = '1'; rCS[r++] = '0'; } else { rCS[r++] = '4'; } } else if (d == '5') { if (lD == '1') { lCS[l++] = '0'; lCS[l++] = '0'; lCS[l++] = '0'; lCS[l++] = '0'; lCS[l++] = '0'; } else if (lD == '2') { lCS[l++] = '1'; lCS[l++] = '0'; lCS[l++] = '1'; } else if (lD == '3') { lCS[l++] = '1'; lCS[l++] = '2'; } else if (lD == '4') { lCS[l++] = '1'; lCS[l++] = '1'; } else if (lD == '5') { lCS[l++] = '1'; lCS[l++] = '0'; } else { lCS[l++] = '5'; } if (rD == '1') { rCS[r++] = '0'; rCS[r++] = '0'; rCS[r++] = '0'; rCS[r++] = '0'; rCS[r++] = '0'; } else if (rD == '2') { rCS[r++] = '1'; rCS[r++] = '0'; rCS[r++] = '1'; } else if (rD == '3') { rCS[r++] = '1'; rCS[r++] = '2'; } else if (rD == '4') { rCS[r++] = '1'; rCS[r++] = '1'; } else if (rD == '5') { rCS[r++] = '1'; rCS[r++] = '0'; } else { rCS[r++] = '5'; } } else if (d == '6') { if (lD == '1') { lCS[l++] = '0'; lCS[l++] = '0'; lCS[l++] = '0'; lCS[l++] = '0'; lCS[l++] = '0'; lCS[l++] = '0'; } else if (lD == '2') { lCS[l++] = '1'; lCS[l++] = '1'; lCS[l++] = '0'; } else if (lD == '3') { lCS[l++] = '2'; lCS[l++] = '0'; } else if (lD == '4') { lCS[l++] = '1'; lCS[l++] = '2'; } else if (lD == '5') { lCS[l++] = '1'; lCS[l++] = '1'; } else if (lD == '6') { lCS[l++] = '1'; lCS[l++] = '0'; } else { lCS[l++] = '6'; } if (rD == '1') { rCS[r++] = '0'; rCS[r++] = '0'; rCS[r++] = '0'; rCS[r++] = '0'; rCS[r++] = '0'; rCS[r++] = '0'; } else if (rD == '2') { rCS[r++] = '1'; rCS[r++] = '1'; rCS[r++] = '0'; } else if (rD == '3') { rCS[r++] = '2'; rCS[r++] = '0'; } else if (rD == '4') { rCS[r++] = '1'; rCS[r++] = '2'; } else if (rD == '5') { rCS[r++] = '1'; rCS[r++] = '1'; } else if (rD == '6') { rCS[r++] = '1'; rCS[r++] = '0'; } else { rCS[r++] = '6'; } } else if (d == '7') { if (lD == '1') { lCS[l++] = '0'; lCS[l++] = '0'; lCS[l++] = '0'; lCS[l++] = '0'; lCS[l++] = '0'; lCS[l++] = '0'; lCS[l++] = '0'; } else if (lD == '2') { lCS[l++] = '1'; lCS[l++] = '1'; lCS[l++] = '1'; } else if (lD == '3') { lCS[l++] = '2'; lCS[l++] = '1'; } else if (lD == '4') { lCS[l++] = '1'; lCS[l++] = '3'; } else if (lD == '5') { lCS[l++] = '1'; lCS[l++] = '2'; } else if (lD == '6') { lCS[l++] = '1'; lCS[l++] = '1'; } else if (lD == '7') { lCS[l++] = '1'; lCS[l++] = '0'; } else { lCS[l++] = '7'; } if (rD == '1') { rCS[r++] = '0'; rCS[r++] = '0'; rCS[r++] = '0'; rCS[r++] = '0'; rCS[r++] = '0'; rCS[r++] = '0'; rCS[r++] = '0'; } else if (rD == '2') { rCS[r++] = '1'; rCS[r++] = '1'; rCS[r++] = '1'; } else if (rD == '3') { rCS[r++] = '2'; rCS[r++] = '1'; } else if (rD == '4') { rCS[r++] = '1'; rCS[r++] = '3'; } else if (rD == '5') { rCS[r++] = '1'; rCS[r++] = '2'; } else if (rD == '6') { rCS[r++] = '1'; rCS[r++] = '1'; } else if (rD == '7') { rCS[r++] = '1'; rCS[r++] = '0'; } else { rCS[r++] = '7'; } } else if (d == '8') { if (lD == '1') { lCS[l++] = '0'; lCS[l++] = '0'; lCS[l++] = '0'; lCS[l++] = '0'; lCS[l++] = '0'; lCS[l++] = '0'; lCS[l++] = '0'; lCS[l++] = '0'; } else if (lD == '2') { lCS[l++] = '1'; lCS[l++] = '0'; lCS[l++] = '0'; lCS[l++] = '0'; } else if (lD == '3') { lCS[l++] = '2'; lCS[l++] = '2'; } else if (lD == '4') { lCS[l++] = '2'; lCS[l++] = '0'; } else if (lD == '5') { lCS[l++] = '1'; lCS[l++] = '3'; } else if (lD == '6') { lCS[l++] = '1'; lCS[l++] = '2'; } else if (lD == '7') { lCS[l++] = '1'; lCS[l++] = '1'; } else if (lD == '8') { lCS[l++] = '1'; lCS[l++] = '0'; } else { lCS[l++] = '8'; } if (rD == '1') { rCS[r++] = '0'; rCS[r++] = '0'; rCS[r++] = '0'; rCS[r++] = '0'; rCS[r++] = '0'; rCS[r++] = '0'; rCS[r++] = '0'; rCS[r++] = '0'; } else if (rD == '2') { rCS[r++] = '1'; rCS[r++] = '0'; rCS[r++] = '0'; rCS[r++] = '0'; } else if (rD == '3') { rCS[r++] = '2'; rCS[r++] = '2'; } else if (rD == '4') { rCS[r++] = '2'; rCS[r++] = '0'; } else if (rD == '5') { rCS[r++] = '1'; rCS[r++] = '3'; } else if (rD == '6') { rCS[r++] = '1'; rCS[r++] = '2'; } else if (rD == '7') { rCS[r++] = '1'; rCS[r++] = '1'; } else if (rD == '8') { rCS[r++] = '1'; rCS[r++] = '0'; } else { rCS[r++] = '8'; } } else if (d == '9') { if (lD == '1') { lCS[l++] = '0'; lCS[l++] = '0'; lCS[l++] = '0'; lCS[l++] = '0'; lCS[l++] = '0'; lCS[l++] = '0'; lCS[l++] = '0'; lCS[l++] = '0'; lCS[l++] = '0'; } else if (lD == '2') { lCS[l++] = '1'; lCS[l++] = '0'; lCS[l++] = '0'; lCS[l++] = '1'; } else if (lD == '3') { lCS[l++] = '1'; lCS[l++] = '0'; lCS[l++] = '0'; } else if (lD == '4') { lCS[l++] = '2'; lCS[l++] = '1'; } else if (lD == '5') { lCS[l++] = '1'; lCS[l++] = '4'; } else if (lD == '6') { lCS[l++] = '1'; lCS[l++] = '3'; } else if (lD == '7') { lCS[l++] = '1'; lCS[l++] = '2'; } else if (lD == '8') { lCS[l++] = '1'; lCS[l++] = '1'; } else if (lD == '9') { lCS[l++] = '1'; lCS[l++] = '0'; } else { lCS[l++] = '9'; } if (rD == '1') { rCS[r++] = '0'; rCS[r++] = '0'; rCS[r++] = '0'; rCS[r++] = '0'; rCS[r++] = '0'; rCS[r++] = '0'; rCS[r++] = '0'; rCS[r++] = '0'; rCS[r++] = '0'; } else if (rD == '2') { rCS[r++] = '1'; rCS[r++] = '0'; rCS[r++] = '0'; rCS[r++] = '1'; } else if (rD == '3') { rCS[r++] = '1'; rCS[r++] = '0'; rCS[r++] = '0'; } else if (rD == '4') { rCS[r++] = '2'; rCS[r++] = '1'; } else if (rD == '5') { rCS[r++] = '1'; rCS[r++] = '4'; } else if (rD == '6') { rCS[r++] = '1'; rCS[r++] = '3'; } else if (rD == '7') { rCS[r++] = '1'; rCS[r++] = '2'; } else if (rD == '8') { rCS[r++] = '1'; rCS[r++] = '1'; } else if (rD == '9') { rCS[r++] = '1'; rCS[r++] = '0'; } else { rCS[r++] = '9'; } } ++p; } lCS[l] = '\0'; rCS[r] = '\0'; mpz_set_str(lC, lCS, 10); mpz_set_str(rC, rCS, 10); if ((mpz_divisible_p(lC, tP) && mpz_cmp(lC, tP) > 0) || (mpz_divisible_p(rC, tP) && mpz_cmp(rC, tP) > 0)){ if (mpz_millerrabin(tP, 25)) { gmp_printf("%Zd %Zd %Zd\n\n", lC, rC, tP); } } mpz_add_ui(tP, tP, increment); } } static void *huntCraftyPrimeThread(void *p) { int* startIndex = (int*) p; huntCraftyPrime(*startIndex); pthread_exit(NULL); } int main(int argc, char *argv[]) { struct timeval time_started, time_now, time_diff; gettimeofday(&time_started, NULL); int startIndexes[THREAD_COUNT]; pthread_t threads[THREAD_COUNT]; int startIndex = START_INDEX; for (int i = 0; i < THREAD_COUNT; ++i) { for (;startIndex % 2 == 0; ++startIndex); startIndexes[i] = startIndex; int rc = pthread_create(&threads[i], NULL, huntCraftyPrimeThread, (void*)&startIndexes[i]); if (rc) { printf("ERROR; return code from pthread_create() is %d\n", rc); exit(-1); } ++startIndex; } for (int i = 0; i < THREAD_COUNT; ++i) { void * status; int rc = pthread_join(threads[i], &status); if (rc) { printf("ERROR: return code from pthread_join() is %d\n", rc); exit(-1); } } gettimeofday(&time_now, NULL); timersub(&time_now, &time_started, &time_diff); printf("Time taken,%ld.%.6d s\n", time_diff.tv_sec, time_diff.tv_usec); pthread_exit(NULL); return 0; } ``` [Answer] # Python, finds 93557 in 0.28s Very similar to OP's code in that it also uses `pyprimes`. I did write this myself though xD ``` import pyprimes, time d = time.clock() def to_base(base, n): if base == 1: return '0'*n s = "" while n: s = str(n % base) + s n //= base return s def crafty(n): digits = str(n) l, r = "", "" for i in range(len(digits)): t = int(digits[i]) base = int(digits[i-1]) l += to_base(base, t) if base else digits[i] base = int(digits[(i+1)%len(digits)]) r += to_base(base, t) if base else digits[i] l, r = int(l) if l else 0, int(r) if r else 0 if (l%n==0 and 2 <= l/n) or (r%n==0 and 2 <= r/n): print(n, l, r, time.clock()-d) for i in pyprimes.primes_above(1): crafty(i) ``` It also prints out the time since start that it finds a number. Output: ``` 2 10 10 3.156656792490237e-05 5 10 10 0.0006756015452219958 3449 3111021 3104100 0.012881854420378145 6287 6210007 11021111 0.022036544076745254 7589 751311 125812 0.026288406792971432 9397 1231007 1003127 0.03185028207808106 93557 123121012 10031057 0.27897531840850603 ``` Format is `number left right time`. As a comparison, OP's code finds 93557 in around `0.37`. ]
[Question] [ A string is [squarefree](http://en.wikipedia.org/wiki/Squarefree_word) if it contains no substring twice in a row. It is possible to have an arbitrarily long squarefree word using a 3-letter alphabet. Write a program which accepts a positive integer n from stdin and prints any squarefree word of length n, using characters `A`, `B` and `C`. Shortest code wins. [Answer] ## Python, 94 ``` n=input() x=[0] exec"x+=[1-y for y in x];"*n print''.join('ABC'[x[i+1]-x[i]]for i in range(n)) ``` It uses the Thue–Morse sequence method from wikipedia. Efficient version (100 chars): ``` n=input() x=[0] while x==x[:n]:x+=[1-y for y in x] print''.join('ABC'[x[i+1]-x[i]]for i in range(n)) ``` [Answer] ## GolfScript (40 27 chars) ``` ~1,{.{!}%+}2$*1,/<{,65+}%n+ ``` The approach is a trivial variant on one of those described in Wikipedia: the run-lengths of 1s in the Thue-Morse sequence. If the extra trailing newline is unacceptable it can be removed at the cost of one character by replacing `n` with `''`. [Answer] ## Python, 129 125 119 Using John Leech's method as described on the linked wiki page. ``` s='A' n=input() while len(s)<=n:s=''.join('ABCBCACABBCAABCCABBCACABABCBCACABBCAABC'[ord(t)%5::3]for t in s) print s[:n] ``` [Answer] ## Python2 - 112 chars This is pretty inefficient. It generates a *much much much* longer string than required and then truncates it. For example the intermediate `s` for `n=7` is 62748517 (13n) characters long ``` s='A' n=input() exec"s=''.join('ABCBCACABBCAABCCABBCACABABCBCACABBCAABC'[ord(t)%5::3]for t in s);"*n print s[:n] ``` [Answer] # Mathematica 159 140 134 **Edit**: A complete rewrite, using recursion (`NestWhile`). Much faster and no wasted effort. **Code** ``` g@n_:=StringTake[NestWhile[#~StringReplace~{"A"-> "ABCBACBCABCBA","B"-> "BCACBACABCACB", "C"->"CABACBABCABAC"}&,"ABC",StringLength[#]<n&],n] ``` **Usage** It takes approximately 1/40 sec to generate a ternary square free word with one million characters. ``` g[10] g[53] g[506] AbsoluteTiming[g[10^6];] ``` ![results](https://i.stack.imgur.com/e9hnU.png) **Verifying** `f` will test whether a string is square free. ``` f[s_]:=StringFreeQ[s, x__~~x__] ``` Checking the above outputs and one case in which the string "CC" appears. ``` f@Out[336] f@Out[337] f@Out[338] f["ABCBACBCABCBABCACBACCABCACBCABACBABCABACBCACBACABCACBA"] ``` > > True > > True > > True > > False > > > ]
[Question] [ In these previous challenges[[1]](https://codegolf.stackexchange.com/q/249026/)[[2]](https://codegolf.stackexchange.com/q/248966/) I've been dealing with "mushroom forests". To help with these I draw little diagrams of the forests to help. In this challenge we are going to reverse engineer the data from these diagrams. To recap *ha!* mushroom forests are a list of pairs of non-negative integers. Each pair represents a mushroom whose center is at that horizontal coordinate. The only part of the mushroom we care about is the cap (the flat bit at the top). The first integer in each pair represents which row the cap is placed in. i.e. the height of the mushroom. The second integer represents the radius of the cap. If it's zero then there just isn't a mushroom in that position. Other for size \$n\$ a total of \$2n-1\$ spaces are occupied centered at the index of the pair. For example `1` means that its cap only occupies a space above it, a `2` means it occupies a space above it and the spaces one unit to the left and right. To draw the data I represent rows using lines of text separated by newlines. There are twice as many lines as there are rows with the even rows being used for spacing. I draw the caps using the `=` and I only draw caps on *odd* numbered lines. If a mushroom cap is present at coordinate \$(x,y)\$ I draw an `=` at \$(2x,2y+1)\$. Here's an example: ``` = = = = = = = = = = = = = = = = = = = = = = = = = = = [ 2,3,9,1,0,1 ] <- Widths [ 0,1,2,3,2,1 ] <- Heights ``` Then between `=`s of the same height I add an extra `=` if they belong to the same mushroom. ``` = ================================= ========= ===== = [ 2,3,9,1,0,1 ] <- Widths [ 0,1,2,3,2,1 ] <- Heights ``` Then I draw stalks extending from the bottom row up to the cap the correspond to. If there's already a `=` in a space I leave it alone. I don't draw any stalks for mushrooms with width `0`. ``` = | ================================= | | ========= | | | ===== | | = | | | | | [ 2,3,9,1,0,1 ] <- Widths [ 0,1,2,3,2,1 ] <- Heights ``` ## Task Your task is to take as input a string of an ascii diagram as described above and output the list of widths used to draw that diagram. We don't care about the heights at all. You may output trailing and leading zeros in your result, as they don't change the diagram. You may also assume that the input is padded to a perfect rectangle enclosing the bounding box of the art. You may assume that there is always a valid solution to the input and you do not have to handle malformed input. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the goal is to minimize the size of your source code as measured in bytes. ## Test cases Test cases are provided with all leading and trailing zeros trimmed in the output, however the output is aligned to the input for clarity. ``` = | ================================= | | ========= | | | ===== | | = | | | | | [2,3,9,1,0,1] = = | | [1,1] ===== ===== | | [2,0,0,0,0,2] ===== ============= = | | | | ===== | ===== | | | | | ===== ========= | | | | | | | [2,2,2,0,0,4,0,3,2,1] ===== = | | ===== ========= | | | | [2,2,0,1,3] ============= | ============= | | ===== | | | | = | | | | | | | ===== | | | | | | | | [2,1,2,4,4] ``` [Answer] # [Python](https://www.python.org), 125 bytes ``` import re def f(s): o=[0]*len(s[0]) for l in s: for m in re.finditer("=+",l):o[sum(m.span())//4]=len(m[0])//4+1 return o ``` [Attempt This Online!](https://ato.pxeger.com/run?1=hZOxTsMwEIYHNj_FyZNNQ1okBlTJE1JfonQoaiKMEjty3AHpeBKWLvBO8DScW9LYSdR6Se7y-fd_v5XP7-bdv1pzOHztfXn3-POh68Y6D65gu6KEUrRyycCq9WJzWxVGtPQiGZTWQQXaQEtfj1UdKlfkpTY77QsnuJrxrJJLu273tajzttkaIeV8_rBRQakOSlTN7hnt83tnwJ5M_N48rVS1rV92W9JvnDZe8Iznb1aTAe-EkeFEE04kg6RcaV9pU7SkL3MidCP4IuNSspXgnD-Tx-FSaTlB4IBQ19ZIA0ca0fnduugDr2v8E2qS6BQwnYcykazPRkHwTlTS791102GkChNskgaMdpyex26njQN1jFg8sgMXZxYjFkfeu30qSiTKYOiXwTkjnMgH0smifPGsn87e3wFGTH9j8T3hkBl1MOn0t94zmDLB_-lf6n7sPw) Bad, terrible, no good. Need variable-length lookbehind. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~23~~ ~~20~~ 16 bytes ``` OḂŒgÄ=U×ƊF€Sm2HĊ ``` [Try it online!](https://tio.run/##y0rNyan8/9//4Y6mo5PSD7fYhh6efqzL7VHTmuBcI48jXf8f7t5yuL3EwFsz8v//aCUlpRguBQxgi8rFoqIGTYUtIcCFaUINTlvguvC6o4awGVAVtjjMqIGbgWQOMEx0uKABY6sAcjhQCUIQ4S6Yv2qQQwVdIUogKGAoh9BgUZjBNWhG1yCprQGrRXMCXG0NktoaVFfDNNkihQKSv9Edy6UAD5ca9DBRUMAVsTVww1F9jQj0GiQ1iChCjpgadDUYIjUoIohoRqipQVUDdHcsAA "Jelly – Try It Online") *-3 thanks to Jonathan Allan, also opening up another -1 (`×=¥UFƊ€` -> `=U×ƊF€`)* ``` Ä Ɗ Consider the cumulative sums of Œg the runs in each row of OḂ whether or not each character is an equals sign Ḃ (ones bit of O the codepoints). = For each element of each cumsummed run, is it equal to U the corresponding element of the run backwards? × Multiply it by the result. F€ Flatten each row, S Sum each column, m2 remove alternating elements, H halve, Ċ and ceiling. ``` [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 39 bytes ``` ^ ¶ (=*)=\1 $1!$1 {*.\Cm`^!|\G== m`^.. ``` [Try it online!](https://tio.run/##K0otycxLNPz/P47r0DYuDVstTdsYQy4VQ0UVQ65qLb0Y59yEOMWaGHdbWy4gS0@P6/9/WxBQsEUGCrZcCgo1CjAAY9WARSEqIKJgNlRtDZLaGrBamEoFhOlgtTVIasE8AA "Retina – Try It Online") ## Explanation `^`, `¶`: Add a line feed at the start of the string. `(=*)=\1`, `$1!$1`: Match each mushroom, and change the centre character to a `!`. `{`: Repeat until no change: * `*.\Cm`^!|\G==`: + `C`: Count matches of `^!|\G==`: `!` at the start of a line (`m` makes `^` match the start of each line), or `==` immediately after the previous match (`\G`). This gives the size of a half-mushroom with its centre at the start of a line, if there is one, or 0 if there is none. (The added empty line at the start of the string makes sure `\G==` does not match at the start of the string.) + `\`: Output the result of the above. + `*`: Do not change the working string. (According to [the documentation](https://github.com/m-ender/retina/wiki/The-Language#output----), this should not be necessary as "output stages are purely used for their side effect and will never affect the working string themselves", but that doesn't seem to be what actually happens?) + `.`: Disable implicit output. * `m`^..` (with an empty second source): Remove the first two characters of each line. (This is implicitly a Replace stage.) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 21 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` '=QεγεƶÐÅsQ*}˜}øOιн;î ``` Port of [*@UnrelatedString*'s Jelly answer](https://codegolf.stackexchange.com/a/249329/52210), since it's shorter than any monstrosity I was attempting.. Input as a (right-padded) matrix of characters. Output as a list of doubles with leading/trailing 0s. [Try it online](https://tio.run/##yy9OTMpM/f9f3Tbw3NZzm89tPbbt8ITDrcWBWrWn59Qe3uF/bueFvdaH1/03ODzr8Pr/0dFKCko6CrQhbKlkVKyOAi2dWUNNZ9rCPT5YCZqEZg1tQpPMNEcsMbjSZs0QCk0inGk7EKFZQ3JokhPCsbEA) or [verify all test cases](https://tio.run/##yy9OTMpM/V@mFFCUWlJSqVtQlJlXkpqikJlXUFpipaCkU6nDpeSYXFKamIMkpuf0qGlNsO1/ddvAc1vPbT639di2wxMOtxYHatWenlN7eIf/uZ0X9lofXvcfpjW/tASq15YL3SqEnMHhWYfX63Ad2mb/P1pJAQPYxuRhCtbE5NkSApj6akD6kEzGpbIGq0qwMIZ7aqAQyFLSUbIFSddAmGA9cN0gXTUIXXAFKE5WQFeG8C6IAzOyBt3QGiTVUKejWY9QXYOkGswDOgWmHOq3GqQQxtSuANekoIAzwBFuwJSFBy40WGEySMFui8ypgXEQ0VCD8AvIMbEA). (Footer `0Úï` is to pretty-print the output; feel free to remove it to see the actual output.) **Explanation:** ``` '=Q '# Check for each character in the (implicit) input-matrix if it's a "=" ε # Map over each row of 0s/1s: γ # Split it into groups of adjacent equal elements ε # Inner map over each group: ƶ # Multiply each value by its 1-based index Ð # Triplicate this list Ås # Pop one, and push the middle item Q # Pop another, and check which values are equal to this middle * # Multiply each at the same positions to the remaining list }˜ # After the inner map: flatten the list of groups }ø # After the outer map: zip/transpose; swapping rows/columns O # Sum each inner list (the columns) ι # Uninterleave it into two parts н # Pop and only leave the first part ; # Halve each value î # Ceil each value # (after which the result is output implicitly) ``` `ÐÅmQ*` could alternatively be `Z>;Qƶ` for the same byte-count: ``` Z # Push the maximum (without popping the list) > # Increase it by 1 ; # Halve it Q # Check which values are equal to this middle ƶ # Multiply each value by its 1-based index ``` [Answer] # [Haskell](https://www.haskell.org), ~~161~~ 160 bytes *-1 bytes thanks to [@Unrelated String](https://codegolf.stackexchange.com/users/85334/unrelated-string)* ``` p[]=[] p(x:y:z)=map(`div`4)[y-x+3,x+y]:p z m=map(=='=') f a=[sum[w|[w,x]<-concat[p[j|(j,x,y)<-zip3[0..](m$' ':b)$m$b++" ",x/=y]|b<-a],x==y]|y<-[1..length$a!!0]] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=jVLdToMwFI6X9ik6QgKEFrfMC0M4L-Ctl02TlbkNJmWNgLSkb-INN8Zn0qcR3Ug0YuZ3c3pyvn75zs_zayaqh01R9P1LU2_pzVuvGAfGkfJ1bOIuACmUv7rPn1bXATNUh0uiQ8NjhTskv4oAHngB2mIBrGokay1rieYJXR_KtaiZYnvr74kmJkhol6slm0cR96XrYS9OA1e6aRg62CH6Cgy3aUIFJxo-3yahbBFFxabc1ZkrZrM550ef7xe3AgNm6NLBvwA_U4dMsuwEC85hUstOan3zM-KsL_s_rRML_mSNSvbUp8MRkiIvhy-qqe_qR-ziKju0Qxj2dhzpeAIf) [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 18 bytes ``` C∷ƛĠv¦ƛṘ=*;f;∑y_½⌈ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJD4oi3xpvEoHbCpsab4bmYPSo7ZjviiJF5X8K94oyIIiwiIiwiW1wiICAgICAgICAgICAgICAgICAgPSAgICAgICAgICAgICAgXCIsXCIgICAgICAgICAgICAgICAgICB8ICAgICAgICAgICAgICBcIixcIj09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PVwiLFwiICAgICAgICAgICAgICAgIHwgfCAgICAgICAgICAgICAgXCIsXCIgICAgICAgICAgPT09PT09PT09ICAgICAgICAgICAgICBcIixcIiAgICAgICAgICAgICAgfCB8IHwgICAgICAgICAgICAgIFwiLFwiICAgICAgICAgID09PT09IHwgfCAgID0gICAgICAgICAgXCIsXCIgICAgICAgICAgICB8IHwgfCB8ICAgfCAgICAgICAgICBcIl0iXQ==) Port of Jelly. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 36 bytes ``` WS⊞υιIΦEEθ⌕⭆υ§λκ=|∧⊕ι⊕⊘L⊟⪪…§υικ ¬﹪κ² ``` [Try it online!](https://tio.run/##TY7BasMwDIbveQrRkwzeZdeSQymUBdoR6BOYxNSmmp2lTreB391TlIXlByPp59Mvd86MXTRUypfzZAGbMEzpmkYfbqgUtNPD4aTBq33VspnwaB4JT56SHfFiBnmfGk4@9LjszQ6vHFITevuNpOGulIZdnXdzPTDYhG60HzYk26Nnbzu/GXpyOdtwSw7bOOB1IM@HfzqyR8fzmiz/mtM5HDhbpOE9JrzEfqKIdw2v4u5LqWdBvRXUFUCGVWuXxV2IxZX@j80bNgu7kvCfLmzesDJV5eVJvw "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a list of newline-terminated strings. Explanation: ``` WS⊞υι ``` Input the forest. ``` Eθ⌕⭆υ§λκ=| ``` Find the first positions of all of the substrings `=|` in the columns, if any. ``` E...∧⊕ι⊕⊘L⊟⪪…§υικ ``` For each column, if the substring was not found then return `0` otherwise truncate the row containing the mushroom at the column, split on spaces, and take the incremented halved length of the last substring, which will be the row of `=`s to the left of the middle of the mushroom. ``` IΦ...¬﹪κ² ``` Output alternate columns, since we're not interested in the other columns. ]
[Question] [ ## The Narrative You are a bad musician. You never bothered to learn how to count rhythms. To remedy this shortcoming, you decide to write a program that will tell you how to count in any given time signature. You are still a bad musician, but you can at least pretend that you can count rhythms. ## The Objective Given a time signature, output a possible counting pattern for said time signature. **For those who don't know musical terms:** A [measure](https://en.wikipedia.org/wiki/Bar_(music)) is, essentially, a group of notes, useful for organizing music and making sure the musicians don't lose their place in the music. A [time signature](https://en.wikipedia.org/wiki/Time_signature) is a set of numbers in a piece of music which tells you how many beats are in a measure, and which note-length is the beat. For example, a `3/4` time signature tells you that each measure has `3` beats, and the quarter note (`4`) is the beat. An `11/16` T.S. tells you that there are `11` sixteenth note beats (`16`) in one measure. A [counting](https://en.wikipedia.org/wiki/Counting_(music)) pattern is a way to verbally express the division of a measure. For example, a song in `3/4` can simply be counted as `"1 2 3"`. `11/16` can be counted as `"1 la li 2 e & a 3 e & a"` (this is more intuitive than counting to 11; I will define this later) *It's important to note that the bottom number of almost all T.S.'s are a power of 2. For this challenge, we will ignore irrational T.S.'s. We will also not look at T.S.'s with a beat greater than 16.* **How to Generate a Counting Pattern:** Time signatures with a `X/1`, `X/2`, or `X/4` can simply be counted with numbers (`4/2` can be counted as `"1 2 3 4"`). T.S.'s with a `X/8` or `X/16` are a bit more tricky. These can be counted by grouping beats together to form larger beats (`6/8`, despite having `6` 'beats', is very often treated as `2` beats with a triplet subdivision). **For this challenge, beats should be grouped in groups of `1`(`"1"`), `2`(`"1 &"`), `3`(`"1 la li"`), or `4`(`"1 e & a"`)** For `X/8`, groups of `3` should be prioritized over `2`, but `1` should be avoided if possible. (For `7/8`, even though `3+3+1` prioritizes `3`'s, `3+2+2` is better because it avoids `1`) For `X/16`, groups of `3` should be prioritized over `4`, but `2` and `1` should be avoided if possible. (For `11/16`, even though `3+3+3+2` prioritizes `3`'s, `3+4+4` is better because it avoids `2`) *It is important to note that the ordering of the groups is not important, i.e. `3+2` and `2+3` are both acceptable groupings of `5/8`. This would be important normally, but you are a bad musician.* *Also note that T.S.'s 'larger' than `1/8` can be grouped entirely with `2`'s and `3`'s; T.S.'s 'larger' than `5/16` can be grouped entirely with `3`'s and `4`'s.* Whew! What a mouthful! ## The Specs **You will take a time signature as input.** this may be formatted within reason (use common sense!). **You will output an acceptable counting pattern.** This will be a string of counts (`1`, `la`, `&`, etc.) separated by spaces. Your output should not include leading or trailing whitespace. **Test Cases:** *To clarify, the 'numerator' is a positive integer, and the 'denominator' is `1`, `2`, `4`, `8`, or `16`.* *Again, note that some T.S.'s have multiple valid outputs.* ``` "Input", "Output" "1/1", "1" "3/2", "1 2 3" "4/4", "1 2 3 4" "1/8", "1" "10/8", "1 la li 2 la li 3 & 4 &" "2/16", "1 &" "5/16", "1 la li 2 &" "29/16", "1 la li 2 la li 3 la li 4 la li 5 la li 6 la li 7 la li 8 e & a 9 e & a" "Input", "Invalid Output" "6/4", "1 la li 2 la li" "7/8", "1 la li 2 la li 3" "10/8", "1 & 2 & 3 & 4 & 5 &" "12/16", "1 e & a 2 e & a 3 e & a" ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins! [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~372~~ ~~354~~ ~~308~~ ~~301~~ ~~299~~ ~~260~~ ~~240~~ ~~237~~ 233 bytes ``` #define p!printf(" %d%s"+!i++,i,a #define q(x,y,z)(j=n%3-z/4)|n<z?p[x]),~j:p[y])+p[y])-z; *a[]={""," &"," la li"," e & a"};f(n,d,i,j){for(i=0;d<5&&n--;)p[0]);n+=d-8?0:q(j,1,4)for(n+=d<16?0:n<2?p[0])-n:q(j=j?j+3:1,3,8)n>0;n-=3)p[2]);} ``` [Try it online!](https://tio.run/##Zc/LboMwEAXQPV/huALZ9VjFQKIU4/IhiAXiUdlKXfKolEDpr1MTqQuazWh0dHVHU/P3up7np6bttG1Rv@lP2l46gpHf@GfMNpox0FB5f4kjucINBkqMsn7Mh5eEfttsyPviWlL4MWlf3ErK7pMP0nuuilKNGANGwTIOFTroZWlRgCo8yY5YaNwJQ8fu80S0CmWTbYPAci5pX4QllZaphu/zMD0SAwISugQXzMTOqc2i/B7kdkkokxsWpwJi2FP7FkrLVeyaItc0ze479FFpS6g3eh0RIKjsvy5ngjGVDmKI1pC4eysQrnYN4X@JQOzWsn2Q6PWBxF28af4F "C (gcc) – Try It Online") *-24 bytes thanks to ceilingcat* *-46 bytes thanks to ceilingcat* *-7 bytes thanks to ceilingcat* *-2 bytes thanks to ceilingcat* *-39 bytes thanks to both Juan Ignacio Díaz and ceilingcat* *-20 bytes thanks to both Juan Ignacio Díaz and ceilingcat* *-3 bytes thanks to ceilingcat* *-4 bytes thanks to ceilingcat* [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 46 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` Œṗi@€o⁸Ṁ;ṢƊɗÞ:5×6Œ?Ɗ}Ḣị““&“la li“e & a”˹Ƈ€K€K ``` A full program that accepts the beats and the note-length and prints the result **[Try it online!](https://tio.run/##y0rNyan8///opIc7p2c6PGpak/@occfDnQ3WD3cuOtZ1cvrheVamh6ebHZ1kf6yr9uGORQ93dz9qmANEakCck6iQkwmkUxXUFBIfNcw9Mu3QzmPtQEO8Qfj///9Glv8NzQA "Jelly – Try It Online")** ### How? ``` Œṗi@€o⁸Ṁ;ṢƊɗÞ:5×6Œ?Ɗ}Ḣị“...”˹Ƈ€K€K - Main Link: beats, B; note-length L Œṗ - all integer partitions of B } - using L: Ɗ - last three links as a monad - f(L): e.g. 1,2,4,8,16 :5 - integer divide by 5 -> 0,0,0,1,3 ×6 - multiply by six -> 0,0,0,6,18 Œ? - shortest permutation of [1..N] which has that lexicographic 1-based-index in a list of all permutaions of [1..N] -> [],[],[],[3,2,1],[3,4,2,1] (our ordering) Þ - sort (the partitions) by: ɗ - last three links as a dyad - f(Partition, Ordering) € - for each (run-length, R) in the partition: i@ - first 1-indexed index of R in Ordering or 0 o⁸ - logical OR with the Partition (vectorises) (replaces 0s with the larger, original Rs) Ɗ - last three links as a monad - f(X): Ṁ - maximum of X Ṣ - sorted X ; - concatenate Ḣ - head “...” - ["", "&", "la li", "e & a"] ị - index into Ė - enumerate (i.e. [A, B, ...] -> [[1,A],[2,B],...]) € - for each: ¹Ƈ - keep truthy (i.e. drop the "" entries) K€ - join each with spaces K - join with spaces - implicit print ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 52 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` 5‹iLëÅœΣ4LRIg·†3†Rsk{}θε…e&aN>©š®D'&‚®…ÿ…å´à)ćè]˜ðý? ``` Two separated inputs \$a\$ and \$b\$, where \$b\$ is the beat and \$a\$ are the amount of notes in the measure. *†*If the input was as strict as the output, a trailing `'/¡`©` (+5 bytes) could be added and the `I` could be replaced with `®`. [Try it online](https://tio.run/##yy9OTMpM/f/f9FHDzkyfw6sPtx6dfG6xiU@QZ/qh7Y8aFhgDcVBxdnXtuR3ntj5qWJaqluhnd2jl0YWH1rmoqz1qmHVoHVD08H4QsfTQlsMLNI@0H14Re3rO4Q2H99r//29oxmVkCQA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWXCoZX/TR817Mz0Obz6cOvRyecWm/gEHVqXfmj7o4YFxkAcVJxdXXtux7mtjxqWpaol@tkdWnl04aF1LupqjxpmHVoHFD28H0QsPbTl8ALNI@2HV9TWnp5zeMPhvfb/D22z/x8dbahjGKsTbaxjBCRNdEyApKGOBYg0AFNGOoZmQMoUQhlZQmgzsEJziEKwklgA) or *†*[try it online with strict input format](https://tio.run/##AW0Akv9vc2FiaWX//ycvwqFgwqk14oC5aUzDq8OFxZPOozRMUsKuZ8K34oCgM@KAoFJza3t9zrjOteKApmUmYU4@wqnFocKuRCcm4oCawq7igKbDv@KApsOlwrTDoCnEh8OoXcucw7DDvT///zE2LzI5). `4LR®g·†3†R` could alternatively be `4L14S.I®gè` for the same byte-count: [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWXCoZX/TR817Mz0Obz6cOvRyecWm/gYmgTreR5al354RXF2de25Hee2PmpYlqqW6Gd3aOXRhYfWuairPWqYdWgdUPTwfhCx9NCWwws0j7QfXlFbe3rO4Q2H99r/P7TN/n90tKGOYaxOtLGOEZA00TEBkoY6FiDSAEwZ6RiaASlTCGVkCaHNwArNIQrBSmIB). **Explanation:** ``` 5‹i # If the first (implicit) input is smaller than 5 (1, 2, or 4): L # Push a list in the range [1, second (implicit) input] ë # Else (it's 8 or 16 instead): Åœ # Get all lists of positive integers that sum to the second # (implicit) input Σ # Sort it by: 4LR # Push list [4,3,2,1] I # Push the second input again g # Pop and push its length · # Double it † # Filter that value to the front 3† # Then filter 3 to the front R # And then reverse the list # (we now have [1,4,2,3] for input=8 # and [1,2,4,3] for input=16) s # Swap so the current list k # Get the index of each in this list (or -1 if higher) { # Sort that list from lowest to highest }θ # After the sort: leave the last list # (so `Σ...}θ` acted as a maximum-by builtin) ε # Map that resulting list to: …e&a # Push string "e&a" N> # Push the 1-based map-index © # Store it in variable `®` (without popping) š # Convert the string to a list, and append it: # ["e","&","a",index] ® # Push index `®` again D # And again, with a duplicate '&‚ '# Pair it with "&" ® # And yet again …ÿ…å´à # Push dictionary string "ÿ la li", # where the `ÿ` is replaced with this index ) # Wrap all values into a list ć # Extract the head; the current list of the map è # Modular 0-based index those into the list ] # Close both the map and if-else statement ˜ # Flatten the list of lists ðý # Join it with a space delimiter ? # Explicitly print it without trailing newline ``` [See this 05AB1E tip of mine (section *How to use the dictionary?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `…ÿ…å´à` is `"ÿ la li"`. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 70 bytes ``` NθNη⪫E⊟Φ…⟦Eθ¹E÷⁺²θ³⁻³‹ι﹪±θ³E÷θ³⁺³‹ι﹪θ³⟧⊕÷η⁸⁼θΣι⁺⊕κ§⪪“/^e)R⁼0⁷Vⅉ8⮌✳”,ι ``` [Try it online!](https://tio.run/##ZY3BSsNAEIbvfYphD2UC46EWReip1BYiWgI9ioc1GczgZpNNdos@/bpJPATd087/z/dNWeu@bLWJMbdd8OfQvHOPLtutlnOd5qIX6/GpFYsvusOi7fAkxqf28F0aPtQpeB0bR7DJCMZvbv2jXKViLEwY8JbApWY7tmJTsCV45mFASUFbBdPimT@0Z5zX0vvrcTM@6f7T7pd6I8ht2XPD1nO1wGuCh8l6dEGbYQQuoUGZT03WJfiZwr3PbcVfeOmMeFTAsAZNBGsCo8GIIlCk0qJMDgUqy3Yx3q029/Hman4A "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` NθNη ``` Input the time signature. ``` ⟦Eθ¹E÷⁺²θ³⁻³‹ι﹪±θ³E÷θ³⁺³‹ι﹪θ³⟧ ``` Try to create three beat patterns: all single beats, as many groups of three as possible with the rest two, and as many groups of three as possible with the rest four. ``` …...⊕÷η⁸ ``` Only consider the first or first two patterns depending on the denominator. ``` Φ...⁼θΣι ``` Only keep those patters that actually sum to the whole bar. (This prevents e.g. `5/16` from trying to use groups of three and four). ``` ⪫E⊟...⁺⊕κ§⪪...,ι ``` Take the last successful pattern and replace each group with its beat number and group suffix obtained by splitting the compressed string `e & a,, &, la li`, finally joining the groups with spaces. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 56 bytes ``` 5<[ɾ|Ṅµ1k½d⁰LǔJ3Jvḟs;tṘ¨2›:£`e&a`fJ¥:\&"¥«cb|«"ṄWḣi;]fṄ₴ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJUIiwiIiwiNTxbyb584bmEwrUxa8K9ZOKBsEzHlEozSnbhuJ9zO3ThuZjCqDLigLo6wqNgZSZhYGZKwqU6XFwmXCLCpcKrY2J8wqtcIuG5hFfhuKNpO11m4bmE4oK0IiwiIiwiMTZcbjI5Il0=) Port of 05AB1E. Quite slow. [Answer] # [Python 2](https://docs.python.org/2/), ~~136~~ 135 bytes *-1 byte thanks to Kevin Cruijssen* ``` def f(m,b,r='',i=1): while m:k=b<5or[m,3-(m<5)+(6<m<9)*b/9][m>2+b/8];m-=k;r+=' '+`i`+[' e & a',' la li',' &',''][-k];i+=1 print r[1:] ``` [Try it online!](https://tio.run/##jVDtaoMwFP3vU1wYGF0iXWK0fmUvIkIrUxo0bZHC2NO7GFMts4X90JN7zsm5R68/t9PlzMbxq2mh9RSpySAQIlJQP3Pg@yT7BlTWibqILkOpSBh4qoh87MWFKlL/vd6lVak@Ga53SZWrQHT5gAUChA/ygEsEDbhwRARBf4ReTgdXv1BVBl2VSyyoA9dBnm8wlDSrxtajhPoA8AbUab2QMDsAg1ATjPCF0CN/GCEE7kz3k/U@XwZdg@lHc/HKmU6aN6il/VZydayrpeTFLSvTD6M/lYEbCyM0thbXVFtG84@matHKLftN4w29Nt5IJs00/rNgldIXgbrtPVh/0OR5ZrmnULqxzIseLOxlyox8WcjS/1khshhb3FtM7PZ0xvEX) Takes input as `f(m,b)` where `m` is the numerator and `b` is the denominator ### Explanation ``` while m: ``` Loop while `m` > 0 ``` k=b<5or[m,3-(m<5)+(6<m<9)*b/9][m>2+b/8] ``` Determine the size of the next group. Essentially the logic is as follows: * `b in [1,2,4]` => **1** * `b == 8 and m == 4` => **2** * `b == 16 and m in [7,8]` => **4** * `(b == 8 and m <= 3) or (b == 16 and m <= 4)` => **m** * otherwise => **3** ``` m-=k;r+=' '+`i`+[' e & a',' la li',' &',''][-k];i+=1 ``` Decrease `m` by the group size. Append the following to `r`: First a space, then the current group index, then the appropriate suffix based on the group size. Increment the group index ``` print r[1:] ``` Output the constructed string, removing the leading space ]
[Question] [ Given an unordered list of musical pitches, write the shortest program/function (scored in bytes) to sort the list from lowest pitch to highest. Pitches will be given in [scientific pitch notation](https://en.wikipedia.org/wiki/Scientific_pitch_notation), consisting of a tone name followed by an octave number. Here, the tone name will be a single letter A–G, possibly followed by a single `#` or `b` character (representing sharp and flat, respectively). The octave number will be a single digit 0–9. From lowest to highest, the order of pitches in this notation may be represented as follows: ``` <--- lower pitch higher pitch ---> _______________________________________________________________ Cb0 C0 C#0 Db0 D0 D#0 Eb0 E0 E#0 Fb0 F0 F#0 Gb0 G0 G#0 Ab0 A0 A#0 Bb0 B0 B#0 Cb1 C1 C#1 Db1 D1 D#1 etc. ``` In this representation, pitch rises from left to right, so vertically aligned notes ([enharmonic pairs](https://en.wikipedia.org/wiki/Enharmonic)) have the same pitch. Each row contains three notes in the order flat, natural, sharp (e.g. Cb0, C0, C#0) and the order of rows within an octave is C, D, E, F, G, A, B. Notice that by a quirk of the notation, the indentation pattern differs for the C and F rows. Your code may sort enharmonic pitches in any order. For example, given `[D#0, Eb0, D#0]` as input, any of `[D#0, D#0, Eb0]`, `[D#0, Eb0, D#0]`, and `[Eb0, D#0, D#0]` is a valid output. ### Test cases ``` [A2, B2, C2, D2, E2, F2, G2, A3] -> [C2, D2, E2, F2, G2, A2, B2, A3] [E5, D#5, E5, D#5, E5, B4, D5, C5, A4] -> [A4, B4, C5, D5, D#5, D#5, E5, E5, E5] [E#6, Fb6, B#6, Cb7, C7] -> [Fb6, E#6, Cb7, B#6, C7] or [Fb6, E#6, Cb7, C7, B#6] ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~31 30~~ 29 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` FµḢ“¤ı¶“Œ’ḥ;ṪV×12Ʋ;=”#Ḥ’ƊSµ$Þ ``` A monadic Link that accepts a list of lists of characters and yields a sorted version. **[Try it online!](https://tio.run/##y0rNyan8/9/t0NaHOxY9aphzaMmRjYe2ARlHJz1qmPlwx1LrhztXhR2ebmh0bJO17aOGucoPdywByhzrCj60VeXwvP8Pd2w63O79/7@rqYKLsqkCgnIyUXAxVXA2VXA0AQA "Jelly – Try It Online")** ### How? ``` FµḢ“¤ı¶“Œ’ḥ;ṪV×12Ʋ;=”#Ḥ’ƊSµ$Þ - Link: notes $Þ - sort by: last two links as a monad: µ - monadic chain: F - flatten (this is to get a copy so we don't alter what we are sorting in place) µ - monadic chain: Ḣ - head of note (removes it too) ḥ - hash with salt & domain: “¤ı¶“Œ’ - base 250 numbers = [256628,20] X = CDEFGAB -> 4,6,8,9,11,13,15 Ʋ - last four links as a monad: Ṫ - tail of note (removes it too) V - evaluate as Jelly code -> integer 12 - twelve × - multiply Y = 12 × octave ; - concatenate -> [X,Y] Ɗ - last three links as a monad - f(v): (v being one of [], ['#'], or ['b']) =”# - equals '#'? (vectorises) Ḥ - double ’ - decrement O = accidental offsets [], [1], or [-1] ; - concatenate -> [X,Y]+O S - sum -> note number ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~92~~ 83 bytes *-9 bytes thanks to [G B](https://codegolf.stackexchange.com/users/18535/g-b)* ## Golfed code ``` lambda l:sorted(l,key=lambda i:12*int(i[-1])+" D EF G A B".find(i[0])-ord(i[1])/48) ``` [Try it online!](https://tio.run/##Xcy9DoIwAATg3adoytIKqPwohoSh5e8hCAMEiI0IBFl4@soZB8Py5dredVqXxzh4uouY7qtX3VSkD9/jvLQN661nu0a/WxU67lENC1OF7ZTcpCQhaUZyIoikp04NzfZyKbk9zkhb5ezfueaHacaqYwUVLrWoBDFIQAoykAPh0ZL/b9IrmgbcR@njjBQD4e@nxg1/11B@c1wHMEBRfwA) ## Commented code ``` lambda l: sorted(l, # Sort the list key=lambda i: # Key used to sort the list, takes a single string as input # Outputs an integer; the lower the integer, the lower the note 12 * int(i[-1]) # Multiply the octave number by 12 + " D EF G A B".find(i[0]) # Add the number of the note within that octave; # C = -1 up to B = 10 -ord(i[1])/48 # Subtract the ASCII code of the second character; # Ends up with sharpened notes having higher values than # no-accidental ones, which have a higher value than flattened ones ) ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 99 bytes ``` n=>n.sort((a,b,l=e=>`b${D=e.slice(-1)}#`.search(e[1])+12*D+'C D EF G A B'.search(e[0]))=>l(a)-l(b)) ``` [Try it online!](https://tio.run/##hY3BasMwEETv/QqBA9I2trHTtDnJYEtOPqIEIrlK4yCsYJlcSr/dnRZKaS45vNlZdmf3bK4mdmN/mbIhvLn5KOdBVkMewzgJYVKbeulkdbCLDy1dHn3fOZGV9Jkc8ujM2J2Eey33tCxXj3rJFdOs3bIdq1nD/xaKPZGsvDCUeWGJ5i4MMXiX@/AujoLXq5Q1QAENWrAFO1A/4dDF95PgKeNE9HATbp8RSiD/TLNGg6pAvb53InnBQwtpvp2yG8jmTkjZAlugBfrXl/A/g6S4yc9f "JavaScript (Node.js) – Try It Online") [Answer] # APL+WIN, 83 bytes Prompts for notes as nested vector ``` m←⊃3↑¨¯1⌽¨s←⎕⋄s[⍋((¯1×m[;3]='b')+m[;3]='#')+(12×(⍎¨m[;1]))+¯1+'C D EF G A B'⍳m[;2]] ``` [Try it online! Thanks to Dyalog APL Classic](https://tio.run/##XY29CoJgFIb37yo@cDiKNKj9DNGgZhEUXUA4aFEESoFTc1FRKTVEt@DW0Nxid3JuxM6pppaH55z3/ATLqDJZBdFiVhlHQZLMxyVm10Eft2dLkPWGZIbA/W5axqR4WFu4vRR5cTfw9CzyhJvZFY@bZITpUVUpeN3iUdPyWxCCpv9UIVUN83VTMc2KnLqGr2k6Tevgyrb0OrIrbekApg8KTd8v6akopwJsEyQ4DJfRZniMDqPLsC0QNOnVOFeY/@pUuWZzGXb1u6DU@U7IdD7uhg1mA8Qb "APL (Dyalog Classic) – Try It Online") Here is an improved 68 byte version but it does not work on Dyalog because of ⎕fi ``` s[⍋∊(¯1+'C D EF G A B'⍳↑¨s)+(+/¨((⊂'b#')∊¨s)ר⊂¯1 1)+12×+/¨⎕fi¨¨s←⎕] ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 70 bytes ``` ->l{l.sort_by{|x|x[-1].ord*12+"C D EF G A B".index(x[0])-x[1].ord/48}} ``` [Try it online!](https://tio.run/##RYzdSsNAFITvfYphF8GfTUxOsq03CvuT5CGWpbDUglCsRMUtbZ89nii2F/MNzJwz41faT5unqXjeHrblx278XKX94ZiPORR1LHfj@q6me@Hg0fUYYGBF@fq2fsk3OVTxtsjh7@yhfTydpndsQhAm1UIJK4npUsP0smKaNHOoRIxX8@X1dzAES3AET@gIPWEgmCZGyOBIcaw4V1wobhQMy87enCc6DS81LmZbeA2nYdrfHdPyD8tp3psl/9GddVmTC/RpAcvu0hJuGeP0Aw "Ruby – Try It Online") [Answer] # JavaScript (ES6), ~~87 86~~ 85 bytes *-1 thanks to [@l4m2](https://codegolf.stackexchange.com/users/76323/l4m2)* ``` a=>a.sort((a,b)=>(g=([a,b,c])=>(b|c)*12+' D EF G A B'.search(a)-!!c+2*(b<g))(a)-g(b)) ``` [Try it online!](https://tio.run/##bY29DoJAEIR7n@KAgl3@EhGlERL@H8JQ3J2AGsIZIFa@O8raGZpvZjaZ2Qd/8UmO9@fsDuraLG208Cjm3qTGGYA7AqMYugguX@vIek3iLdHa@7bJclaUrGIJS01vavgob8DR1TRp@xaIc4e45g4E4iLVMKm@8XrVQQsXPfF1h@kpMSPmxIJYEitictBrxN3/QHGkkkGyEdKATuQzYhJsDxkneilI0l/KREgSrpXlAw "JavaScript (Node.js) – Try It Online") ### Commented ``` a => // a[] = input array a.sort((a, b) => // for each pair of notes (a, b) to be sorted: ( g = // g is a helper function taking a note ([a, b, c]) => // split into [a, b, c] (c may be undefined) (b | c) // use whichever of b or c is a digit ... * 12 // ... as the octave + ' D EF G A B' // add the index of the leading letter: .search(a) // "CDEFGAB" -> [-1,1,3,4,6,8,10] - !!c // subtract 1 if there's an accidental + 2 * (b < g) // add 2 if the accidental is '#' )(a) // invoke g with the 1st note - g(b) // invoke g with the 2nd note and subtract ) // end of sort() ``` [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 95 bytes ``` \d $*-===$& - 12$*= (.+?)=+ $1$& #= == b= [CDE]= $&= T`L`56d`.= \d= $*=$&$*= O$`.+?(=+). $1 = ``` [Try it online!](https://tio.run/##RcuxDoIwGEXh/b4GlSBcSKgUpj8GSnExcdBNTCrBwcXB@Gw@gC@GdXI6yUm@5@11f1yXVXL0XMYZKs1FRMXIUWqVCpIi264lgyrDjAQimAQ4295dBCoWnPzem3r2hWCcw0oD/8mD8sEmkq2LoCFYPm9waTU7TavZazrNQXOn2W7gDPvI8J@uYm9oDdsKLqo5TDW7UDs1tM0X "Retina 0.8.2 – Try It Online") Takes newline-separated input but link is to test suite that converts from and to comma-separated input. Explanation: ``` \d $*-===$& - 12$*= ``` Representing the pitch in unary using `=` signs, multiply the octave by `12` and add `3` (so that I can subtract `2` from it later without it falling to zero). ``` (.+?)=+ $1$& ``` Duplicate the note name. ``` #= == b= ``` Adjust the pitch for a sharp or a flat. ``` [CDE]= $&= T`L`56d`.= \d= $*=$&$*= ``` Adjust the pitch according to the note name. ``` O$`.+?(=+). $1 ``` Sort by the pitch. ``` = ``` Delete all of the `=` signs. [Answer] # [JavaScript (Node.js)](https://nodejs.org), 81 bytes ``` a=>a.sort((a,b)=>(g=([a,b,c])=>(c|b)*7+('0x'+a-5||4)%7-(c?b>g?.6:-.6:0))(a)-g(b)) ``` [Try it online!](https://tio.run/##bY3NCoJQEIX3PUUo4Ux6RcofCFTUrIcQF/feVArxhkq08N1Np120mO@cMzBnHvzFB9nfnyPr1K2a63DmYcTtQfUjALcEhhE0IRSLtWS5JjkJ3AcmGM7bMDnzpsnFXcBAxiJqYts/sWUcRODIGhCIs1TdoNrKblUDNRRactCsrZYSM@KZmBMvxCsxOWol4ua3IPfoSCf5E1KXVuQzYuL@L9J9eilI0m/KREASrCfzBw "JavaScript (Node.js) – Try It Online") Notice that we needn't care whether difference between each pair of letter is 1/2 or 1, just give them 3/4 works ``` #C #D #E #F #G #A #B C D E F G A B C bD bE bF bG bA bB bC [][ ][][ ][ ][ ][ ][][ ][][ ][ ][ ] ``` [Answer] # [Scala](http://www.scala-lang.org/), 59 bytes A port of [@G B' Ruby answer](https://codegolf.stackexchange.com/a/244119/110802) in Scala. --- Golfed version. [Try it online!](https://tio.run/##hY9BT4MwFMfvfIqXcmmdImzIjAlLWmBcNj3saJaFjs5gSCFrDzXGz47ySMwOxl1@v76m7//6zLFqq6GT7@poYVs1GpSzStcGeN/Dp@dBrU5gurN97qwyT0A3jbGvO3tu9Ns@XV1WDNLhEIxvxQd16coFbWXsTTSfkQxyKNZQAgdBgkbXyr2cqKMhY3eORuw@fmQDQP@TY1tNf@fhNEq4jMgtEOHPR2VyMSr3w1FcosqQMMa8fzKwV0wJyBxZINfIEskXV6KKh2k@6o9CxHiF5wzJ42uRfoLfkMm0aDItukQtsflr@AY) ``` _.sortBy(x=>x.last*12+"C D EF G A B".indexOf(x(0))-x(1)/48) ``` Ungolfed version. [Try it online!](https://tio.run/##hU9Na4NAFLznVwzm4vbDxsQmpZDCaowU@nHosfSwxk1jkTW4S0ko/nbrPqVSKM1l5r3dmXnv6Y0oRNOU6YfcGDyKXEEejFSZBt/v8TUCMrmFLivzVBqpXWXxFg@5Nq8vpsrV@xv73WJJNoCknrWGR/Jhedd/AZ@iIEG0E5VuLbb2TGlbXlXi2Mt@JF4htGkF98rgDP4U53AirBCvkYAjdLxcZfLwvHUHy06KjOFyCHF91kdcIbihETVrqR61sG@3N4Vyh1vtVa7DU9@5gBOOp5aidGZpNZ5Y4ilRMnEYY/9lkDfsEghXhDHhmjAh5LMTUfF1N5/ojyYM6InqiJAHpyLHc1ojnXeHzrtDF0QLMtdN8w0) ``` object Main extends App { def sortNotes(notes: List[String]): List[String] = { notes.sortBy(note => { val noteChars = note.toCharArray noteChars.last.toInt * 12 + "C D EF G A B".indexOf(noteChars.head) - noteChars(1).toInt / 48 }) } println(sortNotes(List("Ab1", "B#2", "Cb3", "D#0", "Ab0", "G0"))) println(sortNotes(List("A2", "B2", "C2", "D2", "E2", "F2", "G2", "A3"))) println(sortNotes(List("E5", "D#5", "E5", "D#5", "E5", "B4", "D5", "C5", "A4"))) println(sortNotes(List("E#6", "Fb6", "B#6", "Cb7", "C7"))) } ``` ]
[Question] [ ## Introduction: [Beckett Grading Service (aka BGS)](https://www.beckett.com/grading), is a company which encapusulates and grades Trading Card Game (TCG) cards (i.e. sport cards, Magic The Gathering, Pokémon, Yu-Gi-Oh, etc. etc.). The TCG cards that come in for grading will be checked on four categories (which we will later refer to as subgrades): centering, corners, edges, and surface. These subgrades will be in the range \$[1, 10]\$ in increments of \$0.5\$. Based on these four subgrades, the graded card is also given a final grade (in the same range). This final grade isn't just an average however. To quote [the BGS FAQ page](https://www.beckett.com/grading/faq) (minor note when reading: the *grading level/point* they're talking about is a step of 0.5): > > **Here is how we do it!** > > The overall numerical grade is not a simple average of the four report card grades. Beckett Grading Services uses an algorithm which determines the final grade using the 4 sub grades on the front label of the card holder. The lowest overall grade is the first category to observe because it is the most obvious defect, and the lowest grade is the most heavily weighted in determining the overall grade. > > > **Example :** > > Centering = 9.5; Corners = 9.5; Edges = 9; Surface = 8 > > Final grade = 8.5 > > > The reason that this card received an 8.5 is that even though the Surface grade was an 8 (the lowest grade overall), the 9.5 grades on Centering and Corners were strong enough to bring it up a full point to reach the 8.5 level. > > > **Another example :** > > Centering = 9.5; Corners = 9.5; Edges = 8.5; Surface = 9 > > Final grade = 9 > > > Upon first glance, it may appear that this card should've received a grade different than a 9. The most this card could receive was .5 (or one-half grade) above the lowest sub-grade. The Edges were the lowest in this case, hence, the card received the overall 9 grade. Even though Centering and Corners received grades of 9.5, a key point to remember is that the minimum requirement to receive a grade of Gem Mint is to have at least three grades of 9.5 and the fourth to be no less than a 9. > > > Also, please note that the final grade rarely, if ever, exceeds two levels above the lowest of the four characteristic grades. For example, if a card has characteristic grades of Centering 10, Corners 6, Edges 10 and Surface 10, the final grade will be a "7" (of which is exactly two grading levels above the lowest characteristic grade). > > > Although the algorithm they use to determine the final grade has never been revealed, someone was able to come up with a set of rules as algorithm for determining the final grade based on the four subgrades by looking at as many example graded cards as possible ([source](https://www.spinotron.com/bgs.html)): In pseudo-code: ``` Sort subgrades in decreasing order var fourth = fourth number in this order # so the lowest subgrade var third = third number in this order # so the second to last subgrade - could be equal # to the lowest of course) var first = first number in this order # so the highest subgrade var diff = third - fourth # difference between these two lowest subgrades var finalGrade # our final grade we're calculating If diff == 0: finalGrade = fourth Else: If fourth is Edges OR fourth is Surface: If diff < 1: finalGrade = fourth + 0.5 Else: If (diff == 1 AND fourth + 1 >= 9.5) OR (first - fourth == 1.5 AND first != 10): finalGrade = fourth + 0.5 Else: finalGrade = fourth + 1.0 Else-if fourth is Centering: If diff < 2: finalGrade = fourth + 0.5 Else-if diff < 4: finalGrade = fourth + 1.0 Else: finalGrade = fourth + 1.5 Else(-if fourth is Corners): If diff < 3: finalGrade = fourth + 0.5 Else: finalGrade = fourth + 1 ``` Some examples: * 9.5 8.5 7.5 9.5 = 8.5: `fourth` number is Edges (7.5); `diff` is 1.0. So the final grade becomes `fourth + 1.0`. * 10 10 10 8.5 = 9.5: `fourth` number is Surface (8.5); `diff` is 1.5. So the final grade becomes `fourth + 1.0` (with a different if-else path than the one above) * 9.5 9.5 9 8 = 8.5: `fourth` number is Surface (8); `diff` is 1.0; `first` number is 9.5. So the final grade becomes `fourth + 0.5`. * 5.5 8.5 9 7 = 6: `fourth` number is Centering (5.5); `diff` is 1.5. So the final grade is `fourth + 0.5`. * 5 7 9 9.5 = 6: `fourth` number is Centering (5); `diff` is 2. So the final grade is `fourth + 1`. * 4.5 9 9.5 9 = 6: `fourth` number is Centering (4); `diff` is 4.5. So the final grade is `fourth + 1.5`. * 9 6.5 9 9.5 = 7: `fourth` is Corners (6.5); `diff` is 2.5. So the final grade is `fourth + 0.5`. In summary: Corners is punished hardest, Centering next, Surface/Edges the least. How much the overall grade is better than the worst subgrade depends on which subgrade is the worst, and also depends on how much the other three subgrades are better than the worst subgrade, measured by `diff`. [Here an ungolfed reference implementation of the described algorithm in Java.](https://tio.run/##rVZdT9swFH3vr7jrA0qgTZtC23RZkap9vYxNouwJ8WAat4SVpHIcJAT97d2NHSd2khaYJgUn9jn33A/bl96TR9K9D/7sdos1SRK4IGH03AJIOOHhAh7jMABOE24FcXq7prCgEacsjFYdUCsxiyhLijkNVrScJSlbkgW1M02A@VPC6YMTp9zZoAhfR1b7OyMBTT5CG05KdfxuyxWpXsyFejFT6n5LyEuf1ze4frsSsjCFZy3kItY8yNx@6wvze6yFk/Jw7cwYI0@Jk8SMW4WW7WtOYBmnjN@hfoFf928MBr8LWWAQXJOwDFnCDcKpSViRDcJSp5t7NFJFiYisRQWlYbi0hNEU@rZYAI2CWkojA@g6oc85Ce1UQtO8xi8vUC6Z26h5Op@Cq62KdRWCC0dHSuMEZ8idOENbI6MTS1ahqzlznaGwFMAHnPdtw0VjTuih7wx9jbbVEzxk5xpWrb32b/CqrIWtWdXiGNaL@AkG9nsdKQfS/uwN9q7/3tTcvan1jivJyYtlH/cakjv9p@Tel1BLf2/3NptvmRCI2yY7TqmcX@8GK4Fss3u3wUuHXVFvjg/YMK05zzYWGw850Ohmn69@z37A1df51Ryd5/5Ec3X7HSj/bB96PXw349kV2ktAcL9CDjYTNPAVBTlIAn6XDE8AlSgnGt6B7MlYnoK9SgRe6aFBYZgB43KQhFGThqdF6RlRKqwZFgpnxTBQUZzWSCN8xLs5irF4PAmOK2A5eA1pjssECgW9UKKO4@Yqmtvk1bQFXtlEE/UO18Yryl/s0B6SGEaKNNZJ@oEuK1CTmVRqoBOGepHqJ0HuwESLUgPP1AHQqjAyCjwqGbUddDFu@eS3xIQqd2hQy7uCt/Z2jG7bYXRDCZ6Iof1Kf2pWuJz9/PLrotpzljGzkADh1O37EHa75/gqmrQIdEWxnxNOL0kUxA@iQVp2B/7Dch7DVvXUvJmqnzxNJjIyRnnKIvyFyu8cFqdRYFnyW1AtG45hkv1XyD4GNmBlA9m4t7vdXw) (It can also be used to generate more random test cases; see the bottom section of the output.) ## Challenge: Given the four subgrades as input, output the final grade based on the algorithm above. ## Challenge rules: * Input may be in any reasonable format. Can be four separated inputs. A sorted list. Etc. Make sure to state the order of the subgrades centering, corners, edges, surface you've used. Inputs can be as decimal numbers, strings, or other reasonable input-types. + If your language doesn't have a numeric type that allows decimal values, or if you choose to, you are allowed to take all inputs multiplied by 10 as integers (as long as it's consistent). I.e. instead of `4.5 8 9.5 6.5` you could also take the input as `45 80 95 65`. In which case the output is of course similar. *Make sure to mention in your answer if you're using integers which are multiplied by 10!* * Output may be returned by a function in any reasonable type, output to STDOUT/STDERR/Exit Code, etc. * Of course you don't have to follow the algorithm exactly as described above. As long as it gives the correct result for any of the 130321 possible test cases, it's fine to implement it in any way you'd like. If you think hard-coding all possible test cases is shorter in your language of choice, by all means go for it. ## 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 with [default I/O rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/), so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call. * [Default Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. * If possible, please add a link with a test for your code (i.e. [TIO](https://tio.run/#)). * Also, adding an explanation for your answer is highly recommended. ## Test cases: ``` Centering Corners Edges Surface = Final grade 10 10 10 10 = 10 10 10 10 9.5 = 10 10 10 9.5 10 = 10 10 9.5 10 10 = 10 9.5 10 10 10 = 10 10 9.5 9.5 9 = 9.5 8.5 9 10 9.5 = 9 8 8 8.5 8.5 = 8 9.5 8.5 9.5 9.5 = 9 5.5 7.5 7.5 7 = 6 9.5 8.5 8.5 9 = 8.5 8 8.5 9 9 = 8.5 9.5 4.5 4.5 2.5 = 3.5 9.5 6 6.5 6 = 6 9.5 7 7 8 = 7 9.5 9.5 9.5 8.5 = 9 7.5 8.5 9 8 = 8 9 8 7 8.5 = 8 10 9.5 9.5 8 = 9 10 9 9.5 9 = 9 10 8 9 9 = 8.5 9.5 8.5 7.5 9.5 = 8.5 9.5 8.5 8.5 6.5 = 7.5 10 10 10 8.5 = 9.5 9.5 9.5 9 8 = 8.5 5.5 8.5 9 7 = 6 5 7 9 9.5 = 6 4.5 9 9.5 9 = 6 9 6.5 9 9.5 = 7 1 1 1 1 = 1 1 10 10 10 = 2.5 10 1 10 10 = 2 ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~73~~ 71 bytes ``` ≦⊗θ≔⌊θη≔⁻⌊Φθ⁻κ⌕θηηζI⊘⁺η∧ζ⎇⌕θη∨⎇⊖⌕θη∨›²ζ∨∧⁼²ζ‹¹⁶η∧⁼³⁻⌈θη›²⁰⌈θ›⁶ζ²⊕⌊⟦²÷ζ⁴ ``` [Try it online!](https://tio.run/##VZBNT8MwDIbv/AofU8kgKGwI7TRRBkhU7MCt6iG0EY1IM5qkFezPB2ddus7Kh/LYrz9SNdxUO668z/nP2lr5pVm26z@VqBG6ZHVxZLnUsu1b1iUIzRnu7eTcSOWEYR3CyL8RNlLXATQJWbgQ9iTfGqkde@TWsReuBlGzrSJBg7Cm@D3ChzCamz920iO8GxZxJiojWqEdKWclDjHPRvDQRhpKHUjI@dT1XNkI34S17GZ5FM38t7H3nP/OBqZjSntNIZNzHCv6liE7vVPar/rUYvygIg3cZXKQtQhj3iVlMtrK@6JYINwjPNC6WpSlvxzUPw "Charcoal – Try It Online") Link is to verbose version of code. Takes input as an array of 4 values [Centring, Corners, Edges, Surface]. Explanation: ``` ≦⊗θ ``` Double all the values so we're dealing in grade points rather than grades. ``` ≔⌊θη ``` Find the worst grade. ``` ≔⁻⌊Φθ⁻κ⌕θηηζ ``` Find the worst of the other grades, i.e. the second worst, and subtract the worst grade. ``` I⊘ ``` Halve the final value and cast to string for display. ``` ⁺η ``` Add the bonus to the minimum grade. ``` ∧ζ ``` No bonus if the worst two grades are the same. ``` ⎇⌕θη ``` Check whether the worst grade was for Centring. ``` ∨⎇⊖⌕θη∨›²ζ∨∧⁼²ζ‹¹⁶η∧⁼³⁻⌈θη›²⁰⌈θ›⁶ζ² ``` If not then check whether only one bonus point should be awarded otherwise award two bonus points. (If the worst grade was for Corners then add a bonus point if the difference was less than 6 grade points or 2 if it was 6 or more. The calculation for Edges and Surface is longer but still only adds one or two bonus points.) ``` ⊕⌊⟦²÷ζ⁴ ``` If the worst grade was for Centring then add a bonus point for every 4 grade points between the worst two grades up to 2, plus a further bonus point. [Answer] # Perl 5 (`-ap`), ~~157~~ 154 bytes minor improvements `!$d?0:...` inverted to `$d?...:0`, `>=9.5` changed to `>9.4` and `!=10` to `<10` ``` ($w,$x,$y,$z)=sort{$b<=>$a}@F;$d=$y-$z;$_=$z+=$d?$z==$F[2]|$z==$F[3]?$d<1?.5:$d==1&$z+1>9.4|$w-$z==1.5&$w<10?.5:1:$z==$F[0]?$d<2?.5:$d<4?1:1.5:$d<3?.5:1:0 ``` [TIO](https://tio.run/##lZTfboIwFMbveQouTsj@KFKE0iqVXe0lFrO44MUSM4yaOJl79TGQWk4rdBlXH/A7X8/5Wtiud5u42k@E/zCZeN5unRfz6g6OI/gcwWkE5b3YF7vDF7ylYgGr76fnOeQCTmMo5/AqoHwUkGdQCgHPL@HyLNV0mUGeksyPZzUuiFeDZMH96AzHccMQP/bgmJKgQchMlgWXsrAtS6OMzEgrpy0WVBUJ3OulpBTqXjTasZDcj/8iJTLsqTz6V1ev/9OnKpKCux1ZP3JYZ8rd4ZG4w5Slq6QsZghkuE1mLq45xh2YXKUUCeqS9jqy23FYMw7qUi1ujCdR5BpdpRQh6nOqo1SJ9hkd6jQxBENggkFzh5gWUtKX5q1jHXvP/iRG4QW0HA7syDXQqOBDIDMqLKEzY8/x4RhCpaAIratt36WWpu7KbXnWaDwcvX4@4y76xJwfLU@dqOdj60mU4s2k5jHGszukA4khCHIkGmj5eYRGmq4F/Sm2h/fiY1@NV5vtLw) first answer was ``` ($w,$x,$y,$z)=sort{$b<=>$a}@F;$d=$y-$z;$_=$z+=!$d?0:$z==$F[2]|$z==$F[3]?$d<1?.5:$d==1&$z+1>=9.5|$w-$z==1.5&$w!=10?.5:1:$z==$F[0]?$d<2?.5:$d<4?1:1.5:$d<3?.5:1 ``` straight forward, ungolfed ``` !$d?0 :$z==$F[2]|$z==$F[3]? $d<1?.5 :$d==1&$z+1>=9.5|$w-$z==1.5&$w!=10?.5 :1 :$z==$F[0]? $d<2?.5 :$d<4?1 :1.5 :$d<3?.5 :1 ``` [TIO](https://tio.run/##lZTfboIwFMbveYqanPhnQ6QoUMSKV76EMcbFXZiYScTEydyrj4GWclqBZVx9wO98PedrIX4/HdwsGXHrZTQKF0uexIf9ud8jPZPAxiT2IMz6cDHh04SrCemAJ8fT@QveZnwO2@/FMoQdh@sQ0hA2HNJX3oFdZE8h5RyWK2d9E2q8jmA3o5HlTvMKTrs5S@c8sNwbXIYFRC23C5cOp3YB0dLCvhc6j8LZJKJT@pDjO5Zl1CblJaUQ8p4X2mgh8z7@IgXS7Ck96leXr//TpywSIiAVmT8yWGUakOaRAoNJSyKlKGYIZLhNpi@uOLoV6JdSCB916dU6sudxWDEO6lIuro0nUOQ6KaUQDupzrKKeFI9nXlOnviYYAn0M6jvElJD8ujSfHfPYa/bH1wrvYMvhwI6BAmoVQRPItIqW0Jm25/hwNKFCeAjNq9u@SyVN1TVoyzNH3ebo1fPpVtH7@vxoec@Y1HxsNYl6eDM9/Rjj2Q1agVQTFDlSBWz5eThamqQF/TnG5/3xI8mG20P8Cw) [Answer] # [JavaScript (V8)](https://v8.dev/), ~~160 159 154~~ 151 bytes ``` s=>{[C,O,E,S]=[...s];[a,b,c,d]=s.sort((a,b)=>b-a);e=c-d;return(e?d==E|d==S?e<1?.5:(e==1&d>8.4)|(a-d==1.5&a<10)?.5:1:d-C?e<3?.5:1:e<2?.5:e<4?1:1.5:0)+d} ``` [Try it online!](https://tio.run/##JU49D4IwFNz9FUymje0LVYkIPBiMs4MjYShtYzAGTIss4m/HZxzucl/D3fWkg/Hdc5RTukzaR13/jDCqj5CIlHAgkG5WZujD8HDwGG6MLQHLd30SF3EW1wZrAAhNXmvRCiNsgwHC4EfGKOBYtlLz3KGRNvdufPmeucoinmeia@UKVUGSMYeo1rZMYc9npiV1CpK1LlTMf73KrDzRePc3rtj@hCv2lcpomMV8Yz8LZ/Sf83z5Ag "JavaScript (V8) – Try It Online") ## A bit ungolfed: ``` function calculateScore(score) { [center,corner,edge,surface] = [...score]; // makes a copy because sort is in-place [first,second,third,fourth] = score.sort((a,b)=>b-a); // standard sort is alphabetically, this will sort by value diff = third - fourth; return fourth + (// Every final score is fourth + something else diff != 0 ? fourth == edge || fourth == surface ? diff < 1 ? 0.5 : (diff == 1 && fourth >= 8.5) || (first-fourth == 1.5 && a < 10) ? 0.5 : 1 : fourth != corner ? diff < 3 ? 0.5 : 1 : diff < 2 ? 0.5 : diff < 4 ? 1 : 1.5 : 0 // diff == 0 ); } ``` * -1: `>=8.5` -> `>8.4` * -5 thanks to @Kevin Cruijssen * -3 for ES6 copying with `[...s]` [Answer] # [Python 3](https://docs.python.org/3/), 132 bytes ``` def f(a):c,C,*_=a;w,x,y,z=sorted(a);d=x-w;return(x>w)*[[2-(d<1or d==1<w-7or z-w==1.5>z-8.5),3-(d<2)-(d<4)][w==c],-~(d>=3)][w==C]/2+w ``` [Try it online!](https://tio.run/##lVRNj4IwED0vv2KSvVC3uCsI1I96Mbt/YL0ZsyFQXRODpmBQD/vXXUCECi0qBxycvvemM6/dHePfbWidzwFbwlL30NDHU9z5od4owQd8xCcabXnMgjQ1CujBSEacxXse6odJgjrzuWnowbi35RBQ2hsnhpuGJyNJP7r25GSQro2wla0xUfbuo8U8TfoLbPzpwYRal@/p4t18S/IiZrrPwpjxCPtbHma/LFixCEd7vvR8hlfcCxgaasBZtN/EQNOy562QBdJgx9dhDPoFQ2lOggsKpGmvL9OcYR2uAKYXEoDPjAXg@0IDqRR8rUNvAzlcm@m9DwDAkD9VnEX45p8izh50Fzbo2s/AsuUPq1Xcd4tslPH83iqKa5EDqGWvMCKoVYtkLRmAoEYEviomhZpISkCxN9IsUqVmCwm3jN0C5gq1OPfViKQl5KYl9QS@FtQKE9X6Zdwv1Ewha6lgTsntFDDnkb1VDXCLQNyCq4I1XUJUA3Dlc5Oo3Y5b6pKySJVL2q0sqg2UMIC2E6CCVdxPjZs0PNnIPuZJp270x24uUp/qnXHL5ibC7NZxK8@bXXfdbSfrRr/C@tIrSDY3R2Uup3lM6@ej7KQAq@JeETSyUljrrWwq5watsFLt/A8 "Python 3 – Try It Online") [Answer] # JavaScript (ES6), ~~115 ... 105~~ 102 bytes Takes input as an array. ``` a=>([w,d,,b]=([C,c]=a).sort((a,b)=>a-b),(d-=w)?(w-C?w-c?d<1|(w>8?d:b-w-.5)==1:d<3:d<4?d<2:3)||2:0)/2+w ``` [Try it online!](https://tio.run/##fVQ9k4IwFOz9Fa8jGQOnqBg4A4VjdYUztkyKCHof44iDznGF/90LAQkBtXA12bd5m33gj/gV5yT/Pl3sY5bubnt2EyxEcUFSQracoXhJEs4Eds5ZfkFIkC1mobC3mKDUZgWOUGEvo8JOonQxvqIipFEabO3CdmaYsXGQLibyM5WsG0zw9eoGI/zmDovbezwAiGMYjwgYwGt8RPvO7AktmSfqO9OnDeaVuioEn9cOFE3rTdNaWVSpgZZLCaqQ1jRt96bN4V31rNycNwAwV7TXU1NtjTbWdNvKX4dW6mkDruo9MWnZi4BX/@r3loYaoLw2qGkNtHOxedu0VtPGuV@npg7vptYbCTUzV2Msj2hNrEfTV7HQJvNqJI9oBZ6i5zpz80mtnPum2u/cWx8@68ZizhtAZ@7rp@VOTxuhcW@vHarXrjEmJg2XyxbwGlt05y1xO/du1yi1ywfc2Wf5SiRfCMWCQM4xsBCS7HjODjvnkH3KvxMYgmVh5yTS1TFFYw@XG3YIlvxG6A8Y7JHA2CybluuSZJBDBNb6w4IArNVms95YGOPbPw "JavaScript (Node.js) – Try It Online") or [compare all results](https://tio.run/##lVTbbqMwEH3nK6YvrS0MhaSRuklMVPUzEFoRMClVBCtDlocl354dX7g0UbvdB8BzOWduHt7T32mTyfJX61V1Li4H4EDiTFStkGV1YJDVshKyYSDyg8BPc5JFmomEAo/gjwMQF/VJtm8M2rdS5gx@MihK2bQJMn2HyG9q2RKSMthrzhQ8PCFxXhYFcmha1JkwGwctZUGMkUOgPAGkaE@ysj6oEcdGaAO6GqVy1pGh72FS2SwMy8S8hXBQXZGDC4G/srYxjMWOaYVwfz8BQog4/PBXVMUmujtjQdrbX2l/bbhDOaBT9K/iX2Vw6xr6gTO4fezFOJnb0hffLX2GefocM@Rwleyt2@qzVM3NuU10@d8zugnqnB0HJ3ZJeUTijuWM7RNO4leWJTyl493cUx6l3p4yknu8ozvSea@7zst2@TbsSRc97/L13us8nDHn4TrfLvF5QutivaR9v1gH9HHhdpeilqTCSy2kxHfApjGgGG5m4lZdg7nC5aooqndO0diuWJwVBpQV5xiDMiugMeZoEUb46G8QdkMMZhAsahCvcQAvavvh3@sPyWa@QAWJfd9/wb/LHQ7@MEhzZlDNc90Jdh5P1aQ2SvU@44izumrqo/CP9YGo1rvwoFhUdRQeUXCh0sosbUTzQC9/AQ) with those of the ungolfed reference implementation ### Commented ``` a => ( // a[] = [ centering, corners, edges, surface ] [ w, // w = worst grade (4th grade) d, // d = 3rd grade , // the 2nd grade is ignored b // b = best grade (1st grade) ] = // ([C, c] = a) // before sorting, save C = centering and c = corners .sort((a, b) => a - b), // sort the grades from lowest to highest (d -= w) ? // d = 3rd grade - worst grade; if it's not 0: ( w - C ? // if the worst grade is not for centering: w - c ? // if the worst grade is not for corners: d < 1 | // yield 1 if d < 1 OR ( w > 8 ? // either d // d (if w > 8) : // or b - w - .5 // b - w - 0.5 (if w <= 8) ) == 1 // is equal to 1 : // else (worst grade = corners): d < 3 // yield 1 if d < 3 : // else (worst grade = centering): d < 4 ? // if d < 4: d < 2 // yield 1 if d < 2 : // else: 3 // yield 3 ) || 2 // if the above result is 0, yield 2 as the default value : // else (d = 0): 0 // yield 0 ) / 2 + w // half the above result and add it to w ``` [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 164 bytes ``` (a,b,c,d)=>{int[]e={a,b,c,d};Array.Sort(e);int f=e[0],h=e[1]-f,i=e[3];return(h<1?0:f==c|f==d?h<9?5:h<11&f>84|i-f==15&i<96?5:10:f==a?h<20?5:h<40?10:15:h<30?5:10)+f;} ``` [Try it online!](https://tio.run/##jZVRb6JAEMff/RQTHprddiWAgouI5h7uHu6a9KKX3IPhARF0kwYbpHe9Wj67NyxowQI20f9udn47zM4OQ7DvB3tx/PYcBxMRp@ziP43cI/HZigVsTd3pAZeWXugeyqXM@ZIk/j91sUtSElIHzRC54VLz2BYH3etHTOBk4DlJmD4nMdlO9Jk2jlw3eENZz7YTe2aOcVW/iaZ8@Cb6uKybN2JiW2jQJesjZmiSG2ozXNPz6UCTAL2LnOzo9P74CWzcOPxLosedj2EyOdKld@gBEDRAaTiArjGoSSaVsiukrZrRdTSnrns9U51onfqs13IX2Fkx/wjzE3FxMrAbHAPPLSjFLn5ieVu8vBJFl2dTEqOKAowkbHW75pUD8sYDVuItTtnBFp6HFTWKoAcdOMbIwDpNu4PGU52FS3TUhlaVd6RuVM/Du2felAu7vEAZQ9f9NRQRb60LWZC572q9daH805fBKzVRVtB1vFCrwEfNZVF/octU2B2u7csUN8dhfryP1koGMM/lYFfekAZ0@O6wnmSr5Zqt@oa2YsPj55aKSFJvIy8akNGR3CovnRq0lzm9XrRLQj/YEmzU5ImtqIhhQw@yb/vuk7oIH8MgJS/gTgl@Ryh5ucUuR9Vfu3uxTwktOvyrGxE//774@HVBMXIZeGjt/U5EGt6LOCT7NBHxRv2@EzFRGODPp@pPfz0Xm21KDI3CHSj9KSg4vuIDFpInFWaYI@QVXBeKYFZwmzddmIHy8EOBMShf5/OHuULxydnxPw "C# (Visual C# Interactive Compiler) – Try It Online") ]
[Question] [ ### Challenge: Output all distinct permutations of a, potentially long, list of positive integers. You may assume that the vector has less than 1,000 numbers when testing, but the process should in theory work for any vector with more than one number regardless of size. **Restrictions:** * You must restrict the memory usage to **O(n^2)**, where **n** is the number of elements in the input vector. You can't have **O(n!)**. That means you can't store all permutations in memory. * You must restrict the time complexity to **O(result size \* n)**. If all numbers are equal, then this will be **O(n)**, and if all are distinct, then this will be **O(n!\*n)**. That means you can't create a permutation and check it against all other permutations to ensure distinctness (that would be **O(n!^2\*n)**). * Empirical measurements to show that time and memory restrictions are met are accepted. * You must actually print/output the permutations (since it's impossible to store them). If you run your program long enough, then all permutations should be outputted (in theory)! **Distinct permutations:** The list **[1, 1, 2]** has three permutations, not six: **[1, 1, 2]**, **[1, 2, 1]** and **[2, 1, 1]**. You may choose the order of the output. --- ## Manageable test cases: ``` Input: [1, 2, 1] Output: [1, 1, 2] [1, 2, 1] [2, 1, 1] Input: [1, 2, 3, 2] Output: [1, 2, 2, 3] [1, 2, 3, 2] [1, 3, 2, 2] [2, 1, 2, 3] [2, 1, 3, 2] [2, 2, 1, 3] [2, 2, 3, 1] [2, 3, 1, 2] [2, 3, 2, 1] [3, 1, 2, 2] [3, 2, 1, 2] [3, 2, 2, 1] Input: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] Output: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] ``` ### Larger test case: It's impossible to output all permutations for this one, but it should work in theory if you gave it enough time (but not unlimited memory). ``` Input: [1, 1, 1, 1, 1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, 317, 318, 319, 320, 321, 322, 323, 324, 325, 326, 327, 328, 329, 330, 331, 332, 333, 334, 335, 336, 337, 338, 339, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350, 351, 352, 353, 354, 355, 356, 357, 358, 359, 360, 361, 362, 363, 364, 365, 366, 367, 368, 369, 370, 371, 372, 373, 374, 375, 376, 377, 378, 379, 380, 381, 382, 383, 384, 385, 386, 387, 388, 389, 390, 391, 392, 393, 394, 395, 396, 397, 398, 399, 400, 401, 402, 403, 404, 405, 406, 407, 408, 409, 410, 411, 412, 413, 414, 415, 416, 417, 418, 419, 420, 421, 422, 423, 424, 425, 426, 427, 428, 429, 430, 431, 432, 433, 434, 435, 436, 437, 438, 439, 440, 441, 442, 443, 444, 445, 446, 447, 448, 449, 450, 451, 452, 453, 454, 455, 456, 457, 458, 459, 460, 461, 462, 463, 464, 465, 466, 467, 468, 469, 470, 471, 472, 473, 474, 475, 476, 477, 478, 479, 480, 481, 482, 483, 484, 485, 486, 487, 488, 489, 490, 491, 492, 493, 494, 495, 496, 497, 498, 499, 500, 501, 502, 503, 504, 505, 506, 507, 508, 509, 510, 511, 512, 513, 514, 515, 516, 517, 518, 519, 520, 521, 522, 523, 524, 525, 526, 527, 528, 529, 530, 531, 532, 533, 534, 535, 536, 537, 538, 539, 540, 541, 542, 543, 544, 545, 546, 547, 548, 549, 550, 551, 552, 553, 554, 555, 556, 557, 558, 559, 560, 561, 562, 563, 564, 565, 566, 567, 568, 569, 570, 571, 572, 573, 574, 575, 576, 577, 578, 579, 580, 581, 582, 583, 584, 585, 586, 587, 588, 589, 590, 591, 592, 593, 594, 595, 596, 597, 598, 599, 600, 601, 602, 603, 604, 605, 606, 607, 608, 609, 610, 611, 612, 613, 614, 615, 616, 617, 618, 619, 620, 621, 622, 623, 624, 625, 626, 627, 628, 629, 630, 631, 632, 633, 634, 635, 636, 637, 638, 639, 640, 641, 642, 643, 644, 645, 646, 647, 648, 649, 650, 651, 652, 653, 654, 655, 656, 657, 658, 659, 660, 661, 662, 663, 664, 665, 666, 667, 668, 669, 670, 671, 672, 673, 674, 675, 676, 677, 678, 679, 680, 681, 682, 683, 684, 685, 686, 687, 688, 689, 690, 691, 692, 693, 694, 695, 696, 697, 698, 699, 700, 701, 702, 703, 704, 705, 706, 707, 708, 709, 710, 711, 712, 713, 714, 715, 716, 717, 718, 719, 720, 721, 722, 723, 724, 725, 726, 727, 728, 729, 730, 731, 732, 733, 734, 735, 736, 737, 738, 739, 740, 741, 742, 743, 744, 745, 746, 747, 748, 749, 750, 751, 752, 753, 754, 755, 756, 757, 758, 759, 760, 761, 762, 763, 764, 765, 766, 767, 768, 769, 770, 771, 772, 773, 774, 775, 776, 777, 778, 779, 780, 781, 782, 783, 784, 785, 786, 787, 788, 789, 790, 791, 792, 793, 794, 795, 796, 797, 798, 799, 800, 801, 802, 803, 804, 805, 806, 807, 808, 809, 810, 811, 812, 813, 814, 815, 816, 817, 818, 819, 820, 821, 822, 823, 824, 825, 826, 827, 828, 829, 830, 831, 832, 833, 834, 835, 836, 837, 838, 839, 840, 841, 842, 843, 844, 845, 846, 847, 848, 849, 850, 851, 852, 853, 854, 855, 856, 857, 858, 859, 860, 861, 862, 863, 864, 865, 866, 867, 868, 869, 870, 871, 872, 873, 874, 875, 876, 877, 878, 879, 880, 881, 882, 883, 884, 885, 886, 887, 888, 889, 890, 891, 892, 893, 894, 895, 896, 897, 898, 899, 900] ``` --- You must explain how you know that all permutations are distinct, and that all permutations will be printed, eventually. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code in bytes win. [Answer] ## JavaScript (ES6), ~~177~~ 169 bytes ``` a=>{s=''+a do{console.log(a) k=a.findIndex((e,i)=>a[i-1]>e) if(~k)t=a[k],a[k]=a[l=a.findIndex(e=>e>t)],a[l]=t,a=a.map((e,i)=>i<k?a[k+~i]:e) else a.reverse()}while(a!=s)} ``` Uses the well-known next lexicographic permutation generation algorithm, which I believe has memory O(len(array)) and time O(len(array)\*len(output)). (Note that the array elements are considered to be in reverse order, so that e.g. `2, 2, 1, 1` will enumerate to `2, 1, 2, 1`; `1, 2, 2, 1` etc. [Answer] # [Python 3](https://docs.python.org/3/) with [sympy](http://docs.sympy.org), (50?) 81 bytes ``` lambda a:[print(v)for v in sympy.iterables.multiset_permutations(a)] import sympy ``` **[Try it online!](https://tio.run/##VY7NCoMwEITvPkVuMSWIP7dAn8SGEmmkC/kj2Qg@faoVLWUu3@www4YV394NZb4/ilF2eimixBgiOKwXNvtIFgKOpNWGtQHUUU1Gp8Zmg5A0PoOONqNC8C7ViskKbPARj0LZ@6gT7hP12PFNkpMN@h8MF/D@i/LWtS0TFTm@oOBCRkHZedgHL0N9xjOe/yNWPg "Python 3 – Try It Online")** **50 bytes** if a generator function is acceptable: ``` import sympy sympy.iterables.multiset_permutations ``` The implementation is open source and currently available on [git hub](https://github.com/sympy/sympy/blob/master/sympy/utilities/iterables.py), at the time of writing the function is at [line 983](https://github.com/sympy/sympy/blob/master/sympy/utilities/iterables.py#L983). I think it does, but do let me know if it does not, fulfil the asymptotic bounds. --- ### Python 2, (411?) 439 bytes A golfed version (also ignoring cases we are not required to cover) in Python 2 (still using the built-in `itertools.permutations function`) comes in at [439 bytes](https://tio.run/##VVLLbsMgEDzHX7E3Q0oqk96c0E/opcfVHtyEJCS2sWyMXP98CjSPVpbQjGaYHcDdtzvZdn3d2b1WeZ5fD71twDjdO2vrAUzT2d4ts70@wIlVYlYrKY5K8jKDSaGHg@3Bg2nxKBC9qF53dmwd85zuCgzasYoT4VEpSeYAxdajJNp8qmFsGEbyME/EMwieSakJS0nlRfiACtp8G13v8ZImmmjtq/aoGWIhZsJ5qzwJH4EkThnoOqRUdc38dh23hJyUH5ovIu8i63TfjK5yxrZDLFL8LSJwFh@21TGzIF6mAlCbwbGOxwGDDlmzws9U4H0laWNU8Rt/HxccMKGhcMaVkoFE8RylE0MSc7jOVAkWoe65vB2SXs7PfS9KbkxYske3EzNtNzrGedn1pnXgr@Htku704KKFoRThIwEBrJ/g7QHEOkFayqKIz5kiQUFdNV/7qoxBGfzG50kr8zv/p9nR3UQ96R2LfxJ/iPn1Bw), or 411 with no additional boilerplate to print rather than generate (the `for v in h(input()):print v`): ``` from itertools import* def h(a,z=-1,g=1): x=[v for v in[g,[[v,a.count(v)]for v in set(a)]][g==1]if 0<v[1]];S=sum([v[1]for v in x]) if x==x[:1]:k,v=x[0];yield[k for i in range([[0,z][z<=v],v][z<1])] elif all(v<2for k,v in x): for p in permutations([v[0]for v in x],[z,None][z<0]):yield list(p) else: z=[S,z][z>-1];i=0 for k,v in x: x[i][1]-=1 for j in h([],z-1,x): if j:yield[k]+j x[i][1]+=1;i+=1 for v in h(input()):print v ``` (note: this uses the Python 2 golf of alternating tab and spaces for indents) [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~137~~ ~~128~~ 123 bytes ``` s=>f(x=c=[],s.map(g=i=>g[i]=-~g[i]));f=i=>Object.keys(g).map(i=>g(i,--g[i]||delete g[i],f(x[c++]=i),c--))<1&&console.log(x) ``` [Try it online!](https://tio.run/##Vc69boMwEAfwPU/BFN0ptlOibuSQumTtAyAG6tjUlGIEtMIK6atTO4kqd/J9/H36NdV3NcrB9BPv7FmtJ1pHyjXMJKko2Sg@qx5qMpTXhSmJ/4QHMdNh9PrWKDmJD@VGqPEWDUEwjPOQW5azatWkktAwf7SQu11JBpnkHPGYbrfSdqNtlWhtDTOumfUFRcMsqmmm3N6CorGmA8/Y7PfJw@u1ji7XB9k73B3sIvBF2wFMYnUS0x3iLHrbA@cuVoeG@c3X@A7erAFZfDMzy/Kff92coEjZgaV@@1ezw717GYbKwfMTCm3aFlIU/resJjh43voL "JavaScript (Node.js) – Try It Online") ``` s=> f( x=c=[], s.map(g=i=>g[i]=-~g[i]) // O(n) if all same, <=O(n^2) if different ) ; f=i=> Object.keys(g).map( // for(i in g) breaks when other items get removed i=>g( i, --g[i]||delete g[i], // O(left possible numbers)<O(child situations) f(x[c++]=i), c-- ) )<1 && console.log(x) ``` [Answer] # [C++ (gcc)](https://gcc.gnu.org/), 203 bytes Apparently C++ has this as a builtin function... ``` #import<bits/stdc++.h> using namespace std;main(){vector<int>v;int x;while(cin>>x)v.push_back(x);sort(v.begin(),v.end());do{for(int y:v)cout<<y<<' ';puts("");}while(next_permutation(v.begin(),v.end()));} ``` [Try it online!](https://tio.run/##VY5RC4IwFIWf9Vdc6MENSqjebPhLAplz6Ug3mddlhL/dtiyql3vhnI9zjuj7XS3EsmyUFu1YSWDKDGgl7/L4qzkp0Nhfhbe1sQobj8VKI3RcaUIfcTRglWUrz7yRgzvFUSAm/2@NaiV5IUJpyHOYKLi0H4emKLm4kome3hGDsUhcWso6BG9dKnVFaLAr42uii7EkxN4hA0fXSDMiMOYlfxJIPBv9GclZB3GG1w5Yh2g5YdFL243IURn9UwqfVl87L8seDrCH4xM "C++ (gcc) – Try It Online") Ungolfed code: TIO link. This use `O(n)` memory (guaranteed by `std::vector`) and optimal runtime. Some optimizations in code: * Use `import` instead of `include` (G++ deprecated extension) * Use `bits/stdc++.h` (precompiled header contains all other headers) instead of multiple necessary headers. Often this makes compile time slower. * `using namespace std` which is [known to be a bad idea](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice). * Use `puts("")` instead of `cout<<'\n'` for writing a newline. This is normal for C program, but feels weird for me. So I think this should be mentioned. * `main` return value (`int`) can be omitted. Otherwise (apart from whitespace deletion) it's the same way how I often program in C++. Some possible optimizations: (I don't know if that is allowed by default): * Enter array size before enter elements. This will allow dynamic-size array, overall [save 30 bytes](https://tio.run/##LYzdCoIwGEDvfYphkBv2g9VV3/BFIsLm0kF@G@7TFOnZl4aXh3M4yrl9pVQIG9M425J8GvJHT6VK00OdR503WDEsGu1doTSbDTSFQS4mg8QQlME8R1igv@EdXrblM2yHay/@bgA/f3m/61MUUNppLdi4FLYjKUcpE5aA68jzOBbw/dTmrTnqgR5Ot01HBRmL62P2IVyijJ1Yxs4/ "C++ (gcc) – Try It Online"). * Not separate the outputs with separators. So the output will like `1 1 2 3 1 1 3 2 1 2 1 3 1 2 3 1 1 3 1 2 1 3 2 1 2 1 1 3 2 1 3 1 2 3 1 1 3 1 1 2 3 1 2 1 3 2 1 1` for `1 2 1 3`. This allows save more 9 bytes. * While in C it is allowed to omit headers, I don't know if there is a shorter way to use those functions without `#import` the headers in C++, or a shorter header name. [Answer] # Scala (48 bytes) ``` def%(i:Seq[Int])=i.permutations.foreach(println) ``` [Try it online](https://tio.run/##K05OzEn8n5@UlZpcouCbmJmnkFpRkpqXUqzgWFCgUP0/JTVNVSPTKji1MNozryRW0zZTryC1KLe0JLEkMz@vWC8tvyg1MTlDo6AoM68kJ0/zv6oGUK2GoY6RjqGmJhdUmAshaqxjhEWcKAjUV/sfAA) [permutations](https://www.scala-lang.org/api/2.12.3/scala/collection/immutable/List.html#permutations:Iterator[Repr]) returns an iterator over distinct permutations. [Answer] # APL(NARS), 156 chars, 312 bytes ``` r←d F w;i;k;a;m;j;v r←w⋄→0×⍳1≥k←↑⍴w⋄a←⍳k⋄j←i←1⋄r←⍬⋄→C A: m←i⊃w⋄→B×⍳(i≠1)∧j=m v←m,¨(d,m)∇w[a∼i] →H×⍳0=↑⍴v⋄⎕←∊d,v H: j←m B: i+←1 C: →A×⍳i≤k G←{⍬F⍵[⍋⍵]} ``` They, F and G would be 2 function to use togheter... G first order the array than apply to the that ordined array the function F and write permutations using the observation that if the element is already found, better not to go to recursion (because all the result would be already found). I don't know if this fit all restritions... Test: ``` G 1 1 2 1 1 2 1 2 1 2 1 1 G 1 2 3 2 1 2 2 3 1 2 3 2 1 3 2 2 2 1 2 3 2 1 3 2 2 2 1 3 2 2 3 1 2 3 1 2 2 3 2 1 3 1 2 2 3 2 1 2 3 2 2 1 G 'abb' abb bab bba ``` ]
[Question] [ Write a program/function/script that takes a natural number i from 1 to 10 as input and outputs the URL of the Question with the i th hottest question on the Code Golf Portal The ordering should be like in <https://codegolf.stackexchange.com/?tab=hot>. For example: *input 1* *output [https://codegolf.stackexchange.com/questions/127047/the-spain-license-plates-game](https://codegolf.stackexchange.com/questions/127047/the-spain-license-plates-game_)* (at the point of this edit) There are no strong restrictions to the output, as long as the url can be reasonably retrieved. Valid outputs include strings, console printing etc. It's Code Golf, so shortest code in Bytes wins. ## Notes If your program automatically opens a browser with the webpage, it counts as valid output and is totally cool. If your program does not retrieve the ranking from current information (i.e. hardcoding the links), it is not valid. The contest ends with the end of June. As questioned: The indexing must be 1 based, ie: the input 1 must return the the first site of the hottest questions. ### Comment I hope this question is not too clickbaity, as the stack exchange editor program was mocking me for the title. Originally I planned this challenge with Youtube trends, where it would haven been more fitting. [Answer] # Python + [requests](http://docs.python-requests.org/en/master/), 128 bytes ``` from requests import* lambda n:get('http://api.stackexchange.com/questions?sort=hot&site=codegolf').json()['items'][n-1]['link'] ``` [Answer] # Mathematica, 125 bytes ``` b="http://codegolf.stackexchange.com";b<>"/q/"<>StringCases[Import[b<>"?tab=hot","Text"],"ns/"~~a:DigitCharacter..:>a][[3#]]& ``` Anonymous function. Takes no input and returns a string as output. Was going to use the XML feed, but it seems to follow a different ordering than on the page. [Answer] # Python 2.7, 195 bytes ``` from urllib import* import zlib, json lambda n:json.loads(zlib.decompress(urlopen('http://api.stackexchange.com/questions?sort=hot&site=codegolf').read(),16+zlib.MAX_WBITS))['items'][n-1]['link'] ``` This is same answer by [Dair](https://codegolf.stackexchange.com/users/43537/dair), but using Python 2 [Answer] # Python 3, 221 bytes ``` from urllib.request import* import zlib, json lambda n:json.loads(zlib.decompress(urlopen('http://api.stackexchange.com/questions?sort=hot&site=codegolf').read(),16+zlib.MAX_WBITS),encoding='utf-8')['items'][n-1]['link'] ``` Based off of [ovs](https://codegolf.stackexchange.com/a/127082/43537) answer. Also, thanks to [Oluwafemi Sule](https://stackoverflow.com/a/44618741/667648) for helping me with an issue I had. [Answer] # [Stratos](https://github.com/okx-code/Stratos), 28 bytes ``` "-1"+ f"¹⁵s²&sort=hot"r"⁷s"@ ``` Explanation: ``` "-1"+ Decrement the input, and store it. f"¹⁵s²&sort=hot" Fetch the contents of the URL api.stackexchange.com/questions?site=codegolf&sort=hot. r"⁷s" Get the array named "items" @ Get the nth element, where n is retrieved from storage. ``` [Try it!](http://okx.sh/stratos/?code=%22-1%22%2B%0Af%22%C2%B9%E2%81%B5s%C2%B2%26sort%3Dhot%22r%22%E2%81%B7s%22%40&input=1) [Answer] # PowerShell v5, 83 Bytes ``` (irm api.stackexchange.com/questions?sort=hot`&site=codegolf).Items["$args"-1].Link ``` `irm` is short for `Invoke-RestMethod` which auto-parses the Json, makes life quite easy. add four bytes (`saps` for `start-process`) for version which opens in browser. ``` saps(irm api.stackexchange.com/questions?sort=hot`&site=codegolf).Items["$args"-1].Link ``` [Answer] # JavaScript (ES6), 106 bytes Returns a Promise containing the JSON object for the desired question, which includes the link. ``` n=>fetch`//api.stackexchange.com/questions?sort=hot&site=codegolf`.then(r=>r.json()).then(j=>j.items[--n]) ``` * Sacrificed 2 bytes allowing for 1-indexing. --- # Try it ``` f= n=>fetch`//api.stackexchange.com/questions?sort=hot&site=codegolf`.then(r=>r.json()).then(j=>j.items[--n]) oninput=_=>f(+i.value).then(console.log) f(i.value=1).then(console.log) ``` ``` <input id=i type=number> ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E) + [`json`](https://hex.pm/packages/json), 85 bytes ``` <’¸¸.‚‹º.ŒŒ/…é?€¼=ƒËŠˆ&Šœ=…ß’.w„\"D„\\s‚‡’(EnÆá.€› (JSON.deƒË!"ÿ")["‚Õ"],ÿ)["ƒÚ"]’.E ``` ]
[Question] [ These are raindrops: ``` ! | . " : ``` These are clouds particles: ``` ( ) _ @ $ & ``` I want you to verify, when given a block of text, whether or not it is raining. It is raining if, for every raindrop, there is a cloud particle somewhere above it. There must be one cloud particle for every raindrop. Output a [truthy or falsy value](https://codegolf.meta.stackexchange.com/questions/2190/interpretation-of-truthy-falsey) denoting your conclusions. # Valid examples ``` (@@@@@@) ( $ & ) Q ( ) .. . ! : . |" ! . ``` ``` ()()() ...... ``` ``` @_$ & errrr h_r-5 .:. . " ``` # Invalid examples ``` ! () ``` ``` $$$$$ ( ) ::::: ..... ``` This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest program in *characters* wins. [Answer] # C++11, ~~186~~ 184 bytes ``` #include<map> int i,c;int main(){std::map<int,int>p;while(~(c=getchar())){for(int m:{40,41,95,64,36,38})p[i]+=c==m;for(int m:{33,124,46,34,58})if(c==m&&!p[i]--)return 1;i=c-10?i+1:0;}} ``` Ungolfed ``` #include <map> int i, c; int main() { std::map<int, int> p; while (~(c = getchar())) { // for (int m : { '(', ')', '_', '@', '$', '&'}) for (int m : { 40, 41, 95, 64, 36, 38}) p[i] += c == m; // for (int m : { '!', '|', '.', '"', ':'}) for (int m : { 33, 124, 46, 34, 58}) if (c == m && !p[i]--) return 1; i = c - '\n' ? i + 1 : 0; } return 0; } ``` Basic approach, storing positions of cloud particles in a row and if rain particle is encountered, it checks whether the cloud particle is above it and decreases the counter of cloud particles in that column. The program returns 0 if it's valid and 1 otherwise. [Answer] # APL (30) ``` {∧/∊≤/+⍀¨⍵∘∊¨'!|.":' '()_@$&'} ``` This is a function that takes a character matrix as input, and gives a boolean output. Test: ``` ex1 ex2 ex3 ex4 ex5 ┌─────────┬──────┬─────┬──┬─────┐ │(@@@@@@) │()()()│@_$ &│! │$$$$$│ │ ( $ & )│......│errrr│()│( )│ │Q ( ) │ │h_r-5│ │:::::│ │.. . ! │ │.:. .│ │.....│ │ : . │ │ " │ │ │ │ |" ! │ │ │ │ │ │ . │ │ │ │ │ └─────────┴──────┴─────┴──┴─────┘ {∧/∊≤/+⍀¨⍵∘∊¨'!|.":' '()_@$&'}¨ex1 ex2 ex3 ex4 ex5 1 1 1 0 0 ``` Explanation: * `⍵∘∊¨'!|.":' '()_@$&'`: for both sets of characters (rain and clouds), and each character in ⍵, see if the character is a member of the set. * `+⍀¨`: get a running sum for each column and each set * `≤/`: for each position in ⍵, check that the amount of raindrops does not exceed the amount of cloud particles in the running sum * `∧/∊`: return the boolean AND of all the elements in the result [Answer] # [Snails](https://github.com/feresum/PMA), 125 ``` {t.{t(\(|\)|\_|\@|\$|\&)=(u.,~)d!(.,~)t.!(.,~},!{t(\!|\||\.|\"|\:)ud!(.,~}t(\(|\)|\_|\@|\$|\&)!(d.,~)u.,~},!{t(\!|\||\.|\"|\: ``` The program outputs the area of the grid (or 1 if its area is 0) if it is raining; otherwise 0. If only I had implemented regex-style character classes. **Ungolfed version** This contains fake instructions for clouds or raindrops instead of writing out all the gibberish. `\whatever` (replaced with `.` in the real program) means a thing that ought to be a raindrop, but can actually be anything because it doesn't matter if we match a non-raindrop to a cloud. ``` { t \whatever ,, Pick a drop in a new column { t \cloud ,, Find a cloud with =(u.,~) ,, nothing above in the same column marked !(d.,~) ,, but not in an empty column t \whatever !(d.,~) }, !(t \drop ud !(.,~) ) ,,no drops remaining in column t \cloud !(d.,~) u.,~ }, ,, repeated 0 or more times ! (t \drop) ,, no drops left ``` [Answer] # Python 2, 121 bytes ``` def f(i): for l in zip(*i.split('\n')): s=0 for p in l: s+=p in'()_@$&';s-=p in'!|.":' if s<0:return return 1 ``` Expects the input to be padded to be rectangular. [Answer] # JavaScript ES6, 112 Test running the snippet below in an EcmaScript 6 compliant browser implementing arrow functions, spread operator and template strings (I use Firefox) ``` f=t=>!t.split` `.some(r=>[...r].some((c,i)=>(c='!|.":()_@$&'.indexOf(c),n[i]=~c?c<5?~-n[i]:-~n[i]:n[i])<0),n=[]) //TEST console.log=x=>O.innerHTML+=x+'\n'; test_valid = [ '(@@@@@@)\n ( $ & )\nQ ( )\n.. . !\n : .\n |" !\n .', '()()()\n......', '@_$ &\nerrrr\nh_r-5\n.:. .\n "' ] console.log('Valid'); test_valid.forEach(t=>console.log(t+'\n'+f(t)+'\n')) test_invalid = ['!\n()','$$$$$\n( )\n:::::\n.....'] console.log('Invalid'); test_invalid.forEach(t=>console.log(t+'\n'+f(t)+'\n')) ``` ``` <pre id=O></pre> ``` [Answer] ## Perl 5, 80 79, plus one for `-E` instead of `-e` ``` @a=();while(<>){@_=split'';(0>($a[$_]+=/[()_@&\$]/-/[!|.":]/)?die:1)for@_}say 1 ``` [Answer] # Julia, 90 characters ``` s->all(cumsum(map(i->i∈"!|.\":"?-1:i∈"()_@\$&",mapfoldl(collect,hcat,split(s," ")))').>-1) ``` Unlike the original solution (below), this uses mathematics to determine the solution. `mapfoldl(collect,hcat,split(s,"\n"))` (written above with `\n` replaced with an actual newline to save characters) converts the string into a 2d array of characters. `map(i->i∈"!|.\":"?-1:i∈"()_@\$&",...)` creates an array of numbers, with 1 if the character is a cloud, -1 if the character is rain, and 0 otherwise. `cumsum(...')` calculates the cumulative sums of the rows (would normally be written `cumsum(...,2)`, but since we don't care about orientation from this point on, transposing only costs one character), and then `all(... .>-1)` checks for a negative number - negatives will only occur if a rain character appears without being preceded by a cloud character. ## Julia, ~~139~~ 136 *characters* ``` s->(t=join(mapfoldl(i->split(i,""),.*,split(s," "))," ");while t!=(t=replace(t,r"[()_@$&](.*?)[!|.\":]",s"\g<1>"))end;∩("!|.\":",t)==[]) ``` This function first transposes the text so that rows become columns and vice-versa. Note that newlines are present in the code in the form of actual newlines, to save one character per instance. The function then iteratively replaces cloud/droplet pairs with spaces, and once all such pairs are removed, it returns true if there are any droplets remaining and false otherwise. `r"[()_@$&](.*?)[!|.\":]"` - this is a regex that will match cloud/droplet pairs in a lazy manner, with group 1 containing everything between cloud and droplet. Then `s"\g<1>"` tells it to remove the matched cloud and droplets, but keep the stuff in between (necessary as it may contain clouds) - the `\g<1>` is whatever was matched in group 1 of the regex. `∩("!|.\":",t)==[]` will generate the intersection of the droplet characters with the final string, and if it's empty, then none of the droplet characters are present, and it's raining. ]
[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. --- I've got an infinite supply of \$n\$-dimensional chocolate for some positive integer \$n\$. The shape of the chocolate is not important. You may assume that they are just \$n\$-dimensional hypercubes with side length \$1\$. To celebrate the upcoming Christmas, I want to assemble them into a giant chocolate pyramid with \$x\$ layers. The base of the pyramid is an \$(n-1)\$-dimensional hypercube with side length \$x\$, which contains \$x^{n-1}\$ chocolates. The next layer is an \$(n-1)\$-dimensional hypercube with side length \$x-1\$, which contains \$(x-1)^{n-1}\$ chocolates. And so on. The top layer is a single chocolate. For example, when \$n=3\$, the pyramid would contain \$1^2 + 2^2 + \dots + x^2 = \frac{1}{6}x(x+1)(2x+1)\$ chocolates. [![enter image description here](https://i.stack.imgur.com/6o97a.png)](https://i.stack.imgur.com/6o97a.png) Interestingly, for any dimension \$n\$, the number of chocolates in the pyramid is always a polynomial in \$x\$. * When \$n=1\$, this is \$\sum\_{k=1}^x k^0 = x\$. * When \$n=2\$, this is \$\sum\_{k=1}^x k^1 = \frac{1}{2}x^2+\frac{1}{2}x\$. * When \$n=3\$, this is \$\sum\_{k=1}^x k^2 = \frac{1}{3}x^3+\frac{1}{2}x^2+\frac{1}{6}x\$. * When \$n=4\$, this is \$\sum\_{k=1}^x k^3 = \frac{1}{4}x^4+\frac{1}{2}x^3+\frac{1}{4}x^2\$. * When \$n=5\$, this is \$\sum\_{k=1}^x k^4 = \frac{1}{5}x^5+\frac{1}{2}x^4+\frac{1}{3}x^3-\frac{1}{30}x\$. The general formula for these polynomials is called the [Faulhaber's Formula](https://en.wikipedia.org/wiki/Faulhaber%27s_formula). Your task is to find the coefficients of these polynomials. ## Rules The usual [sequence](/questions/tagged/sequence "show questions tagged 'sequence'") rules apply. So you may: * Output all the polynomials. * Take an input \$n\$ and output the \$n\$-th polynomial. * ake an input \$n\$ and output the first \$n\$ polynomial. You may use \$0\$-indexing or \$1\$-indexing. You may output the polynomials in any reasonable format. Here are some example formats: * a list of coefficients, in descending order, e.g. \$\frac{1}{5}x^5+\frac{1}{2}x^4+\frac{1}{3}x^3-\frac{1}{30}x\$ is represented as `[1/5,1/2,1/3,0,-1/30,0]`; * a list of coefficients, in ascending order, e.g. \$\frac{1}{5}x^5+\frac{1}{2}x^4+\frac{1}{3}x^3-\frac{1}{30}x\$ is represented as `[0,-1/30,0,1/3,1/2,1/5]`; * a function that takes an input \$k\$ and gives the coefficient of \$x^k\$; * a built-in polynomial object. Since the coefficients are not integers, you may output them as rational numbers, floating-point numbers, or any other reasonable format. You may also take two integers \$n, k\$, and output the coefficient of \$x^k\$ in \$n\$-th polynomial. You may assume that \$k\le n\$. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins. ## Testcases Here I output lists of coefficients in descending order. ``` 1 -> [1, 0] 2 -> [1/2, 1/2, 0] 3 -> [1/3, 1/2, 1/6, 0] 4 -> [1/4, 1/2, 1/4, 0, 0] 5 -> [1/5, 1/2, 1/3, 0, -1/30, 0] 6 -> [1/6, 1/2, 5/12, 0, -1/12, 0, 0] 7 -> [1/7, 1/2, 1/2, 0, -1/6, 0, 1/42, 0] 8 -> [1/8, 1/2, 7/12, 0, -7/24, 0, 1/12, 0, 0] 9 -> [1/9, 1/2, 2/3, 0, -7/15, 0, 2/9, 0, -1/30, 0] 10 -> [1/10, 1/2, 3/4, 0, -7/10, 0, 1/2, 0, -3/20, 0, 0] 11 -> [1/11, 1/2, 5/6, 0, -1, 0, 1, 0, -1/2, 0, 5/66, 0] 12 -> [1/12, 1/2, 11/12, 0, -11/8, 0, 11/6, 0, -11/8, 0, 5/12, 0, 0] 13 -> [1/13, 1/2, 1, 0, -11/6, 0, 22/7, 0, -33/10, 0, 5/3, 0, -691/2730, 0] 14 -> [1/14, 1/2, 13/12, 0, -143/60, 0, 143/28, 0, -143/20, 0, 65/12, 0, -691/420, 0, 0] 15 -> [1/15, 1/2, 7/6, 0, -91/30, 0, 143/18, 0, -143/10, 0, 91/6, 0, -691/90, 0, 7/6, 0] 16 -> [1/16, 1/2, 5/4, 0, -91/24, 0, 143/12, 0, -429/16, 0, 455/12, 0, -691/24, 0, 35/4, 0, 0] ``` [Answer] # Python3, 207 bytes: ``` import math R=range C=math.comb B=lambda n,c={0:1,1:0.5}:c[n]if n in c else 1-sum(B(k)/(n-k+1)*C(n,k)for k in R(n)) def r(N): d=[0]*-~N for i in R(N):d[N-i]+=(1/N)*(-1)**i*C(N,i)*[B(i),-.5][i==1] return d ``` [Try it online!](https://tio.run/##PY@xboMwEIbn@iluPDs2waqiVpa8kJ0hq@WBYEgswoEcMkRR@@rUtFLH0333/f/Nz@U60fvnnNY1jvOUFhib5cpONjV06djRbmPRTuOZVfbWjOfQAMnWvkqjpTZlcfgyrSMfeyCIBC10t3sHWt0fI1Y48D2SGnaaiyOSHHg/JRg28ITEOQtdDwlrbhgE60ov1HfNYIPiH5RXwdUq@p1Fva@5QJVdImZdLSMXrsLIpSoO3kVrtWeQuuWRCML6b/l9BXPdj5zzNqdIC6Z85oxR2vP1Bw) [Answer] # JavaScript (ES6), 73 bytes *-7 bytes thanks to [@Neil](https://codegolf.stackexchange.com/users/17602/neil)* Expects `(n,k)`, with \$n\$ 0-indexed. Returns the coefficient of \$x^k\$ in the \$n\$-th polynomial as a floating-point number. ``` f=(n,k,p=k)=>p--?f(n,k,p)*(p-n)/~p:(b=j=>j--?b(j)-f(k,j):1)(k)/(n+1-k||1) ``` [Try it online!](https://tio.run/##bVTNcpswEL77KfaGFPMnASLYxZleeusTeDwdYuPU4EgMIUzapn2CzvTSY/sefZ68QB/BESCEIb5Iy@633367ksiSOnnYloeisrjYpafTPkbczM0iznG8KizrZt994ytUWBw7P4oFuo2zeJXJ2C3KsLVHuZnhBcEoxw7ic2Llz88En9KnIt1W6Q5iWM8A1kBMcGFjdrZDzW45c3lm72cjv6/90nJHoUCHvDZkSWOMYAoROIT2EGWdoULzXFILYq0ha45FXitQqPlCh/oK@5Y4UnDaC5R5QWvRJnZRMnFVkqcabpJcVUIV9RzqTmsRontlirpL6ut0uTI6ni/pGydkGFLbqdv62MQVXOiT6MPT4C6N0ma4rWSv7yLoh8EimRNO29fn7Q1yfM9hagTSpNeDW82BDQfcsPoXxhPoo1MdRWr0HSk5I1VCI918wxl1znByPclwxXzN218Jf@jBp1GLlbYfjNUqtBcMN3y2Wc64KO@T4@FrKt9QDfEK0Mek@myX4pHvUA1XQFKGwWk3uxIfDk/pDjG8nO1FibhMcpfA4R0QJvf5HMM3KVk8Vs2TtG37fVkmXyRuDhRv7PukQOiTCTluKunSqPkBSCfGdiYOHBlgyAIA8nlLmv6Rr7kiqN8S1NPUreAP4pjaR3GHpBqzk9SSwQ0Y///9evnzW64GLMB4@fuzyfp@egU "JavaScript (Node.js) – Try It Online") ### Less golfed ``` c = (n, k) => k-- ? c(n, k) * (k - n) / ~k : 1 b = (n, k) => k-- ? b(n, k)- f(n, k) : 1 f = (n, k) => k == n + 1 ? 0 : c(n, k) * b(k, k) / (n + 1 - k) ``` [Try it online!](https://tio.run/##bY3LbsIwFET3@YrZcU2wIUh0AbhVN@z6BQgh51USg41MikAV/HpwwktIrObO3DOaUu3VLnHFtuLGplldJ5Ag04NmkJ/QnOMLyS3ogjQ4DEMfZ40xoiB@g8fXgCO/fRowfwUhJQxCRJ4feOA5EZNur77HW4B7V@fWeSsxmPjaFNGH1zBk@A@AxJqdXWdibX9pLoT4dk4d2/KQLcRGbYmW92H6UdVKOPtnUsofm1E2agYbEZWdFYcspRFjorSFoQ46jAWn@gI "JavaScript (Node.js) – Try It Online") ### How? As a starting point, I used: * the first alternate expression [given on Wikipedia](https://en.wikipedia.org/wiki/Faulhaber%27s_formula#Alternate_expressions) for Faulhaber's formula: $$\color{grey}{\sum\_{k=1}^n k^p=}\sum\_{k=0}^p\dfrac{(-1)^{p-k}}{k+1}\binom{p}{k}B^-\_{p-k}\color{grey}{n^{k+1}}$$ (note that the convention used here is \$B^-\_1=-1/2\$ rather than \$B^+\_1=+1/2\$) * the following recursive formula for Bernoulli numbers (also [from Wikipedia](https://en.wikipedia.org/wiki/Bernoulli_number#Recursive_definition)): $$B^-\_m=\delta\_{m,0}-\sum\_{k=0}^{m-1}\binom{m}{k}\dfrac{B^-\_k}{m-k+1}$$ (where \$\delta\$ is the Kronecker delta, which means that we have \$\delta\_{m,0}=1\$ if \$m=0\$ and \$\delta\_{m,0}=0\$ otherwise) We can notice similarities between these formulae. So I've tried to factorize as much code as possible (especially the binomial and the division) and eventually came up with the following recursive functions: $$b(n,k)=\begin{cases}1&\text{if }k=0\\ b(n,k-1)-f(n,k-1)&\text{if }k>0\end{cases}$$ $$f(n,k)=\begin{cases}0&\text{if }k=n+1\\ \dfrac{\binom{n}{k}\times b(k,k)}{n+1-k}&\text{if }k<n+1 \end{cases}$$ The coefficient of \$x^k\$ in the 0-indexed \$n\$-th polynomial is given by \$f(n,k)\$. In the final JS code, the recursive computation of the binomial is merged into \$f\$ and the first argument of \$b\$ is actually taken from the scope of the caller. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 52 bytes ``` Nθ≔⟦¹⟧ηFθ«⊞υ⁻¹↨Eυ∕×κ§ηλ⁻⊕ιλ¹⊞η⁰UMη⁺κ§η⊖λ»I∕Eυ×ι§ηκθ0 ``` [Try it online!](https://tio.run/##XY69C8IwEMVn@1cEpwtEsINTJz@WDkoHN3GI7WlDm7TNhwji3x4TrYguB/fevd@9sua67Hjrfa56Z3dOnlDDQLNkaYy4KDikR0bqsJ87TYJB7smkcKYGx8hWKGcgZWTFDcKW91HciKuoEPZCooGGkaXNVYU3qBlpKf2EclVqlKgsViDoywozDTMb@eF@HpeAXXdSclVFqWjdP3WDX1TEhNAjKbRQFtbcWBgLjfXevcQPoYm/h1fynZvOpzTzfuFn1/YJ "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` Nθ ``` Input `n`. ``` ≔⟦¹⟧η ``` Start with the first row of Pascal's Triangle. ``` Fθ« ``` Loop `n` times. ``` ⊞υ⁻¹↨Eυ∕×κ§ηλ⁻⊕ιλ¹ ``` Calculate the next Bernoulli number. ``` ⊞η⁰UMη⁺κ§η⊖λ ``` Calculate the next row of Pascal's triangle. ``` »I∕Eυ×ι§ηκθ ``` Output the first `n` coefficients. ``` 0 ``` Output the constant term. 55 bytes for a version with less floating-point inaccuracy using the newer version of Charcoal on ATO: ``` Nθ≔⟦¹⟧η≔Π…·¹θζFθ«⊞υ⁻ζ↨E⮌×υη÷κ⁺²λ¹⊞η⁰UMη⁺κ§η⊖λ»I∕×υη×θζ0 ``` [Attempt This Online!](https://ato.pxeger.com/run?1=TVBNS8NAEMWj-RVD8DCBLTSCIORU20sOlVC8lR62m2mzmGya_QhS8Zd4KaLob_LXuNsE6mWY9-a9N7vz_iMqrkXL69Ppy9nd5P736iZXB2cfXbMljV2SRTNj5F7hOt0wqC640G3phMVcidoZ2dOKqz1hyqBLEgZHr9y1GnwEvEbXhTMVOgZLqZzBI4MHbgiX_IAr6kn7_kk2ZIKkCvZc2YXsZUn4zKDwC_CWQZ2EUeprNiZWDKYB-KB52zRclYE6671vZnNV0kugFiQ0NaQslRhivOktKrRUFufcWByX_XsEgwF04S9nwyCPp3GSfZqtMOPJvtfxpK_jzUd6NxB_ "Charcoal – Attempt This Online") Link is to verbose version of code. Saves 8 bytes by being able to vectorised multiply two arrays. Explanation: Premultiplies the Bernoulli numbers by `n!` and then divides the final result by an extra `n!`. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~24 23~~ 15 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` c×>ɗþḶZæ*-ṪŻN-¦ ``` A monadic Link that accepts a positive integer, \$n\$, and yields the coefficients in ascending order. **[Try it online!](https://tio.run/##ASQA2/9qZWxsef//Y8OXPsmXw77huLZaw6YqLeG5qsW7Ti3Cpv///zU "Jelly – Try It Online")** ### How? ``` c×>ɗþḶZæ*-ṪŻN-¦ - Link: positive integer, n Ḷ - lowered range (n) -> [0 .. n-1] þ - (i in [1 .. n]) table (j in [0 .. n-1]) with operator: ɗ - last three links as a dyad f(i,j): c - (i) choose (j) > - (i) greater than (j)? × - multiply -> iCj if i>j else 0 Z - transpose - - -1 æ* - matrix power Ṫ - tail Ż - prepend a zero ¦ - sparse application... - - ...to indices: -1 (penultimate) N - ...action: negate ``` [Answer] # [Desmos](https://desmos.com/calculator), ~~86~~ 84 bytes ``` K=[0...m-1] S(m)=join(nCr(m,K)/m∑_{k=0}^K∑_{v=0}^k(-1)^vnCr(k,v)(v+1)^K/(k+1),0) ``` My outputs quickly deviate from the actual solutions due to some weird floating point issues, though that is allowed by OP. [Try It On Desmos!](https://www.desmos.com/calculator/dkqxshzcco) [Try it On Desmos! - Prettified](https://www.desmos.com/calculator/dngxrnku6x) Copying off formulas from Wikipedia go brrr :P ### How? I first started off from this [formula](https://en.wikipedia.org/wiki/Bernoulli_number#Sum_of_powers) from Wikipedia: $$S\_m(n)=\frac1{m+1}\sum\_{k=0}^m\binom{m+1}kB\_k^+n^{m+1-k}$$ Where ([formula](https://en.wikipedia.org/wiki/Bernoulli_number#Explicit_definition) also from Wikipedia): $$B\_m^+=\sum\_{k=0}^m\sum\_{v=0}^k(-1)^v\binom kv\frac{(v+1)^m}{k+1}$$ So, $$S\_m(n)=\frac{\displaystyle\sum\_{k=0}^mn^{m+1-k}\binom{m+1}k\sum\_{x=0}^k\sum\_{v=0}^x(-1)^v\binom xv\frac{(v+1)^k}{x+1}}{m+1}$$ But this formula is shifted one to the left of what is expected; for example, \$S\_3(n)\$ gives \$0.25n^4+0.5n^3+0.25n^2\$, which is actually the expected output for `4`. To fix this, we will have to shift it back to the right; namely, we have to calculate \$S\_{m-1}(n)\$ instead. Plugging this into our formula gives: $$S\_{m-1}(n)=\frac{\displaystyle\sum\_{k=0}^{m-1}n^{m-k}\binom mk\sum\_{x=0}^k\sum\_{v=0}^x(-1)^v\binom xv\frac{(v+1)^k}{x+1}}m$$ Notice that this is just a sum of monomials in terms of \$n\$, and that the sum goes from higher powers of \$n\$ to lower powers of \$n\$. So, the list of descending coefficients would be: $$\frac{\displaystyle\binom mk\sum\_{x=0}^k\sum\_{v=0}^x(-1)^v\binom xv\frac{(v+1)^k}{x+1}}m$$ for \$k=0,1,\ldots,m-1\$. But looking back at the formula for \$S\_{m-1}(n)\$, the outer sum only goes from monomials in terms of \$n^m\$ to \$n\$; specifically, we are missing the constant term. This means that the constant term is always \$0\$, which have the concatenate to the end of the list. [Answer] # [Python](https://www.python.org) NumPy, 99 bytes ``` f=lambda n,i=1:q**~-n if i>n else(X:=f(n,i+1))+(q-1)**i/i*X[i-1] from numpy import* q=poly1d([1,0]) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=NY4xDoIwFEB3TvHHttDI3wxJPQcJYUCh-gn9LbUMLF7EhUXv5G10wPm95L3nO6zp5nnbXkuy-vi5WDN17tx3wAUZrGalHpqBLNCJYZjug6grY8WP5ihlLmaNUik6kKob0thmNnoHvLiwArngY1LZbIKfVuxFg0XZyj0F1kcYgRhix9dBYIGlrEIkTsKKUe7ef-0L) # [Python](https://www.python.org), 103 bytes ``` def f(n): Q=8**n;D,N=1,Q**n while n:D*=n;s=(2*N//Q**n-~Q)//2%Q-Q//2;N=N*n+Q*(Q-1)**n*s;yield s/D;n-=1 ``` [Attempt This Online!](https://ato.pxeger.com/run?1=NY5BCoMwFET3nuJ3UUi-hjSuxJCd60COUDDRiHxFLcVNL9KNm_ZOvU0tbVcz8B7M3J_jurQDbdvjsgRRvJraBwiMeJmAMwUi6SqzRmVurwlc29h7oLJCQ3o2LEcr5QeJm-NS5kcn3B7aGouUOmROKL5jnPUafV_DLCtNwqjf3CEME3QQCaYzNZ6pTJ14OU6RFoaBdZx_xf-_Nw) Pure Python version using [this tip](https://codegolf.stackexchange.com/a/169115/107561) by @xnor. ### [Python](https://www.python.org) NumPy, 104 bytes ``` lambda n:[Q:=q**~-n,*[Q:=Q+(q-1)**i/i*Q[i-1]for i in r_[n:0:-1]]][-1] from numpy import* q=poly1d([1,0]) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=LY1BDoIwFET3nKLL9ksj3ZkmHIJ1aQwGKyX0tzRlwcaLuCExeidvIyibmclk8ubxDnPqPC5PU9avKRl--nRD4y5tQ1CqSpYjwJ1jDluuDnTkggHYo4VKWS608ZFYYpHEs0JZyLXSWq2amegdwcmFmVgXfEyQjWXwwyxaqkReaLb_kY3R_xgN3q5U5KJgMkSLiRras323LH__Ag) Now doing the Gauss elimination by hand. ### [Python](https://www.python.org) NumPy, 115 bytes ``` lambda n:-q*([q**~-n]*mat([q**n+((q-1)**i-q**i)for i in r_[n:0:-1]])[:,1:].I).A1 from numpy import* q=poly1d([1,0]) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=RY1NCsIwFIT3PUWWSWxK304CXbj0DDFIpEYDzcuP6aIbL-KmIHonb6NowdUwfMM3t2ecyjngfLfd7jEWK9avy2D8oTcEpUicqsT5VaDm3pRvwRWlSQDj3H04d8yGTBxxSPJeoWylAK2ZkjVI3WxZs4HK5uAJjj5OxPkYcuFV6mIYJuipgrrVbLkmf5fB05FCDS2TMTss1FLHlt08__IN) Directly solves the linear system of equations that arises from checking terms between p(X) and p(X-1). Uses polynomial (X-1)^k to generate binomial coefficients as needed. Returns actual polynomials (`poly1d` objects). ### More explanation: Consider the n+1 dimensional vector space of polynomials of degree <= n with monomials 1,X,X^2,... as a basis. Changing variables X |-> X+d for any constant d induces a linear map L\_d from the vector space onto itself as evaluating a polynomial p(X) at X+d yields a new polynomial in X of the same degree. The coefficients of the matrix representing this map will be products of binomial coefficients and powers of d. Now let us focus on the specific polynomial c(X) this challenge is asking for. This polynomial has the property c(j)-c(j-1)=j^(n-1) for any natural number j. As both sides of this equation are polynomials they must be identical c(X)-c(X-1) = X^(n-1). This can be written in terms of the substitution maps L\_d, viz.:X^(n-1) =(L\_0-L\_-1) c. What the code does is solving (or asking a library to solve) this equation. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~39~~ 30 (or 29) [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` LIÝδcθāε!©yL/yGü-ā*}®/}*I/`a)˜ ``` -9 bytes and increased both speed and floating point accuracy (up to \$n\leq20\$) by porting [*@Neil*'s Charcoal answer](https://codegolf.stackexchange.com/a/255156/52210) instead. Therefore also outputs as decimals. [Try it online](https://tio.run/##ATMAzP9vc2FiaWX//0xJw53OtGPOuMSBzrUhwql5TC95R8O8LcSBKn3Cri99KkkvYGEpy5z//zU) or [verify all test cases](https://tio.run/##AUsAtP9vc2FiaWX/MTZFTj8iIOKGkiAiP07/TE7Dnc60Y864xIHOtSHCqXlML3lHw7wtxIEqfcKuL30qTi9gYSnLnP8s//8tLW5vLWxhenk). If we're allowed to output each inner value wrapped in a list, it's 1 [byte](https://github.com/Adriandmen/05AB1E/wiki/Codepage) less by removing the trailing `˜`: [Try it online](https://tio.run/##ATEAzv9vc2FiaWX//0xJw53OtGPOuMSBzrUhwql5TC95R8O8LcSBKn3Cri99KkkvYGEp//81) or [verify all test cases](https://tio.run/##AUkAtv9vc2FiaWX/MTZFTj8iIOKGkiAiP07/TE7Dnc60Y864xIHOtSHCqXlML3lHw7wtxIEqfcKuL30qTi9gYSn/LP//LS1uby1sYXp5). **Original 39 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) answer:** ``` ÎLD<δcÅl¾ζÐøU˜nO/тF©X2Føδ*O®}·s-}θ`s(s) ``` Port of [*@JonathanAllan*'s Jelly answer](https://codegolf.stackexchange.com/a/213920/52210), except without the builtins.. :/ Therefore also outputs as decimals in reversed order. [Try it online](https://tio.run/##AU8AsP9vc2FiaWX//8OOTEQ8zrRjw4Vswr7OtsOQw7hVy5xuTy/RgkbCqVgyRsO4zrQqT8KufcK3cy19zrhgcyhzKf81LsOy/zX/LS1uby1sYXp5) or [verify the first 6 test cases](https://tio.run/##AVwAo/9vc2FiaWX/NkVOPyIg4oaSICI//8K@TkxEPM60Y8OFbMK@zrbDkMO4Vcucbk8v0YJGwqlYMkbDuM60Kk/Crn3Ct3Mtfc64YHMocyn/NS7Dsiz//y0tbm8tbGF6eQ). Very slow. Also rounds the result to 5 decimal points in the footer (feel free to remove the `5.ò` to see the actual unrounded output). These kind of challenges aren't really 05AB1E's strong suit.. **Explanation:** ``` LIÝδcθ # Get the input'th Pascal Triangle row: L # Push a list in the range [1, (implicit) input] IÝ # Push another list in the range [0,input] δ # Apply double-vectorized over these two lists, creating a table of: c # Choose (binomial coefficient builtin) θ # Then only keep the last row of this matrix āε!©yL/yGü-ā*}®/} # Get the first input amount of Bernoulli values: ā # Push a list in the range [1,length] (without popping the list) ε # Map over each value: ! # Push the factorial of this value © # Store it in variable `®` (without popping) yL # Push a list in the range [1,value] / # Divide value! by each of these values yG # Loop the value-1 amount of times: ü # Map over each overlapping pair: - # Subtract them from one another ā # Push a list in the range [1,length] (basically [1,value]) * # Multiply the values at the same positions in the lists # (removing any access items of unequal length lists) } # Close the loop (resulting in a single wrapped value) ®/ # Divide this wrapped result by the value! we've saved in variable `®` } # Close the map * # Multiply the values at the same positions in the lists together I/ # Divide each value by the input `a) # Transform the trailing value to a 0: ` # Pop the list and dump its values to the stack a # Transform the top value to 0 with an is_alphabetic builtin ) # Wrap the values on the stack back into a list ˜ # (Optional: flatten the list of wrapped items to a list of items) # (after which the result is output implicitly) ``` `!©yL/yGü-ā*}®/` calculates [Bernoulli numbers](https://en.wikipedia.org/wiki/Bernoulli_number), based on [this CJam answer of @PeterTaylor](https://codegolf.stackexchange.com/a/65537/52210). ([A 05AB1E port of his answer would start to give incorrect results from around \$n>20\$.](https://tio.run/##ATcAyP9vc2FiaWX/NjDGkk4/IiDihpIgIj9O/yHCqU4@TC9ORsO8LcSBKn3Cri//LP//LS1uby1sYXp5)) ``` Î # Push 0 and the input-integer L # Pop and push a list in the range [1,input] D< # Duplicate, and decrease each value to range [0,input) δ # Apply double-vectorized over these two lists, creating a table of: c # Choose (binomial coefficient builtin) Ål # Get the lower triangle of this matrix ζ # Zip/transpose this triangular matrix, ¾ # using 0 as filler for the unequal length rows ÐøU˜nO/тF©X2Føδ*O®}·s-} # Calculate the Inverse of this matrix: Ð # Triplicate this matrix ø # Zip/transpose the now square matrix back in the top copy U # Pop and put this transposed copy in variable `X` ˜ # Flatten another copy n # Get the square of each value in this list O # Then sum it together / # Divide the values in the matrix by this sum тF # Loop 100 times: © # Store the current matrix in variable `®` X # Push the matrix from variable `X` 2F # Inner loop 2 times: ø # Zip/transpose; swapping rows/columns δ # Apply double-vectorized on the two matrices: * # Multiply the values at the same positions in the matrices together O # Sum each inner row ® # Push the matrix from variable `®` }· # After the inner loop: double each inner value in the top matrix s # Swap so the other matrix is at the top - # Subtract the values at the same positions of the matrices } # Close the outer loop θ # Leave the last row of this Inverted matrix ` # Pop and dump its values to the stack s # Swap so the second last value as at the top ( # Negate it s # Swap it back ) # Wrap all values (including the initial 0) on the stack into a list # (which is output implicitly as result) ``` `ÐøU˜nO/тF©X2Føδ*O®}·s-` calculates the [inverse of a matrix](https://en.wikipedia.org/wiki/Invertible_matrix), which I've done before in [this 05AB1E answer of mine](https://codegolf.stackexchange.com/a/213920/52210). [Answer] # [APL(Dyalog Unicode)](https://dyalog.com), ~~25 24 22~~ 20 bytes [SBCS](https://github.com/abrudz/SBCS) -2 thanks to [rak1507](https://codegolf.stackexchange.com/posts/comments/565732) ``` -0,⊢⌷∘⌹(1∘+!⍥-⍳)⍤0∘⍳ ``` [Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=0zXQedS16FHP9kcdMx717NQwBNLaio96l@o@6t2s@ah3iQFIonczAA&f=40pTMORKUzACYmMgNgFiUwA&i=AwA&r=tryapl&l=apl-dyalog&m=dfn&n=f) Outputs coefficients in ascending order. [Answer] # [Wolfram Mathematica](https://www.wolfram.com/wolframscript/), 22 bytes [Try it online!](https://tio.run/##y00syUjNTSzJTE78n6ZgqxDz3yOxKDc/LzPZrzQ3KbUoukLHUFc5Vg0oqe@gEJSYl54abaijYKqjYBiroK8fUJSZV/IfAA) ``` HarmonicNumber[x,1-#]& ``` --- ### How? `Sum[k^(n - 1), {k, 1, x}] // FullSimplify` reduces to `HarmonicNumber[x, 1 - n]`. Here `HarmonicNumber[n, r]` means the \$n\$-th harmonic number of order \$r\$: \$\ \ \ H\_n^{(r)}=\sum\_{i=1}^n 1 / i^r\$ [Answer] # [PARI/GP](https://pari.math.u-bordeaux.fr), 21 bytes ``` n->sumformal(x^n--,x) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMHiNAXbpaUlaboWW_N07YpLc9Pyi3ITczQq4vJ0dXUqNCFyN1WAwhp5CrYKhjoKhmY6CgVFmXklQAElBV07IJGmkaepCVW7YAGEBgA) A built-in. --- # [PARI/GP](https://pari.math.u-bordeaux.fr), 36 bytes ``` n->(1/(1-1/matpascal(n))[,^n+1])[n,] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMHiNAXbpaUlaboWN1XydO00DPU1DHUN9XMTSwoSi5MTczTyNDWjdeLytA1jNaPzdGJhatPyizTyFGwVDHUUDM10FAqKMvNKgAJKCrp2QCINpE0TonbBAggNAA) Output a list of coefficients in ascending order. ]
[Question] [ This is OEIS sequence [A055397](https://oeis.org/A055397). In Conway's Game of life, a **still life** is a pattern that does not change over time. We can see from the rules of Conway's Game of life that, a pattern is a still life if and only if: * every living cell has exactly two or three living neighbors, * none of the dead cells have three living neighbors. Given a positive integer \$n\$, what is the maximum number of living cells of a still life in a \$n \times n\$ bounding box? The following table shows the results for small \$n\$s: (Screenshot from the book *[Conway's Game of Life - Mathematics and Construction](https://conwaylife.com/book/)* by Nathaniel Johnston and Dave Greene) [![Screenshot from Conway's Game of Life - Mathematics and Construction by Nathaniel Johnston and Dave Greene](https://i.stack.imgur.com/8CjGD.png)](https://i.stack.imgur.com/8CjGD.png) In 2012, [G. Chu and P. J. Stuckey gave a complete solution for all \$n\$](https://people.eng.unimelb.edu.au/pstuckey/papers/still-life.pdf). When \$n > 60\$, the results are: $$\begin{cases} \lfloor n^2/2 + 17n/27 - 2 \rfloor, & \text{ if } n \equiv 0, 1, 3, 8, 9, 11, 16, 17, 19, 25, 27, \\ & \quad \quad \ \ \ \, 31, 33, 39, 41, 47, \text{or } 49 \ (\text{mod } 54) , \text{ and} \\ \lfloor n^2/2 + 17n/27 - 1 \rfloor, & \text{ otherwise}. \end{cases}$$ When \$n \le 60\$, the results are not so regular. They are given in the testcases. ## Task Given a positive integer \$n\$, output the maximum number of living cells of a still life in a \$n \times n\$ bounding box. 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. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins. ## Testcases ``` 1 0 2 4 3 6 4 8 5 16 6 18 7 28 8 36 9 43 10 54 11 64 12 76 13 90 14 104 15 119 16 136 17 152 18 171 19 190 20 210 21 232 22 253 23 276 24 301 25 326 26 352 27 379 28 407 29 437 30 467 31 497 32 531 33 563 34 598 35 633 36 668 37 706 38 744 39 782 40 824 41 864 42 907 43 949 44 993 45 1039 46 1085 47 1132 48 1181 49 1229 50 1280 51 1331 52 1382 53 1436 54 1490 55 1545 56 1602 57 1658 58 1717 59 1776 60 1835 61 1897 62 1959 63 2022 64 2087 65 2151 66 2218 67 2285 68 2353 69 2422 70 2492 71 2563 72 2636 73 2708 74 2783 75 2858 76 2934 77 3011 78 3090 79 3168 80 3249 ``` [Answer] # [Python 2](https://docs.python.org/2/), 99 bytes ``` lambda n:n*(27*n+34)/54+(~0x282828a0b0b0b>>n%54&1)-(0x9f4f41e064109edb1e1397137967e232263/5**n+2)%5 ``` [Try it online!](https://tio.run/##RZPLbttADEX3/orJIo3kqMiQQ84jQAJ00y/org0KuZZbA65sWC6QbvrrLh9BKy10Rc3wcC6p0@/Lj@OM193Tl@th/LnZjmF@nNcdlvV8n6h/YLrv/sRXrHqPcaP38/N8y/QO@vddfG072hFMMRPENm03MEFqBVJpuUyYEHN64LVkw/6Wr5dpuXz9Ni7TEp7C5w6GEPshdDgE0mcaQtYnDaHqk4cAFsgiLFKGgCbqEJJ9arI3qYA4BLY0IHmzK8lcbBlI7mYwkOwQ/bMCoJlUhGcEgQCjScFAAZMCAs@AQkJwKSg5pUlhIVspKDB0LgotRcuAQkvoUaElR6DQxC2TQqNYTNqxTCahUXYpNGouhcbJ8iahcTZwEho3MygJLSePCi1njwqtRKshCa2Q@y60Uq0cElpFi5LQqvtIqO4ZmNRIsnpJaK0ZgtTJmDysVsbKptVLcINIzYRqNZO6iWjrOaqu5ieDtsHPxajay2KhAnl/WBtI3gpWLpOxWLk5@nrlZvYp8iZa9azc4q3Jyq3J9mblVrc2K7ex1Za1kxEtZybV1dewjgBbnVm4iD6fWQcU/ey56mz4RGThInmeouNDzbXOz1vzig5Q9jMWm6DoM6/cUn2Ncqufqyi3JWtQKTZmVk/RfyO6P0W4Cbz3Ner8SeteVqvvx@NWfsFP51/Tanc8h3nYhP0c/v@fj6sg134XNuHmKey6ufeIXqfzfr50smXQeP8v/pb043hYppVs1Xff5TvuPhwOhljCaVyWaXtz11//Ag "Python 2 – Try It Online") The formula in the challenge description works pretty well for \$n<60\$ and is always within 2 of the actual value, so we first calculate the formula: ``` n*(27*n+34)/54+~(0x282828a0b0b0b>>n%54&1) = n*(27*n+34)/54+(~0x282828a0b0b0b>>n%54&1)-2 ``` And add the offset: ``` -(0x9f4f41e064109edb1e1397137967e232263/5**n+2)%5+2 ``` The `-2` and `+2` cancel out [Answer] # [MATL](https://github.com/lmendo/MATL), 32 bytes ``` UTFZ^!"@GeTTYat3Y6QZ+5:7m=?@svX> ``` Brute force. Times out for input exceeding `3`. Part of the code reused from [this answer](https://codegolf.stackexchange.com/a/216092/36398). Takes *n* as input. [Try it online!](https://tio.run/##y00syfn/PzTELSpOUcnBPTUkJDKxxDjSLDBK29TKPNfW3qG4LMLu/39jAA) ### How it works ``` U % Input (implicit): n TF % Push [1, 0] Z^ % Cartesian power: all Cartesian tuples of length n containing % 1 or 0. Gives a matrix with n^2 columns, where each row is a % Cartesian tuple !" % For each row @ % Push current row Ge % Reshape with n rows (and n columns) TTYa % Add a frame of zeros t % Duplicate 3Y6QZ+5:7m % Perform one iteration of the Game of Life (see linked answer) =? % If all entries (before and after the iteration) are equal @s % Push sum of current row (that is, number of active cells) vX> % Concatenate with previous result, if any, and take maximum % End (implicit) % End (implicit) % Display (implicit) ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 122 bytes ``` n=>n*n/2+17*n/27+1-("1201304124344333343332333333322423223224232332232322323323223"[n]||2+(706447126760203/2**(n%54)&1))|0 ``` [Try it online!](https://tio.run/##LcZBDoIwEIXhqxASTUtFZqYjXShexLggCKSGTA0YV9y9gvgW//ee9aeemtG/3rmERxu7Kkp1lUwKMuhWnMFcpUiAFhiJLbNdtobsNiKmJX/t727ZTG9yn2cyykHJ7JBKVwKBLSjLlOxOrPeo9QyxC6PyFZwTf0FYMMbrJsgUhvY4hF75Q9Ipr3X8Ag "JavaScript (Node.js) – Try It Online") Uncompressed table # [JavaScript (Node.js)](https://nodejs.org), 109 bytes ``` n=>n*(34+27*n)/54+!(706447126760203/2**(n%54)&1)-[0xbffab022c9fe1aebcdf9b3aabadf0e5376en.toString(5)[n]||2]|0 ``` [Try it online!](https://tio.run/##DcXBDoIgGADgV7FDDTD1BxHmyl6io/MACI7mfpq61sF3t77L9zIfs7olvrcC0@iP0B3YPZCRWuZCM6RVI/MT0aCk1FworUBAXQnGCJ4bSS@cFj18bQjGghCuDZ4bb90YWlsbY80YwDe1Vh7LLT23JeJEGtrjsO9i2OEIaSGxg1sW7xz@5XmkLuGaZl/OaSLxmgUSKT1@ "JavaScript (Node.js) – Try It Online") Indirect port of gsitcia's solution [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 57 bytes ``` NθI⁻÷×⁺ײ⁷θ³⁴θ⁵⁴⊖§⁺”)⊞E?ü⍘ï″ê&8,⁴&0S6.¬↶”…”{∨>~iRz÷↙Ja”θθ ``` [Try it online!](https://tio.run/##VU7LCoMwELz7FeJpBQu6SduDp6IXDy0e@gNWFxqI8RWl/frUGBE6h5nZYRamfldj3VXSmEL1s37M7YtGGMLUK0ehNGTVpOEu1DxBoXQuFtEQPEVLE5RyDZ3Fa@QPYeQzHjpztsbLqR6pJaWpgZsuVEMf9xUkGCcs5glyxjlbYQmZAyLHlXZlm3XkNIj87FtLyt5dD8Ge4qGujf/XoXsrsDu3sRapMZfYnBZZ/QA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Based on the formula in the challenge description, but looks up the value to subtract in one of two lookup tables, depending on whether the input is greater than `60` or not. ``` Nθ First input as an integer ²⁷ Literal integer 27 × Multiplied by θ Input integer ⁺ Plus ³⁴ Literal integer 34 × Multiplied by θ Input integer ÷ Integer divided by ⁵⁴ Literal integer 54 ⁻ Subtract ... Compressed lookup table for 0..60 ⁺ Concatenated with ... Compressed lookup table for 61..114 … Cyclically extended to length θ Input integer § Indexed by θ Input integer ⊖ Decremented I Cast to string Implicitly print ``` [Answer] # [Python 3](https://docs.python.org/3/), 285 bytes ``` lambda n:max(map(len,[q for s in r(n**2+1)for q in combinations([(x,y)for x in r(n)for y in r(n)],s)if{*q}==g(q,n)])) g=lambda c,n:{(x,y)for x in r(-1,n+1)for y in r(-1,n+1)if sum((q,r)in c for q in[x-1,x,x+1]for r in[y-1,y,y+1])in[[3],[3,4]][(x,y)in c]} r=range from itertools import* ``` [Try it online!](https://tio.run/##XY/BjsMgDETv@QqOkHoPafZUiS@hHGg3ZJGCSRxWAlX99iy06aE9@nk8M55z/A3Yb1aet8n4y49hePImcW9mPg0IamE2EFuZQ0Yc2/Z46EQlSyXX4C8OTXQBV654gvzYpV39GPJr0LAKZ2/tcpdy5AsUIkQzyj33Cni6fVp8dYB7YH4jzrL1z/NiQ6IWYa9OKhVFgnTodEVUUS4oQy6oaJXqNagevrV@Nq7n@t6QJIPj0FgKnrk4UAxhKn/7OVBst5kcRm55L8T2Dw "Python 3 – Try It Online") Times out pretty fast because it just brute-forces. Pretty sure it's \$O\left(2^{n^2}\right)\$ but it could be worse. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 87 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` •1ÏUΓ’∍GTšƒΘQ74₅βvćsZý[Σi—т°/βΩùŠ·ćeeðZGïQ©.†•60в.¥In;17I*27÷+<•6WÁ.‹Ñ•7в.¥I54%å-ª.ÞI<è ``` Boring approach: hard-codes the values \$\leq60\$, and calculates the values \$\gt60\$ given the formula in the challenge description. I might try to a brute-force approach later, but 05AB1E overall isn't too great at matrix challenges. [Try it online](https://tio.run/##yy9OTMpM/f//UcMiw8P9oecmP2qY@aij1z3k6MJjk87NCDQ3edTUem5T2ZH24qjDe6PPLc581DDlYtOhDfrnNp1beXjn0QWHth9pT009vCHK/fD6wEMr9R41LAAaZmZwYZPeoaWeedaG5p5aRuaHt2vbgITDDzcCVew8PBHIMYcoMTVRPbxU99AqvcPzPG0Or/j/38wEAA) or [verify all test cases](https://tio.run/##yy9OTMpM/W9h4Opnr6TwqG2SgpL9/0cNiwwP94eem/yoYeajjl73kKMLj006NyPQ3ORRU@u5TWVH2oujDu@NPrc481HDlItNhzbon9t0buXhnUcXHNp@pD019fCGKPfD6wMPrdR71LAAaJiZwYVNeoeW@uVZG5r7aRmZH96ubQMSDj/cCFSx8/BEIMccrMTT1ET18FLdQ6v0Ds/zszm84r/OfwA). **Explanation:** ``` •1ÏUΓ’∍GTšƒΘQ74₅βvćsZý[Σi—т°/βΩùŠ·ćeeðZGïQ©.†• # Push compressed integer 54764668022476930839561631116267184217708747839781677738253594755809981424425189706066485884825983031999 60в # Convert it to base-60 as list: [4,2,2,8,2,10,8,7,11,10,12,14,14,15,17,16,19,19,20,22,21,23,25,25,26,27,28,30,30,30,34,32,35,35,35,38,38,38,42,40,43,42,44,46,46,47,49,48,51,51,51,54,54,55,57,56,59,59,59] .¥ # Undelta with leading 0: [0,4,6,8,16,18,28,36,43,54,64,76,90,104,119,136,152,171,190,210,232,253,276,301,326,352,379,407,437,467,497,531,563,598,633,668,706,744,782,824,864,907,949,993,1039,1085,1132,1181,1229,1280,1331,1382,1436,1490,1545,1602,1658,1717,1776,1835] I # Push the input-integer n # Square it ; # Halve it 17I* # Push the input*17 27÷ # Integer-divided by 27 + # Add those two together < # Decrease it by 1 •6WÁ.‹Ñ• # Push compressed integer 6607718158603 7в # Convert it to base-7 as list: [1,2,5,1,2,5,1,2,6,2,4,2,6,2,6,2] .¥ # Undelta with leading 0: [0,1,3,8,9,11,16,17,19,25,27,31,33,39,41,47,49] I # Push the input-integer 54% # Modulo-54 å # Check if it's in this list - # Subtract that check ª # Append it to the earlier list of 60 values .Þ # Infinitely cycle this trailing item I<è # Pop the list and get its 0-based (input-1)'th value # (after which it is output implicitly as result) ``` [See this 05AB1E (sections *How to compress large integers?* and *How to compress integer lists?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand how the compression works. [Answer] # [Befunge-98 (PyFunge)](https://pythonhosted.org/PyFunge/), 236 bytes ``` <v.ke0" $+6@LZhw .AUk3Lf >\z?b+Qw Jr Jv'U  8 h"a 'a"Q  = s"c-'cf'd!'d"\U"0F='(4"FPSP" kv>'}*+.:! $ >:::M2FD\:'FM'FD\I'6%4gFNAAI.1FA  ``` Code is almost entirely unprintables, many of which get omitted by Stack Exchange's markdown renderer. See the TIO link for the full code. Brief explanation: 1. The first line is set-up, which first enables the [`FPSP` fingerprint](https://pythonhosted.org/PyFunge/fingerprint/FPxP.html), then pushes 61 as a floating-point number, and a zero as a sentinel value for later. The rest of the first line is a base-124 encoding of the hardcoded numbers for still lifes of value less than 60. The `.ke` at the beginning of the first line (since code is read in reverse) mean "execute the `.` instruction 0xe (14) times", printing the values less than 124. 2. The second line just prints the values that are greater than 124 but still hardcoded, until it reaches the sentinel. 3. The third line is a `$`, which discards the `0` sentinel from earlier. At this point the 61 and then some garbage is left on the stack. 4. The fourth line does the formula part; each `/` separated segment is one of the terms on the equation. ``` ::: Makes 3 copies of the index being output (leaving 4 on the stack) M Multiplies the first two together, leaving n^2 and 2 copies of N 2FD Divides by two, leaving N^2/2 and 2 copies of N \: Swap the top two values and duplicate, leaving 2 copies of N, then n^2 \ 2, then 1 more copy of N ' FM' FD Do the multiplying by 17 and dividing by 27 for the second term (there's an unprintable character after each ') \I Swap the top two values, then convert the number to an integer. Stack at this point is N then 17n/27 then n^2/2 then N again '6%4g Mod N by 54, then look it up in the lookup table in the fourth line of code (which is all unprintables) FN Convert it from a positive integer to a negative floating-point number AAI. Add all of the terms on the stack together, convert it to an integer, and output 1FA Increment the index on the stack by one for the next iteration. ``` 5. The fifth line of code is a lookup table for whether to subtract one or two. It is never actually executed, merely read using Befunge's ability to look at its own source code. [Try it online!](https://tio.run/##S0pNK81LT9W1tNAtqAQz//9XsCnTy041UGJh4xAQklHRNnPwicooZ@RmlGbUY3RkDGXMZmJmkmIyZvJhSmNmYVZgtmOOYa5ikWexZ0li5WDVZg1kLWdTYPNiK2JXYPdiL@NQ5wjlZOe04MxQSpRTT1QK5GbntuUuVkrWVU9OU09RVE9RiuGT4gtVMnCzVdcwUXILCA5Q4sous1Ov1dLWs1LkUuGys7Ky8jVyc4mxUhd081WXBrI81c1UTdLd/BwdPfUM3Ry5mJgYmRiBAJ1mhNCoPDj9/z8A "Befunge-98 (PyFunge) – Try It Online") ]
[Question] [ The title is an homage of the [Natural Number Game](https://wwwf.imperial.ac.uk/%7Ebuzzard/xena/natural_number_game/), which is a nice interactive tutorial into proving certain properties of natural numbers in Lean. Given that the [previous](https://codegolf.stackexchange.com/q/236105/78410) [two](https://codegolf.stackexchange.com/q/236132/78410) were slightly too involved (either mathematically or technically) for newcomers to Lean (i.e. the vast majority of CGCC community), I decided to pose some simpler theorems. --- Let's start with the classic definition of a linked list. You can ignore most of the theoretical fluff; the point is that `list A` is a linked list containing values of type `A`, and defined as either an empty list `[]` (aka `list.nil`) or a pair (cons) of a value and a tail `h :: t` (aka `list.cons`). Our definitions of `list` and functions on it live in the namespace `mylist` in order to avoid clash with the existing definitions. ``` universe u variables {A : Type u} namespace mylist inductive list (T : Type u) : Type u | nil : list | cons : T → list → list infixr ` :: `:67 := list.cons notation `[]` := list.nil ``` We then define `append` and `rev` (reverse) on lists. Note that `has_append` instance is necessary in order to use `++` notation, and unfolding lemmas are needed to use the definitional equations of `append` on `++`. Also, `rev` is defined using the simplest possible definition via `++`. ``` def append : list A → list A → list A | [] t := t | (h :: s) t := h :: (append s t) instance : has_append (list A) := ⟨@append A⟩ @[simp] lemma nil_append (s : list A) : [] ++ s = s := rfl @[simp] lemma cons_append (x : A) (s t : list A) : (x :: s) ++ t = x :: (s ++ t) := rfl @[simp] def rev : list A → list A | [] := [] | (h :: t) := rev t ++ (h :: []) ``` Now your task is to prove the following statement: ``` theorem rev_rev (s : list A) : rev (rev s) = s := sorry ``` You can change the name of this statement and golf its definition, as long as its type is correct. [Any kind of sidestepping is not allowed.](https://codegolf.meta.stackexchange.com/a/23938/78410) Due to the nature of this challenge, adding imports is also not allowed (i.e. no mathlib). The entire boilerplate is provided [here](https://leanprover-community.github.io/lean-web-editor/#code=universe%20u%0Avariables%20%7BA%20%3A%20Type%20u%7D%0Anamespace%20mylist%0A%0Ainductive%20list%20%28T%20%3A%20Type%20u%29%20%3A%20Type%20u%0A%7C%20nil%20%3A%20list%0A%7C%20cons%20%3A%20T%20%E2%86%92%20list%20%E2%86%92%20list%0A%0Ainfixr%20%60%20%3A%3A%20%60%3A67%20%3A%3D%20list.cons%0Anotation%20%60%5B%5D%60%20%3A%3D%20list.nil%0A%0Adef%20append%20%3A%20list%20A%20%E2%86%92%20list%20A%20%E2%86%92%20list%20A%0A%7C%20%5B%5D%20t%20%3A%3D%20t%0A%7C%20%28h%20%3A%3A%20s%29%20t%20%3A%3D%20h%20%3A%3A%20%28append%20s%20t%29%0Ainstance%20%3A%20has_append%20%28list%20A%29%20%3A%3D%20%E2%9F%A8%40append%20A%E2%9F%A9%0A%0A%40%5Bsimp%5D%20lemma%20nil_append%20%28s%20%3A%20list%20A%29%20%3A%20%5B%5D%20%2B%2B%20s%20%3D%20s%20%3A%3D%20rfl%0A%40%5Bsimp%5D%20lemma%20cons_append%20%28x%20%3A%20A%29%20%28s%20t%20%3A%20list%20A%29%20%3A%20%28x%20%3A%3A%20s%29%20%2B%2B%20t%20%3D%20x%20%3A%3A%20%28s%20%2B%2B%20t%29%20%3A%3D%20rfl%0A%0A%40%5Bsimp%5D%20def%20rev%20%3A%20list%20A%20%E2%86%92%20list%20A%0A%7C%20%5B%5D%20%3A%3D%20%5B%5D%0A%7C%20%28h%20%3A%3A%20t%29%20%3A%3D%20rev%20t%20%2B%2B%20%28h%20%3A%3A%20%5B%5D%29%0A%0A---%0A--%20edit%20this%20region%20to%20solve%20the%20challenge%0Atheorem%20rev_rev%20%28s%20%3A%20list%20A%29%20%3A%20rev%20%28rev%20s%29%20%3D%20s%20%3A%3D%20sorry%0A---%0A%0Aexample%20%3A%20%E2%88%80%20%28s%20%3A%20list%20A%29%2C%20rev%20%28rev%20s%29%20%3D%20s%20%3A%3D%20rev_rev%0Aend%20mylist). Your score is the length of the code between the two dashed lines, measured in bytes. The shortest code wins. For beginners, proving the following lemmas in order will help you solve the challenge: > > > ``` > lemma append_nil (s : list A) : s ++ [] = s := sorry > lemma append_assoc (s t u : list A) : s ++ t ++ u = s ++ (t ++ u) := sorry > lemma rev_append (s t : list A) : rev (s ++ t) = rev t ++ rev s := sorry > ``` > > > > [Answer] # Lean, 101 bytes ``` def r:∀s,rev(@rev A s)=s|[]:=rfl|(x::t):=by conv{to_rhs,rw<-r t};simp;induction rev t;simp;simp[ih] ``` [Try it online!](https://leanprover-community.github.io/lean-web-editor/#code=universe%20u%0Avariables%20%7BA%20%3A%20Type%20u%7D%0Anamespace%20mylist%0A%0Ainductive%20list%20%28T%20%3A%20Type%20u%29%20%3A%20Type%20u%0A%7C%20nil%20%3A%20list%0A%7C%20cons%20%3A%20T%20%E2%86%92%20list%20%E2%86%92%20list%0A%0Ainfixr%20%60%20%3A%3A%20%60%3A67%20%3A%3D%20list.cons%0Anotation%20%60%5B%5D%60%20%3A%3D%20list.nil%0A%0Adef%20append%20%3A%20list%20A%20%E2%86%92%20list%20A%20%E2%86%92%20list%20A%0A%7C%20%5B%5D%20t%20%3A%3D%20t%0A%7C%20%28h%20%3A%3A%20s%29%20t%20%3A%3D%20h%20%3A%3A%20%28append%20s%20t%29%0Ainstance%20%3A%20has_append%20%28list%20A%29%20%3A%3D%20%E2%9F%A8%40append%20A%E2%9F%A9%0A%0A%40%5Bsimp%5D%20lemma%20nil_append%20%28s%20%3A%20list%20A%29%20%3A%20%5B%5D%20%2B%2B%20s%20%3D%20s%20%3A%3D%20rfl%0A%40%5Bsimp%5D%20lemma%20cons_append%20%28x%20%3A%20A%29%20%28s%20t%20%3A%20list%20A%29%20%3A%20%28x%20%3A%3A%20s%29%20%2B%2B%20t%20%3D%20x%20%3A%3A%20%28s%20%2B%2B%20t%29%20%3A%3D%20rfl%0A%0A%40%5Bsimp%5D%20def%20rev%20%3A%20list%20A%20%E2%86%92%20list%20A%0A%7C%20%5B%5D%20%3A%3D%20%5B%5D%0A%7C%20%28h%20%3A%3A%20t%29%20%3A%3D%20rev%20t%20%2B%2B%20%28h%20%3A%3A%20%5B%5D%29%0A%0A---%0A--%20edit%20this%20region%20to%20solve%20the%20challenge%0Adef%20r%3A%E2%88%80s%2Crev%28%40rev%20A%20s%29%3Ds%7C%5B%5D%3A%3Drfl%7C%28x%3A%3At%29%3A%3Dby%20conv%7Bto_rhs%2Crw%3C-r%20t%7D%3Bsimp%3Binduction%20rev%20t%3Bsimp%3Bsimp%5Bih%5D%0A---%0A%0Aexample%20%3A%20%E2%88%80%20%28s%20%3A%20list%20A%29%2C%20rev%20%28rev%20s%29%20%3D%20s%20%3A%3D%20r%0Aend%20mylist) I'm pretty happy with this. *Thanks to Huỳnh Trần Khanh for their help.* [Answer] # Lean, ~~102~~ 93 bytes ``` def R:∀s,rev(@rev A s)=s:=by let:(∀s(h:A),rev(s++h::[])=h::rev s);intro;induction s;simp* ``` [Try it on Lean Web Editor](https://leanprover-community.github.io/lean-web-editor/#code=universe%20u%0Avariables%20%7BA%20%3A%20Type%20u%7D%0Anamespace%20mylist%0A%0Ainductive%20list%20%28T%20%3A%20Type%20u%29%20%3A%20Type%20u%0A%7C%20nil%20%3A%20list%0A%7C%20cons%20%3A%20T%20%E2%86%92%20list%20%E2%86%92%20list%0A%0Ainfixr%20%60%20%3A%3A%20%60%3A67%20%3A%3D%20list.cons%0Anotation%20%60%5B%5D%60%20%3A%3D%20list.nil%0A%0Adef%20append%20%3A%20list%20A%20%E2%86%92%20list%20A%20%E2%86%92%20list%20A%0A%7C%20%5B%5D%20t%20%3A%3D%20t%0A%7C%20%28h%20%3A%3A%20s%29%20t%20%3A%3D%20h%20%3A%3A%20%28append%20s%20t%29%0Ainstance%20%3A%20has_append%20%28list%20A%29%20%3A%3D%20%E2%9F%A8%40append%20A%E2%9F%A9%0A%0A%40%5Bsimp%5D%20lemma%20nil_append%20%28s%20%3A%20list%20A%29%20%3A%20%5B%5D%20%2B%2B%20s%20%3D%20s%20%3A%3D%20rfl%0A%40%5Bsimp%5D%20lemma%20cons_append%20%28x%20%3A%20A%29%20%28s%20t%20%3A%20list%20A%29%20%3A%20%28x%20%3A%3A%20s%29%20%2B%2B%20t%20%3D%20x%20%3A%3A%20%28s%20%2B%2B%20t%29%20%3A%3D%20rfl%0A%0A%40%5Bsimp%5D%20def%20rev%20%3A%20list%20A%20%E2%86%92%20list%20A%0A%7C%20%5B%5D%20%3A%3D%20%5B%5D%0A%7C%20%28h%20%3A%3A%20t%29%20%3A%3D%20rev%20t%20%2B%2B%20%28h%20%3A%3A%20%5B%5D%29%0A%0A---%0Adef%20R%3A%E2%88%80s%2Crev%28%40rev%20A%20s%29%3Ds%3A%3Dby%20let%3A%28%E2%88%80s%28h%3AA%29%2Crev%28s%2B%2Bh%3A%3A%5B%5D%29%3Dh%3A%3Arev%20s%29%3Bintro%3Binduction%20s%3Bsimp*%0A---%0A%0Aexample%20%3A%20%E2%88%80%20%28s%20%3A%20list%20A%29%2C%20rev%20%28rev%20s%29%20%3D%20s%20%3A%3D%20R%0Aend%20mylist) The 102 byte solution I advertised [earlier](https://codegolf.stackexchange.com/questions/236182/lean-golf-list-game-rev-rev#comment536684_236182) had suboptimal type annotations: ``` def R:∀s:list A,rev(rev s)=s:=by let:(∀(s:list A)h,rev(s++h::[])=h::rev s);intro;induction s;simp* ``` ]
[Question] [ If 1 is not counted as a factor, then * 40 has two neighboring factors (4 and 5) * 1092 has two neighboring factors (13 and 14) * 350 does not have two neighboring factors (out of its factors 2, 5, 7, 10, 14, 25, 35, 50, 70, and 175, no two are consecutive) The proportion of positive integers that have this property is the proportion divisible by any of 6 (2 × 3), 12 (3 × 4), 20 (4 × 5), 30, 56, …. If we only calculate the proportion divisible by the first *n* of these, we get an approximation that gets more accurate as *n* increases. For example, for *n=1*, we find the proportion of integers divisible by 2 × 3 = 6, which is 1/6. For *n=2*, all integers divisible by 3 × 4 = 12 are also divisible by 6, so the approximation is still 1/6. For *n=3*, the proportion of integers divisible by 6 or 20 is 1/5, and so on. Here are the first few values: ``` 1 1/6 0.16666666666666666 3 1/5 0.20000000000000000 6 22/105 0.20952380952380953 9 491/2310 0.21255411255411255 12 2153/10010 0.21508491508491510 15 36887/170170 0.21676558735382265 21 65563/301070 0.21776663234463747 24 853883/3913910 0.21816623274423785 27 24796879/113503390 0.21846817967287144 ``` For values of *n* between the provided values, the output should be the same as the output for the value above (e.g. *n=5* → 1/5). Your program should take *n* and output either a fraction or decimal answer. You may take *n* at any offset (e.g. 0-indexing or 2-indexing into this sequence, instead of 1-indexing). For decimal output, your program must be accurate to at least 5 digits for all the test cases given. Scoring is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), with the shortest code winning. Inspired by [What proportion of positive integers have two factors that differ by 1?](https://math.stackexchange.com/q/3038712/65867) by [marty cohen](https://math.stackexchange.com/users/13079/marty-cohen) -- specifically, by [Dan](https://math.stackexchange.com/users/1374/dan)'s answer. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~14 13~~ 10 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) -1 using Erik the Outgolfer's idea to take the mean of a list of zeros and ones. -3 by using 3-indexing (as allowed in the question) - thanks to Dennis for pointing this out. ``` ḊPƝḍⱮ!Ẹ€Æm ``` A monadic Link accepting an integer, `n+2`, which yields a float. **[Try it online!](https://tio.run/##ASEA3v9qZWxsef//4biKUMad4biN4rGuIeG6uOKCrMOGbf///zk "Jelly – Try It Online")** (very inefficient since it tests divisibility over the range \$[2, (n+2)!]\$) (Started out as `+2µḊPƝḍⱮ!§T,$Ẉ`, taking `n` and yielding `[numerator, denominator]`, unreduced) ### How? ``` ḊPƝḍⱮ!Ẹ€Æm - Link: integer, x=n+2 Ḋ - dequeue (implicit range of) x - i.e. [2,3,4,...,n+2] Ɲ - apply to neighbours: P - product [2×3,3×4,...,(n+1)×(n+2)] ! - factorial of x x! Ɱ - map across (implicit range of) x! with: ḍ - divides? [[2×3ḍ1,3×4ḍ1,...,(n+1)×(n+2)ḍ1],[2×3ḍ2,3×4ḍ2,...,(n+1)×(n+2)ḍ2],...,[2×3ḍ(x!),3×4ḍ(x!),...,(n+1)×(n+2)ḍ(x!)]] € - for each: Ẹ - any? (1 if divisible by any of the neighbour products else 0) Æm - mean ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 15 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` Ì©!Lε®LüP¦Öà}ÅA ``` Port of [*@JonathanAllan*'s Jelly answer](https://codegolf.stackexchange.com/a/177683/52210), so also extremely slow. [Try it online](https://tio.run/##ASMA3P9vc2FiaWX//8OMwqkhTM61wq5Mw7xQwqbDlsOgfcOFQf//Ng) or [verify the first three test cases](https://tio.run/##ATUAyv9vc2FiaWX/fHZ5PyIg4oaSICI/ef/DjMKpIUzOtcKuTMO8UMKmw5bDoH3DhUH/LP8xCjMKNg). **Explanation:** ``` Ì # Add 2 to the (implicit) input # i.e. 3 → 5 © # Store this in the register (without popping) ! # Take the factorial of it # i.e. 5 → 120 L # Create a list in the range [1, (input+2)!] # i.e. 120 → [1,2,3,...,118,119,120] ε } # Map over each value in this list ® # Push the input+2 from the register L # Create a list in the range [1, input+2] # i.e. 5 → [1,2,3,4,5] ü # Take each pair # i.e. [1,2,3,4,5] → [[1,2],[2,3],[3,4],[4,5]] P # And take the product of that pair # i.e. [[1,2],[2,3],[3,4],[4,5]] → [2,6,12,20] ¦ # Then remove the first value from this product-pair list # i.e. [2,6,12,20] → [6,12,20] Ö # Check for each product-pair if it divides the current map-value # (1 if truthy; 0 if falsey) # i.e. [1,2,3,...,118,119,120] and [6,12,20] # → [[0,0,0],[0,0,0],[0,0,0],...,[0,0,0],[0,0,0],[1,1,1]] à # And check if it's truthy for any by taking the maximum # i.e. [[0,0,0],[0,0,0],[0,0,0],...,[0,0,0],[0,0,0],[1,1,1]] # → [0,0,0,...,0,0,1] ÅA # After the map, take the mean (and output implicitly) # i.e. [0,0,0,...,0,0,1] → 0.2 ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes ``` Ḋב$ḍẸ¥ⱮP$Æm ``` [Try it online!](https://tio.run/##ASQA2/9qZWxsef//4biKw5figJgk4biN4bq4wqXisa5QJMOGbf///zU "Jelly – Try It Online") -2 thanks to [Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan)'s suggestion to replace the LCM with the product (i.e. the LCM multiplied by an integer). [Dennis](https://codegolf.stackexchange.com/users/12012/dennis) noticed I can 2-index as well. [Answer] # JavaScript (ES6), ~~94 92~~ 90 bytes *Saved 2 bytes thanks to @Shaggy + 2 more bytes from there* Returns a decimal approximation. ``` n=>(x=2,g=a=>n--?g([...a,x*++x]):[...Array(1e6)].map((_,k)=>n+=a.some(d=>k%d<1))&&n/1e6)`` ``` [Try it online!](https://tio.run/##FYpLDoIwFAD3nqILNO9JqQEF46cYF3oJQ@QFCv5oCRCDIZwdYTGLmcyLvlQn1bNsHG1SNWRy0DKEVno8lyRD7TinHG5CCOLt0rbbCPeTnauKfuCqACNRUAlw528cd1uSqE2hIJXhe54eXcTFQq@mMY6Hw83lbM1ZwNmOM9cb8TnzxuhtRrbRTGSmulDyAM1kyBKja/NR4mNyiAmsTvc4davLQKNozPXZqhR87GPE4Q8 "JavaScript (Node.js) – Try It Online") --- # JavaScript (ES6), 131 bytes A much longer solution that returns an exact result as a pair \$[numerator, denominator]\$. ``` f=(n,a=[],p=x=1)=>n?f(n-1,[...a,q=++x*-~x],p*q/(g=(a,b)=>a?g(b%a,a):b)(p,q)):[...Array(p)].map((_,k)=>n+=a.some(d=>-~k%d<1))&&[n,p] ``` [Try it online!](https://tio.run/##FU7JTsMwEL3zFT50mWkmLgGBRMGpOPAVltVOVrrZjoNQUJX8ekgO7/BWvTP/cpuHk/@JrSvKcawUWGKlDXnVqQRVavcV2DghLaVkalQUdZt46KbAptlCrYApm2K8ryFbMjHuMgRPDeJurnyGwH/g0cgbe4ADXebNSLFs3a2EQqXxcFkWHwniaqUteTO@64TEM4lXEm8kkqcJL@ZBVi58cf4NVqhU5M627lrKq6vhyLC42x5nfXGHIJSYLiPKsztZWIutWGMvBjWZQT@aiQedmP6IOP4D "JavaScript (Node.js) – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 78 bytes ``` lambda n:sum(any(-~i%(j*-~j)<1for j in range(2,n+2))for i in range(10**7))/1e7 ``` [Try it online!](https://tio.run/##RcixDkAwEADQX7lFcleEdmki/ImlQmnDkarB4tcrJm98xx2XnVWyXZ9Wsw2jAW7Oa0PDN5aPy9CL8vHUSrsH8OAYguF5QlVwroi@df/KWghNVMlJpyM4jmBRaUov "Python 2 – Try It Online") Returns the approximate decimal to +5 digits; uses the naive brute force approach [xnor](https://codegolf.stackexchange.com/users/20260/xnor) suggests in comments on the question. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 26 bytes ``` FN⊞υ×⁺²ι⁺³ιI∕LΦΠυ¬⌊Eυ﹪ιλΠυ ``` [Try it online!](https://tio.run/##PY07DsIwEER7TuFyLZmG0FGCkJBI5IILmMTglfyJ7N1c39gpmGqk0XszO5PnZHytn5QFPOLKNHF42wxSCs3FASvxwmALaM8FTkqgVGLvQ@9SXg46YyS4mkJwww0XC08bv@Tgjp6aSue08EzAjZwSwYgRAwcYzdr1Y1t9AlTCyz3N/yf6Qa3netz8Dw "Charcoal – Try It Online") Link is to verbose version of code. Hopelessly inefficient (O(n!²)) so only works up to `n=4` on TIO. Explanation: ``` FN⊞υ×⁺²ι⁺³ι ``` Input `n` and calculate the first `n` products of neighbouring factors. ``` I∕LΦΠυ¬⌊Eυ﹪ιλΠυ ``` Take the product of all of those factors and use that to calculate the proportion of numbers having at least one of those factors. 30-byte less slow version is only O(n!) so can do up to `n=6` on TIO: ``` F⊕N⊞υ⁺²ιI∕LΦΠυΣEυ∧μ¬﹪ι×λ§υ⊖μΠυ ``` [Try it online!](https://tio.run/##RY7NCsIwEITvPkWOG4gXD156EotQsCWgLxCT1QbyU5JN8e1jeqlzGphvhtGzSjoqV@s7JgZD0Ak9BkLT/FJoKv6FCTjnTJY8QxFMupLhJJjlvDvIZAPBVWWC3q7WINwxfGiGm3XUijJFUzRB4YI9iodRLdvGJRjwgk2RYGyAi2AFe1qPGVxLaQgGvxvY4/@Q57vai324qav1XI@r@wE "Charcoal – Try It Online") Link is to verbose version of code. ~~46-byte faster version is only O(lcm(1..n+2)) so can do up to `n=10` on TIO:~~ ``` FN⊞υ×⁺²ι⁺³ι≔⁰η≔⁰ζW∨¬η⌈Eυ﹪ηκ«≦⊕η≧⁺⌈Eυ¬﹪ηκζ»I∕ζη ``` [Try it online!](https://tio.run/##ZY/NTsMwEITP5Cn2uJaMlMKRE4JLDmkjxAu4iVuv6p/KPwEF8eyu3SKhtnua0Wi/nR2V8KMTOued84CdPaa4TmYrPTIGQwoKE4dPMjLgoFPAJw7EOJz1c9WMvTSvIdDeYstBXbmluC9FWgJuPK5dRFV2e/FNJhnsxbHCezcl7VBxOLA68NM8lOiP0tnRSyNtlNOF/p990F7Fc6s7Zj11w720@W0GTzbimwgR32mmSeJSweWNnFdtfpz1CQ "Charcoal – Try It Online") Link is to verbose version of code. 45-byte faster version is only O(2ⁿ) so can do up to `n=13` on TIO: ``` ⊞υ±¹FEN×⁺²ι⁺³ιF⮌υ⊞υ±÷×ικ⌈Φ⊕ι∧λ¬∨﹪ιλ﹪κλIΣ∕¹✂υ¹ ``` [Try it online!](https://tio.run/##XY69DsIwDIR3niKjK4WhdOyEQEgdChXlBUJrwCI/VX4q3j4kFBY8@U6@7zw8hB2MkDF2wT0gcHbEu/AIZVHUq5uxDFoxQaOn4I9BXdFCwdmFFDroZHCw4YyS89mrvKdhn9wZZ7QOISTjD95ov6eZRoSFRJw9E6QVL1JBwYGkT0WNHiwq1B5HyB1bPYJMDOPhZKE1Y5AmR2WOLuqZ1W/qVWdJe9gJ56FP3G9nyVkvacD8ULlcxlhWcT3LNw "Charcoal – Try It Online") Link is to verbose version of code. 54-byte fastest version uses more efficient LCM so can do up to `n=18` on TIO: ``` ⊞υ±¹FEN×⁺²ι⁺³ιFEυ⟦κι⟧«W⊟κ⊞⊞Oκλ﹪§κ±²λ⊞υ±÷Π…κ²⊟κ»IΣ∕¹✂υ¹ ``` [Try it online!](https://tio.run/##XU87a8MwEJ7jX6HxBMrgZAlkKsniIYkg2UIHVb7EwrJlZCkPSn@7ejKmQ284jo/vdbpRXjtlU5JxbCAKdsS7Cggl59vi5jyDgxqg6ocYjrH7Qg9csIvpcARp4wgrwQwh073ONw3705HftSX0k8DvYvFsjEUG0g3QEjJF5nUa0KvgPBDXktvB1dE6@AhVX@Mro3OrFeeZQdUW//pWfdibh6kRpCe1DrB7a4u7JmcJNgnnXFL/FNKbnjhqDHCOHczaUrCzNRqzcZlf4duUyk1aPuwv "Charcoal – Try It Online") Link is to verbose version of code. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~69~~ ~~68~~ ~~61~~ 52 bytes ``` Count[Range[#!],b_/;Or@@(# #-#&@Range[3,#]∣b)]/#!& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE7872b73zm/NK8kOigxLz01WlkxVicpXt/av8jBQUNZQVlXWc0BImOsoxz7qGNxkmasvrKi2v@Aosy8EgctN30HDSPtakMdYx0zHUsdQ6Nazf8A "Wolfram Language (Mathematica) – Try It Online") 3-indexed. At first I was going to use `LCM@@` but realized that `#!` would be shorter... but now it a lot of memory for `Range[#!]`... Managed to golf down the condition by 2 bytes, which was nice. --- Older numerical solution (56 bytes): ``` N@Count[Range[5^8],b_/;Or@@Array[(# #-#)∣b&,#,3]]/5^8& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE7872b738/BOb80ryQ6KDEvPTXaNM4iVicpXt/av8jBwbGoKLEyWkNZQVlXWfNRx@IkNR1lHePYWH2gKrX/AUWZeSUOWm76DhqG2tWGOsY6ZjqWOoZGOoamOkaGtZr/AQ "Wolfram Language (Mathematica) – Try It Online") 2-indexed. More efficient when `#!>5^8` (`#>9`, assuming `#` is an integer). ]
[Question] [ ### Given a German string and an indication of a case (lower/upper/title), fold the string to that case. ## Specifications 1. Input will consist only of `a`–`z` plus `äöüß-,.;:!?'"` in uppercase and/or lowercase. 2. The target case may be taken as any three unique values (please specify what they are) of a consistent type; either three characters, or three numbers, or three bit patterns. (Other formats are currently not allowed to prevent "outsourcing" the answer to the case specification. Comment if you think that an additional format should be allowed.) 3. Titlecase means uppercase everything except letters that follow a letter (letters are `a`–`z` plus `äöüß`). ## Gotchas 1. When `ß` needs to be uppercase, it must become `ẞ`. Some case-folding built-ins and libraries do not do this. 2. When `ß` needs to be titlecase, it must become `Ss`. Some case-folding built-ins and libraries do not do this. 3. `ss` may occur in the text, and should never be converted to `ß` or `ẞ`. ## Examples Upper case `die Räder sagen "ßß ss" für dich, wegen des Öls!` is `DIE RÄDER SAGEN "ẞẞ SS" FÜR DICH, WEGEN DES ÖLS!` Lower case `die Räder sagen "ßß ss" für dich, wegen des Öls!` is `die räder sagen "ßß ss" für dich, wegen des öls!` Title case `die Räder sagen "ßß ss" für dich, wegen des Öls!` is `Die Räder Sagen "Ssß Ss" Für Dich, Wegen Des Öls!` [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~42~~ 40 bytes *Saved 2 bytes thanks to @Oliver* ``` r'ßQ=7838d)u mV,@W¦vW=X ?Xv :X¥Q?"Ss":Xu ``` Whew, that took quite some effort. Input is the string to convert, and a single character: `u` for uppercase, `v` for lowercase, `m` for title case. [Test it online!](https://ethproductions.github.io/japt/?v=1.4.5&code=ciffUT03ODM4ZCl1IG1WLEBXpnZXPVggP1h2IDpYpVE/IlNzIjpYdQ==&input=J2RpZSBS5GRlciBzYWdlbiAi398gc3MiIGb8ciBkaWNoLCB3ZWdlbiBkZXMg1mxzIScKJ20n) [Answer] # [Python 3](https://docs.python.org/3/), 92 bytes ``` lambda s,c:[str.lower,str.upper,str.title][c](s.replace("ẞ","ß").replace("ß"*c,"ẞ"*c)) ``` [Try it online!](https://tio.run/##rVAxCgIxEOx9xZrmLhJFsRP8hK1nEZM9DcYzZCOHH7HUxleIXV7iS847EUQRLLSb3RlmZ9btwnJTDKt8nFVWrudaAgk1mlLwPbsp0YsGbZ17oGCCxdlUzVLqeXRWKkzZ9XxggsUj489dPXWUuFMdxXnlvClCmqeJNgiTeNLogeQCC6il8QhEDPJ48aCNWgoosaE0EsS9pXYiYMB562eT/j9Mui9R6oZEBCZL1lA/r5ArfE/7WdL/LmkuVTc "Python 3 – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 23 bytes Uses **0** = lower, **1** = upper, **2** = title ``` •^ŠX•4ôçIiR}`:"lu™"¹è.V ``` [Try it online!](https://tio.run/##MzBNTDJM/f//UcOiuKMLIoCUyeEth5d7ZgbVJlgp5ZQ@almkdGjn4RV6Yf//G3GlZKYqBB1ekpJapFCcmJ6ap6B0eP7h@QrFxUoKaYf3FCmkZCZn6CiUp4KkUlKLFQ5PyylWBAA "05AB1E – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 50 bytes ``` ⁽ñWỌ”ß;y⁸Œu Ñ⁾SsÇ⁼?€1¦”ß Œl Çe€“Ġẹṇṣ‘ỌÇ;Øa¤Œg⁸ṁ⁹Ŀ€ ``` [Try it online!](https://tio.run/##HYwhDsIwFED9TlGmMWAnuAMI9ELLGGkQawjBrZgaDBNkAjISFhQGR2FAsr8dpP8ipWDfe3lzxvnaWpQvuI3Nc4vpEYpgjfLeZksPdijfIwEKZTXAzbVXX/6B12bcA8UcwvTQnMxDG62MPmOauwmoAPKwLtssciOjJUrdfFxsraUxI0MoKUuICCO2ID4UUBAhfDKFKiE0nsy6ZMV@ijJBYM9Fx/a/ "Jelly – Try It Online") Full program. Phew, this took much time to golf... Argument 1: String (may need to be escaped) Argument 2: `1` for uppercase, `2` for title case, `3` for lowercase. [Answer] # [Clean](https://clean.cs.ru.nl), ~~649~~ ~~279~~ ~~275~~ ~~274~~ 246 bytes Yes, that's ~~123~~ ~~122~~ 94 bytes of imports, which is already longer than every other answer. ``` from StdList import++,map,flatten import StdLib,StdInt,StdBool,Text.Unicode,Text.Unicode.UChar $ =fromInt ? =isAlpha ^ =toUpper @0s=map^s @1s=map toLower s @2s=flatten(map(\[h:t]=if($223==h||h> $999)[$83,$115][^h]++ @1t)(groupBy(\a b= ?a== ?b)s)) ``` [Try it online!](https://tio.run/##ZVLNbtNAEL7vUwwhUm3FaUkqpCbSpqFApUo5INKc8qNs7HW8YO@anXVLpD4H1154DG55L8z4p4WKy87MNzvzzV@YSqHLzERFKiETSpexNRnMXTRT6EBlubGu1wsykQdxKpyTmjVg82cXkLjRrhJXxqTBrfzuThdahSaSL4zTxftEWNYFXjFQCLsErvBdmieCbYA7s8hzadn0DXJi2yCbDmoNnJmZe2mBkCHytgqPPN5qmYzdmqvY6w6H55wnDw/JBLqj0chfdi/Og@5g8Ha93CTrXg@mA@d7e2uK/OrgrQTsOFwKTs/OR98v26ZeVPxRk1B6j6eL2@sLdnYGYmfuJMSFDp0yGiIjUZ84sPJboawElyhsZxaAcicIXwqaYoEyoi7AFVaDgO3cWcq6BaUJJLvKDv@BLVDTaopP/iHOrblTEWU1Oj2AljLCvxH192097m0A2riGYcueVntNadoywVT5UWUqFTY9BG0L@FxzJr7KmjtSmKfiQAQgBSraFIvHY6/h7E8qBp/F9XIbjDFH/grvTxrEZ47W/OSdO2Edew10fBI4DEnF2kVGJ1ISPh9/RtXaxV5qWHWOj8dHQFx1ID7@slRPmARwLytnJBGOP1J81WEcPGoKqjLaNZLlTWsWn1Q6s2c49lvG8ndIZ7XHsn8zKz8ctMhU2BjNkdfqJzq82NjsDw) Defines the function `@`, taking an `Int` and a `UString`, and returning a `UString`. Conveniently, `UString` (Clean's default way of handling Unicode), is just a type alias for `[Int]` - which is a list of `Int` containing unicode codepoints of the characters in the string. *Inconveniently*, `Text.Unicode.UChar` is really long, and I can't `import StdEnv` because the definitions in `StdChar` conflict with the definitions in `Text.Unicode.UChar` (as they are not intended for use together). The three values are 0, 1, and 2 for Upper, Lower, and Title case. ]
[Question] [ In the misty years of yore, when fanfold terminals walked the earth, there lived a strange creature. Oddly crippled and yet oddly powerful, the line editor teemed across the programming landscape in untold numbers; covering the earth as far as the eye could see. Now it is fallen on hard times. That vast population hunted, hounded, and driven to the brink of extinction. Only a few specimens remain, most in cramped and unembelished cages in the less enlightened kind of zoo, though a few stuffed and mounted examples can be seen in backwater museums. Oh, and there is [`ed`](http://en.wikipedia.org/wiki/Ed_%28text_editor%29). **Frankenstein-like, we shall resurrect the noble beast!** ## Commands Our editor is fairly minimal and will support the following commands **Focus moving commands** * `<number>[,<number>]` -- move the focus to the stated line and if the second argument is given to the state column. Excessive line number gets the last line. Excessive column number gets the end of the line. * `,<number>` -- move to column number on the current line * `e` -- move the focus to the end of the file but do not begin a new line. * `b` -- move the focus to the beginning of the file. **Informational commands** * `L` -- Echo the current context. The five lines centered on the current line are printed. All five lines are indented by one character; the current line is marked with a ">", the others with a " ". Under these lines another line is printed consisting entirely of spaces except for a "^" in the current column (a total of six lines are printed). * `l` -- echo the current line * `p [[<start>],[<end>]]` -- Print the file from starting to ending address. These value default to 1 and 0 (the end of the file). **File altering commands** * `A [<text>]` -- Move to the line beyond the end of the file (that is begin a new line) and (possibly) append text. * `<return>` (alone) -- Insert a newline. Thus `a <return> <return>` inserts a newline after the current one. * `r <text>` -- replaces everything from the focus to the end of the line with text. * `i [<text>]` -- inserts text followed by by newline at the current focus. Any portion of this line beyond the focus ends up on the next line. * `I <text>` -- inserts text at the current focus, preserving the rest of the line. Focus remains on this line. * `d` -- Delete the contents of the current line or if the current line is already empty, remove the line. * `j` -- join this line to the next Of this last group the first four end with the focus moving to the next line, while `I` preserves the focus at the end of the added text. When deleting or joining focus remains at the same line and column *number*. **The Interpretation of line numbers in commands** Number beginning with '+' or '-' are interpreted as *offsets* from the current line number. Numbers without a sign are interpreted as absolute line numbers, except that '0' means the last line of the file. ## Prompt and interaction The editor functions as a shell, and the prompt has the form `<line>','<column>'>'` where line is the line number except that "end" is used when the focus is at the last character of the file. Each command is accepted only when the user presses newline. And takes affect. Readline support is allowed but not required. No feedback is provided except the changing values of and in the prompt, unless explicitly stated in the commands description. # Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in each language wins. ### Special thanks to dmkee for making this in sandbox where I adopted it. [Answer] ## C (gcc), 1288 1212 1188 1171 1146 bytes ``` #define P printf( #define A case #define B break #define L(i,e,t,f,s)for(o=i;o e;){strcpy(l[o t],l[o f]);c[o t]=c[s o];} #define R(m,o){return b<1|b>m?m o:b;} #define N(f)sscanf(f,"%d,%d",&i,&j)||sscanf(f,",%d",&j) r,i,j,o,z,c[999],*C,x=1,y=1;char a[999],l[999][999],(*L)[999];D(){L(r,>y,,-1,--)r++?strcpy(l[o],l[o-1]+--x),c[o-1]=x,l[o-1][x]=0:0;c[y++]=strlen(l[o]);x=1;}U(){strcat(*L,l[y]);*C=strlen(*L);L(y+1,<r,-1,,++)--r;*l[r]=c[r]=0;}X(b)R(c[y-1],+1)Y(b)R(r,)main(){for(;;){z=i=y;L=l+--z;C=c+z;j=x;!r||y/r&&x>*C?P"end> "):P"%d,%d> ",y,x);scanf("%[^\n]%*c",a)?a[2]*=!!a[1],N(a)?y=Y(i+(i<0|*a=='+')*y),x=X(j+(j<0||strchr(a+1,'+'))*x):0:(*a=D(),scanf("%*c"));switch(*a){A'e':y=r;x=c[r-1]+1;B;A'b':y=1;x=1;B;A'L':for(o=y-4;++o<y+2;)o<0^o<r&&P"%c%s\n",o^z?' ':'>',l[o]);for(o=x+1;--o;)P" ");P"^\n");B;A'l':puts(*L);B;A'p':i=1;j=0;N(a+2);for(o=Y(i)-1;o<Y(j);++o)puts(l[o]);B;A'A':y=r++;strcpy(l[y],a+2);x=c[y]=strlen(a+2);++x;++y;B;A'i':D();--y;x=X(0);A'r':strcpy(*L+x-1,a+2);*C=strlen(*L);x=1;++y>r&&++r;B;A'I':o=strlen(a+2);memmove(*L+x+o-1,*L+x-1,*C-x+1);*C+=o;memcpy(*L+x-1,a+2,o);x+=o;B;A'd':**L?**L=*C=0,x=1:U();y=y>r?r:y;B;A'j':y<r&&U();}}} ``` ## [Demo](https://repl.it/JFOI/7) First time trying to do something like this, so there are probably some missed opportunities for making it smaller. (Thanks Jerry Jeremiah for pointing out some) Here's a (slightly) more readable version: ``` // often used functions/keywords: #define P printf( #define A case #define B break // loops for copying rows upwards/downwards are similar -> macro #define L(i,e,t,f,s)for(o=i;o e;){strcpy(l[o t],l[o f]);c[o t]=c[s o];} // range check for rows/columns is similar -> macro #define R(m,o){return b<1|b>m?m o:b;} // checking for numerical input is needed twice (move and print command): #define N(f)sscanf(f,"%d,%d",&i,&j)||sscanf(f,",%d",&j) // room for 999 rows with each 999 cols (not specified, should be enough) // also declare "current line pointers" (*L for data, *C for line length), // an input buffer (a) and scratch variables r,i,j,o,z,c[999],*C,x=1,y=1;char a[999],l[999][999],(*L)[999]; // move rows down from current cursor position D() { L(r,>y,,-1,--) r++?strcpy(l[o],l[o-1]+--x),c[o-1]=x,l[o-1][x]=0:0; c[y++]=strlen(l[o]); x=1; } // move rows up, appending uppermost to current line U() { strcat(*L,l[y]); *C=strlen(*L); L(y+1,<r,-1,,++) --r; *l[r]=c[r]=0; } // normalize positions, treat 0 as max X(b)R(c[y-1],+1) Y(b)R(r,) main() { for(;;) { // initialize z as current line index, the current line pointers, // i and j for default values of positioning z=i=y;L=l+--z;C=c+z;j=x; // prompt: !r||y/r&&x>*C?P"end> "):P"%d,%d> ",y,x); // read a line of input (using scanf so we don't need an include) scanf("%[^\n]%*c",a)? // no command arguments -> make check easier: a[2]*=!!a[1], // numerical input -> have move command: // calculate new coordinates, checking for "relative" N(a)?y=Y(i+(i<0|*a=='+')*y),x=X(j+(j<0||strchr(a+1,'+'))*x):0: // check for empty input, read single newline and perform <return> command: (*a=D(),scanf("%*c")); switch(*a) { A'e':y=r;x=c[r-1]+1;B; A'b':y=1;x=1;B; A'L':for(o=y-4;++o<y+2;)o<0^o<r&&P"%c%s\n",o^z?' ':'>',l[o]);for(o=x+1;--o;)P" ");P"^\n");B; A'l':puts(*L);B; A'p':i=1;j=0;N(a+2);for(o=Y(i)-1;o<Y(j);++o)puts(l[o]);B; A'A':y=r++;strcpy(l[y],a+2);x=c[y]=strlen(a+2);++x;++y;B; A'i':D();--y;x=X(0); // Commands i and r are very similar -> fall through from i to r // after moving rows down and setting position at end of line: A'r':strcpy(*L+x-1,a+2);*C=strlen(*L);x=1;++y>r&&++r;B; A'I':o=strlen(a+2);memmove(*L+x+o-1,*L+x-1,*C-x+1);*C+=o;memcpy(*L+x-1,a+2,o);x+=o;B; A'd':**L?**L=*C=0,x=1:U();y=y>r?r:y;B; A'j':y<r&&U(); } } } ``` --- This challenge leaves quite a lot of corner cases to explore -- I *guess* I fixed all bugs by now, but if somebody finds one more, please comment. Regarding the revisions, I removed byte counts for earlier versions that contained subtle bugs. [Answer] # [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), ~~747 807 829~~ 807 bytes ``` func d(D){if(D>0){for(;D<NR;)f[D++]=f[D+1];NR--}else{for(c=NR;x>-D;x--)f[x+1]=f[x];NR++}} {f[r=NR]=$0} END{while(1){printf"%s,%d>",r==NR?"end":r,c getline v<"-" split(" > ",l,"") if(v=="e")r=NR if(v=="b")r=1 if(v=="L"){for(i=-2;i<3;i++)print l[i+3] f[r+i];printf"%"c+1"s\n","^"}if(v=="l")print f[r] if(v=="d")z=f[r]=""?d(r):f[r]="" if(v=="j"){f[r]=f[r] f[r+1];d(r+1)} S=index(v," ") z=S?substr(v,S+1):v a=substr(v,1,1) n=split(z,N,",") x=N[1]~/[-+].*/?r+N[1]:N[1] y=N[2]~/[-+].*/?c+N[2]:N[2] if(!S&&v~/[0-9+-,]+.*/){r=x?x>NR?NR:x:x=="0"?NR:r C=length(f[r]) c=n>1?y>C?C:y:c} if(a=="p")for(i=x?x:1;i<=(y?y:NR);)print f[i++] if(a=="r"||a=="i"||a=="I"){k=substr(f[r],c) if(a=="i"){if(c<length(f[r])){d(-r-1);f[r+1]=k}f[r]=substr(f[r],1,c) z (a=="I"?k:"")}if(a="a"||a=="A"){if(a=="A")r=NR;r=r+1;d(r);f[r]=z}}}} ``` [Try it online!](https://tio.run/##TZLLbtswEEX3/Ap10ARiSTZmsiplSijsLgoEWthLVwUcPRLWgmpQjiNbUX/dHeoRWAuSQx7dmbnk9m13uRSvVepl/pK2pvCX4Yy2xV/rB8t5vAposVkylmg3ySSIV0J0eVnnPZJqJJpQLINGCCQbRJBsHMdY15G22FhkEv151pEf8bJ9ezFl7kva7q2pDgXc1PwmC4FbjVgEeZWBsjwlz/mhNFXuHecggNT70hx88LzQ84CXHIASLPWoNeRAXYYpfHKhnKJHGFoxWtwHZv4QGMZon9krN4Y9JB7Wx0wSTNVAyiTUvyrg8Bu6UaWE8R@Ek0k6A3rWbkMDRJlvqRqDCfjjcrstN/R50D4EmaQdWWtTZXnjHzl42MtZr6P69ak@WNxZI6GOZKs/diSXlFR6cOHMY47lUdLoeCOTf3cbwZKvX@4iy1ys3EBOeHZ/dZYyFys3uPo@rW9vj3g6E9@Y4AlDhLZWN1ET4i3EK9WoBluYgVtbstBlXj0fXnzXCiWprkIZncJFtFAnlXZOcYv4HuhgNuooiX5r/xSdVLyiwYeBeAHJxFt4f3ezGeef6Nhu6tql4imdWAP940zn15XQNvOFFZIGg7161/WOX0tIFPHOnj8kiHYK307Xi8J2zPt90B6X7jUFVqOeu61eOtHnDr/L5T8 "AWK – Try It Online") Removing the `else`s makes the lines a bit shorter/readable but the cursor assignment is a bit more complicated. Just for giggles, I created a version to add a bit more "functionality": `q` quits the program `w <outfile[defaults to input file]>` writes the changes. [Try it online!](https://tio.run/##TZLfb5swEMff@SvYaa3wjNfQPs3EoCqkUqWWh@QxY1LKj9YLYpmhCYGyfz0786MKDzZ3/vh7d77bHnfnc/ZexGZiBaSVmRV4M9Jmf5TlBvNw5ZJsE1AaCb05kRuuGOvSvEx7JBZI1B4L3JoxJGtEkKw1R2nXGW22UchE4uusM5Zh0B7fZJ5aDmn3ShZVBlelfZV4YCuBmA9pkQBXdmy8plUui9Q8zIGBUe5zWVlgmp5pgp3bAMTAVA9CQApER5jMF206k/UEQylSsFtXzu9cSSnpI5v5RtK7yMT8qIzcKRuIqQPlzwJs@AXdqJLDeAfhaJJOgDRCOwSAn1iK8NGYgN86tnbppY@Dz4cgdcgk/BdIWsvKWAtZJGltHWwwsbJGrP3y/aWsFHrWyPODsRWfHsd2iFGI4U0aO7QxWWLUItw40b@bDaPR9283vqLa5noxTnh2e3EWU21zvehsv6yvrw94OmM/KLMjighplaj92sOehCte8xqznYH@V8ZC5GnxWr1ZujBixKLwHP/kLfwFP/G404pbxI9Y/4NohDj4D49Py/D@eckbd@jGTDein67pYWXkPXxe3QMZOEyBO9g4YZ38Ew9X5OICDuXEK/j40Lsc90cMvZseTGdpx2RiJfRTHs8viyBtYjHFHOIOfRK7rm/dpYSDImZjWkMAf8dxCLteFLZj3PtBe/zVY@kqgXq67b10JJoOv/P5Pw "AWK – Try It Online") [Answer] ## 6502 Assembly (C64, BASIC loader), 5761 5352 bytes ``` 0fOa=49152to50573:rEb:pOa,b:nE:sY49152 1dA162,54,134,1,162,1,134,7,134,8,202,142,0,96,134,251,162,96,134,21,162,128 2dA142,145,2,162,23,142,24,208,166,8,169,0,160,253,32,98,194,32,126,195,32,173 3dA195,166,2,240,103,202,202,16,2,162,0,142,160,191,173,162,191,201,69,240,93 4dA201,66,240,95,201,204,240,97,201,76,240,96,201,80,240,100,201,193,240,99,201 5dA73,240,123,201,82,240,122,201,201,240,121,201,68,240,123,201,74,240,122,162 6dA0,32,108,196,165,34,166,251,32,81,194,201,255,240,10,133,8,170,169,0,160,253 7dA32,98,194,160,0,177,253,170,232,165,35,201,255,208,2,165,7,32,81,194,133,7 8dA16,134,32,156,194,76,30,192,169,0,133,35,240,204,169,1,133,35,208,198,76,76 9dA193,166,8,32,198,193,76,30,192,76,233,192,166,251,232,134,251,134,8,169,0 10dA160,253,32,98,194,169,0,168,145,253,200,132,7,32,244,193,76,30,192,76,153 11dA193,76,178,193,32,244,193,76,30,192,76,45,193,32,8,195,76,30,192,166,251 12dA240,249,162,1,134,34,202,134,35,162,2,173,160,191,240,3,32,49,196,165,34 13dA166,251,32,81,194,201,255,208,2,169,1,133,34,166,251,165,35,201,255,208,2 14dA169,0,32,81,194,141,37,193,166,34,32,198,193,166,34,224,255,240,190,232,134 15dA34,208,242,160,0,177,253,208,17,165,8,197,251,208,5,198,8,200,132,7,32,8 16dA195,76,30,192,152,145,253,200,132,7,208,245,166,251,240,70,166,8,160,3,202 17dA240,6,200,202,240,2,200,202,232,140,120,193,142,122,193,228,8,240,7,169,32 18dA32,210,255,208,5,169,62,32,210,255,32,198,193,160,255,162,255,136,240,4,228 19dA251,208,219,169,32,166,7,32,210,255,202,208,250,169,94,32,210,255,169,13,32 20dA210,255,76,30,192,32,156,194,198,8,160,0,177,253,133,7,230,7,32,244,193,230 21dA8,162,1,134,7,76,30,192,160,0,166,7,202,138,145,253,32,244,193,230,8,162,1 22dA134,7,76,30,192,169,193,160,219,32,98,194,174,219,193,232,142,229,193,174 23dA220,193,142,230,193,174,255,255,240,16,142,236,193,160,0,185,255,255,32,210 24dA255,200,192,255,208,245,169,13,76,210,255,165,253,24,101,7,141,38,194,141 25dA57,194,165,254,105,0,141,39,194,141,58,194,173,38,194,109,160,191,141,41 26dA194,173,39,194,105,0,141,42,194,160,0,177,253,56,229,7,48,11,170,24,189,255 27dA255,157,255,255,202,16,247,174,160,191,202,16,1,96,189,164,191,157,255,255 28dA202,16,247,160,0,177,253,24,109,160,191,145,253,165,7,24,109,160,191,133,7 29dA96,141,93,194,201,255,240,9,201,0,240,4,224,255,16,1,138,96,141,154,194,141 30dA146,194,140,153,194,200,140,145,194,202,138,41,7,168,138,74,74,74,170,169,0 31dA24,202,48,4,105,3,144,249,141,161,191,185,129,197,41,3,109,161,191,105,96 32dA141,255,255,185,129,197,41,240,141,255,255,96,166,251,232,134,251,142,172 33dA194,169,195,160,120,32,98,194,162,255,202,142,194,194,228,8,240,16,48,14 34dA169,195,160,117,32,98,194,32,101,195,162,255,16,220,173,120,195,141,244,194 35dA141,235,194,173,121,195,141,245,194,141,236,194,160,0,177,253,141,240,194 36dA198,7,56,229,7,72,165,7,145,253,104,170,142,255,255,240,11,160,255,177,253 37dA157,255,255,136,202,208,247,162,1,134,7,166,8,228,251,240,3,232,134,8,96 38dA166,8,228,251,240,86,232,169,195,160,53,32,98,194,173,53,195,141,39,195,173 39dA54,195,141,40,195,160,0,177,253,174,255,255,240,18,142,48,195,24,105,255 40dA145,253,168,189,255,255,145,253,136,202,208,247,166,8,232,228,251,240,30 41dA142,79,195,169,195,160,120,32,98,194,162,255,232,142,95,195,169,195,160,117 42dA32,98,194,32,101,195,162,255,208,222,198,251,96,173,117,195,141,114,195,173 43dA118,195,141,115,195,174,255,255,189,255,255,157,255,255,202,16,247,96,165,8 44dA197,251,144,22,160,0,177,253,197,7,16,14,162,0,189,137,197,32,210,255,232 45dA224,5,208,245,96,165,8,32,196,196,169,44,32,210,255,165,7,32,196,196,162,3 46dA208,225,162,0,134,2,134,204,32,228,255,240,251,36,21,240,17,166,2,224,30 47dA240,241,32,210,255,157,162,191,232,134,2,16,230,201,13,208,19,169,0,166,2 48dA157,162,191,230,204,169,32,32,210,255,169,13,76,210,255,201,20,208,203,166 49dA2,240,199,32,210,255,202,134,2,16,191,141,11,196,141,22,196,32,117,197,160 50dA0,189,162,191,240,44,201,43,208,7,169,1,133,255,232,208,9,201,45,208,8,169 51dA255,133,255,232,189,162,191,240,19,201,48,48,15,201,58,16,11,153,194,191 52dA232,200,192,3,16,2,48,232,96,142,69,196,160,0,132,25,132,32,136,132,34,132 53dA35,169,25,32,244,195,224,255,240,10,142,81,196,32,31,197,133,34,162,255,189 54dA162,191,201,44,208,18,232,142,99,196,169,32,32,244,195,224,255,240,5,32,31 55dA197,133,35,96,32,49,196,169,1,36,25,240,36,16,21,165,34,197,8,48,6,169,1 56dA133,34,208,22,165,8,56,229,34,133,34,208,13,165,8,24,101,34,133,34,144,4 57dA169,0,133,34,169,1,36,32,240,36,16,21,165,35,197,7,48,6,169,1,133,35,208,22 58dA165,7,56,229,35,133,35,208,13,165,7,24,101,35,133,35,144,4,169,0,133,35,96 59dA32,215,196,162,0,189,194,191,240,3,32,210,255,232,224,3,208,243,96,133,20 60dA32,117,197,162,8,160,2,185,194,191,201,5,48,5,105,2,153,194,191,136,16,241 61dA160,2,165,20,10,133,20,185,194,191,42,201,16,41,15,153,194,191,136,16,242 62dA202,208,215,173,196,191,9,48,141,196,191,160,1,185,194,191,240,8,9,48,153 63dA194,191,136,16,243,96,173,196,191,208,19,173,195,191,141,196,191,173,194 64dA191,141,195,191,169,0,141,194,191,240,232,160,2,185,194,191,240,5,41,207 65dA153,194,191,136,16,243,162,8,160,125,24,185,69,191,144,2,9,16,74,153,69,191 66dA200,16,242,165,20,106,202,208,1,96,133,20,160,2,185,194,191,201,8,48,5,233 67dA3,153,194,191,136,16,241,48,211,169,0,141,194,191,141,195,191,141,196,191 68dA96,0,96,192,33,129,225,66,162,69,78,68,62,32 ``` ## [Demo](https://vice.janicek.co/c64/#%7B"controlPort2":"joystick","primaryControlPort":2,"keys":%7B"SPACE":"","RETURN":"","F1":"","F3":"","F5":"","F7":""%7D,"files":%7B"edldr.prg":"data:;base64,AQglCAAAgUGyNDkxNTKkNTA1NzM6h0I6l0EsQjqCOp40OTE1MgB0CAEAgzE2Miw1NCwxMzQsMSwxNjIsMSwxMzQsNywxMzQsOCwyMDIsMTQyLDAsOTYsMTM0LDI1MSwxNjIsOTYsMTM0LDIxLDE2MiwxMjgAxQgCAIMxNDIsMTQ1LDIsMTYyLDIzLDE0MiwyNCwyMDgsMTY2LDgsMTY5LDAsMTYwLDI1MywzMiw5OCwxOTQsMzIsMTI2LDE5NSwzMiwxNzMAFQkDAIMxOTUsMTY2LDIsMjQwLDEwMywyMDIsMjAyLDE2LDIsMTYyLDAsMTQyLDE2MCwxOTEsMTczLDE2MiwxOTEsMjAxLDY5LDI0MCw5MwBnCQQAgzIwMSw2NiwyNDAsOTUsMjAxLDIwNCwyNDAsOTcsMjAxLDc2LDI0MCw5NiwyMDEsODAsMjQwLDEwMCwyMDEsMTkzLDI0MCw5OSwyMDEAuAkFAIM3MywyNDAsMTIzLDIwMSw4MiwyNDAsMTIyLDIwMSwyMDEsMjQwLDEyMSwyMDEsNjgsMjQwLDEyMywyMDEsNzQsMjQwLDEyMiwxNjIACgoGAIMwLDMyLDEwOCwxOTYsMTY1LDM0LDE2NiwyNTEsMzIsODEsMTk0LDIwMSwyNTUsMjQwLDEwLDEzMyw4LDE3MCwxNjksMCwxNjAsMjUzAFoKBwCDMzIsOTgsMTk0LDE2MCwwLDE3NywyNTMsMTcwLDIzMiwxNjUsMzUsMjAxLDI1NSwyMDgsMiwxNjUsNywzMiw4MSwxOTQsMTMzLDcAqwoIAIMxNiwxMzQsMzIsMTU2LDE5NCw3NiwzMCwxOTIsMTY5LDAsMTMzLDM1LDI0MCwyMDQsMTY5LDEsMTMzLDM1LDIwOCwxOTgsNzYsNzYA+goJAIMxOTMsMTY2LDgsMzIsMTk4LDE5Myw3NiwzMCwxOTIsNzYsMjMzLDE5MiwxNjYsMjUxLDIzMiwxMzQsMjUxLDEzNCw4LDE2OSwwAEkLCgCDMTYwLDI1MywzMiw5OCwxOTQsMTY5LDAsMTY4LDE0NSwyNTMsMjAwLDEzMiw3LDMyLDI0NCwxOTMsNzYsMzAsMTkyLDc2LDE1MwCXCwsAgzE5Myw3NiwxNzgsMTkzLDMyLDI0NCwxOTMsNzYsMzAsMTkyLDc2LDQ1LDE5MywzMiw4LDE5NSw3NiwzMCwxOTIsMTY2LDI1MQDlCwwAgzI0MCwyNDksMTYyLDEsMTM0LDM0LDIwMiwxMzQsMzUsMTYyLDIsMTczLDE2MCwxOTEsMjQwLDMsMzIsNDksMTk2LDE2NSwzNAA0DA0AgzE2NiwyNTEsMzIsODEsMTk0LDIwMSwyNTUsMjA4LDIsMTY5LDEsMTMzLDM0LDE2NiwyNTEsMTY1LDM1LDIwMSwyNTUsMjA4LDIAhQwOAIMxNjksMCwzMiw4MSwxOTQsMTQxLDM3LDE5MywxNjYsMzQsMzIsMTk4LDE5MywxNjYsMzQsMjI0LDI1NSwyNDAsMTkwLDIzMiwxMzQA0wwPAIMzNCwyMDgsMjQyLDE2MCwwLDE3NywyNTMsMjA4LDE3LDE2NSw4LDE5NywyNTEsMjA4LDUsMTk4LDgsMjAwLDEzMiw3LDMyLDgAIw0QAIMxOTUsNzYsMzAsMTkyLDE1MiwxNDUsMjUzLDIwMCwxMzIsNywyMDgsMjQ1LDE2NiwyNTEsMjQwLDcwLDE2Niw4LDE2MCwzLDIwMgBzDREAgzI0MCw2LDIwMCwyMDIsMjQwLDIsMjAwLDIwMiwyMzIsMTQwLDEyMCwxOTMsMTQyLDEyMiwxOTMsMjI4LDgsMjQwLDcsMTY5LDMyAMQNEgCDMzIsMjEwLDI1NSwyMDgsNSwxNjksNjIsMzIsMjEwLDI1NSwzMiwxOTgsMTkzLDE2MCwyNTUsMTYyLDI1NSwxMzYsMjQwLDQsMjI4ABUOEwCDMjUxLDIwOCwyMTksMTY5LDMyLDE2Niw3LDMyLDIxMCwyNTUsMjAyLDIwOCwyNTAsMTY5LDk0LDMyLDIxMCwyNTUsMTY5LDEzLDMyAGYOFACDMjEwLDI1NSw3NiwzMCwxOTIsMzIsMTU2LDE5NCwxOTgsOCwxNjAsMCwxNzcsMjUzLDEzMyw3LDIzMCw3LDMyLDI0NCwxOTMsMjMwALYOFQCDOCwxNjIsMSwxMzQsNyw3NiwzMCwxOTIsMTYwLDAsMTY2LDcsMjAyLDEzOCwxNDUsMjUzLDMyLDI0NCwxOTMsMjMwLDgsMTYyLDEABQ8WAIMxMzQsNyw3NiwzMCwxOTIsMTY5LDE5MywxNjAsMjE5LDMyLDk4LDE5NCwxNzQsMjE5LDE5MywyMzIsMTQyLDIyOSwxOTMsMTc0AFYPFwCDMjIwLDE5MywxNDIsMjMwLDE5MywxNzQsMjU1LDI1NSwyNDAsMTYsMTQyLDIzNiwxOTMsMTYwLDAsMTg1LDI1NSwyNTUsMzIsMjEwAKUPGACDMjU1LDIwMCwxOTIsMjU1LDIwOCwyNDUsMTY5LDEzLDc2LDIxMCwyNTUsMTY1LDI1MywyNCwxMDEsNywxNDEsMzgsMTk0LDE0MQDzDxkAgzU3LDE5NCwxNjUsMjU0LDEwNSwwLDE0MSwzOSwxOTQsMTQxLDU4LDE5NCwxNzMsMzgsMTk0LDEwOSwxNjAsMTkxLDE0MSw0MQBEEBoAgzE5NCwxNzMsMzksMTk0LDEwNSwwLDE0MSw0MiwxOTQsMTYwLDAsMTc3LDI1Myw1NiwyMjksNyw0OCwxMSwxNzAsMjQsMTg5LDI1NQCUEBsAgzI1NSwxNTcsMjU1LDI1NSwyMDIsMTYsMjQ3LDE3NCwxNjAsMTkxLDIwMiwxNiwxLDk2LDE4OSwxNjQsMTkxLDE1NywyNTUsMjU1AOQQHACDMjAyLDE2LDI0NywxNjAsMCwxNzcsMjUzLDI0LDEwOSwxNjAsMTkxLDE0NSwyNTMsMTY1LDcsMjQsMTA5LDE2MCwxOTEsMTMzLDcANREdAIM5NiwxNDEsOTMsMTk0LDIwMSwyNTUsMjQwLDksMjAxLDAsMjQwLDQsMjI0LDI1NSwxNiwxLDEzOCw5NiwxNDEsMTU0LDE5NCwxNDEAhhEeAIMxNDYsMTk0LDE0MCwxNTMsMTk0LDIwMCwxNDAsMTQ1LDE5NCwyMDIsMTM4LDQxLDcsMTY4LDEzOCw3NCw3NCw3NCwxNzAsMTY5LDAA1REfAIMyNCwyMDIsNDgsNCwxMDUsMywxNDQsMjQ5LDE0MSwxNjEsMTkxLDE4NSwxMjksMTk3LDQxLDMsMTA5LDE2MSwxOTEsMTA1LDk2ACQSIACDMTQxLDI1NSwyNTUsMTg1LDEyOSwxOTcsNDEsMjQwLDE0MSwyNTUsMjU1LDk2LDE2NiwyNTEsMjMyLDEzNCwyNTEsMTQyLDE3MgByEiEAgzE5NCwxNjksMTk1LDE2MCwxMjAsMzIsOTgsMTk0LDE2MiwyNTUsMjAyLDE0MiwxOTQsMTk0LDIyOCw4LDI0MCwxNiw0OCwxNADDEiIAgzE2OSwxOTUsMTYwLDExNywzMiw5OCwxOTQsMzIsMTAxLDE5NSwxNjIsMjU1LDE2LDIyMCwxNzMsMTIwLDE5NSwxNDEsMjQ0LDE5NAASEyMAgzE0MSwyMzUsMTk0LDE3MywxMjEsMTk1LDE0MSwyNDUsMTk0LDE0MSwyMzYsMTk0LDE2MCwwLDE3NywyNTMsMTQxLDI0MCwxOTQAYhMkAIMxOTgsNyw1NiwyMjksNyw3MiwxNjUsNywxNDUsMjUzLDEwNCwxNzAsMTQyLDI1NSwyNTUsMjQwLDExLDE2MCwyNTUsMTc3LDI1MwCwEyUAgzE1NywyNTUsMjU1LDEzNiwyMDIsMjA4LDI0NywxNjIsMSwxMzQsNywxNjYsOCwyMjgsMjUxLDI0MCwzLDIzMiwxMzQsOCw5NgABFCYAgzE2Niw4LDIyOCwyNTEsMjQwLDg2LDIzMiwxNjksMTk1LDE2MCw1MywzMiw5OCwxOTQsMTczLDUzLDE5NSwxNDEsMzksMTk1LDE3MwBPFCcAgzU0LDE5NSwxNDEsNDAsMTk1LDE2MCwwLDE3NywyNTMsMTc0LDI1NSwyNTUsMjQwLDE4LDE0Miw0OCwxOTUsMjQsMTA1LDI1NQCdFCgAgzE0NSwyNTMsMTY4LDE4OSwyNTUsMjU1LDE0NSwyNTMsMTM2LDIwMiwyMDgsMjQ3LDE2Niw4LDIzMiwyMjgsMjUxLDI0MCwzMADuFCkAgzE0Miw3OSwxOTUsMTY5LDE5NSwxNjAsMTIwLDMyLDk4LDE5NCwxNjIsMjU1LDIzMiwxNDIsOTUsMTk1LDE2OSwxOTUsMTYwLDExNwA/FSoAgzMyLDk4LDE5NCwzMiwxMDEsMTk1LDE2MiwyNTUsMjA4LDIyMiwxOTgsMjUxLDk2LDE3MywxMTcsMTk1LDE0MSwxMTQsMTk1LDE3MwCQFSsAgzExOCwxOTUsMTQxLDExNSwxOTUsMTc0LDI1NSwyNTUsMTg5LDI1NSwyNTUsMTU3LDI1NSwyNTUsMjAyLDE2LDI0Nyw5NiwxNjUsOADfFSwAgzE5NywyNTEsMTQ0LDIyLDE2MCwwLDE3NywyNTMsMTk3LDcsMTYsMTQsMTYyLDAsMTg5LDEzNywxOTcsMzIsMjEwLDI1NSwyMzIALxYtAIMyMjQsNSwyMDgsMjQ1LDk2LDE2NSw4LDMyLDE5NiwxOTYsMTY5LDQ0LDMyLDIxMCwyNTUsMTY1LDcsMzIsMTk2LDE5NiwxNjIsMwB9Fi4AgzIwOCwyMjUsMTYyLDAsMTM0LDIsMTM0LDIwNCwzMiwyMjgsMjU1LDI0MCwyNTEsMzYsMjEsMjQwLDE3LDE2NiwyLDIyNCwzMADMFi8AgzI0MCwyNDEsMzIsMjEwLDI1NSwxNTcsMTYyLDE5MSwyMzIsMTM0LDIsMTYsMjMwLDIwMSwxMywyMDgsMTksMTY5LDAsMTY2LDIAHBcwAIMxNTcsMTYyLDE5MSwyMzAsMjA0LDE2OSwzMiwzMiwyMTAsMjU1LDE2OSwxMyw3NiwyMTAsMjU1LDIwMSwyMCwyMDgsMjAzLDE2NgBsFzEAgzIsMjQwLDE5OSwzMiwyMTAsMjU1LDIwMiwxMzQsMiwxNiwxOTEsMTQxLDExLDE5NiwxNDEsMjIsMTk2LDMyLDExNywxOTcsMTYwALwXMgCDMCwxODksMTYyLDE5MSwyNDAsNDQsMjAxLDQzLDIwOCw3LDE2OSwxLDEzMywyNTUsMjMyLDIwOCw5LDIwMSw0NSwyMDgsOCwxNjkAChgzAIMyNTUsMTMzLDI1NSwyMzIsMTg5LDE2MiwxOTEsMjQwLDE5LDIwMSw0OCw0OCwxNSwyMDEsNTgsMTYsMTEsMTUzLDE5NCwxOTEAWhg0AIMyMzIsMjAwLDE5MiwzLDE2LDIsNDgsMjMyLDk2LDE0Miw2OSwxOTYsMTYwLDAsMTMyLDI1LDEzMiwzMiwxMzYsMTMyLDM0LDEzMgCrGDUAgzM1LDE2OSwyNSwzMiwyNDQsMTk1LDIyNCwyNTUsMjQwLDEwLDE0Miw4MSwxOTYsMzIsMzEsMTk3LDEzMywzNCwxNjIsMjU1LDE4OQD7GDYAgzE2MiwxOTEsMjAxLDQ0LDIwOCwxOCwyMzIsMTQyLDk5LDE5NiwxNjksMzIsMzIsMjQ0LDE5NSwyMjQsMjU1LDI0MCw1LDMyLDMxAEkZNwCDMTk3LDEzMywzNSw5NiwzMiw0OSwxOTYsMTY5LDEsMzYsMjUsMjQwLDM2LDE2LDIxLDE2NSwzNCwxOTcsOCw0OCw2LDE2OSwxAJcZOACDMTMzLDM0LDIwOCwyMiwxNjUsOCw1NiwyMjksMzQsMTMzLDM0LDIwOCwxMywxNjUsOCwyNCwxMDEsMzQsMTMzLDM0LDE0NCw0AOgZOQCDMTY5LDAsMTMzLDM0LDE2OSwxLDM2LDMyLDI0MCwzNiwxNiwyMSwxNjUsMzUsMTk3LDcsNDgsNiwxNjksMSwxMzMsMzUsMjA4LDIyADgaOgCDMTY1LDcsNTYsMjI5LDM1LDEzMywzNSwyMDgsMTMsMTY1LDcsMjQsMTAxLDM1LDEzMywzNSwxNDQsNCwxNjksMCwxMzMsMzUsOTYAhxo7AIMzMiwyMTUsMTk2LDE2MiwwLDE4OSwxOTQsMTkxLDI0MCwzLDMyLDIxMCwyNTUsMjMyLDIyNCwzLDIwOCwyNDMsOTYsMTMzLDIwANcaPACDMzIsMTE3LDE5NywxNjIsOCwxNjAsMiwxODUsMTk0LDE5MSwyMDEsNSw0OCw1LDEwNSwyLDE1MywxOTQsMTkxLDEzNiwxNiwyNDEAJhs9AIMxNjAsMiwxNjUsMjAsMTAsMTMzLDIwLDE4NSwxOTQsMTkxLDQyLDIwMSwxNiw0MSwxNSwxNTMsMTk0LDE5MSwxMzYsMTYsMjQyAHUbPgCDMjAyLDIwOCwyMTUsMTczLDE5NiwxOTEsOSw0OCwxNDEsMTk2LDE5MSwxNjAsMSwxODUsMTk0LDE5MSwyNDAsOCw5LDQ4LDE1MwDDGz8AgzE5NCwxOTEsMTM2LDE2LDI0Myw5NiwxNzMsMTk2LDE5MSwyMDgsMTksMTczLDE5NSwxOTEsMTQxLDE5NiwxOTEsMTczLDE5NAARHEAAgzE5MSwxNDEsMTk1LDE5MSwxNjksMCwxNDEsMTk0LDE5MSwyNDAsMjMyLDE2MCwyLDE4NSwxOTQsMTkxLDI0MCw1LDQxLDIwNwBiHEEAgzE1MywxOTQsMTkxLDEzNiwxNiwyNDMsMTYyLDgsMTYwLDEyNSwyNCwxODUsNjksMTkxLDE0NCwyLDksMTYsNzQsMTUzLDY5LDE5MQCyHEIAgzIwMCwxNiwyNDIsMTY1LDIwLDEwNiwyMDIsMjA4LDEsOTYsMTMzLDIwLDE2MCwyLDE4NSwxOTQsMTkxLDIwMSw4LDQ4LDUsMjMzAAEdQwCDMywxNTMsMTk0LDE5MSwxMzYsMTYsMjQxLDQ4LDIxMSwxNjksMCwxNDEsMTk0LDE5MSwxNDEsMTk1LDE5MSwxNDEsMTk2LDE5MQAzHUQAgzk2LDAsOTYsMTkyLDMzLDEyOSwyMjUsNjYsMTYyLDY5LDc4LDY4LDYyLDMyAAAA"%7D,"vice":%7B"-autostart":"edldr.prg"%7D%7D) This entry is *just for fun* and will probably never reach a decent byte count. It's just because the challenge is about some "ancient" tool, why not implement it for an ancient machine ;) [![See it in action here](https://i.stack.imgur.com/CDIRP.png)](https://i.stack.imgur.com/CDIRP.png) In the course of creating this thing, I was reminded once again that the C64 system doesn't provide any sensible way of converting between strings and integers -- only strings and floats are covered and this is ridiculous, so this piece of code contains own conversion routines. In fact, the only OS routines called are `GETIN` (read a single character from keyboard) and `CHROUT` (write a single character to the screen). Now, assembly is probably the "least golfy" language ever. For how to "golf" this, my idea as seen here is a BASIC loader, writing the bytes of the final binary to some memory location and jumping there. It's a working BASIC program this way ;) If anyone has a better idea how to golf this, please leave a comment! The text buffer is quite limited, using up the space between `$6000` and `$BFFF` (BASIC ROM is turned off as it's not needed) and the program itself resides at `$C000`. All in all, there's room for 255 lines with 95 characters each, and the program doesn't do *any* bounds checking, so playing with it, make sure your lines don't grow too large ;) Finally, [look here for the readable source](https://github.com/Zirias/c64ed/tree/eba2a6e8247b8eaae869110afe910729e502a948), including my "golfing tool". --- As this is pretty limited stuff, and the C64 *can* do better, here comes the "deluxe edition" using 80 columns display. To do this, the Kernal must be deactivated, so basic things like a keyboard driver, a font, bitmap manipulation logic for output, interrupt handling etc must be included, therefore it's quite a challenge to fit all this in the 4K area `$C000-$CFFF` (and this is needed for loading the program from a BASIC program to work). Some random facts about this version: * fits in the 4K, but narrowly ... got 6 "spare" bytes now 3686 3841 bytes ;) * the basic loader is 13743 13385 13963 bytes (used the saved bytes for new feature "line editing") * screen color and sprite data is hidden in the ram "below" the MMIO area `$D000-$DFFF` * The PC-style text cursor is a "hardware cursor", using a sprite * the bitmap uses the area `$E000-$FF3F`, freely accessible because the kernal is switched off * There's an additional command implemented: `q` exits the editor * Extra feature: command line editing using cursor `RIGHT` and `LEFT`, Pos1 (`HOME`), End (`SHIFT + HOME`) and backspace (`DEL`) [![Screenshot of 80col version](https://i.stack.imgur.com/6QSY5.png)](https://i.stack.imgur.com/6QSY5.png) ## [Demo](https://vice.janicek.co/c64/#%7B"controlPort2":"joystick","primaryControlPort":2,"keys":%7B"SPACE":"","RETURN":"","F1":"","F3":"","F5":"","F7":""%7D,"files":%7B"deluxed.prg":"data:;base64,AQglCAAAgUGyNDkxNTKkNTI5OTI6h0I6l0EsQjqCOp40OTE1MgB1CAEAgzE2MiwyLDE4MSwwLDE1NywwLDIwNywyMzIsMjA4LDI0OCwxNzMsMzIsMjA4LDEzMywyLDE3MywzMywyMDgsMTMzLDMsMTczLDE3AMcIAgCDMjA4LDEzMyw1LDEyMCwxNjksMCwxNDEsMjEsMjA4LDE2OSw1MiwxMzMsMSwxNjksMTUsMTYyLDAsMzIsNjcsMTk2LDMyLDk2LDE5NgAZCQMAgzE2MiwxMjcsMTY5LDAsMTU3LDAsMjE4LDIwMiwxNiwyNTAsMTY5LDI0MCwxNDEsMTgsMjE4LDE0MSwyMSwyMTgsMTY5LDEwNCwxNDEAagkEAIMyNDgsMjIzLDE2OSw1MywxMzMsMSwxNjksMjUsMTQxLDAsMjA4LDE2OSw1MCwxNDEsMSwyMDgsMTY5LDAsMTQxLDE2LDIwOCwxNDEAuwkFAIMyOSwyMDgsMTQxLDIzLDIwOCwxNDEsMjgsMjA4LDE2OSwxLDE0MSwzOSwyMDgsMTQxLDI3LDIwOCwxNDEsMjEsMjA4LDE2OSwyMjgADQoGAIMxNDEsMjUwLDI1NSwxNjksMTk1LDE0MSwyNTEsMjU1LDE2OSwwLDE0MSwxNCwyMjEsMTQxLDQsMjIxLDE0MSw1LDIyMSwxNjksMTI5AF0KBwCDMTQxLDEzLDIyMSwxNjksMSwxNDEsMTQsMjIxLDE3MywwLDIyMSw0MSwyNTIsMTQxLDAsMjIxLDE3MywyNCwyMDgsMTMzLDQsMzIArAoIAIMyNDEsMTk1LDMyLDM5LDE5NiwxNjksMCwxMzMsNiwxMzMsNywxNDEsMzIsMjA4LDg4LDE2MiwxLDEzNCw0NiwzMiwxNTYsMTk2APsKCQCDMTIwLDMyLDI1LDE5NiwxNzMsMCwyMjEsOSwzLDE0MSwwLDIyMSwxNjUsNCwxNDEsMjQsMjA4LDE2OSw1NSwxMzMsMSwxNjksMQBJCwoAgzE0MSwxMywyMjEsMTczLDEzLDIyMSwxNjUsNSwxNDEsMTcsMjA4LDE2NSwyLDE0MSwzMiwyMDgsMTY1LDMsMTQxLDMzLDIwOACYCwsAgzE2OSwwLDE0MSwyMSwyMDgsMTYyLDIsMTg5LDAsMjA3LDE0OSwwLDIzMiwyMDgsMjQ4LDg4LDk2LDEzMywxMCwxNjksMCwxMzMA6AsMAIMxMSwxNjUsMTAsMTAsMzgsMTEsMTAsMzgsMTEsMTAsMzgsMTEsMTMzLDEwLDE2OSwxLDI0LDEwMSwxMCwxMzMsMTAsMTY5LDIwMwA3DA0AgzEwMSwxMSwxMzMsMTEsOTYsMTY5LDAsMTMzLDksMTY1LDYsMTAsMTAsMTAsMTAsMzgsOSwxMCwzOCw5LDEwLDM4LDksMTMzLDgAhwwOAIMxNjUsOSwxMDEsNiwxMDUsMjI0LDEzMyw5LDE2NSwxMiwxMCwxMCwxMCwxNDQsMywyMzAsOSwyNCwxMDEsOCwxNDQsMiwyMzAsOQDVDA8AgzEzMyw4LDk2LDE2MCwyMjQsMTMyLDksMjAwLDEzMiwxMSwxNjAsNjQsMTMyLDEwLDE2MCwwLDEzMiw4LDE2Miw1MCwxNjksMAAjDRAAgzE2OCwyMjQsMyw0OCwyLDE3NywxMCwxNDUsOCwyMDAsMTkyLDE2MCwyMDgsMjQzLDIwMiwyNDAsMjMsMTY5LDE1OSwxMDEsOAB0DREAgzEzMyw4LDE0NCwzLDIzMCw5LDI0LDE2OSwxNjAsMTAxLDEwLDEzMywxMCwxNDQsMjE4LDIzMCwxMSwxNzYsMjE0LDk2LDcyLDEzMgDFDRIAgzIxLDc2LDE5OSwxOTMsNzIsMTMyLDIxLDIwMSwxMywyNDAsMTUsMjAxLDE3LDI0MCwzMCwzMiwyNDEsMTkzLDIzMCw3LDE2MCw4MAAUDhMAgzE5Niw3LDIwOCw1MiwxNjAsMCwxMzIsNywyMzAsNiwxNjAsMjUsMTk2LDYsMjA4LDQwLDE5OCw2LDMyLDU5LDE5MywyNDAsMzMAZA4UAIMxNjksMzIsMTY0LDcsMjQwLDUsMTM2LDEzMiw3LDE2LDE5LDE2MCw3OSwxMzIsNywxNjQsNiwyNDAsNSwxMzYsMTMyLDYsMTYsNgCzDhUAgzE2MCwwLDEzMiw3LDI0MCwzLDMyLDI0MSwxOTMsMTY1LDYsMTAsMTAsMTAsMTA1LDUwLDE0MSwxLDIwOCwxNjksMCwxNDEsMTYAAQ8WAIMyMDgsMTY1LDcsMTAsMTAsMTQ0LDQsMjM4LDE2LDIwOCwyNCwxMDUsMjQsMTQ0LDMsMjM4LDE2LDIwOCwxNDEsMCwyMDgsMzIAUQ8XAIMyMjksMTk1LDEwNCwxNjQsMjEsOTYsMjQsNzQsMTc2LDY3LDMyLDIzNSwxOTIsMTYwLDcsMTc3LDEwLDQxLDI0MCwxNTMsMTMsMACiDxgAgzEzNiwxNiwyNDYsMTY1LDcsNzQsMTMzLDEyLDE3NiwxOCwzMiwxMiwxOTMsMTYwLDcsMTc3LDgsNDEsMTUsMjUsMTMsMCwxNDUsOADxDxkAgzEzNiwxNiwyNDQsOTYsMzIsMTIsMTkzLDE2MCw3LDE3Nyw4LDQxLDI0MCw3NCw3NCw3NCw3NCw3NCwyNSwxMywwLDEwNiwxMDYAQBAaAIMxMDYsMTA2LDE0NSw4LDEzNiwxNiwyMzUsOTYsMzIsMjM1LDE5MiwxNjAsNywxNzcsMTAsNDEsMTUsMTUzLDEzLDAsMTM2LDE2AJAQGwCDMjQ2LDE2NSw3LDc0LDEzMywxMiwxNzYsMjUsMzIsMTIsMTkzLDE2MCw3LDE3Nyw4LDEwLDEwLDEwLDEwLDEwLDI1LDEzLDAsNDIA4RAcAIM0Miw0Miw0MiwxNDUsOCwxMzYsMTYsMjM3LDk2LDMyLDEyLDE5MywxNjAsNywxNzcsOCw0MSwyNDAsMjUsMTMsMCwxNDUsOCwxMzYAMhEdAIMxNiwyNDQsOTYsMTc0LDExMywyMDIsMjM2LDExNCwyMDIsMjQwLDExLDE4MSwyMiwyMDIsMTYsMiwxNjIsMTUsMTQyLDExMywyMDIAghEeAIMyNCw5NiwxNjksMCwxMzMsNDMsMTMzLDM4LDEzMyw0MCwxNjksMTI3LDE0MSwwLDIyMCwxNzMsMSwyMjAsNzMsMjU1LDI0MCwyNQDRER8AgzE3MCw0MSw0LDI0MCw2LDE2NSw0Myw5LDEyOCwxMzMsNDMsMTM4LDQxLDI1MSwyNDAsOSwyMzAsNDAsMzIsMTYxLDE5NSwxMDUAIRIgAIM1NiwxMzMsMzgsMTY5LDE5MSwxNDEsMCwyMjAsMTczLDEsMjIwLDczLDI1NSwyNDAsMjUsMTcwLDQxLDE2LDI0MCw2LDE2NSw0MwBxEiEAgzksNjQsMTMzLDQzLDEzOCw0MSwyMzksMjQwLDksMjMwLDQwLDMyLDE2MSwxOTUsMTA1LDQ4LDEzMywzOCwxNjksMjIzLDE0MSwwAL8SIgCDMjIwLDE3MywxLDIyMCw3MywyNTUsMjQwLDksMjMwLDQwLDMyLDE2MSwxOTUsMTA1LDQwLDEzMywzOCwxNjksMjM5LDE0MSwwAA0TIwCDMjIwLDE3MywxLDIyMCw3MywyNTUsMjQwLDksMjMwLDQwLDMyLDE2MSwxOTUsMTA1LDMyLDEzMywzOCwxNjksMjQ3LDE0MSwwAFsTJACDMjIwLDE3MywxLDIyMCw3MywyNTUsMjQwLDksMjMwLDQwLDMyLDE2MSwxOTUsMTA1LDI0LDEzMywzOCwxNjksMjUxLDE0MSwwAKkTJQCDMjIwLDE3MywxLDIyMCw3MywyNTUsMjQwLDksMjMwLDQwLDMyLDE2MSwxOTUsMTA1LDE2LDEzMywzOCwxNjksMjUzLDE0MSwwAPkTJgCDMjIwLDE3MywxLDIyMCw3MywyNTUsMjQwLDI1LDE3MCw0MSwxMjgsMjQwLDYsMTY1LDQzLDksNjQsMTMzLDQzLDEzOCw0MSwxMjcAShQnAIMyNDAsOSwyMzAsNDAsMzIsMTYxLDE5NSwxMDUsOCwxMzMsMzgsMTY5LDI1NCwxNDEsMCwyMjAsMTczLDEsMjIwLDczLDI1NSwyNDAAmxQoAIM3LDIzMCw0MCwzMiwxNjEsMTk1LDEzMywzOCwxNjUsNDAsMjA4LDUsMTY5LDEyOCwxMzMsMzksOTYsMTY1LDM4LDE5NywzOSwyNDAA6hQpAIM1MSwxMzMsMzksMTYyLDI1LDEzNCw0MSwxNjIsMSwxMzQsNDIsNSw0MywxNzQsMTE0LDIwMiwxNDksMjIsMjAyLDE2LDIsMTYyADgVKgCDMTUsMTQyLDExNCwyMDIsMjM2LDExMywyMDIsMjA4LDgsMjAyLDE2LDIsMTYyLDE1LDE0MiwxMTMsMjAyLDk2LDE2Miw3LDc0AIcVKwCDMTc2LDQsMjAyLDE2LDI1MCw5NiwxMzgsMjQsOTYsMTY2LDQxLDI0MCw0LDIwMiwxMzQsNDEsOTYsMTY2LDQyLDI0MCw0LDIwMgDYFSwAgzEzNCw0Miw5NiwxNjIsMSwxMzQsNDIsNzYsMTMyLDE5NSwxMzMsNDQsMTM0LDQ1LDE5OCw0NiwyMDgsMTIsMTY5LDI0LDEzMyw0NgAnFi0AgzE2OSwxLDc3LDIxLDIwOCwxNDEsMjEsMjA4LDMyLDE0MSwxOTQsMTY5LDI1NSwxNDEsMjUsMjA4LDE2Niw0NSwxNjUsNDQsNjQAdxYuAIMxMjAsMTYwLDEsMTQwLDIxLDIwOCwxNjAsMjQsMTMyLDQ2LDg4LDk2LDE2OSwxMjcsMTQxLDEzLDIyMCwxNzMsMTMsMjIwLDE2OQDHFi8AgzEsMTQxLDI2LDIwOCwxNDEsMjUsMjA4LDE2OSwxNiwxNDEsMTgsMjA4LDE3MywxNywyMDgsNDEsMTI3LDE0MSwxNywyMDgsMTY5ABcXMACDMTk2LDE0MSwyNTQsMjU1LDE2OSwxOTUsMTQxLDI1NSwyNTUsOTYsMTY5LDAsMTQxLDI2LDIwOCwxNDEsMjUsMjA4LDE2OSwxMzEAZhcxAIMxNDEsMTMsMjIwLDk2LDE3MywxNywyMDgsOSwzMiwxNDEsMTcsMjA4LDE2OSwxMjEsMTQxLDI0LDIwOCw5NiwxNzMsMTcsMjA4ALUXMgCDNDEsMjIzLDE0MSwxNywyMDgsMTY5LDExNCwxNDEsMjQsMjA4LDk2LDEzNCw0NywxMCwxMCwxMCwxMCwxMDEsNDcsMTYyLDIyMAADGDMAgzEzNCw0OCwxNjAsMCwxMzIsNDcsMTYyLDQsMTQ1LDQ3LDIwMCwyMDgsMjUxLDIzMCw0OCwyMDIsMjA4LDI0Niw5NiwxNjksMABTGDQAgzE2OCwxMzMsNDcsMTYyLDIyNCwxMzQsNDgsMTYyLDMxLDE0NSw0NywyMDAsMjA4LDI1MSwyMzAsNDgsMjAyLDIwOCwyNDYsMTYwAKEYNQCDNjMsMTQ1LDQ3LDEzNiwxNiwyNTEsOTYsMzIsMTIxLDE5NCwxODQsMTc2LDI0LDE3MCwxNiwzLDQ0LDExNSwyMDIsNDEsMTI3APAYNgCDMTcwLDE4OSwxMTYsMjAyLDgwLDIsOSwxMjgsMjAxLDMxLDE3NiwzLDQ0LDExNSwyMDIsMjQsOTYsMTYyLDEsMTM0LDU2LDEzNAA/GTcAgzU1LDIwMiwxNDIsMCw5NiwxMzQsNTQsMTY2LDU1LDE2MCw1NywzMiwyMDgsMTk4LDMyLDE4OCwxOTksMzIsMjM1LDE5OSwxNjYAjhk4AIM2NSwyNDAsMTA4LDIwMiwyMDIsMTYsMiwxNjIsMCwxMzQsNDksMTY1LDEyOCwyMDEsNjksMjQwLDk5LDIwMSw2NiwyNDAsMTAxAN8ZOQCDMjAxLDEwOCwyNDAsMTAzLDIwMSw3NiwyNDAsMTAyLDIwMSw4MCwyNDAsMTA1LDIwMSw5NywyNDAsMTAzLDIwMSw3MywyNDAsMTI0AC4aOgCDMjAxLDgyLDI0MCwxMjIsMjAxLDEwNSwyNDAsMTIwLDIwMSw2OCwyNDAsMTIxLDIwMSw3NCwyNDAsMTE5LDIwMSw4MSwyMDgsMQB8GjsAgzk2LDE2MiwwLDMyLDEwNCwyMDEsMTY1LDY3LDE2Niw1NCwyMjQsMCwyNDAsMTY3LDMyLDE5MSwxOTgsMjAxLDI1NSwyNDAsOADMGjwAgzEzMyw1NSwxNzAsMTYwLDU3LDMyLDIwOCwxOTgsMTYwLDAsMTc3LDU3LDE3MCwyMzIsMTY1LDY4LDIwMSwyNTUsMjA4LDIsMTY1ABsbPQCDNTYsMzIsMTkxLDE5OCwxMzMsNTYsMTYsMTMxLDMyLDAsMTk5LDE2LDYzLDE2OSwwLDEzMyw2OCwyNDAsMjAzLDE2OSwxLDEzMwBsGz4AgzY4LDIwOCwxOTcsNzYsMTAsMTk4LDE2Niw1NSwzMiw4NywxOTgsODAsNDEsMjQwLDQyLDE2Niw1NCwyMzIsMTM0LDU0LDEzNCw1NQC7Gz8AgzE2MCw1NywzMiwyMDgsMTk4LDE2OSwwLDE2OCwxNDUsNTcsMjAwLDEzMiw1NiwzMiwxMTgsMTk4LDE2LDE0LDI0MCw4MiwyNDAAChxAAIMxMDQsMzIsMTE4LDE5OCwxNiw1LDI0MCwxMjIsMzIsOTQsMTk5LDc2LDE2OCwxOTYsMTY2LDU0LDI0MCwyNDksMTYyLDEsMTM0AFscQQCDNjcsMjAyLDEzNCw2OCwxNjIsMiwxNjUsNDksMjQwLDMsMzIsNDksMjAxLDE2NSw2NywxNjYsNTQsMzIsMTkxLDE5OCwyMDEsMjU1AKwcQgCDMjA4LDIsMTY5LDEsMTMzLDY3LDE2Niw1NCwxNjUsNjgsMjAxLDI1NSwyMDgsMiwxNjksMCwzMiwxOTEsMTk4LDE0MSwxNjcsMTk3APwcQwCDMTY2LDY3LDMyLDg3LDE5OCwxNjYsNjcsMjI0LDI1NSwyNDAsMTkxLDIzMiwxMzQsNjcsMjA4LDI0MiwzMiwwLDE5OSwxOTgsNTUATR1EAIMxNjAsMCwxNzcsNTcsMTMzLDU2LDIzMCw1NiwzMiwxMTgsMTk4LDIzMCw1NSwxNjIsMSwxMzQsNTYsMjA4LDE2MiwxNjAsMCwxNjYAnR1FAIM1NiwyMDIsMTM4LDE0NSw1NywzMiwxMTgsMTk4LDE2Niw1NCwyMjgsNTUsMjQwLDEyNCwyMzAsNTUsMTYyLDEsMTM0LDU2LDIwOADsHUYAgzExNiwxNjAsMCwxOTYsNTQsMjQwLDExMCwxNzcsNTcsMjA4LDI0LDE2NSw1NSwxOTcsNTQsMjA4LDUsMTk4LDU1LDIwMCwxMzIAOx5HAIM1NiwzMiw5NCwxOTksMTYwLDEsMTk2LDU1LDQ4LDg2LDEzMiw1NSwxNiw4MiwxNTIsMTQ1LDU3LDIwMCwxMzIsNTYsMjA4LDc0AIoeSACDMTY2LDU0LDI0MCw3MCwxNjYsNTUsMTYwLDMsMjAyLDI0MCw2LDIwMCwyMDIsMjQwLDIsMjAwLDIwMiwyMzIsMTQwLDU0LDE5OADbHkkAgzE0Miw1NiwxOTgsMjI4LDU1LDI0MCw3LDE2OSwzMiwzMiwxMjUsMTkzLDIwOCw1LDE2OSw2MiwzMiwxMjUsMTkzLDMyLDg3LDE5OAAqH0oAgzE2MCwyNTUsMTYyLDI1NSwxMzYsMjQwLDQsMjI4LDU0LDIwOCwyMTksMTY5LDMyLDE2Niw1NiwzMiwxMjUsMTkzLDIwMiwyMDgAeh9LAIMyNTAsMTY5LDM4LDMyLDEyNSwxOTMsMTY5LDEzLDMyLDEyNSwxOTMsNzYsMTY4LDE5NiwxNjAsNTAsMzIsMjA4LDE5OCwxNjAsMADKH0wAgzE3Nyw1MCwyNDAsMTUsMTQxLDExMCwxOTgsMjMwLDUwLDE3Nyw1MCwzMiwxMjUsMTkzLDIwMCwxOTIsMjU1LDIwOCwyNDYsMTY5ABsgTQCDMTMsNzYsMTI1LDE5MywxNjUsNTcsMjQsMTAxLDU2LDEzMyw1MCwxNjUsNTgsMTA1LDAsMTMzLDUxLDE2NSw1MCwxMDEsNDksMTMzAGwgTgCDNTIsMTY1LDUxLDEwNSwwLDEzMyw1MywxNjAsMCwxNzcsNTcsNTYsMjI5LDU2LDQ4LDgsMTY4LDE3Nyw1MCwxNDUsNTIsMTM2LDE2ALsgTwCDMjQ5LDE2NCw0OSwxMzYsMTYsMSw5NiwxODUsMTMwLDAsMTQ1LDUwLDEzNiwxNiwyNDgsMTYwLDAsMTc3LDU3LDI0LDEwMSw0OQAMIVAAgzE0NSw1NywxNjUsNTYsMjQsMTAxLDQ5LDEzMyw1Niw5NiwxNDEsMjAzLDE5OCwyMDEsMjU1LDI0MCw5LDIwMSwwLDI0MCw0LDIyNABbIVEAgzI1NSwxNiwxLDEzOCw5NiwxNDAsMjU0LDE5OCwyMDAsMTQwLDI0NywxOTgsMjAyLDEzOCw0MSw3LDE2OCwxMzgsNzQsNzQsNzQAqiFSAIMxNzAsMTY5LDAsMjQsMjAyLDQ4LDQsMTA1LDMsMTQ0LDI0OSwxMzMsNjMsMTg1LDI0NCwyMDIsNDEsMywxMDEsNjMsMTA1LDk2APghUwCDMTMzLDI1NSwxODUsMjQ0LDIwMiw0MSwyNDAsMTMzLDI1NSw5NiwxNjYsNTQsMjMyLDEzNCw1NCwxMzQsNjQsMTYwLDU5LDMyAEgiVACDMjA4LDE5OCwxOTgsNjQsMTY2LDY0LDIyOCw1NSwyNDAsMTQsNDgsMTIsMTYwLDYxLDMyLDIwOCwxOTgsMzIsMTc1LDE5OSwxNjYAlyJVAIM2NCwxNiwyMjcsMTY1LDU5LDE0MSw3NCwxOTksMTY1LDYwLDE0MSw3NSwxOTksMTYwLDAsMTc3LDU3LDE0MSw3MCwxOTksMTk4AOUiVgCDNTYsNTYsMjI5LDU2LDcyLDE2NSw1NiwxNDUsNTcsMTA0LDE2MCwwLDE0NSw1OSwxNzAsMjQwLDExLDE2MCwyNTUsMTc3LDU3ADUjVwCDMTU3LDI1NSwyNTUsMTM2LDIwMiwyMDgsMjQ3LDE2MiwxLDEzNCw1NiwxNjYsNTUsMjI4LDU0LDI0MCwzLDIzMiwxMzQsNTUsOTYAgyNYAIMxNjYsNTUsMjI4LDU0LDI0MCw3NCwyMzIsMTYwLDYxLDMyLDIwOCwxOTgsMTY1LDYxLDE0MSwxMzQsMTk5LDE2NSw2MiwxNDEA0yNZAIMxMzUsMTk5LDE2MCwwLDE3Nyw2MSwyNDAsMjAsMTcwLDE3Nyw1NywxMzQsNjQsMjQsMTAxLDY0LDE0NSw1NywxNjgsMTg5LDI1NQAhJFoAgzI1NSwxNDUsNTcsMTM2LDIwMiwyMDgsMjQ3LDE2Niw1NSwyMzIsMTM0LDY0LDIyOCw1NCwyNDAsMjEsMTYwLDU5LDMyLDIwOAByJFsAgzE5OCwyMzAsNjQsMTY2LDY0LDE2MCw2MSwzMiwyMDgsMTk4LDMyLDE3NSwxOTksMTY2LDY0LDIwOCwyMzEsMTk4LDU0LDk2LDE2MADCJFwAgzAsMTc3LDYxLDE2OCwxNzcsNjEsMTQ1LDU5LDEzNiwxNiwyNDksOTYsMTY1LDU1LDE5Nyw1NCwxNDQsMjIsMTYwLDAsMTc3LDU3ABAlXQCDMTk3LDU2LDE2LDE0LDE2MiwwLDE4OSwyNTIsMjAyLDMyLDEyNSwxOTMsMjMyLDIyNCw1LDIwOCwyNDUsOTYsMTY1LDU1LDMyAGAlXgCDMTkyLDIwMSwxNjksNDQsMzIsMTI1LDE5MywxNjUsNTYsMzIsMTkyLDIwMSwxNjIsMywyMDgsMjI1LDE2Niw3LDEzNCw3NCwxNjYAriVfAIM2LDEzNCw3NSwxNjAsMCwxMzIsNjUsMTMyLDY2LDEzMiw3NiwxNjQsNzYsMjQwLDYsMTY5LDEzLDMyLDEyNSwxOTMsOTYsMzIA/SVgAIMxMjUsMTk2LDE3NiwyNDEsMTEyLDg2LDE2NCw2NSwxOTIsODAsMjQwLDIzMywxOTYsNjYsMjQwLDcsMTgyLDEyNywxNTAsMTI4AEsmYQCDMTM2LDE2LDI0NSwzMiwxMjUsMTkzLDE2Niw2LDEzNCw3MiwxNjYsNywxMzQsNzMsMjA4LDgsMTY2LDYsMjI4LDc1LDIwOCwyAJwmYgCDMTk4LDc1LDE1MywxMjgsMCwyMDAsMTMyLDY2LDIzMCw2NSwxOTYsNjUsMjQwLDIzLDE4NSwxMjgsMCwzMiwxMjUsMTkzLDE2NSw3AO0mYwCDMjA4LDEwLDE2OSwyNCwxOTcsNzIsMjA4LDQsMTk4LDcyLDE5OCw3NSwyMDAsMTYsMjI5LDE2Niw3MiwxMzQsNiwxNjYsNzMsMTM0AD0nZACDNywzMiwxMTksMTkzLDE2LDE1MywyMDEsMTMsMjA4LDQsMjMwLDc2LDIwOCw0MCwyMDEsMTEsMjA4LDEwLDE2Niw2NiwyMjgsNjUAjCdlAIMyNDAsMTM1LDIzMCw2NiwxNiwzMCwyMDEsMTIsMjA4LDgsMTY2LDY2LDI0MCw0NiwxOTgsNjYsMTYsMTgsMjAxLDE1LDIwOCw2ANonZgCDMTYyLDAsMTM0LDY2LDE2LDgsMjAxLDE2LDIwOCwzMSwxNjYsNjUsMTM0LDY2LDE2Niw3NSwxMzQsNiwyNCwxNjUsNzQsMTAxACkoZwCDNjYsMjAxLDgwLDEzMyw3LDE0NCw2LDIzMyw4MCwxMzMsNywyMzAsNiwzMiwxMTksMTkzLDc2LDI1MSwxOTksMjAxLDE3LDIwOAB3KGgAgzI0OSwxNjQsNjYsMjQwLDI0NSwxMzYsMTk4LDY1LDEzMiw2NiwxOTYsNjUsMjQwLDcsMTgyLDEyOSwxNTAsMTI4LDIwMCwxNgDGKGkAgzI0NSwzMiwxMjUsMTkzLDE2Niw2LDEzNCw3MiwxNjYsNywxMzQsNzMsMTY0LDY2LDE5Niw2NSwyNDAsOSwxODUsMTI4LDAsMzIAFSlqAIMxMjUsMTkzLDIwMCwxNiwyNDMsMTY5LDMyLDMyLDEyNSwxOTMsMTY2LDcyLDEzNCw2LDE2Niw3MywxMzQsNywzMiwxMTksMTkzAGIpawCDNzYsMjUxLDE5OSwxNDEsMTIsMjAxLDE0MSwyMywyMDEsMzIsMTA0LDIwMiwxNjAsMCwxODEsMTI4LDI0MCw0MywyMDEsNDMAsilsAIMyMDgsNywxNjksMSwxMzMsMjU1LDIzMiwyMDgsOSwyMDEsNDUsMjA4LDcsMTY5LDI1NSwxMzMsMjU1LDIzMiwxODEsMTI4LDI0MAACKm0AgzE5LDIwMSw0OCw0OCwxNSwyMDEsNTgsMTYsMTEsMTUzLDIwOSwwLDIzMiwyMDAsMTkyLDMsMTYsMiw0OCwyMzMsOTYsMTM0LDcxAFAqbgCDMTYwLDAsMTMyLDY5LDEzMiw3MCwxMzYsMTMyLDY3LDEzMiw2OCwxNjksNjksMzIsMjQ2LDIwMCwyMjgsNzEsMjQwLDksMTM0AJ8qbwCDNzEsMzIsMjQsMjAyLDEzMyw2NywxNjYsNzEsMTgxLDEyOCwyMDEsNDQsMjA4LDE3LDIzMiwxMzQsNzEsMTY5LDcwLDMyLDI0NgDsKnAAgzIwMCwyMjgsNzEsMjQwLDUsMzIsMjQsMjAyLDEzMyw2OCw5NiwzMiw0OSwyMDEsMTY5LDEsMzYsNjksMjQwLDM2LDE2LDIxADsrcQCDMTY1LDY3LDE5Nyw1NSw0OCw2LDE2OSwxLDEzMyw2NywyMDgsMjIsMTY1LDU1LDU2LDIyOSw2NywxMzMsNjcsMjA4LDEzLDE2NQCLK3IAgzU1LDI0LDEwMSw2NywxMzMsNjcsMTQ0LDQsMTY5LDAsMTMzLDY3LDE2OSwxLDM2LDcwLDI0MCwzNiwxNiwyMSwxNjUsNjgsMTk3ANkrcwCDNTYsNDgsNiwxNjksMSwxMzMsNjgsMjA4LDIyLDE2NSw1Niw1NiwyMjksNjgsMTMzLDY4LDIwOCwxMywxNjUsNTYsMjQsMTAxACgsdACDNjgsMTMzLDY4LDE0NCw0LDE2OSwwLDEzMyw2OCw5NiwzMiwyMTAsMjAxLDE2MiwwLDE4MSwyMDksMjQwLDMsMzIsMTI1LDE5MwB2LHUAgzIzMiwyMjQsMywyMDgsMjQ0LDk2LDEzMywyMTIsMzIsMTA0LDIwMiwxNjIsOCwxNjAsMiwxODUsMjA5LDAsMjAxLDUsNDgsNQDGLHYAgzEwNSwyLDE1MywyMDksMCwxMzYsMTYsMjQxLDE2MCwyLDE2NSwyMTIsMTAsMTMzLDIxMiwxODUsMjA5LDAsNDIsMjAxLDE2LDQxABQtdwCDMTUsMTUzLDIwOSwwLDEzNiwxNiwyNDIsMjAyLDIwOCwyMTUsMTY1LDIxMSw5LDQ4LDEzMywyMTEsMTYwLDEsMTg1LDIwOSwwAGMteACDMjQwLDgsOSw0OCwxNTMsMjA5LDAsMTM2LDE2LDI0Myw5NiwxNjUsMjExLDIwOCwxNCwxNjUsMjEwLDEzMywyMTEsMTY1LDIwOQCxLXkAgzEzMywyMTAsMTY5LDAsMTMzLDIwOSwyNDAsMjM4LDE2MCwyLDE4NSwyMDksMCwyNDAsNSw0MSwyMDcsMTUzLDIwOSwwLDEzNgABLnoAgzE2LDI0MywxNjIsOCwxNjAsMTI1LDI0LDE4NSw4NCwwLDE0NCwyLDksMTYsNzQsMTUzLDg0LDAsMjAwLDE2LDI0MiwxNjUsMjEyAFEuewCDMTA2LDIwMiwyMDgsMSw5NiwxMzMsMjEyLDE2MCwyLDE4NSwyMDksMCwyMDEsOCw0OCw1LDIzMywzLDE1MywyMDksMCwxMzYsMTYAoS58AIMyNDEsNDgsMjExLDE2OSwwLDEzMywyMDksMTMzLDIxMCwxMzMsMjExLDk2LDE1LDE1LDEyNyw5LDUsMywxLDcsMTEsMTMsMTcsMADxLn0AgzY5LDgzLDkwLDUyLDY1LDg3LDUxLDg4LDg0LDcwLDY3LDU0LDY4LDgyLDUzLDg2LDg1LDcyLDY2LDU2LDcxLDg5LDU1LDc4LDc5AEEvfgCDNzUsNzcsNDgsNzQsNzMsNTcsNDQsNjQsNTgsNDYsNDUsNzYsODAsNDMsNDcsOTQsNjEsMCwxNSw1OSw0MiwxMjQsMjEsODEsMTkAkS9/AIMzMiw1MCwwLDAsNDksMTAsNiw0LDIsOCwxMiwxNCwxOCwwLDEwMSwxMTUsMTIyLDM2LDk3LDExOSwzNSwxMjAsMTE2LDEwMiw5OQDfL4AAgzM4LDEwMCwxMTQsMzcsMTE4LDExNywxMDQsOTgsNDAsMTAzLDEyMSwzOSwxMTAsMTExLDEwNywxMDksNDgsMTA2LDEwNSw0MQAvMIEAgzYwLDY0LDkxLDYyLDQ1LDEwOCwxMTIsNDMsNjMsOTQsNjEsMCwxNiw5Myw0MiwxMjQsMjIsMTEzLDIwLDMyLDM0LDAsMCwzMywwAH8wggCDOTYsMTkyLDMzLDEyOSwyMjUsNjYsMTYyLDY5LDc4LDY4LDYyLDMyLDM0LDIwLDM0LDg1LDExOSw4NSw4NSwwLDgyLDUsMzQsODUAzzCDAIMxMTksODUsODUsMCwzNCwyMCwxMTksNjgsMTAyLDY4LDExOSwwLDgyLDUsMTE5LDY4LDEwMiw2OCwxMTksMCwzNCwyMCwzNCw4NQAdMYQAgzg1LDg1LDM0LDAsODIsNSwzNCw4NSw4NSw4NSwzNCwwLDY1LDM0LDg1LDg1LDg1LDg1LDM0LDAsODIsNSw4MCw4NSw4NSw4NQBtMYUAgzM0LDAsMCwzNCwyMCwxMDIsMTcsNTEsMTE5LDAsMCw4Miw1LDEwMiwxNyw1MSwxMTksMCwwLDM0LDIwLDM0LDExOSw2OCwzNCwwALsxhgCDMCw4Miw1LDM0LDExOSw2OCwzNCwwLDAsMzQsMjAsMzQsODUsODUsMzQsMCwwLDgyLDUsMzQsODUsODUsMzQsMCwwLDY1LDM0AAkyhwCDODUsODUsODUsNTEsMCwwLDgyLDUsODAsODUsODUsNTEsMCwyLDIsMiwyLDIsMCwyLDAsMTAyLDEwMiwxNSw2LDE1LDYsNiwwAFgyiACDMzcsMTEzLDY2LDk4LDE4LDEwMCwzNywwLDM0LDgyLDQsMCwwLDAsMCwwLDM2LDY2LDY2LDY2LDY2LDY2LDM2LDAsMCw4MiwzNACnMokAgzExOSwzNCw4MiwwLDAsMCwwLDAsNywwLDMyLDMyLDY0LDEsMSwyLDIsMiwzNiwzNiwwLDMzLDgzLDExNywxMTMsODEsODEsMzMA9TKKAIMwLDM0LDg1LDE3LDM0LDMzLDY5LDExNCwwLDIzLDUyLDg2LDExMywxNywyMSwxOCwwLDM5LDY1LDY1LDk4LDgyLDgyLDM0LDAARTOLAIMzNCw4NSw4NSwzNSw4MSw4MSwzNCwwLDAsMzQsMzQsMCwwLDM0LDM0LDQsMCwxNiwzOSw2NCwzOSwxNiwwLDAsMiw2OSwzMywxOACTM4wAgzM0LDY0LDIsMCwzMiw4MCwxMTgsODEsMTE1LDY5LDM5LDAsNjQsNjQsOTksODQsODQsODQsOTksMCwxNiwxNiw1MCw4NSw4NwDjM40Agzg0LDUwLDAsMTYsMzIsMTE1LDM3LDM3LDM1LDMzLDIsNjYsNjQsOTgsODIsODIsODIsODIsMCwzNiw0LDM3LDM4LDM4LDM4LDM3ADE0jgCDNjQsMzIsMzIsMzgsMzksMzcsMzcsMzcsMCwwLDAsOTgsODUsODUsODUsODIsMCwwLDAsOTksODUsODUsOTksNjUsNjUsMCwwAH80jwCDOTgsODQsNzAsNjUsNzAsMCwzMiwzMiwxMTcsMzcsMzcsMzcsMTksMCwwLDAsODUsODUsODcsMTE5LDM0LDAsMCwwLDg1LDM3AM40kACDMzcsMzQsODIsNCwxLDIsMTE0LDM2LDM0LDY2LDExMywwLDM2LDM0LDM0LDMzLDM0LDM0LDM2LDAsODIsMTY1LDUsNiw1LDUsNgAdNZEAgzQsMzQsMzcsMjEsNyw1LDUsNSwwLDk5LDg0LDg0LDEwMCw4NCw4NCw5OSwwLDEwMyw4NCw4NCw4Niw4NCw4NCwxMDMsMCwxMTgAbDWSAIM2OSw2OCwxMDMsNjksNjksNzEsMCw4Nyw4Miw4MiwxMTQsODIsODIsODcsMCwyMSwyMSwyMiwyMiwyMiw4NSwzNywwLDY5LDcxALs1kwCDNzEsNjksNjksNjksMTE3LDAsODIsODUsMTE3LDExNywxMTcsODUsODIsMCw5OCw4NSw4NSwxMDEsNjksNzEsNjcsMCw5OCw4NQAKNpQAgzg0LDk4LDk3LDg1LDgyLDAsMTE3LDM3LDM3LDM3LDM3LDM3LDM0LDAsODUsODUsODUsODUsODcsMTE5LDM3LDAsODUsODUsMzcAWjaVAIMzNCwzNCw4Miw4MiwwLDExNSwxOCwzNCwzNCwzNCw2NiwxMTUsMCw2LDUwLDY2LDExNCwyMjYsNjYsNTQsMCw0OCw2NCw2Nyw2OACnNpYAgzY4LDUxLDE3LDM0LDIyMSwyMzUsMjIxLDE3MCwxMzYsMTcwLDE3MCwyNTUsMTczLDI1MCwyMjEsMTcwLDEzNiwxNzAsMTcwAPQ2lwCDMjU1LDIyMSwyMzUsMTM2LDE4NywxNTMsMTg3LDEzNiwyNTUsMTczLDI1MCwxMzYsMTg3LDE1MywxODcsMTM2LDI1NSwyMjEAQTeYAIMyMzUsMjIxLDE3MCwxNzAsMTcwLDIyMSwyNTUsMTczLDI1MCwyMjEsMTcwLDE3MCwxNzAsMjIxLDI1NSwxOTAsMjIxLDE3MACON5kAgzE3MCwxNzAsMTcwLDIyMSwyNTUsMTczLDI1MCwxNzUsMTcwLDE3MCwxNzAsMjIxLDI1NSwyNTUsMjIxLDIzNSwxNTMsMjM4ANs3mgCDMjA0LDEzNiwyNTUsMjU1LDE3MywyNTAsMTUzLDIzOCwyMDQsMTM2LDI1NSwyNTUsMjIxLDIzNSwyMjEsMTM2LDE4NywyMjEAKDibAIMyNTUsMjU1LDE3MywyNTAsMjIxLDEzNiwxODcsMjIxLDI1NSwyNTUsMjIxLDIzNSwyMjEsMTcwLDE3MCwyMjEsMjU1LDI1NQB1OJwAgzE3MywyNTAsMjIxLDE3MCwxNzAsMjIxLDI1NSwyNTUsMTkwLDIyMSwxNzAsMTcwLDE3MCwyMDQsMjU1LDI1NSwxNzMsMjUwAMI4nQCDMTc1LDE3MCwxNzAsMjA0LDI1NSwyNTMsMjUzLDI1MywyNTMsMjUzLDI1NSwyNTMsMjU1LDE1MywxNTMsMjQwLDI0OSwyNDAADzmeAIMyNDksMjQ5LDI1NSwyMTgsMTQyLDE4OSwxNTcsMjM3LDE1NSwyMTgsMjU1LDIyMSwxNzMsMjUxLDI1NSwyNTUsMjU1LDI1NQBcOZ8AgzI1NSwyMTksMTg5LDE4OSwxODksMTg5LDE4OSwyMTksMjU1LDI1NSwxNzMsMjIxLDEzNiwyMjEsMTczLDI1NSwyNTUsMjU1AKk5oACDMjU1LDI1NSwyNDgsMjU1LDIyMywyMjMsMTkxLDI1NCwyNTQsMjUzLDI1MywyNTMsMjE5LDIxOSwyNTUsMjIyLDE3MiwxMzgA9jmhAIMxNDIsMTc0LDE3NCwyMjIsMjU1LDIyMSwxNzAsMjM4LDIyMSwyMjIsMTg2LDE0MSwyNTUsMjMyLDIwMywxNjksMTQyLDIzOABDOqIAgzIzNCwyMzcsMjU1LDIxNiwxOTAsMTkwLDE1NywxNzMsMTczLDIyMSwyNTUsMjIxLDE3MCwxNzAsMjIwLDE3NCwxNzQsMjIxAJA6owCDMjU1LDI1NSwyMjEsMjIxLDI1NSwyNTUsMjIxLDIyMSwyNTEsMjU1LDIzOSwyMTYsMTkxLDIxNiwyMzksMjU1LDI1NSwyNTMA3TqkAIMxODYsMjIyLDIzNywyMjEsMTkxLDI1MywyNTUsMjIzLDE3NSwxMzcsMTc0LDE0MCwxODYsMjE2LDI1NSwxOTEsMTkxLDE1NgAqO6UAgzE3MSwxNzEsMTcxLDE1NiwyNTUsMjM5LDIzOSwyMDUsMTcwLDE2OCwxNzEsMjA1LDI1NSwyMzksMjIzLDE0MCwyMTgsMjE4AHc7pgCDMjIwLDIyMiwyNTMsMTg5LDE5MSwxNTcsMTczLDE3MywxNzMsMTczLDI1NSwyMTksMjUxLDIxOCwyMTcsMjE3LDIxNywyMTgAxDunAIMxOTEsMjIzLDIyMywyMTcsMjE2LDIxOCwyMTgsMjE4LDI1NSwyNTUsMjU1LDE1NywxNzAsMTcwLDE3MCwxNzMsMjU1LDI1NQARPKgAgzI1NSwxNTYsMTcwLDE3MCwxNTYsMTkwLDE5MCwyNTUsMjU1LDE1NywxNzEsMTg1LDE5MCwxODUsMjU1LDIyMywyMjMsMTM4AF48qQCDMjE4LDIxOCwyMTgsMjM2LDI1NSwyNTUsMjU1LDE3MCwxNzAsMTY4LDEzNiwyMjEsMjU1LDI1NSwyNTUsMTcwLDIxOCwyMTgAqzyqAIMyMjEsMTczLDI1MSwyNTQsMjUzLDE0MSwyMTksMjIxLDE4OSwxNDIsMjU1LDIxOSwyMjEsMjIxLDIyMiwyMjEsMjIxLDIxOQD7PKsAgzI1NSwxNzMsOTAsMjUwLDI0OSwyNTAsMjUwLDI0OSwyNTEsMjIxLDIxOCwyMzQsMjQ4LDI1MCwyNTAsMjUwLDI1NSwxNTYsMTcxAEg9rACDMTcxLDE1NSwxNzEsMTcxLDE1NiwyNTUsMTUyLDE3MSwxNzEsMTY5LDE3MSwxNzEsMTUyLDI1NSwxMzcsMTg2LDE4NywxNTIAlT2tAIMxODYsMTg2LDE4NCwyNTUsMTY4LDE3MywxNzMsMTQxLDE3MywxNzMsMTY4LDI1NSwyMzQsMjM0LDIzMywyMzMsMjMzLDE3MADiPa4AgzIxOCwyNTUsMTg2LDE4NCwxODQsMTg2LDE4NiwxODYsMTM4LDI1NSwxNzMsMTcwLDEzOCwxMzgsMTM4LDE3MCwxNzMsMjU1AC8+rwCDMTU3LDE3MCwxNzAsMTU0LDE4NiwxODQsMTg4LDI1NSwxNTcsMTcwLDE3MSwxNTcsMTU4LDE3MCwxNzMsMjU1LDEzOCwyMTgAfD6wAIMyMTgsMjE4LDIxOCwyMTgsMjIxLDI1NSwxNzAsMTcwLDE3MCwxNzAsMTY4LDEzNiwyMTgsMjU1LDE3MCwxNzAsMjE4LDIyMQDMPrEAgzIyMSwxNzMsMTczLDI1NSwxNDAsMjM3LDIyMSwyMjEsMjIxLDE4OSwxNDAsMjU1LDI0OSwyMDUsMTg5LDE0MSwyOSwxODksMjAxAPU+sgCDMjU1LDIwNywxOTEsMTg4LDE4NywxODcsMjA0LDIzOCwyMjEAAAA="%7D,"vice":%7B"-autostart":"deluxed.prg"%7D%7D) Program to type in yourself, if you want 80s computer mag feeling: ``` 0fOa=49152to52992:rEb:pOa,b:nE:sY49152 1dA162,2,181,0,157,0,207,232,208,248,173,32,208,133,2,173,33,208,133,3,173,17 2dA208,133,5,120,169,0,141,21,208,169,52,133,1,169,15,162,0,32,67,196,32,96,196 3dA162,127,169,0,157,0,218,202,16,250,169,240,141,18,218,141,21,218,169,104,141 4dA248,223,169,53,133,1,169,25,141,0,208,169,50,141,1,208,169,0,141,16,208,141 5dA29,208,141,23,208,141,28,208,169,1,141,39,208,141,27,208,141,21,208,169,228 6dA141,250,255,169,195,141,251,255,169,0,141,14,221,141,4,221,141,5,221,169,129 7dA141,13,221,169,1,141,14,221,173,0,221,41,252,141,0,221,173,24,208,133,4,32 8dA241,195,32,39,196,169,0,133,6,133,7,141,32,208,88,162,1,134,46,32,156,196 9dA120,32,25,196,173,0,221,9,3,141,0,221,165,4,141,24,208,169,55,133,1,169,1 10dA141,13,221,173,13,221,165,5,141,17,208,165,2,141,32,208,165,3,141,33,208 11dA169,0,141,21,208,162,2,189,0,207,149,0,232,208,248,88,96,133,10,169,0,133 12dA11,165,10,10,38,11,10,38,11,10,38,11,133,10,169,1,24,101,10,133,10,169,203 13dA101,11,133,11,96,169,0,133,9,165,6,10,10,10,10,38,9,10,38,9,10,38,9,133,8 14dA165,9,101,6,105,224,133,9,165,12,10,10,10,144,3,230,9,24,101,8,144,2,230,9 15dA133,8,96,160,224,132,9,200,132,11,160,64,132,10,160,0,132,8,162,50,169,0 16dA168,224,3,48,2,177,10,145,8,200,192,160,208,243,202,240,23,169,159,101,8 17dA133,8,144,3,230,9,24,169,160,101,10,133,10,144,218,230,11,176,214,96,72,132 18dA21,76,199,193,72,132,21,201,13,240,15,201,17,240,30,32,241,193,230,7,160,80 19dA196,7,208,52,160,0,132,7,230,6,160,25,196,6,208,40,198,6,32,59,193,240,33 20dA169,32,164,7,240,5,136,132,7,16,19,160,79,132,7,164,6,240,5,136,132,6,16,6 21dA160,0,132,7,240,3,32,241,193,165,6,10,10,10,105,50,141,1,208,169,0,141,16 22dA208,165,7,10,10,144,4,238,16,208,24,105,24,144,3,238,16,208,141,0,208,32 23dA229,195,104,164,21,96,24,74,176,67,32,235,192,160,7,177,10,41,240,153,13,0 24dA136,16,246,165,7,74,133,12,176,18,32,12,193,160,7,177,8,41,15,25,13,0,145,8 25dA136,16,244,96,32,12,193,160,7,177,8,41,240,74,74,74,74,74,25,13,0,106,106 26dA106,106,145,8,136,16,235,96,32,235,192,160,7,177,10,41,15,153,13,0,136,16 27dA246,165,7,74,133,12,176,25,32,12,193,160,7,177,8,10,10,10,10,10,25,13,0,42 28dA42,42,42,145,8,136,16,237,96,32,12,193,160,7,177,8,41,240,25,13,0,145,8,136 29dA16,244,96,174,113,202,236,114,202,240,11,181,22,202,16,2,162,15,142,113,202 30dA24,96,169,0,133,43,133,38,133,40,169,127,141,0,220,173,1,220,73,255,240,25 31dA170,41,4,240,6,165,43,9,128,133,43,138,41,251,240,9,230,40,32,161,195,105 32dA56,133,38,169,191,141,0,220,173,1,220,73,255,240,25,170,41,16,240,6,165,43 33dA9,64,133,43,138,41,239,240,9,230,40,32,161,195,105,48,133,38,169,223,141,0 34dA220,173,1,220,73,255,240,9,230,40,32,161,195,105,40,133,38,169,239,141,0 35dA220,173,1,220,73,255,240,9,230,40,32,161,195,105,32,133,38,169,247,141,0 36dA220,173,1,220,73,255,240,9,230,40,32,161,195,105,24,133,38,169,251,141,0 37dA220,173,1,220,73,255,240,9,230,40,32,161,195,105,16,133,38,169,253,141,0 38dA220,173,1,220,73,255,240,25,170,41,128,240,6,165,43,9,64,133,43,138,41,127 39dA240,9,230,40,32,161,195,105,8,133,38,169,254,141,0,220,173,1,220,73,255,240 40dA7,230,40,32,161,195,133,38,165,40,208,5,169,128,133,39,96,165,38,197,39,240 41dA51,133,39,162,25,134,41,162,1,134,42,5,43,174,114,202,149,22,202,16,2,162 42dA15,142,114,202,236,113,202,208,8,202,16,2,162,15,142,113,202,96,162,7,74 43dA176,4,202,16,250,96,138,24,96,166,41,240,4,202,134,41,96,166,42,240,4,202 44dA134,42,96,162,1,134,42,76,132,195,133,44,134,45,198,46,208,12,169,24,133,46 45dA169,1,77,21,208,141,21,208,32,141,194,169,255,141,25,208,166,45,165,44,64 46dA120,160,1,140,21,208,160,24,132,46,88,96,169,127,141,13,220,173,13,220,169 47dA1,141,26,208,141,25,208,169,16,141,18,208,173,17,208,41,127,141,17,208,169 48dA196,141,254,255,169,195,141,255,255,96,169,0,141,26,208,141,25,208,169,131 49dA141,13,220,96,173,17,208,9,32,141,17,208,169,121,141,24,208,96,173,17,208 50dA41,223,141,17,208,169,114,141,24,208,96,134,47,10,10,10,10,101,47,162,220 51dA134,48,160,0,132,47,162,4,145,47,200,208,251,230,48,202,208,246,96,169,0 52dA168,133,47,162,224,134,48,162,31,145,47,200,208,251,230,48,202,208,246,160 53dA63,145,47,136,16,251,96,32,121,194,184,176,24,170,16,3,44,115,202,41,127 54dA170,189,116,202,80,2,9,128,201,31,176,3,44,115,202,24,96,162,1,134,56,134 55dA55,202,142,0,96,134,54,166,55,160,57,32,208,198,32,188,199,32,235,199,166 56dA65,240,108,202,202,16,2,162,0,134,49,165,128,201,69,240,99,201,66,240,101 57dA201,108,240,103,201,76,240,102,201,80,240,105,201,97,240,103,201,73,240,124 58dA201,82,240,122,201,105,240,120,201,68,240,121,201,74,240,119,201,81,208,1 59dA96,162,0,32,104,201,165,67,166,54,224,0,240,167,32,191,198,201,255,240,8 60dA133,55,170,160,57,32,208,198,160,0,177,57,170,232,165,68,201,255,208,2,165 61dA56,32,191,198,133,56,16,131,32,0,199,16,63,169,0,133,68,240,203,169,1,133 62dA68,208,197,76,10,198,166,55,32,87,198,80,41,240,42,166,54,232,134,54,134,55 63dA160,57,32,208,198,169,0,168,145,57,200,132,56,32,118,198,16,14,240,82,240 64dA104,32,118,198,16,5,240,122,32,94,199,76,168,196,166,54,240,249,162,1,134 65dA67,202,134,68,162,2,165,49,240,3,32,49,201,165,67,166,54,32,191,198,201,255 66dA208,2,169,1,133,67,166,54,165,68,201,255,208,2,169,0,32,191,198,141,167,197 67dA166,67,32,87,198,166,67,224,255,240,191,232,134,67,208,242,32,0,199,198,55 68dA160,0,177,57,133,56,230,56,32,118,198,230,55,162,1,134,56,208,162,160,0,166 69dA56,202,138,145,57,32,118,198,166,54,228,55,240,124,230,55,162,1,134,56,208 70dA116,160,0,196,54,240,110,177,57,208,24,165,55,197,54,208,5,198,55,200,132 71dA56,32,94,199,160,1,196,55,48,86,132,55,16,82,152,145,57,200,132,56,208,74 72dA166,54,240,70,166,55,160,3,202,240,6,200,202,240,2,200,202,232,140,54,198 73dA142,56,198,228,55,240,7,169,32,32,125,193,208,5,169,62,32,125,193,32,87,198 74dA160,255,162,255,136,240,4,228,54,208,219,169,32,166,56,32,125,193,202,208 75dA250,169,38,32,125,193,169,13,32,125,193,76,168,196,160,50,32,208,198,160,0 76dA177,50,240,15,141,110,198,230,50,177,50,32,125,193,200,192,255,208,246,169 77dA13,76,125,193,165,57,24,101,56,133,50,165,58,105,0,133,51,165,50,101,49,133 78dA52,165,51,105,0,133,53,160,0,177,57,56,229,56,48,8,168,177,50,145,52,136,16 79dA249,164,49,136,16,1,96,185,130,0,145,50,136,16,248,160,0,177,57,24,101,49 80dA145,57,165,56,24,101,49,133,56,96,141,203,198,201,255,240,9,201,0,240,4,224 81dA255,16,1,138,96,140,254,198,200,140,247,198,202,138,41,7,168,138,74,74,74 82dA170,169,0,24,202,48,4,105,3,144,249,133,63,185,244,202,41,3,101,63,105,96 83dA133,255,185,244,202,41,240,133,255,96,166,54,232,134,54,134,64,160,59,32 84dA208,198,198,64,166,64,228,55,240,14,48,12,160,61,32,208,198,32,175,199,166 85dA64,16,227,165,59,141,74,199,165,60,141,75,199,160,0,177,57,141,70,199,198 86dA56,56,229,56,72,165,56,145,57,104,160,0,145,59,170,240,11,160,255,177,57 87dA157,255,255,136,202,208,247,162,1,134,56,166,55,228,54,240,3,232,134,55,96 88dA166,55,228,54,240,74,232,160,61,32,208,198,165,61,141,134,199,165,62,141 89dA135,199,160,0,177,61,240,20,170,177,57,134,64,24,101,64,145,57,168,189,255 90dA255,145,57,136,202,208,247,166,55,232,134,64,228,54,240,21,160,59,32,208 91dA198,230,64,166,64,160,61,32,208,198,32,175,199,166,64,208,231,198,54,96,160 92dA0,177,61,168,177,61,145,59,136,16,249,96,165,55,197,54,144,22,160,0,177,57 93dA197,56,16,14,162,0,189,252,202,32,125,193,232,224,5,208,245,96,165,55,32 94dA192,201,169,44,32,125,193,165,56,32,192,201,162,3,208,225,166,7,134,74,166 95dA6,134,75,160,0,132,65,132,66,132,76,164,76,240,6,169,13,32,125,193,96,32 96dA125,196,176,241,112,86,164,65,192,80,240,233,196,66,240,7,182,127,150,128 97dA136,16,245,32,125,193,166,6,134,72,166,7,134,73,208,8,166,6,228,75,208,2 98dA198,75,153,128,0,200,132,66,230,65,196,65,240,23,185,128,0,32,125,193,165,7 99dA208,10,169,24,197,72,208,4,198,72,198,75,200,16,229,166,72,134,6,166,73,134 100dA7,32,119,193,16,153,201,13,208,4,230,76,208,40,201,11,208,10,166,66,228,65 101dA240,135,230,66,16,30,201,12,208,8,166,66,240,46,198,66,16,18,201,15,208,6 102dA162,0,134,66,16,8,201,16,208,31,166,65,134,66,166,75,134,6,24,165,74,101 103dA66,201,80,133,7,144,6,233,80,133,7,230,6,32,119,193,76,251,199,201,17,208 104dA249,164,66,240,245,136,198,65,132,66,196,65,240,7,182,129,150,128,200,16 105dA245,32,125,193,166,6,134,72,166,7,134,73,164,66,196,65,240,9,185,128,0,32 106dA125,193,200,16,243,169,32,32,125,193,166,72,134,6,166,73,134,7,32,119,193 107dA76,251,199,141,12,201,141,23,201,32,104,202,160,0,181,128,240,43,201,43 108dA208,7,169,1,133,255,232,208,9,201,45,208,7,169,255,133,255,232,181,128,240 109dA19,201,48,48,15,201,58,16,11,153,209,0,232,200,192,3,16,2,48,233,96,134,71 110dA160,0,132,69,132,70,136,132,67,132,68,169,69,32,246,200,228,71,240,9,134 111dA71,32,24,202,133,67,166,71,181,128,201,44,208,17,232,134,71,169,70,32,246 112dA200,228,71,240,5,32,24,202,133,68,96,32,49,201,169,1,36,69,240,36,16,21 113dA165,67,197,55,48,6,169,1,133,67,208,22,165,55,56,229,67,133,67,208,13,165 114dA55,24,101,67,133,67,144,4,169,0,133,67,169,1,36,70,240,36,16,21,165,68,197 115dA56,48,6,169,1,133,68,208,22,165,56,56,229,68,133,68,208,13,165,56,24,101 116dA68,133,68,144,4,169,0,133,68,96,32,210,201,162,0,181,209,240,3,32,125,193 117dA232,224,3,208,244,96,133,212,32,104,202,162,8,160,2,185,209,0,201,5,48,5 118dA105,2,153,209,0,136,16,241,160,2,165,212,10,133,212,185,209,0,42,201,16,41 119dA15,153,209,0,136,16,242,202,208,215,165,211,9,48,133,211,160,1,185,209,0 120dA240,8,9,48,153,209,0,136,16,243,96,165,211,208,14,165,210,133,211,165,209 121dA133,210,169,0,133,209,240,238,160,2,185,209,0,240,5,41,207,153,209,0,136 122dA16,243,162,8,160,125,24,185,84,0,144,2,9,16,74,153,84,0,200,16,242,165,212 123dA106,202,208,1,96,133,212,160,2,185,209,0,201,8,48,5,233,3,153,209,0,136,16 124dA241,48,211,169,0,133,209,133,210,133,211,96,15,15,127,9,5,3,1,7,11,13,17,0 125dA69,83,90,52,65,87,51,88,84,70,67,54,68,82,53,86,85,72,66,56,71,89,55,78,79 126dA75,77,48,74,73,57,44,64,58,46,45,76,80,43,47,94,61,0,15,59,42,124,21,81,19 127dA32,50,0,0,49,10,6,4,2,8,12,14,18,0,101,115,122,36,97,119,35,120,116,102,99 128dA38,100,114,37,118,117,104,98,40,103,121,39,110,111,107,109,48,106,105,41 129dA60,64,91,62,45,108,112,43,63,94,61,0,16,93,42,124,22,113,20,32,34,0,0,33,0 130dA96,192,33,129,225,66,162,69,78,68,62,32,34,20,34,85,119,85,85,0,82,5,34,85 131dA119,85,85,0,34,20,119,68,102,68,119,0,82,5,119,68,102,68,119,0,34,20,34,85 132dA85,85,34,0,82,5,34,85,85,85,34,0,65,34,85,85,85,85,34,0,82,5,80,85,85,85 133dA34,0,0,34,20,102,17,51,119,0,0,82,5,102,17,51,119,0,0,34,20,34,119,68,34,0 134dA0,82,5,34,119,68,34,0,0,34,20,34,85,85,34,0,0,82,5,34,85,85,34,0,0,65,34 135dA85,85,85,51,0,0,82,5,80,85,85,51,0,2,2,2,2,2,0,2,0,102,102,15,6,15,6,6,0 136dA37,113,66,98,18,100,37,0,34,82,4,0,0,0,0,0,36,66,66,66,66,66,36,0,0,82,34 137dA119,34,82,0,0,0,0,0,7,0,32,32,64,1,1,2,2,2,36,36,0,33,83,117,113,81,81,33 138dA0,34,85,17,34,33,69,114,0,23,52,86,113,17,21,18,0,39,65,65,98,82,82,34,0 139dA34,85,85,35,81,81,34,0,0,34,34,0,0,34,34,4,0,16,39,64,39,16,0,0,2,69,33,18 140dA34,64,2,0,32,80,118,81,115,69,39,0,64,64,99,84,84,84,99,0,16,16,50,85,87 141dA84,50,0,16,32,115,37,37,35,33,2,66,64,98,82,82,82,82,0,36,4,37,38,38,38,37 142dA64,32,32,38,39,37,37,37,0,0,0,98,85,85,85,82,0,0,0,99,85,85,99,65,65,0,0 143dA98,84,70,65,70,0,32,32,117,37,37,37,19,0,0,0,85,85,87,119,34,0,0,0,85,37 144dA37,34,82,4,1,2,114,36,34,66,113,0,36,34,34,33,34,34,36,0,82,165,5,6,5,5,6 145dA4,34,37,21,7,5,5,5,0,99,84,84,100,84,84,99,0,103,84,84,86,84,84,103,0,118 146dA69,68,103,69,69,71,0,87,82,82,114,82,82,87,0,21,21,22,22,22,85,37,0,69,71 147dA71,69,69,69,117,0,82,85,117,117,117,85,82,0,98,85,85,101,69,71,67,0,98,85 148dA84,98,97,85,82,0,117,37,37,37,37,37,34,0,85,85,85,85,87,119,37,0,85,85,37 149dA34,34,82,82,0,115,18,34,34,34,66,115,0,6,50,66,114,226,66,54,0,48,64,67,68 150dA68,51,17,34,221,235,221,170,136,170,170,255,173,250,221,170,136,170,170 151dA255,221,235,136,187,153,187,136,255,173,250,136,187,153,187,136,255,221 152dA235,221,170,170,170,221,255,173,250,221,170,170,170,221,255,190,221,170 153dA170,170,170,221,255,173,250,175,170,170,170,221,255,255,221,235,153,238 154dA204,136,255,255,173,250,153,238,204,136,255,255,221,235,221,136,187,221 155dA255,255,173,250,221,136,187,221,255,255,221,235,221,170,170,221,255,255 156dA173,250,221,170,170,221,255,255,190,221,170,170,170,204,255,255,173,250 157dA175,170,170,204,255,253,253,253,253,253,255,253,255,153,153,240,249,240 158dA249,249,255,218,142,189,157,237,155,218,255,221,173,251,255,255,255,255 159dA255,219,189,189,189,189,189,219,255,255,173,221,136,221,173,255,255,255 160dA255,255,248,255,223,223,191,254,254,253,253,253,219,219,255,222,172,138 161dA142,174,174,222,255,221,170,238,221,222,186,141,255,232,203,169,142,238 162dA234,237,255,216,190,190,157,173,173,221,255,221,170,170,220,174,174,221 163dA255,255,221,221,255,255,221,221,251,255,239,216,191,216,239,255,255,253 164dA186,222,237,221,191,253,255,223,175,137,174,140,186,216,255,191,191,156 165dA171,171,171,156,255,239,239,205,170,168,171,205,255,239,223,140,218,218 166dA220,222,253,189,191,157,173,173,173,173,255,219,251,218,217,217,217,218 167dA191,223,223,217,216,218,218,218,255,255,255,157,170,170,170,173,255,255 168dA255,156,170,170,156,190,190,255,255,157,171,185,190,185,255,223,223,138 169dA218,218,218,236,255,255,255,170,170,168,136,221,255,255,255,170,218,218 170dA221,173,251,254,253,141,219,221,189,142,255,219,221,221,222,221,221,219 171dA255,173,90,250,249,250,250,249,251,221,218,234,248,250,250,250,255,156,171 172dA171,155,171,171,156,255,152,171,171,169,171,171,152,255,137,186,187,152 173dA186,186,184,255,168,173,173,141,173,173,168,255,234,234,233,233,233,170 174dA218,255,186,184,184,186,186,186,138,255,173,170,138,138,138,170,173,255 175dA157,170,170,154,186,184,188,255,157,170,171,157,158,170,173,255,138,218 176dA218,218,218,218,221,255,170,170,170,170,168,136,218,255,170,170,218,221 177dA221,173,173,255,140,237,221,221,221,189,140,255,249,205,189,141,29,189,201 178dA255,207,191,188,187,187,204,238,221 ``` [Readable source code](https://github.com/Zirias/c64ed/tree/c31a9e3cfb53ffbeea865a3399964fa550198f7b). ]
[Question] [ # The Task In this challenge, your task is to write a program, which takes in no input, with as many anagrams that are quine of themselves as possible. Your score will be the number of anagrams of your program's source code that are valid quines divided by the total number of anagrams possible, i.e. the percentage of the anagrams that are valid quines. [Standard Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) and [rules of standard quines](https://codegolf.meta.stackexchange.com/questions/4877/what-counts-as-a-proper-quine) apply. **Note:** Your program must have at least 3 *characters* (not 3 bytes). --- ## Input Each anagram (or permutation) of your program which is quine of itself (i.e. the anagrams which you are including in your score) must not take any input. If your language *requires* input as a necessity, then you can assume that your program will be given a String consisting of the lowercase letter A. However, you must not make any use of the input in any way. --- ## Output `n` number of distinct anagrams of your program's source-code must be valid quines, where `n` represents the number of those anagrams that you are including in your score, i.e. [![Math Equation](https://i.stack.imgur.com/QK7RT.gif)](https://i.stack.imgur.com/QK7RT.gif) Those quine-anagarams can output in any way except writing the output to a variable. Writing to file, console, screen etc. is allowed. Function `return` is allowed as well. --- ## Scoring Example Suppose your program's source code is `code`. And, 1. `code` outputs `code`. 2. `coed` outputs `coed`. 3. `cdoe` outputs `cdoe`. 4. `cdeo` outputs `cdeo`. 5. `cedo` outputs `cedo`. 6. `ceod` outputs `ceod`. 7. `ocde` outputs `ocde`. 8. `oced` outputs `oced`. 9. `odce` outputs `odce`. 10. `odec` does not output `odec` or produces error. 11. `oedc` does not output `oedc` or produces error. 12. `oecd` does not output `oecd` or produces error. 13. `doce` does not output `doce` or produces error. 14. `doec` does not output `doec` or produces error. 15. `dcoe` does not output `dcoe` or produces error. 16. `dceo` does not output `deco` or produces error. 17. `deco` does not output `deco` or produces error. 18. `deoc` does not output `deoc` or produces error. 19. `eodc` does not output `eodc` or produces error. 20. `eocd` does not output `eocd` or produces error. 21. `edoc` does not output `edoc` or produces error. 22. `edco` does not output `edco` or produces error. 23. `ecdo` does not output `ecdo` or produces error. 24. `ecod` does not output `ecod` or produces error. The score of this solution will be [![Math Equation](https://i.stack.imgur.com/GLjbW.gif)](https://i.stack.imgur.com/GLjbW.gif) --- ## Winning Criterion The solution with the highest score wins! In case of a tie, the answer with higher char-count (not byte-count) wins (hence the [code-bowling](/questions/tagged/code-bowling "show questions tagged 'code-bowling'"))! If a tie still persists, then the solution which was posted earlier wins! [Answer] # Unary, 100% This is essentially the same as the [Lenguage answer](https://codegolf.stackexchange.com/a/122068/38183) because of how the two are related. I think it's worth noting, though. I scored it as 100% because every permutation of the code will result in a quine of itself and I see that as X/X \* 100 = 100%. 5.71728886e+3431 zeroes. The full number can be found in this snippet: ``` 571,728,886,299,524,079,667,110,831,585,172,705,903,242,988,869,730,233,666,941,239,930,957,383,634,990,884,017,758,011,673,661,456,375,420,014,789,453,910,279,412,516,365,039,911,616,569,776,194,653,994,845,706,814,330,810,597,741,840,830,026,333,447,578,878,492,702,908,613,882,908,168,867,637,282,596,648,914,407,902,821,648,635,054,942,485,156,519,086,239,517,305,702,705,783,520,430,327,882,724,649,323,623,993,252,952,774,346,675,694,385,891,810,563,667,798,834,846,369,950,692,136,274,353,903,969,878,343,229,031,870,459,050,270,140,433,402,333,183,995,076,273,934,316,316,041,923,055,208,568,854,697,194,015,046,079,301,420,468,901,769,118,098,230,767,460,924,846,552,476,679,293,134,684,448,847,449,288,151,944,932,525,087,248,192,275,095,934,337,598,653,981,534,386,220,451,824,875,829,915,842,538,357,082,913,137,430,485,883,178,947,004,702,124,084,633,123,544,060,730,650,995,512,745,030,590,989,195,409,454,379,726,020,068,090,543,485,377,485,846,396,271,958,108,709,617,635,354,477,293,970,464,272,097,575,501,779,386,668,756,938,340,200,794,894,015,824,708,091,428,944,573,831,257,244,094,409,870,775,301,993,104,432,870,895,478,408,037,450,837,230,273,086,589,639,225,269,690,034,191,664,788,952,560,282,035,550,980,217,998,364,096,267,637,012,870,557,015,775,372,943,770,232,826,937,792,678,659,741,977,391,285,036,126,978,266,614,181,473,074,907,458,591,514,305,961,253,806,814,023,933,864,985,407,267,169,604,856,107,931,116,888,268,748,039,451,683,353,551,414,447,462,928,850,923,445,503,652,021,793,168,648,510,513,597,305,336,955,173,718,471,931,736,313,986,020,652,567,023,366,257,316,037,210,037,318,158,858,503,724,736,280,981,391,398,280,363,850,853,361,932,459,586,164,155,418,666,917,331,478,035,204,211,067,642,357,524,068,995,687,396,230,593,421,768,310,516,964,395,591,974,018,305,173,396,770,508,740,001,527,520,092,344,197,005,623,355,537,596,657,473,766,544,801,370,212,627,256,410,732,664,011,822,421,191,103,127,619,073,582,845,123,484,719,578,718,376,300,070,162,355,969,718,786,766,544,705,666,866,547,241,576,008,751,585,319,953,584,072,266,931,915,765,118,041,170,749,844,694,686,800,072,822,536,450,477,293,767,227,280,278,303,598,479,313,816,303,539,184,630,996,668,979,230,004,925,749,414,158,627,159,671,600,379,023,203,894,575,932,729,998,748,035,419,783,450,180,418,397,923,824,642,227,478,374,530,825,875,117,414,862,969,170,359,605,774,864,660,165,183,532,258,493,867,754,625,154,388,052,741,695,648,070,594,472,531,159,793,952,847,078,816,841,601,345,611,759,202,959,380,748,999,978,577,549,942,317,774,738,570,775,404,426,481,919,733,186,968,468,431,270,431,605,972,498,637,946,956,126,022,229,614,797,087,117,225,823,565,342,748,501,153,741,450,722,494,697,466,495,557,622,414,355,168,111,360,033,562,039,346,636,733,121,121,610,857,454,876,606,487,443,794,811,222,591,756,267,144,914,006,412,918,432,311,781,300,777,103,610,374,114,091,997,695,742,108,877,002,082,862,282,098,075,681,749,979,978,446,425,489,037,395,541,763,956,873,201,738,020,809,689,085,082,333,652,677,837,122,632,903,083,224,964,125,736,624,491,672,540,404,024,051,399,430,701,347,505,739,704,581,760,444,853,708,889,328,730,053,965,944,499,104,791,856,210,999,740,898,398,825,918,657,619,888,095,865,548,102,735,913,913,094,386,735,714,696,418,726,741,576,678,447,905,375,266,819,534,780,270,705,492,733,528,843,064,273,668,310,355,948,806,085,914,998,909,078,430,123,434,842,644,353,766,593,108,209,757,731,578,915,664,389,676,321,477,765,937,156,616,387,196,395,610,946,243,206,146,663,560,610,797,140,874,906,254,178,018,061,181,083,047,209,661,789,909,286,724,851,898,477,573,800,702,633,601,175,620,396,600,949,134,122,178,276,685,812,142,120,568,127,180,096,273,903,971,758,009,993,201,718,908,993,673,764,199,386,800,398,143,178,502,530,082,660,500,014,722,964,981,864,977,851,706,298,981,882,062,478,994,083,243,364,559,882,663,594,491,418,634,537,443,259,947,411,981,605,363,306,172,530,522,346,606,185,828,881,879,282,631,498,937,150,281,652,951,729,913,616,393,089,658,674,346,663,853,707,461,126,940,124,422,764,766,614,384,500,640,200,165,833,857,590,144,741,546,981,402,879,612,572,412,230,319,659,934,882,344,598,744,566,237,876,680,653,747,327,784,600,034,796,624,136,727,679,072,247,471,775,907,417,517,609,655,422,229,860,544,695,004,718,249,668,190,489,544,232,936,202,367,307,609,329,582,839,156,431,588,444,789,676,252,562,273,585,535,627,566,417,124,298,941,319,814,273,113,830,010,077,536,882,402,273,792,934,052,604,658,425,046,299,684,558,311,449,368,519,016,440,435,219,777,519,127,752,414,574,327,366,464,226,160,312,027,143 ``` The Brainf\*ck equivalent is in this snippet: ``` >+++++>++>++++++>+>+++++>+++++>+>++++++>+>+++++>+>++++++>+>+++++>+>++++++>+++>+++++>+++++>+>+++>++>+ +++>++++++>++>++++++>+++>+++++>++>++++++>++>+++++>++>++++++>+>+++++>+++++>+>++++++>+>+++++>+>++++++> +>+++++>+>++++++>++>+++>+++++>+++++>+>+++>++>++++>++++++>++>++++++>+++>+++>+++>+++++>++>++++++>++>++ +++>++>++++++>+>++++>++++++>+>++++++>+>+++++>+>++++++>+>+++++>++++>+++++>++>+++>+>++++>++++++>+>++++ ++>++>++>+++++>++>++++++>+>+++++>+++++>+++++>+>++++++>+>+++>++>++>+++++>++>++++++>+>++++>++++++>+>++ +++>+>++++++>+++>+>++++>+++++>++++>+++++>++++>+++++>++++>+++++>++++>+++++>++++>+++++>++++>++>++++>+> +>+>+++++>+>+>+>++++++>+++>+++>+>+>+>+++>+>+>+>+++>+++++>++>++>++>++++++>+>++++++>++>+++++>++++>+>+> +>+++++>+>+>+>++++++>+++>+++>+>+>+>+++>+++>+>+>+>+++>+++>+++++>++>++>++>++++++>++++++>+>++++++>++>++ +++>++++>+>+>+>+++++>+>+>+>++++++>+++>+++>+>+>+>+++>+++>+>+>+>+++>+++++>++>++>++>++++++>++++++>+>+++ +++>++>+++++>++++>+>+>+>+++++>+>+>+>++++++>+++>+>+>+>+++>+++>+>+>+>+++>+++>+++++>++>++>++>++++++>+++ +++>+>++++++>++>+++++>++++>+>+>+>+++++>+>+>+>++++++>+++>+>+>+>+++>+++>+>+>+>+++>+++++>++>++>++>+++++ +>++++++>+>++++++>++>+++++>++++>+>+>+>+++++>+>+>+>++++++>+++>+>+>+>+++>+>+>+>+++>+++>+++++>++>++>++> ++++++>++++++>+>++++++>++>+++++>++++>+>+>+>+++++>+>+>+>++++++>+++>+>+>+>+++>+>+>+>+++>+++++>++>++>++ >++++++>++++++>++>+++++>++>++++++>+>++++++>+++>+++>++>+++>+++++>++>+++>+>+>+++++>+++++>+>+++>+>+++>+ +>++>++++>++++++>+>+++++>++>+++>+>++++>++++++>+>++++>+++++>++++>+++++>++++>+>+++++>+>+++>+>+++>++>++ >++++>++++++>+>+++++>++>+++>+>++++>++++++>+>+++++>++>+++>+>++++>+++++>++>++++>+>+++++>++++>++++++>++ ++++>++++++>++>+++++>++++>++>++++>+>+>+>+++++>+>+>+>++++++>++>++>++>+++++>+++++>+>+>+>+++>++>++>++>+ +++>++++++>++>++>++>++++++>+>+>+>+++>+++>+++>++>++>++>+++>+++>+++>++>++>++>++++>++++>++++>++>++>++>+ ++++>++>++>++>++++++>+>++++>+>+>+++++>+>+>+>++++++>+++>+++++>+>+>+>++++++>+>++++++>++>++>++++++>++++ ++>+>++++++>++>++>++>+++++>++>++>++>++++++>+>+++++>++>++>+++>+>+++>+>++++>++++++>++>++>+++++>+>+>+++ >++>++>++++>++++++>+>+++++>++++>+>+>+>+++++>+++++>+>+++>+>+++>++>++>++++>++++++>+>+++++>++>+++>+>+++ +>++++++>+>++++>+++++>++>+++>+>++++>+++++>++>++++>+>++++>++++++>++>+++++>++++>++>++++>++++>+>+>+>+++ ++>+>+>+>++++++>++>++>++>+++++>+++++>+>+>+>+++>++>++>++>++++>++++++>++>++>++>++++++>+>+>+>+++>+++>++ +>++>++>++>++>++>++>+++++>++>++>++>++++++>+>++++>+>+>+++++>+>+>+>++++++>+++>+++++>+>+>+>++++++>++>++ >++++++>+>++++++>+>++++++>++>++>++>+++++>++>++>++>++++++>++++++>+>+++++>++>++>+++>+>+++>+>++++>+++++ +>++>++>+++++>+>+>+++>++>++>++++>++++++>+>+++++>++++>+>+>+>+++++>+++++>+>+++>+>+++>++>++>++++>++++++ >+>+++++>++>+++>+>++++>++++++>+++>+>++++>+++++>++>++++>+>+++++>++++>++++++>++++++>++>+++++>++++>++>+ +++>++>++>++>+++++>++>++>++>++++++>+>++++>+>+>+++++>+>+>+>++++++>+>+>+>+++++>+++++>++>++>++>+++>+>+> +>++++>++++++>+>+>+>++++++>++>++>++>++>++>++++++>+>+>++++++>++>++>++>+++++>++>++>++>++++++>++++++>+> +++++>+>++++>++>++++>++++++>+>++++++>+>+++++>+++>+++>+++>+++++>+>+++>+++>+++>+++>+++>+++>+++>+++>++> ++++>++++++>+>+++++++>+>+>++++++[<]>[[>]>[>]>[>]+[[>+<-]<]+[<]<[<]>[[>]>[>]>[>]<+[[>+<-]<]+++[<]<[<] >-]>]>[>]>[-[<+>-]>]<<[<]>[[[>]>+<<[<]>-]>[>]+>-[-[-[-[-[-[-<->>>[>>>]++>>>+>>>+[<<<]>]<[->>>[>>>]++ >>>++>>>++[<<<]]>]<[->>>[>>>]++>>>++>>>+[<<<]]>]<[->>>[>>>]+>>>++>>>++[<<<]]>]<[->>>[>>>]+>>>++>>>+[ <<<]]>]<[->>>[>>>]+>>>+>>>++[<<<]]>]<[->>>[>>>]+>>>+>>>+[<<<]]<[<]>]++ % <+[<+>>[[>+>+<<-]>[<+>-]>-[-[->[>+>+<<-]>[<+>-]>[<+>-[<->[-]]]<[-<->>>[>>>]<<<[[>>>+<<<-]<<<]>>>+++< <<+++<<<---<<<[<<<]>->>[>>>]+[>>>]>]<<]]>]<<<[<<<]>[<<+>+>-]<<[>>+<<-]>[->>>[[>+>+<<-]>[<+>-]>-[<+>- [<->-]<[-<-->>>[>>>]<<<[[>>>+<<<-]<<<]>>>+++<<<<<<[<<<]>->>[>>>]+[>>>]<<]>]>]<<<[<<<]]>[<<+>+>-]<<[> >+<<-]>[->>>[[>+>+<<-]>[<+>-]+>-[<->[-]]<[-<-<<<[<<<]>->>[>>>]>>>[[<<<+>>>-]>>>]<<<<<]>>]<<<[<<<]]>[ >-<-]>]>[+++[>++++++++<-]>.>>] ``` [Source of source](http://esolangs.org/wiki/Talk:Unary#A_quine_in_Unary) [Answer] # Lenguage, 100% 5.71728886e+3431 null bytes. The full number can be found in this snippet: ``` 571728886299524079667110831585172705903242988869730233666941239930957383634990884017758011673661456375420014789453910279412516365039911616569776194653994845706814330810597741840830026333447578878492702908613882908168867637282596648914407902821648635054942485156519086239517305702705783520430327882724649323623993252952774346675694385891810563667798834846369950692136274353903969878343229031870459050270140433402333183995076273934316316041923055208568854697194015046079301420468901769118098230767460924846552476679293134684448847449288151944932525087248192275095934337598653981534386220451824875829915842538357082913137430485883178947004702124084633123544060730650995512745030590989195409454379726020068090543485377485846396271958108709617635354477293970464272097575501779386668756938340200794894015824708091428944573831257244094409870775301993104432870895478408037450837230273086589639225269690034191664788952560282035550980217998364096267637012870557015775372943770232826937792678659741977391285036126978266614181473074907458591514305961253806814023933864985407267169604856107931116888268748039451683353551414447462928850923445503652021793168648510513597305336955173718471931736313986020652567023366257316037210037318158858503724736280981391398280363850853361932459586164155418666917331478035204211067642357524068995687396230593421768310516964395591974018305173396770508740001527520092344197005623355537596657473766544801370212627256410732664011822421191103127619073582845123484719578718376300070162355969718786766544705666866547241576008751585319953584072266931915765118041170749844694686800072822536450477293767227280278303598479313816303539184630996668979230004925749414158627159671600379023203894575932729998748035419783450180418397923824642227478374530825875117414862969170359605774864660165183532258493867754625154388052741695648070594472531159793952847078816841601345611759202959380748999978577549942317774738570775404426481919733186968468431270431605972498637946956126022229614797087117225823565342748501153741450722494697466495557622414355168111360033562039346636733121121610857454876606487443794811222591756267144914006412918432311781300777103610374114091997695742108877002082862282098075681749979978446425489037395541763956873201738020809689085082333652677837122632903083224964125736624491672540404024051399430701347505739704581760444853708889328730053965944499104791856210999740898398825918657619888095865548102735913913094386735714696418726741576678447905375266819534780270705492733528843064273668310355948806085914998909078430123434842644353766593108209757731578915664389676321477765937156616387196395610946243206146663560610797140874906254178018061181083047209661789909286724851898477573800702633601175620396600949134122178276685812142120568127180096273903971758009993201718908993673764199386800398143178502530082660500014722964981864977851706298981882062478994083243364559882663594491418634537443259947411981605363306172530522346606185828881879282631498937150281652951729913616393089658674346663853707461126940124422764766614384500640200165833857590144741546981402879612572412230319659934882344598744566237876680653747327784600034796624136727679072247471775907417517609655422229860544695004718249668190489544232936202367307609329582839156431588444789676252562273585535627566417124298941319814273113830010077536882402273792934052604658425046299684558311449368519016440435219777519127752414574327366464226160312027143 ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 33.333...% ``` ”ṘṘ ``` [Try it online!](https://tio.run/nexus/jelly#@/@oYe7DnTOA6P9/AA "Jelly – TIO Nexus") Community wiki because I did not write this. If you like this solution, or want an explanation, see [Dennis's original post here](https://codegolf.stackexchange.com/a/73930/31716). [Answer] # Microscript II, score 1/1814399=5.5e-7 ``` "qp1h"qp1h ``` `"qph1"qph1` is also a quine. # Microscript II, score 5/119750399=4.2e-8 ``` "qp12h"qp12h ``` `"qp21h"qp21h`, `"qph12"qph12`, `"qph21"qph21`, `"qp1h2"qp1h2` and `"qp2h1"qp2h1` are also quines. I'm sure someone can come up with a much higher score than either of these, but this is still the only answer with at least one quine that isn't the original program (which, IMO, shouldn't be counted). [Answer] # [V](https://github.com/DJMcMayhem/V), 16.666...% ``` 2i2i ``` [Try it online!](https://tio.run/nexus/v#@2@UaZT5/z8A "V – TIO Nexus") There are 6 possible anagrams of this code: ``` 2i2i 22ii i22i i2i2 ii22 2ii2 ``` And one of them is a quine. ]
[Question] [ # Challenge Given a user's **name** (not ID, we have that challenge already), output their current reputation and their ID. ### Input Input will be a single string which is the user's username. You may assume that this user exists. ### Output Output will be two integers to either STDOUT or STDERR which will be the user's reputation and the user's ID. They must be in that specific order and can be output in any reasonable format ### Specifics * The reputation output must not be more than 10 minutes out of date. * Your program may not throw any errors during normal execution * Standard loopholes apply (including No URL Shorteners) * If there is more than one user with that username, you may output the stats of any user with that username. This is also why you must output the ID. * The reputation to be output is the reputation of the user on PPCG, not the network total score. The Stack Exchange API site can be found [here](http://api.stackexchange.com/). You can read the documentation from there. [Answer] # JavaScript (ES6), 145 139 136 125 123 117 bytes ``` a=>fetch(`//api.stackexchange.com/users?site=codegolf&filter=!)LgZAmQ6ls0hH&inname=`+a).then(_=>_.text()).then(alert) ``` Saved 6 bytes thanks to Shaggy and 6 bytes thanks to Cyoce. I'm not sure if it should output all users with the same name, or just one of them; this code outputs all of them. ``` f=a=>fetch(`//api.stackexchange.com/users?site=codegolf&filter=!)LgZAmQ6ls0hH&inname=`+a).then(_=>_.text()).then(alert) f("tom") ``` [Answer] # Groovy, ~~144~~ 156 bytes ``` {new groovy.json.JsonSlurper().parse(new URL("http://api.stackexchange.com/2.2/users/?site=codegolf&inname=$it")).items.collect{[it.user_id,it.reputation]}} ``` Anonymous closure. EDIT: forgot to use import of `groovy.json.` for JSON Slurper + 14 bytes. **Example output `[[UserID, Reputation],...]`:** ``` [[20260, 60695], [20469, 21465], [3103, 8856], [41805, 7783], [134, 6829], [42643, 5622], [45268, 4389], [10732, 3976], [32, 3635], [53745, 3392], [10801, 3216], [49362, 2418], [2104, 2160], [3563, 1988], [18280, 1491], [742, 1466], [59487, 1362], [19039, 1330], [56642, 1133], [9522, 951], [34438, 886], [1744, 793], [52661, 778], [18187, 768], [11426, 751], [26850, 711], [178, 637], [29451, 631], [19700, 616], [15862, 601]] ``` [Answer] # Python 2, ~~178~~ ~~169~~ 149 Bytes I'd use requests for this: ``` from requests import* a=get("http://api.stackexchange.com/users?site=codegolf&inname="+input()).json()["items"][0] print a["reputation"],a["user_id"] ``` Basically, it uses stack's api to fetch the information as JSON and then gets the item "reputation". Additionally, the [API](http://api.stackexchange.com/docs/users-by-ids#order=desc&sort=reputation&ids=7668911&filter=default&site=stackoverflow&run=true) featured many extra parameters, I shaved those off as well. Generous contributions from: carusocomputing, ElPedro, Malivil, Keerthana Prabhakaran [Answer] # Bash + [JQ](https://stedolan.github.io/jq/), 93 bytes Rolled back the 87 byte version, as it was not handling multi-user responses correctly. **Golfed** ``` curl "api.stackexchange.com/users?site=codegolf&inname=$1"|zcat|jq ..\|numbers|sed -n 4p\;12p ``` Will output first user id and reputation on the separate lines. **How It Works ?** 1)`curl + zcat` are used to fetch the JSON formatted API reply 2) `jq ..|numbers` will unfold JSON recursively, and print all the numeric values, one per line ``` ... 1 35 2 8 3 2 4 3315904 5 1487694154 6 1492702469 7 4565 8 82 9 82 10 60 11 20 12 6275 ... ``` (line numbers were added with `nl` for illustration purposes only) 3) Next we use `sed` to lookup the first `account_id` and `reputation`, by their absolute row numbers **Test** ``` >./reputation zeppelin 3315904 6275 ``` [Answer] # Swift, ~~225~~ 201 bytes ``` import Foundation;var f:(String)->Any={return try!JSONSerialization.jsonObject(with:Data(contentsOf:URL(string:"http://api.stackexchange.com/users?site=codegolf&filter=!)LgZAmQ6ls0hH&inname=\($0)")!))} ``` Un-golfed: ``` import Foundation var f:(String) -> [String: Any] = { return try! JSONSerialization.jsonObject(with:Data(contentsOf:URL(string:"http://api.stackexchange.com/users?site=codegolf&filter=!)LgZAmQ6ls0hH&inname=\($0)")!)) as! [String:Any] } ``` Example output: ``` ["items": <__NSArrayI 0x6180001ffc00>( { reputation = 2820; "user_id" = 42295; }, { reputation = 2468; "user_id" = 31203; }, { reputation = 2106; "user_id" = 2800; }, { reputation = 1479; "user_id" = 6689; }, { reputation = 1287; "user_id" = 64424; }, { reputation = 1037; "user_id" = 64070; }, { reputation = 644; "user_id" = 25193; }, { reputation = 641; "user_id" = 3171; }, { reputation = 639; "user_id" = 743; }, { reputation = 590; "user_id" = 33233; }, { reputation = 571; "user_id" = 26993; }, { reputation = 563; "user_id" = 1730; }, { reputation = 321; "user_id" = 18570; }, { reputation = 309; "user_id" = 39156; }, { reputation = 291; "user_id" = 7880; }, { reputation = 281; "user_id" = 25190; }, { reputation = 261; "user_id" = 40820; }, { reputation = 231; "user_id" = 14154; }, { reputation = 206; "user_id" = 2774; }, { reputation = 196; "user_id" = 48231; }, { reputation = 181; "user_id" = 1230; }, { reputation = 176; "user_id" = 64077; }, { reputation = 171; "user_id" = 31365; }, { reputation = 171; "user_id" = 43455; }, { reputation = 163; "user_id" = 21469; }, { reputation = 161; "user_id" = 11845; }, { reputation = 157; "user_id" = 25181; }, { reputation = 131; "user_id" = 263; }, { reputation = 131; "user_id" = 3922; }, { reputation = 128; "user_id" = 67227; } ) ] ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 58 bytes ``` ’¸¸.‚‹º.ŒŒ/†š?€¼=ƒËŠˆ&€†‚ˆ=ÿ’.wD„n"¡1è¦',¡н,'‡¾¡2覦',¡н, ``` Beats all other answers. ``` ’...’.wD„n"¡1è¦',¡н,'‡¾¡2覦',¡н, # trimmed program , # output... н # first element of... è # element at 0-based index... 1 # literal... è # in... .wD # content of response to request to URL... # (implicit) "http://" concatenated with... ’...’ # "api.stackexchange.com/users?site=codegolf&inname=ÿ"... # (implicit) with ÿ replaced by... # implicit input... ¡ # split by... „n" # literal ¦ # excluding the first character... ¡ # split by... ', # literal , # output... н # first element of... è # element at 0-based index... 2 # literal... è # in... .w # content of response to request to URL... # (implicit) "http://" concatenated with... ’...’ # "api.stackexchange.com/users?site=codegolf&inname=ÿ"... # (implicit) with ÿ replaced by... # implicit input... ¡ # split by... '‡¾ # "id"... ¦ # excluding the first character... ¦ # excluding the first character... ¡ # split by... ', # literal ``` ]
[Question] [ A [constructible \$n\$-gon](https://en.wikipedia.org/wiki/Constructible_polygon) is a regular polygon with n sides that you can construct with only a compass and an unmarked ruler. As stated by Gauss, the only \$n\$ for which a \$n\$-gon is constructible is a product of any number of distinct Fermat primes and a power of \$2\$ (ie. \$n = 2^k \times p\_1 \times p\_2 \times ...\$ with \$k\$ being an integer and every \$p\_i\$ some distinct Fermat prime). A Fermat prime is a prime which can be expressed as \$2^{2^n}+1\$ with \$n\$ a positive integer. The only known Fermat primes are for \$n = 0, 1, 2, 3 \text{ and } 4\$ # The challenge Given an integer \$n>2\$, say if the \$n\$-gon is constructible or not. # Specification Your program or function should take an integer or a string representing said integer (either in unary, binary, decimal or any other base) and return or print a truthy or falsy value. This is code-golf, so shortest answer wins, [standard loopholes](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply. [Relevant OEIS](https://oeis.org/A003401) # Examples ``` 3 -> True 9 -> False 17 -> True 1024 -> True 65537 -> True 67109888 -> True 67109889 -> False ``` [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), ~~7~~ 5 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) *Thanks to Sp3000 for saving 2 bytes.* ``` ÆṪBSỊ ``` Uses the following classification: > > These are also the numbers for which phi(n) is a power of 2. > > > Where *phi* is [Euler's totient function](https://en.wikipedia.org/wiki/Euler's_totient_function). ``` ÆṪ # Compute φ(n). B # Convert to binary. S # Sum bits. Ị # Check whether it's less than or equal to 1. This can only be the # case if the binary representation was of the form [1 0 0 ... 0], i.e. e# a power of 2. ``` [Try it online!](http://jelly.tryitonline.net/#code=w4bhuapCU-G7ig&input=&args=NjcxMDk4ODg) Alternatively (credits to xnor): ``` ÆṪ’BP ÆṪ # Compute φ(n). ’ # Decrement. B # Convert to binary. P # Product. This is 1 iff all bits in the binary representation are # 1, which means that φ(n) is a power of 2. ``` A direct port of [my Mathematica answer](https://codegolf.stackexchange.com/a/92273/8478) is two bytes longer: ``` ÆṪ # Compute φ(n). µ # Start a new monadic chain, to apply to φ(n). ÆṪ # Compute φ(φ(n)). H # Compute φ(n)/2. = # Check for equality. ``` [Answer] ## Mathematica, 24 bytes ``` e=EulerPhi e@e@#==e@#/2& ``` Uses the following classification from OEIS: > > Computable as numbers such that cototient-of-totient equals the totient-of-totient. > > > The [totient](https://en.wikipedia.org/wiki/Euler%27s_totient_function) `φ(x)` of an integer `x` is the number of positive integers below `x` that are coprime to `x`. The cototient is the number of positive integers that aren't, i.e. `x-φ(x)`. If the totient is equal to the cototient, that means that the totient of `φ(x) == x/2`. The more straightforward classification > > These are also the numbers for which phi(n) is a power of 2. > > > ends up being a byte longer: ``` IntegerQ@Log2@EulerPhi@#& ``` [Answer] ## Retina, ~~51~~ 50 bytes ``` 0+$ +`^(.*)(?=(.{16}|.{8}|....|..?)$)0*\1$ $1 ^1$ ``` Input is in binary. The first two lines divide by a power of two, the next two divide by all known Fermat primes (if in fact the number is a product of Fermat primes). Edit: Saved 1 byte thanks to @Martin Ender♦. [Answer] ## JavaScript (ES7), 61 bytes ``` n=>[...Array(5)].map((_,i)=>n%(i=2**2**i+1)?0:n/=i)&&!(n&n-1) ``` [Answer] # Actually, 6 bytes This answer is based on [xnor's algorithm in Martin Ender's Jelly answer](https://codegolf.stackexchange.com/a/92275/47581). Golfing suggestions welcome. [Try it online!](http://actually.tryitonline.net/#code=4paSROKUnOKZguKJiM-A&input=MTc) ``` ▒D├♂≈π ``` **How it works** ``` Implicit input n. ▒ totient(n) D Decrement. ├ Convert to binary (as string). ♂≈ Convert each char into an int. π Take the product of those binary digits. If the result is 1, then bin(totient(n) - 1) is a string of 1s, and totient(n) is power of two. ``` [Answer] ## Batch, 97 bytes ``` @set/pn= @for /l %%a in (4,-1,0)do @set/a"p=1<<(1<<%%a),n/=p*!(n%%-~p)+1" @cmd/cset/a"!(n-1&n)" ``` Input is on stdin in decimal. This is actually 1 byte shorter than calculating the powers of powers of 2 iteratively. I saved 1 byte by using @xnor's power of 2 check. ]
[Question] [ # Definition The chain rule with two functions state that: ``` D[f(g(x))] = f'(g(x)) * g'(x) ``` Or, alternatively: ``` D[f1(f2(x))] = f1'(f2(x)) * f2'(x) ``` The chain rule with three functions state that: ``` D[f(g(h(x)))] = f'(g(h(x))) * g'(h(x)) * h'(x) ``` Or, alternatively: ``` D[f1(f2(f3(x)))] = f1'(f2(f3(x))) * f2'(f3(x)) * f3'(x) ``` Et cetera. # Task * Given an integer between 2 and 21, output the chain rule with that many functions, either in the first form or in the second form. * Please specify if you are using the second form. # Specs * The format of the string must be exactly that stated above, with: 1. all the spaces kept intact 2. a capitalized `D` 3. a square bracket immediately following `D` 4. the asterisk kept intact * One extra trailing space (U+0020) is allowed. * Leading zeros in the function names in the second form (e.g. `f01` instead of `f1`) is allowed. # Testcases If you use the first form: ``` input output 2 D[f(g(x))] = f'(g(x)) * g'(x) 3 D[f(g(h(x)))] = f'(g(h(x))) * g'(h(x)) * h'(x) ``` If you use the second form: ``` input output 2 D[f1(f2(x))] = f1'(f2(x)) * f2'(x) 3 D[f1(f2(f3(x)))] = f1'(f2(f3(x))) * f2'(f3(x)) * f3'(x) ``` ### Leaderboard ``` var QUESTION_ID=86652,OVERRIDE_USER=48934;function answersUrl(e){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"http://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i; ``` ``` body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px} ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> ``` [Answer] ## Python 2, 79 bytes ``` f=lambda n:0**n*"D[x] ="or f(n-1).replace("x","f%d(x)"%n)+1%n*" *"+" f%d'(x)"%n ``` Outputs with numbered functions. Builds the output by repeatedly replacing each `x` with `fn(x)`, then appending `* fn'(x)`. The `*` is omitted for `n==1`. Compare to the iterate program (92 bytes): ``` r="D[x] = ";n=0 exec'n+=1;r=r.replace("x","f%d(x)"%n)+"f%d\'(x) * "%n;'*input() print r[:-3] ``` --- **96 bytes:** ``` n=input();r='';s='x' while n:s='f%d(%%s)'%n%s;r=" * f%d'"%n+s[2:]+r;n-=1 print"D[%s] = "%s+r[3:] ``` Outputs with numbered functions. Accumulates the nested function `f1(f2(f3(x)))` in `s` and the right-hand-side expression in `r`. The string formatting is clunky; f-strings from 3.6 would do better. [Answer] # [Sesos](https://github.com/DennisMitchell/sesos), 49 bytes ``` 0000000: 2ac992 63fb92 245fb6 6c57be 255bbe 2cc9bf 6d49da *..c..$_.lW.%[.,..mI. 0000015: 025e7f fdced0 fd67f8 fcde33 b6a7b2 643d4f 65597e .^.....g...3...d=OeY~ 000002a: f77a72 dd73cf fe .zr.s.. ``` [Try it online](http://sesos.tryitonline.net/#code=c2V0IG51bWluCmFkZCA2OCAgIDsgJ0QnCnB1dApzdWIgNyAgICA7ICc9JyAtICdEJwpmd2QgMQphZGQgMzIgICA7ICcgJwpmd2QgMQphZGQgOTEgICA7ICdbJwpwdXQKYWRkIDIgICAgOyAnXScgLSAnWycKZndkIDEKYWRkIDEwMiAgOyAnZicKZndkIDEKYWRkIDQwICAgOyAnKCcKZndkIDMKYWRkIDEyMCAgOyAneCcKcndkIDIKZ2V0CmptcAogICAgam1wCiAgICAgICAgZndkIDEKICAgICAgICBhZGQgMQogICAgICAgIHJ3ZCAzCiAgICAgICAgcHV0CiAgICAgICAgYWRkIDEKICAgICAgICBmd2QgMQogICAgICAgIHB1dAogICAgICAgIGZ3ZCAxCiAgICAgICAgc3ViIDEKICAgIGpuegogICAgc3ViIDEKICAgIHJ3ZCAxCiAgICBhZGQgMSAgICA7ICcpJyAtICcoJwogICAgZndkIDMKICAgIHB1dAogICAgcndkIDEKICAgIGptcAogICAgICAgIHJ3ZCAzCiAgICAgICAgc3ViIDEKICAgICAgICBmd2QgMQogICAgICAgIHB1dAogICAgICAgIGZ3ZCAxCiAgICAgICAgYWRkIDEKICAgICAgICBmd2QgMQogICAgICAgIHN1YiAxCiAgICBqbnoKICAgIHJ3ZCA0CiAgICBwdXQKICAgIGdldAogICAgYWRkIDQxICAgOyAnKScKICAgIHJ3ZCAxCiAgICBwdXQKICAgIHJ3ZCAxCiAgICBwdXQKICAgIGdldAogICAgYWRkIDQyICAgOyAnKicKICAgIGZ3ZCAxCiAgICBwdXQKICAgIGZ3ZCAyCiAgICBwdXQKICAgIGFkZCAxCiAgICBmd2QgMQogICAgc3ViIDIgICAgOyAnXCcnIC0gJyknCiAgICBwdXQKICAgIGFkZCAxICAgIDsgJygnIC0gJ1wnJwogICAgcHV0CiAgICBmd2QgMQpqbnoKZndkIDIKcHV0CnJ3ZCA1CnB1dA&input=Mw&debug=on) ### Disassembled ``` set numin add 68 ; 'D' put sub 7 ; '=' - 'D' fwd 1 add 32 ; ' ' fwd 1 add 91 ; '[' put add 2 ; ']' - '[' fwd 1 add 102 ; 'f' fwd 1 add 40 ; '(' fwd 3 add 120 ; 'x' rwd 2 get jmp jmp fwd 1 add 1 rwd 3 put add 1 fwd 1 put fwd 1 sub 1 jnz sub 1 rwd 1 add 1 ; ')' - '(' fwd 3 put rwd 1 jmp rwd 3 sub 1 fwd 1 put fwd 1 add 1 fwd 1 sub 1 jnz rwd 4 put get add 41 ; ')' rwd 1 put rwd 1 put get add 42 ; '*' fwd 1 put fwd 2 put add 1 fwd 1 sub 2 ; '\'' - ')' put add 1 ; '(' - '\'' put fwd 1 jnz fwd 2 put rwd 5 put ``` [Answer] # JavaScript (ES6), 89 bytes ``` f=n=>--n?f(n).replace(/x/g,`${c=(n+15).toString(36)}(x)`)+` * ${c}'(x)`:`D[f(x)] = f'(x)` ``` Or 75 bytes using the second form: ``` f=n=>n>1?f(n-1).replace(/x/g,`f${n}(x)`)+` * f${n}'(x)`:`D[f1(x)] = f1'(x)` ``` Or 82/64 bytes if I'm allowed an extra `1 *` term: ``` f=n=>n?f(n-1).replace(/x/g,`${c=(n+14).toString(36)}(x)`)+` * ${c}'(x)`:`D[x] = 1` f=n=>n?f(n-1).replace(/x/g,`f${n}(x)`)+` * f${n}'(x)`:`D[x] = 1` ``` [Answer] # Ruby, 72 bytes Second form. Port to Ruby from @Neil answer. ``` f=->n{n>1?f[n-1].gsub(?x,"f#{n}(x)")+" * f#{n}'(x)":"D[f1(x)] = f1'(x)"} ``` [Answer] # Julia, 66 bytes ``` !x=x>1?replace(!~-x,"x","f$x(x)")*" * f$x'(x)":"D[f1(x)] = f1'(x)" ``` Port of @Neil's ES6 answer. Uses the second form. [Answer] # Python 2, 174 bytes ``` i=input()+1 a=lambda x:'('.join(['f%d'%e for e in range(x,i)])+'(x'+')'*(i-x) print'D[%s] = %s'%(a(1),' * '.join(["f%d'%s%s)"%(e+1,'('*(i-e-2>0),a(e+2))for e in range(i-1)])) ``` Lots of room left to be golfed here. Uses the second form (`f1`, `f2`, etc.). [Answer] # JavaScript (ES6), 194 bytes ``` n=>{s="D[";for(i=1;i<=n;i++)s+="f"+i+"(";s+="x";s+=")".repeat(n);s+="] = ";for(i=1;i<=n;i++){s+="f"+i+"'(";for(j=i+1;j<=n;j++)s+="f"+j+"(";s+="x";s+=")".repeat(n-i+1);if(i-n)s+=" * ";}return s;} ``` 31 bytes saved thanks to @LeakyNun. It's an anonymous lambda function. I'm sure there's some way to shorten this... ## Ungolfed ``` var chain = function(n) { var str = "D["; // derivative symbol for (var i = 1; i <= n; i++) { str += "f"+i+"("; // put in n functions, each labeled f1(, f2(, etc. } str += "x"; // add in the function input, usually "x" for (var i = 0; i < n; i++) { str += ")"; // add in n end parentheses } str += "] = "; // add in the end bracket and the equals operator for (var i = 1; i <= n; i++) { str += "f"+i+"'("; // add in all n of the outer functions with the prime operator for (var j = i+1; j <= n; j++) { str += "f"+j+"("; // add in all of the inner functions } str += "x"; // add in the input, "x" for (var j = 1; j <= n; j++) { str += ")"; // close the parentheses } if (i !== n) { str += " * "; // the multiplication of all of the outer primed functions } } return str; }; ``` ]
[Question] [ A person has to complete `N` units of work; the nature of work is the same. In order to get the hang of the work, he completes only **one unit of work in the first day**. He wishes to celebrate the completion of work, so he decides to complete **one unit of work in the last day**. He is only allowed to complete **`x`, `x+1` or `x-1` units of work in a day**, where `x` is the units of work completed on the previous day. Your task is to create a program or function that will compute the **minimum** number of days will he take to complete `N` units of work. ### Sample Input and Ouput: ``` input -> output (corresponding work_per_day table) -1 -> 0 [] 0 -> 0 [] 2 -> 2 [1,1] 3 -> 3 [1,1,1] 5 -> 4 [1,1,2,1] or [1,2,1,1] 9 -> 5 [1,2,3,2,1] 13 -> 7 [1,2,2,2,3,2,1] ``` Input may be taken through `STDIN` or as function argument, or in any appropriate way. Output may be printed or as the result of a function, or in any appropriate way. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Shortest solution wins. [Answer] # [Pyth](https://github.com/isaacg1/pyth), 8 bytes ``` tfg/*TT4 ``` How it works: ``` tfg/*TT4 Q is implicitly assigned to the input. f test for T=1,2,3,... returning the first successful case /*TT4 whether T * T / 4 g Q is greater than or equal to the input (second argument implied) t and subtract 1 from the first successful case ``` [Try it online!](http://pyth.herokuapp.com/?code=tfg%2F*TT4&input=13&test_suite=1&test_suite_input=-1%0A0%0A2%0A3%0A9%0A13&debug=0) In pseudo-code: ``` for(int T=1;;T++) if(T*T/4 >= Q) return T-1; ``` ### bonus, 22 bytes "should return 7 for -1" ``` +tfg/*TT4?>Q0Q-2Q1*4g1 ``` [Try it online!](http://pyth.herokuapp.com/?code=%2Btfg%2F%2aTT4%3F%3EQ0Q-2Q1%2a4g1&input=13&test_suite=1&test_suite_input=-1%0A0%0A2%0A3%0A9%0A13&debug=0) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes ``` ×4’½Ḟ ``` This uses a closed form of [@LeakyNun's approach](https://codegolf.stackexchange.com/a/78263). [Try it online!](https://tio.run/##ATQAy/9qZWxsef//w5c04oCZwr3huJ7/xbzDh@KCrEf//1stMSwgMCwgMiwgMywgNSwgOSwgMTNd "Jelly – Try It Online") Due to a lucky coincidence, `Ḟ` is overloaded as `floor`/`real` for real/complex numbers. This is one of the only three overloaded atoms in Jelly. ### How it works ``` ×4’½Ḟ Main link. Argument: n (integer) ×4 Compute 4n. ’ Decrement; yield 4n - 1. ½ Square root; yield sqrt(4n - 1). If n < 2, this produces an imaginary number. Ḟ If sqrt(4n - 1) is real, round it down to the nearest integer. If sqrt(4n - 1) is complex, compute its real part (0). ``` [Answer] # JavaScript (ES2016), 24 bytes Shortened version of the ES6 variant below thanks to [@Florent](https://codegolf.stackexchange.com/questions/78255/how-many-minimum-days-will-he-take-to-complete-n-units-of-work/78297?noredirect=1#comment191445_78297) and the [Exponentiation Operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Exponentiation) (currently only in Firefox nightly builds or transpilers). ``` n=>(n-1)**.5+(n+1)**.5|0 ``` # JavaScript (ES6), 30 bytes ``` n=>(s=Math.sqrt)(n-1)+s(n+1)|0 ``` Based upon [this sequence](https://oeis.org/A000267). ``` f=n=>(s=Math.sqrt)(n-1)+s(n+1)|0 units.oninput = () => output.value = f(+units.value||0); ``` ``` <label>Units: <input id="units" type="number" value="0" /></label> <label>Days: <input id="output" type="number" value="0" disabled /></label> ``` [Answer] # JavaScript, ~~32~~ 31 bytes ``` f=(q,t=1)=>q>t*t/4?f(q,t+1):t-1 ``` **Ungolfed code:** ``` function f(q, t = 1) { return q > t * t / 4 ? f(q, t + 1) : t - 1 } ``` It uses the same algorithm as Kenny Lau's anwser but it is implemented as recursive closure to save some bytes. **Usage:** ``` f(-1) // 0 f(0) // 0 f(2) // 2 f(3) // 3 f(5) // 4 f(9) // 5 f(13) // 7 ``` **REPL solution, 23 bytes** ``` for(t=1;t*t++/4<q;);t-2 ``` Prepend `q=` to run the snippet: ``` q=-1;for(t=1;t*t++/4<q;);t-2 // 0 q=9;for(t=1;t*t++/4<q;);t-2 // 5 q=13;for(t=1;t*t++/4<q;);t-2 // 7 ``` [Answer] ## Python, 28 bytes ``` lambda n:max(4*n-1,0)**.5//1 ``` Outputs a float. The `max` is there to give `0` for `n<=0` while avoiding an error for square root of negative. [Answer] # [UGL](https://github.com/schas002/Unipants-Golfing-Language), ~~30~~ 25 bytes ``` i$+$+dc^l_u^^$*%/%_c=:_do ``` [Try it online!](http://schas002.github.io/Unipants-Golfing-Language/?code=aSQrJCtkY15sX3VeXiQqJS8lX2M9Ol9kbw&input=MTM) Does not work for negative inputs. ### How it works: ``` i$+$+dc^l_u^^$*%/%_c=:_do i$+$+d #n = 4*input-1 c #i=0 ^l_ %/%_c=:_ #while > n: ^^$* # i**2 u # i = i+1 do #print(i) ``` ## Previous 30-byte solution: ``` iuc^l_u^^$*cuuuu/%_u%/%_c=:_do ``` Online interpreter [here](http://schas002.github.io/Unipants-Golfing-Language/). Does not work for negative inputs. ### How it works: ``` iuc^l_u^^$*cuuuu/%_u%/%_c=:_do iuc #push input; inc; i=0; ^l_u %/%_c=:_ #while > input: ^^$*cuuuu/%_ # i**2/4 u # i = i+1 do #print(i) ``` [Answer] # MATL, 11 bytes ``` E:t*4/G<f0) ``` Similar algorithm to @KennyLau except that rather than looping indefinitely, I loop from 1...2n to save some bytes. [**Try it Online!**](http://matl.tryitonline.net/#code=RTp0KjQvRzxmMCk&input=MTM) **Explanation** ``` % Implicitly grab the input E % Double the input : % Create an array from 1...2n t* % Square each element 4/ % Divide each element by 4 G< % Test if each element is less than G f % Get the indices of the TRUE elements in the array from the previous operation 0) % Get the last index (the first index where T*T/4 >= n) % Implicitly display the result. ``` [Answer] ## Pyke, 8 bytes ``` #X4f)ltt ``` [Try it here!](http://pyke.catbus.co.uk/?code=%23X4f%29ltt&input=5) Uses same algorithm as @KennyLau [Answer] # Python, 43 bytes ``` f=lambda n,i=1:i-1if i*i>=n*4 else f(n,i+1) ``` [Answer] # Java 8, ~~30~~ 24 bytes ``` n->(int)Math.sqrt(n*4-1) ``` [Try it online.](https://tio.run/##hY3PDoIwDIfvPEWPm8mI@OdgjL4BXDgaD3OgDqEgKyTG8OxzU84uaZq039f@KjlKURUPq2ppDKRS4zsC0Ehlf5WqhMyP3wUo5jvyvdtMkWuGJGkFGSAcwKI4eoGnku6xefbEcLERCbfed9UNl9rZ89HY6gIaF8dy6jXeTmfJf1H5y1DZxO1AcecI1cgwVkwkS/6N/mMEhNCDVYCvA3wb4LsAT@aAKZrsBw) No need to check if `n` is larger than 0, because Java's `Math.sqrt` returns `NaN` for negative inputs, which becomes `0` with the cast to `int` we already use for the positive inputs. [Answer] # [Ruby](https://www.ruby-lang.org/), 30 bytes ``` ->n{n<1?0:((4*n-1)**0.5).to_i} ``` [Try it online!](https://tio.run/##RY3hCoIwFIX/7ykuA0FtDleaIVkPEhKrTRJkiptQZM@@ponx/Thwzj3n9sPtZavCRif1Vkd2jnPfT0IVsSAMY5oG1LTX@mON1OYquOFQwCUmMWFkS3aOxJHO7GeyhUOJkB8xSlkWUMnvDxAtjLXqBjMiAPns5N1I4ebW6cucbljp8l7qoTEurX7u5DnRgL2tgOgEk/ieDjB48DshS4ms5eL/5gy441pjyAFXvG5wiaQS9gs "Ruby – Try It Online") Saving a byte here with `.to_i` instead of `.floor`. Support for non-positive amounts of work comes at a cost of 6 bytes (`n<1?0:`). ]
[Question] [ Your task is to analyse the input and output the formula for the n-th term if it is an arithmetic sequence, otherwise it should print "NAAP". --- ## Input Input (from STDIN) will consist of few numbers, between 4 to 10 numbers where each number will be in the range between -1000 and 1000 inclusive, separated by a delimiter (a space or a comma or a semi-colon [whichever is to your preference]). Here are some example inputs. ``` 12,14,16,18 //valid -3 4 5 1 -2 -4 //valid 45;35;-35 //invalid (only three numbers are present instead of the minimum of 4 numbers) 2,32;21,321 //invalid (it uses two different delimiters: `,` and `;`) ``` ## Output The program should first check whether the input is an [arithmetic](https://en.wikipedia.org/wiki/Arithmetic_progression) progression or not. Arithmetic Progressions (AP) in a nutshell: Every AP will have a common difference. This is the difference between the $n$ and ${n-1}$ th terms (basically $a(n+1) - a(n)$ where `a` is the function for the sequnce). This difference stays the same for any value of $n$ in an AP. If there is no common difference, then it is **not** an arithmetic sequence. To calculate the value of the n-th term, use this formula $a(n) = a(1) + (n-1)d$ where $a(1)$ is the first term and $d$ is the common difference. If it **is not** an arithmetic progression, then the program should print the error message "NAAP" (short for "Not An Arithmetic Progression"). If it **is** an arithmetic progression, then the program should print the simplified n-th term of the sequence to STDOUT. Example: ``` > 1,3,5,7,9 2n-1 ``` Explanation: This is an AP because there is a common difference ($3 - 1 = 2$). Then you use the formula $a(n) = a(1) + (n-1)d$ $$a\_n = a\_1 + (n-1)d$$ $$a\_n = 1 + (n-1)2$$ $$a\_n = 1 + 2n - 2$$ $$a\_n = 2n - 1$$ Therefore output is `2n-1` (notice the absence of spaces) --- Standard loopholes are disallowed by default. You are allowed to create a function if you want (with the array of numbers as your parameter). If not, then you must create a **full** program that takes input as a string or an array and outputs accordingly. ## Test cases: 1. ``` 1,3,5,7,9 2n-1 ``` 2. ``` 1 3 12312 7 9 NAAP ``` 3. ``` -6;8;22;36;50 14n-20 ``` 4. ``` 5,1,-3,-7,-11,-15 -4n+9 ``` 5. ``` -5,-7,-9,-11,-13,-15 -2n-3 ``` 6. ``` 3,3,3,3,3,3,3,3,3 0n+3 ``` 7. ``` -4,-5,-6,-7 -1n-3 ``` --- This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code in bytes wins! (sorry for bad math-jax) Any suggestions are welcome! [Answer] # Pyth, 30 bytes ``` ?tJ{-VtQQ"NAAP"+hJ%"n%+d"-hQhJ ``` [Test suite](https://pyth.herokuapp.com/?code=%3FtJ%7B-VtQQ%22NAAP%22%2BhJ%25%22n%25%2Bd%22-hQhJ&test_suite=1&test_suite_input=1%2C3%2C5%2C7%2C9%0A1%2C3%2C12312%2C7%2C9%0A-6%2C8%2C22%2C36%2C50%0A7%2C3%2C-1%2C-5&debug=0) To check whether it's a arithmetic procession, this uses a vectorized subtraction between each element and the previous, `-VtQQ`. A ternary checks if there are multiple values in the result (`?tJ{`) and prints `NAAP` if so. Then, to get the `+` or `-` right, the mod-formating `%+d` is used. [Answer] ## Haskell, 103 bytes ``` z=(tail>>=).zipWith f l@(a:b:_:_:_)|and$z(==)$z(-)l=show(b-a)++'n':['+'|b-a<=a]++show(a+a-b) f _="NAAP" ``` Usage example: ``` f [-6,8,22,36,50] -> "14n-20" f [60,70,80,90] -> "10n+50" f [2,3,4,6,7,8] -> "NAAP" ``` As always in Haskell, fancy output formatting (e.g. mixing numbers with strings) eats a lot of bytes (around 40). The program logic is quite compact: ``` f l@(a:b:_:_:_) -- pattern match an input list with at least 4 elements, -- call the whole list l, the first two elements a and b z=(tail>>=).zipWith -- the helper function z takes a function f and a list l -- and applies f element wise to the tail of l and l z(-)l -- make a list of neighbor differences z(==) -- then compare these differences for equality and -- and see if only True values occur show ... -- if so format output string f _="NAAP" -- in all other cases ( < 4 elements or False values) -- return "NAAP" ``` [Answer] ## TI-BASIC, 70 bytes ``` Input X ΔList(∟X->Y If variance(Ans Then ∟X(1)-min(Ans Text(0,0,min(∟Y),"n",sub("+-",(Ans<0)+1,1),abs(Ans Else "NAAP ``` To remedy TI-BASIC's lack of number-to-string conversion, this uses output on the graphscreen (`Text(`) if the progression is arithmetic, which automatically concatenates the arguments together. This assumes that negative numbers are entered using TI-BASIC's high-minus character (which looks a little like `⁻`), not the binary minus sign. However, output uses the binary minus sign. [Answer] # [Japt](https://github.com/ETHproductions/Japt), ~~60~~ ~~52~~ 51 bytes ``` V=N¤£X-NgY+1};W=Vg;Ve_¥W} ?W+'n+'+sU<W +(U-W :"NAAP ``` [Try it online!](http://ethproductions.github.io/japt?v=master&code=Vj1Oo1gtTmdZLTF9IKQ7Vz1WZztWZV+lV30gP1crJ24rJytzVTxXICsoVS1XIDoiTkFBUA==&input=LTY7ODsyMjszNjs1MA==) Input can be given with whichever separator you like, as that's how the interpreter is designed ;) ### Ungolfed and explanation ``` V=N¤ £ X-NgY+1};W=Vg;Ve_ ¥ W} ?W+'n+'+sU<W +(U-W :"NAAP V=Ns2 mXYZ{X-NgY+1};W=Vg;VeZ{Z==W} ?W+'n+'+sU<W +(U-W :"NAAP // Implicit: N = list of inputs, U = first input V=Ns2 // Set variable V to N, with the first 2 items sliced off, mXYZ{ // with each item X and index Y mapped to: X-NgY+1} // X minus the item at index Y+1 in N. // This results in a list of the differences (but the first item is NaN). W=Vg; // Set W to the first item in V (the multiplication part). VeZ{Z==W} // Check if every item in V is equal to W. ?W+'n+ // If true, return W + "n" + '+sU<W // "+".slice(U<W) (this is "+" if U >= W, and "" otherwise) +(U-W // + (U minus W [the addition part]). :"NAAP // Otherwise, return "NAAP". // Implicit: output last expression ``` [Answer] # Matlab, 103 bytes ``` x=str2num(input('','s'));y=diff(x);if range(y) disp('NAAP'),else fprintf('%gn%+g\n',y(1),x(1)-y(1)),end ``` [Answer] # CJam, 38 bytes ``` {:T2ew::-):U-"NAAP"UW*"n%+d"T0=U+e%+?} ``` This is an anonymous function that takes an array on the stack as input, and leaves a string on the stack as output. [Try it online](http://cjam.aditsu.net/#code=q~%5D%0A%7B%3AT2ew%3A%3A-)%3AU-%22NAAP%22UW*%22n%25%2Bd%22T0%3DU%2Be%25%2B%3F%7D%0A~&input=-6%208%2022%2036%2050) with additional I/O code for testing. Explanation: ``` :T Save a copy of input in variable T for output generation. 2ew Generate list of pairs of sequential elements. ::- Reduce all pairs with subtraction operator. ) Pop last value from list of differences. :U Save difference value in variable U for output generation. - Set difference. This will leave an empty list (falsy) if all values are the same. "NAAP" First value for ternary operator, for case where not all values are the same. UW* Start generating output for success case. Need to flip sign of difference saved in variable U, since it was 1st value minus 2nd, and we need the opposite. "n%+d" Push format string for printf operator. The + sign in the format specifies that the sign is always generated, saving us from needing different cases for the value being negative or positive. T0= Extract first value from original input saved in variable T. U+ Add the difference (with the "wrong" sign) to it. e% "printf" operator. + Concatenate two parts of result. ? Ternary operator for picking one of the two output cases. ``` [Answer] # JavaScript (ES6), 91 bytes ``` x=>(s=x.split`,`,m=s[1]-s[0],a=s[0]-m,s.some((n,i)=>n!=m*i+m+a)?"NAAP":m+"n"+(a<0?a:"+"+a)) ``` ## Explanation ``` x=>( s=x.split`,`, // s = array of input numbers m=s[1]-s[0], // m = the multiplication part of the formula a=s[0]-m, // a = the addition part of the formula s.some((n,i)=> // check if the rest of the numbers follow this sequence n!=m*i+m+a )?"NAAP": m+"n"+(a<0?a:"+"+a) // output the formula ) ``` ## Test ``` <input type="text" id="input" value="5,1,-3,-7,-11,-15" /><button onclick='result.innerHTML=( x=>(s=x.split`,`,m=s[1]-s[0],a=s[0]-m,s.some((n,i)=>n!=m*i+m+a)?"NAAP":m+"n"+(a<0?a:"+"+a)) )(input.value)'>Go</button><pre id="result"></pre> ``` [Answer] ## Perl 6, ~~123~~ ~~102~~ 101 bytes EDIT: Don't negate difference EDIT: use anonymous sub, logical operators and string interpolation. Thanks Brad Gilbert b2gills ``` sub{my@b=@_.rotor(2=>-1).map({[-] $_}).squish;$_=@_[0]+@b[0];@b.end&&"NAAP"||"@b[0]n{'+'x($_>=0)}$_"} ``` Test program (reads from stdin): ``` my $f = <the code above> $f(split(/<[;,]>/, slurp)).say ``` Explanation: ``` my @b = @_.rotor(2=>-1) # sliding window of 2: (1,2,3,4) => ((1,2),(2,3),(3,4)) .map({[-] $_}) # calculate difference (subtract all elements and negate) .squish; # remove adjacent elements that are equal @b.end # @b.end is last index, @b.end = 0 means @b has only 1 element && "NAAP" # true branch || "@b[0]n{'+'x($_>=0)}$_" # string for an+b, # {'+'x($_>=0)} inserts a plus sign using the repetition operator x ``` [Answer] # Ruby, ~~95~~ ~~78~~ 76 bytes ``` ->s{i,j=s;puts s.reduce(:+)==s.size*(s[-1]+i)/2?"%dn%+d"%[v=j-i,i-v]:"NAAP"} ``` **78 bytes** ``` ->s{puts s.reduce(:+)==s.size*(s[-1]+i=s[0])/2?"%dn%+d"%[v=s[1]-i,i-v]:"NAAP"} ``` **95 bytes** ``` ->s{puts s.reduce(:+)==s.size*(s[0]+s[-1])/2?"#{v=s[1]-s[0]}n#{"+"if (i=s[0]-v)>0}#{i}":"NAAP"} ``` **Ungolfed:** ``` -> s { i,j=s puts s.reduce(:+)==s.size*(s[-1]+i)/2?"%dn%+d"%[v=j-i,i-v]:"NAAP" } ``` **Usage:** ``` ->s{i,j=s;puts s.reduce(:+)==s.size*(s[-1]+i)/2?"%dn%+d"%[v=j-i,i-v]:"NAAP"}[[-6,8,22,36,50]] => 14n-20 ``` [Answer] **Python 3, 92 bytes** Based on my answer from [Find the Sequence](https://codegolf.stackexchange.com/questions/68745/find-the-sequence/163676?noredirect=1#comment396346_163676) `def m(t):s=str;a=t[0];b=t[1];q=b-a;return((s(q)+'n'+'+'*(0<a-q)+s(a-q)),'NAAP')[t[2]/b==b/a]` ]
[Question] [ (Continuing on the number sequences code-golf, here is an interesting sequence) Eban Numbers ([A006933](http://oeis.org/A006933)) are the sequence of numbers whose names (in English) do not contain the letter "e" (i.e., "e" is "banned") The first few numbers in the sequence are: ``` 2, 4, 6, 30, 32, 34, 36, 40, 42, 44, 46, 50, 52, 54, 56 ``` Given an integer `n`, via function argument or STDIN, return the first `n` terms of the Eban Numbers (in numbers) . Since some answers will involve some sort of string check for character `e`, assume that the maximum value of `n` can be such that the `nth` Eban number is less than 1 Quadrillion. [Answer] ## ~~Mathematica~~ CJam, ~~108~~ ~~95~~ ~~46~~ ~~35~~ 30 bytes **Edit:** Ported to CJam! The original and ungolfed Mathematica code is at the bottom and explains the algorithm quite well. ``` li,{)Kb65430s2046sm*$f=0s*ip}/ ``` And now I know CJam. :D Thanks to Dennis for some golfing improvements. After analysing them a bit to determine how many there are below one quadrillion, I came to the conclusion that all eban numbers are basically base-1000 numbers using only a set of 20 digits: ``` 0, 2, 4, 6, 30, 32, 34, 36, 40, 42, 44, 46, 50, 52, 54, 56, 60, 62, 64, 66 ``` So we enumerate them by converting the input to base 20, picking the right digit from the set and build a base 1000 number from it. This is how the code works in detail: ``` li "Read from STDIN, convert to integer n"; li, "Turn into a range array [0 ... n-1]"; li,{ }/ "For each number execute a block"; li,{) }/ "Increment"; li,{)K }/ "K is initialised to 20, push that"; li,{)Kb }/ "Convert to base 20"; li,{)Kb65430s }/ "Push a string with possible multiples of 10"; li,{)Kb65430s2046s }/ "Push a string with possible least significant digits"; li,{)Kb65430s2046sm* }/ "Take the Cartesian product of the two character arrays, generating the 20 'digits'"; li,{)Kb65430s2046sm*$ }/ "Sort the result"; li,{)Kb65430s2046sm*$f= }/ "For each digit in our base-20 number, get the base-1000 digit from the list"; li,{)Kb65430s2046sm*$f=0s }/ "Push a '0' character"; li,{)Kb65430s2046sm*$f=0s* }/ "Join all the digits, with that '0' as the delimiter"; li,{)Kb65430s2046sm*$f=0s*ip}/ "Convert to an integer and print the result"; ``` Here was the original Mathematica code, which doesn't encode the digit list and is hence fairly readable: ``` {0,2,4,6,30,32,34,36,40,42,44,46,50,52,54,56,60,62,64,66}[[IntegerDigits[#,20]+1]]~FromDigits~1000 & /@ Range @ # & ``` [Answer] # Bash+coreutils+[BSDGames](http://wiki.linuxquestions.org/wiki/BSD_games) package, 79 70 bytes ``` seq $[9**16]|while read n do number $n|grep -q e||echo $n done|sed $1q ``` Unfortunately this spawns `number $n|grep -q e` for every number, so is rather slow. ### Output: ``` $ ./eban.sh 5 2 4 6 30 32 $ ``` --- ### Previous answer - outputs words instead of digits, 43 bytes ``` seq $[9**16]|number -l|grep -v [e.]|sed $1q ``` This outputs each term written in words: ``` $ ./eban.sh 5 two four six thirty thirty-two $ ``` A bit faster, because each process is only spawned once. --- # Much faster, no dependence on cheaty `number`, 77 bytes ``` t=0{0,3,4,5,6}{0,2,4,6} eval echo $t$t$t$t$t|tr \ ' '|sed "s/^0*//;$[$1+1]q" ``` This one uses [bash brace expansion](https://www.gnu.org/software/bash/manual/html_node/Brace-Expansion.html) to generate all (according to my thinking) eban numbers up to 10^15. Looking at each group of 3 digits, the units digit must be one of {zero,two,four,six}, the tens digit must be one of {zero,thirty,forty,fifty,sixty}, and the hundreds digit must be zero. Since *x*-illion contains no e's up to quadrillion, then we can just combine the groups of three digits up to one quadrillion. The only exception is zero which must be skipped. So we simply build a brace expansion to generate all these numbers. There are thus 205-1 of them (3.2 million). Evaluating the full bash brace expansion takes less than 5 seconds on my VM. The `sed` expression just strips off leading zeros and counts to n. ### Output: ``` $ time ./eban.bash 5 2 4 6 30 32 real 0m4.065s user 0m3.724s sys 0m0.276s $ ./eban.bash 10000000 | wc -w 3199999 $ ./eban.bash 3199999 | tail -5 66066066066056 66066066066060 66066066066062 66066066066064 66066066066066 $ ``` [Answer] ## Ruby, ~~128~~ ~~121~~ 119 bytes ``` f=->n{a=[] i=0 (j=i+=2 b=p (m=j%t=1000 b=b||m%2>0||m%10==8||m>9&&m<30||m>69 j/=t)while j>0 a<<i if !b)while a.size<n a} ``` I'm basically just checking groups of three digits for numbers that contain `e`s, because none of `{thousand, million, billion, trillion, quadrillion}` contains an `e`. [Answer] ## Perl - 78 Here is a Perl one-liner to do it. ``` perl -MLingua::EN::Numbers=num2en -nE'while($n<=$_){$n++&&say$i if num2en($i)!~/e/;$i++}' <(echo 5) ``` It is 50 characters plus 1 for the `M`, 1 for the `n`, and 26 for `Lingua::EN::Numbers=num2len`. Using [Lingua::EN::Numbers](http://search.cpan.org/perldoc/Lingua::EN::Numbers) from CPAN. Here are [instructions](http://www.cpan.org/modules/INSTALL.html) for installing CPAN modules. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 66 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 8.25 bytes ``` Þ∞'∆ċ\ec¬;Ẏ ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyI9IiwiIiwiw57iiJ4n4oiGxItcXGVjwqw74bqOIiwiIiwiNyJd) Bitstring: ``` 001001110101101011111000111110011011000101110000000110101001010010 ``` ``` Þ∞'∆ċ\ec¬;Ẏ­⁡​‎‎⁡⁠⁡‏⁠‎⁡⁠⁢‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁣‏⁠‎⁡⁠⁣⁢‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁤‏⁠‎⁡⁠⁢⁡‏⁠‎⁡⁠⁢⁢‏⁠‎⁡⁠⁢⁣‏⁠‎⁡⁠⁢⁤‏⁠‎⁡⁠⁣⁡‏‏​⁡⁠⁡‌⁤​‎‎⁡⁠⁣⁣‏‏​⁡⁠⁡‌­ Þ∞ # ‎⁡infinite list of integers ' ; # ‎⁢filter by ∆ċ\ec¬ # ‎⁣cardinal of the number does not contain 'e' Ẏ # ‎⁤slice to length of input 💎 ``` Created with the help of [Luminespire](https://vyxal.github.io/Luminespire). ]
[Question] [ Text may be translated to a written version of [TUT language](http://www.tutlanguage.com/pages/amSpeech.html) by replacing each letter by the corresponding "TUT word", as given in the following table (adapted from the linked article)\*: ``` a e h hash o o u yu b bub i ay p pup v vuv c kut j jag q kwak w waks d dud k kak r rut x eks e i l lul s sus y yak f fuf m mum t tut z zuz g jug n nun * Exceptions: (1) Upper case letters have corresponding TUT words in upper case. (2) A doubled letter becomes 'skwer' ('SKWER') followed by the TUT word for that letter. - An n-fold letter is treated as a number of doubles, followed by a single if needed. - To be considered a double or n-fold letter, the letters must be in the same case. (3) 'rut' ('RUT') is replaced by 'rud' ('RUD') if immediately followed by 'dud' ('DUD'). ``` Write a program with the following i/o behavior: **Input** (from stdin): A binary (0/1) indicator *i* and an ASCII string *s*. * If *i* = 0 then *s* may contain any ASCII text. * If *i* = 1 then *s* must be the TUT Language output for some valid input. **Output** (to stdout): A binary (0/1) indicator *j* and an ASCII string *t*. * If *i* = 0 then *j* = 1 and *t* is the translation of *s* **to** TUT Language. * If *i* = 1 then *j* = 0 and *t* is the translation of *s* **from** TUT Language. * For any valid input, applying the program to its own output must exactly reproduce the original input; i.e., *program* (*program* (*i*, *s*)) = (*i*, *s*). Input and output must have exactly the same format. **Scoring**: The score is the number of characters in the program -- lowest score wins. **Examples** [**(a)**](http://www.youtube.com/watch?v=yJzQiemCIuY) ``` (0, 'Look for the birds.') (1, 'LULskwerokak fuforut tuthashi bubayruddudsus.') ``` [**(b)**](http://www.youtube.com/watch?v=tsAZ0RweVxk) ``` (0, '"Mrs. Hogwallop up and R-U-N-N-O-F-T."') (1, '"MUMrutsus. HASHojugwakseskwerlulopup yupup enundud RUT-YU-NUN-NUN-O-FUF-TUT."') ``` (**c**) ``` (0, 'QWX WWW Rrrrd deeeeep') (1, 'KWAKWAKSEKS SKWERWAKSWAKS RUTskwerrutruddud dudskweriskweriipup') ``` (**d**) ``` (0, 'aa AA aA Aa rd RD rD Rd') (1, 'skwere SKWERE eE Ee ruddud RUDDUD rutDUD RUTdud) ``` (((Aside about pronunciation: The TUT words for the vowels (`e`, `i`, `ay`, `o`, `yu`) are supposed to represent the usual sounds of (a, e, i, o, u) when reciting the alphabet -- i.e., rhyming with (may, me, my, mow, mew). In the three-or-more-letter TUT words, the symbols (`u`,`a`,`e`) are supposed to sound as in (but, bat, bet) respectively -- these are ASCII replacements for (`ʌ` `æ` `ɛ`) in the linked article.))) [Answer] ### Ruby, ~~310~~ 311 characters ``` h=Hash[(?a..?z).zip %w{e bub kut dud i fuf jug hash ay jag kak lul mum nun o pup kwak rut sus tut yu vuv waks eks yak zuz}] h["rd"]="ruddud" h.keys.each{|k|h[k[0]+k]="skwer"+h[k]} h.keys.each{|k|h[k.upcase]=h[k].upcase} h=h.invert if b=getc==?1 i=gets print b ?0:1;(k=i;k=k.chop until h[k]||!k[1];$><<(h[k]||k);i[k]="")until i=="" ``` Correctly handles: * squared uppercase (unfix by merging iterations gains 18 characters) + if `AA` should turn into `skwerE`, swap lines #3 and #4 + I also assume `aA` and `Aa` should turn into `eE` and `Ee` respectively * `rrd` translates to `skwerruddud (unfix gains 3 characters) * in cubes the first pair is reported as a square. `rrrd` turns into `skwerrutruddud`. `rrrrd` becomes `skwerrutskwerruddud` * the output is now a valid input. It is, indeed, required by the spec * uses newline as input terminator ~~Input requires there be no newline between the indicator and the string, output puts it there (fix: 1 character).~~ Console output suppressed at this point to prevent mixing with STDIN. Unfix free, it's just a little bit uglier. Example input: ``` 0Hello ``` Output: ``` 1 HASHiskwerlulo ``` [Answer] ## Perl, ~~453~~ ~~443~~ ~~309~~ ~~307~~ ~~303~~ 299 ``` ($x,$_)=split//,<>,2;@x{a..z,rd}=(e,bub,kut,dud,i,fuf,jug,hash,ay,jag,kak,lul,mum,nun,o,pup,kwak,rut,sus,tut,yu,vuv,waks,eks,yak,zuz,ruddud);$x{$_ x2}=skwer.$x{$_}for a..z;$x{uc$_}=uc$x{$_}for keys%x;%x=reverse%x if$x;$z=join"|",sort{length$b<=>length$a}keys%x;s/\G(.*?)($z)/$1$x{$2}/g;print!$x+0,$_ ``` **Test cases:** I have tested successfully the (a),(b),(c) and (d) test cases provided in the OP. **A \*somewhat\* more readable version:** ``` ($x,$_)=split//,<>,2; @x{a..z,rd}=(e,bub,kut,dud,i,fuf,jug,hash,ay,jag,kak,lul,mum,nun,o,pup,kwak,rut,sus,tut,yu,vuv,waks,eks,yak,zuz,ruddud); $x{$_ x2}=skwer.$x{$_}for a..z; $x{uc$_}=uc$x{$_}for keys%x; %x=reverse%x if$x; $z=join"|",sort{length$b<=>length$a}keys%x; s/\G(.*?)($z)/$1$x{$2}/g; print!$x+0,$_ ``` [Answer] ## APL (Dyalog) (372) You can really tell APL doesn't have built-in string handling functions (except for the generic array ones). I had to write my own `tolower` (it's `L`). As always with multiline Dyalog APL, to test it, paste it in an edit window and then call it (`T`). ``` T Q←⎕UCS L←{Q(Q⍵)+32×⍵∊⎕A} Z←{⎕←⊃z,.⍺⍺1⌽z←⍵,' '} w←L¨W←1↓¨W⊂⍨' '=W←' E BUB KUT DUD I FUF JUG HASH AY JAG KAK LUL MUM NUN O PUP KWAK RUT SUS TUT YU VUV WAKS EKS YAK ZUZ RUD SKWER' ⍞{⎕←~⍵:{U←L⍣(l←⍺∊L⎕A) ~l∨⍺∊⎕A:⍺ ⍺=⍵:U⊃⌽W 'rd'≡L¨⍺⍵:U'RUD' U⊃W[96-⍨Q+L⍺]}Z⍺ {'rR'∊⍨v←⊃⍺:v (⊃⌽w)≡m←L⍺:⍵∇⍬ ~w∊⍨⊂m:⍺ L⍣(⍺≡L⍺)⍨⎕A/⍨26↑≡∘m¨w}Z{~×⍴⍵:'' ∨/H←⊃¨⍷∘(L⍵)¨w:(⊂l↑⍵),∇⍵↓⍨l←⍴⊃H/W (⊂⊃⍵),∇1↓⍵}⍺}⎕ ``` Usage: ``` T ⎕: 0 "Mrs. Hogwallop up and R-U-N-N-O-F-T." 1 "MUMrutsus. HASHojugwakseskwerlulopup yupup enundud RUT-YU-NUN-NUN-O-FUF-TUT." T ⎕: 1 "MUMrutsus. HASHojugwakseskwerlulopup yupup enundud RUT-YU-NUN-NUN-O-FUF-TUT." 0 "Mrs. Hogwallop up and R-U-N-N-O-F-T." ``` [Answer] ## Tcl, ~~395~~ ~~394~~ 392 ``` set m { rd ruddud a e h hash o o u yu b bub i ay p pup v vuv c kut j jag q kwak w waks d dud k kak r rut x eks e i l lul s sus y yak f fuf m mum t tut z zuz g jug n nun ঙ skwer} set m $m[string tou $m] if [read stdin 1] {puts 0[regsub -all ঙ(.) [string map [lreverse $m] [gets stdin]] {\1\1}]} {puts 1[string map $m [regsub -all (.)\\1 [gets stdin] ঙ\\1]]} ``` Notes: * Uses `skwerruddud` for `rrd`. * `skwereskweree` for `aaaaa`. Example input: ``` 0Hello ``` Output: ``` 1HASHiskwerlulo ``` How it works: * `m` is at the beginning a string. * I concatiate it with the uppercase map. * [string map] does most of the stuff for me (uses a list, so anything that is a valid list...) * regexp for for the double characters. Use a special replacement character (`ঙ`). [Answer] ## Perl 385 ``` $t=e0bub0kut0dud0i0fuf0jug0hash0ay0jag0kak0lul0mum0nun0o0pup0kwak0rut0sus0tut0yu0vuv0waks0eks0yak0zuz;@t=split 0,$t."0\U$t";@s=(a..z,A..Z);while(<>){($-,$_)=split/ /,$_,2;@l{$-?@t:@s}=$-?@s:@t;if($-){for$@(@t){s/skwer$@/$@$@/gi}for$@(@t){s/$@/$l{$@}/g}s/(r)ud/$1/gi}else{s/(.)/$l{$1}||$1/ge;for$@(@t){$r=lc$@eq$@?"skwer":"SKWER";s/$@$@/$r$@/g}s/(ru)t(d)/$1$2$2/gi}$-=!$-;print"$- $_"} ``` Syntax highlighter hates this one... Expects input on STDIN, format is `0 (or 1) String to convert here.`: ``` 0 Hello! # input 1 HASHiskwerlulo! # output 1 HASHiskwerlulo! 0 Hello! 0 Look for the birds. 1 LULskwerokak fuforut tuthashi bubayruddudsus. 1 LULskwerokak fuforut tuthashi bubayruddudsus. 0 Look for the birds. 0 "Mrs. Hogwallop up and R-U-N-N-O-F-T." 1 "MUMrutsus. HASHojugwaksaskwerlulopup yupup anundud RUT-YU-NUN-NUN-O-FUF-TUT." 1 "MUMrutsus. HASHojugwaksaskwerlulopup yupup anundud RUT-YU-NUN-NUN-O-FUF-TUT." 0 "Mrs. Hogwallop up and R-U-N-N-O-F-T." ``` **Edit**: I've noticed an issue with the translation of X (it becomes 'aks' in the reversion, I'll look into this later. Might need to re-order the hash :(. [Answer] ## GNU Sed, 514 ``` s/$/\n@a!e@b!bub@c!kut@d!dud@e!i@f!fuf@g!jug@h!hash@i!ay@k!kak@l!lul@m!mum@n!nun@o!o@p!pup@q!kwak@r!rud@r!rut@s!sus@t!tut@u!yu@v!vuv@w!waks@x!eks@y!yak@z!zuz/ s/.*\n\(.*\)/&\U\1@/ ta :a s/^1/0\v/ td s/^0/1\v/ :t /\v\n/bf s/\v\([^a-z]\)/\1\v/i tt s/\v\([a-z]\)\1/skwer\v\1/ s/\v\([A-Z]\)\1/SKWER\v\1/ s/\v\(.*\)\(.*\n.*@\1!\(\w\+\)@\)/\3\v\2/ s/rut\vd/rud\vd/ s/RUT\vD/RUD\vD/ bt :d /\v\n/bf s/\v\([^a-z]\)/\1\v/i td s/\v\(skwer\)/\1\v/i s/\v\(.*\)\(.*\n.*@\(.\)!\1@\)/\3\v\2/ s/skwer\(.\)\v/\1\1\v/ bd :f s/\v.*// ``` Could probably be shortened, though I'm done for now. Uses a lookup table to handle conversions in both directions, should handle all exceptions including skwer case and ruddud/RUDDUD correctly. input taken on each line as 0/1 followed by the string. Uses `\v` (vertical tab) as a cursor. ]
[Question] [ ## Introduction You are given a random integer generator with the following implementation * The first invocation always returns 1. * The second invocation returns a random integer between 1 and 2. * The third invocation returns a random integer between 1 and 3. * The nth invocation returns a random integer between 1 and n, inclusive. Based on the above function, write a random dice generator that is perfectly random, returning a value between 1 and 6 (inclusive) with equal probability. ## Rules * Your program/function should result in a random integer between 1 and 6, inclusive, in some usable form, i.e., to standard output or as a function return value. * The ascending random number generator above can be defined as a "free" function in your program (i.e., doesn't count toward your character count), or a separate script/program that is executed as needed, assuming the state (`n`) is persistent between calls. * Assume that no more than 1000 dice rolls will ever be requested in a single use case of your program, and the initial random number generator can be reset to `1` at the end of 1000 dice rolls to avoid overflow of `n`. * Your program may not use *any* other source of random numbers except the ascending random generator defined above. You may of course request multiple random numbers from the random number generator for each single dice roll output. * This is code-golf, so winner is shortest answer or most votes in the event of a tie. If you can generate 1000 dice rolls using less than 1000 generated random numbers, give yourself a **10-point efficiency bonus**. ## Example ``` ./asc-rand 1 # random integer between 1 and 1 ./asc-rand 1 # random integer between 1 and 2 ./asc-rand 3 # random integer between 1 and 3 ./asc-rand 4 # random integer between 1 and 4 # dice-gen generates random dice based on output of asc-rand program. ./dice-gen 3 ./dice-gen 6 ./dice-gen 5 ./dice-gen 1 ``` [Answer] ## Python, 31 chars Similarly to scleaver, define the generator like this: ``` from random import randint n=0 def r(): global n;n+=1 return randint(1,n) ``` Then a function to return dice rolls: ``` D=lambda:eval('r(),'*6)[-1]%6+1 ``` Call `D()` any time you need a uniformly random dice roll. [Answer] ## Scala 23 ``` def s={r;r;r;r;r;r%6+1} ``` The method r can be (approx.) implemented like this: ``` var cnt = 0 val rnd = new util.Random def r = { cnt %= 1000 cnt += 1 rnd.nextInt (cnt) } ``` a rough test: ``` scala> (1 to 6).map (i => ((1 to 600) map (_=>s)).filter (_ == i).size) res26: scala.collection.immutable.IndexedSeq[Int] = Vector(110, 105, 91, 96, 106, 102) ``` Every 6th call should produce an equal distribution over the 6 values, so I throw away 5. [Answer] # J - 13 char This makes the same assumptions as Golfscript: that the number of dice is in stdin and we list the dice rolls that are to come out. ``` r=:1+? NB. free random function r>:i.".1!:1]1 ``` Explained by explosion: ``` r=:1+? NB. r(x) = 1 + a random number between 0 and n-1 ]1 NB. input file handle 1!:1 NB. read in a string ". NB. convert to integer >:i. NB. make a list of numbers, from 1 to that integer r NB. apply the random function ``` If that is somehow unsatisfactory, here is a longer, 21-char program, that can be called with `f''` to generate random numbers, featuring a state and everything. ``` r=:1+? NB. free random function c=:0 f=:3 :'r c=:1+c' ``` [Answer] ## GolfScript (15 chars) This assumes that the number of rolls required is supplied on stdin and lists that many results to stdout. ``` # The free increasing random function 0:N;{N):N rand)}:r; ~{r{;r}5*6%)n}* ``` [Online demo](http://golfscript.apphb.com/?c=IyBNb2NrIGlucHV0CjsnOCcKCiMgVGhlIGZyZWUgaW5jcmVhc2luZyByYW5kb20gZnVuY3Rpb24KMDpOO3tOKTpOIHJhbmQpfTpyOwoKfntyeztyfTUqNiUpbn0q) While I could get the 10 point bonus for using fewer than 1000 rolls to generate 1000 numbers, it would cost me far more than 10 characters. The trivial approach of extracting suitable entropy when N is a multiple of a power of 2 or 3 falls well short because the number of results available mod 3 is only 333 + 111 + 37 + 12 + 4 + 1 = 498. Therefore it's necessary to take a sample-and-reject approach. Using this approach you can get an expected 2242 rolls from 1000 calls to `r`, but there's extra overhead from the book-keeping and `base` is a very long function name. [Answer] # Python 65 63 ``` i=7 while i>5:[R()for x in range(9)];i=int(`R()`[-1]) print i+1 ``` The function `R()` is the ascending randomizer. ### Usage: ``` $ ./rollDice.py 3 $ ./rollDice.py 5 ``` [Answer] # Python, 56 r is defined as: ``` from random import randint n=0 def r(z): global n;n+=1 return randint(1,n) ``` the dice generator d: ``` import math;d=lambda:math.ceil(6.*r(r(r(r(r(r(0))))))/n) ``` usage, eg, for 100 rolls: ``` for i in range(100):print d() ``` [Answer] # Mathematica 51 The random number generator, `r`, is reset by setting the global variable, `n` to 1. ``` n = 1; r[c_] := RandomInteger[{1, c}] ``` **Code** Not in the running for the shortest code... ``` h := (n++; If[n < 4 \[Or] (y = r@n) > 6 Quotient[n, 6], h, y~Mod~6 + 1]) ``` --- **Usage** ``` t = Table[h, {60000}]; n SortBy[Tally[t], First] ``` 60000 rolls of the dice required 60031 calls to `h`. `Tally` shows the breakdown by numbers 1-6. > > 60031 > > > {{1, 9923}, {2, 9966}, {3, 10016}, {4, 10028}, {5, 10009}, {6, 10058}} > > > [Answer] ## Perl, 22 or 45 Implementation of the ascending random number generator: ``` my $n=0; sub r { $n++; return 1+int(rand$n); } ``` Generating: ``` #copy of the Scala solution; short code; uses 6N rolls sub s{r;r;r;r;r;1+r%6} #more efficient implementation, uses approximately 6+N+lnN rolls sub roll { do{$a=r-1}while($a>$n-$n%6);return 1+(1+$a)%6 } ``` Testing out: ``` n number chisquare 1 10001867 0.348569 2 10004853 2.355161 3 9994395 3.141602 4 10000177 0.003133 5 9999227 0.059753 6 9999481 0.026936 T 60000000 5.935154 60000000 dice rolls took 60000042 calls to r and 570.432735 seconds ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 35 bytes ``` //random number generating function g=1;f=()=>(1+g>1000?g++:5*Math.random())|0 ``` ``` i=0;while(i++<5)f();t=()=>f()%6+1|0 ``` [Try it online!](https://tio.run/##HcxBDsIgEIXh05jMOLGBRV1IqSfoIUgLFINMQ4ndeHek7t7ie//LfMw@57CVW@LFVq@lchpQjyDJj1II8fREj/46mbJ22aSF34D4FTVooY41RAuBaOjRAaryv7Z1uZNsxnGG04XhLKkGcea0c7RdZA@llVT9AQ "JavaScript (Node.js) – Try It Online") [Answer] # x86 opcode, 15 bytes ``` f: mov cx, 6 call r ; return in AX loop $-3 cwd div word [f+1] inc dx ret ; return in DX ``` [Answer] # [GolfScript](http://www.golfscript.com/golfscript/), 8 bytes ``` f;3f*f(- ``` [Try it online!](https://tio.run/##S8/PSStOLsosKPlvYJVpXZ2paZWpUJSYl6JZa5Vm/T/N2jhNK01D9/9/AA "GolfScript – Try It Online") It pops the generator once, then gets rid of the result. Then it rolls f2, and multiplies it by 3 (3 or 6), then subtracts f3-1 (0, 1, 2) which results in (3-2, 3-1, 3-0) or (6-2, 6-1, 6-0) W5. Golfscript and the random function existed before this question was posted, so is a legal submission. This is the run-only-once submission. If you need to run it several times in one call, # [GolfScript](http://www.golfscript.com/golfscript/), 12 bytes ``` f;3f*f-)0:i; ``` [Try it online!](https://tio.run/##S8/PSStOLsosKPlvYJVpXZ2paZWpUJSYl6JZa5VmXf0/zdo4TStNVxMk@b/W1EDrPwA "GolfScript – Try It Online") This resets your i call to 0 so it resets accordingly. This TIO shows 50 random results. [Answer] # [C (gcc)](https://gcc.gnu.org/), 31 bytes ``` f(i){for(i=5;i--;)c;i=~-c%6+1;} ``` Every 6 calls, the probability of every number between 1 and 6 inclusive being generated is equal. `c` is `#define`d as a call to a function that generates the perfect random numbers. [Try it online!](https://tio.run/##dU9BbsIwELzvK1agSLZMkHNoLya8BKkKa5uuRAxyDBcUvp7a5kJVdU@j2dmZWWpPRMuaA51v1uFuSvbMx@33HoBDwsxHN0wcTl9xCFbcL2wlPADzTGlITFhkBTpT2ejSLQasaokNKlWXqLAzMAOsrfMcHNIfb7l4wfLhL1Fw/2G4bY0kw/2zpeZTdWZ@q5l4dKXkv8XHgcPvtjWj3AktpYFK1qysphSxR20q2GGn9QsrJavuZVHmGrPei1VjD2G1QS@KV1nM8P6@zr8uPw "C (gcc) – Try It Online") ]
[Question] [ As the title says, given a valid chess move in algebraic notation, produce the string describing the move. **Example:** ``` fxg8=Q+ -> Pawn takes g8 promotes to Queen check Bb7# -> Bishop to b7 mate ``` Here is a list of all the keywords and their respective notation ``` R -> Rook x -> takes N -> Knight + -> check B -> Bishop # -> mate Q -> Queen = -> promotes to K -> King 0-0 -> short castle 0-0-0 -> long castle ``` --- *Note: Long and short castle can be represented with either number `0` or letter `O` uppercase. You can choose any you'd like.* ***From wiki:** Both algebraic notation and descriptive notation indicate kingside castling as 0-0 and queenside castling as 0-0-0 (using the digit zero). Portable Game Notation and some publications use O-O for kingside castling and O-O-O for queenside castling (using the letter O) instead* --- Piece moves format follows `{Piece name} to {square}` Moves without a piece are consider pawn moves. Example: ``` g4 -> Pawn to g4 Nh7 -> Knight to h7 ``` For ambiguous moves, input will specify both departure rank and file. Example: ``` Rh8b8 -> Rook h8 to b8 Qb3e6 -> Queen b3 to e6 ``` --- ## Input String with a valid chess move in algebraic notation ## Output String describing the move (Upper case or Lower case is ok) --- ## Test Cases ``` fxg8=Q+ -> Pawn takes g8 promotes to Queen check Bb7# -> Bishop to b7 mate 0-0 -> short castle 0-0+ -> short castle check 0-0-0# -> long castle mate Rxg8 -> Rook takes g8 fxe6 -> Pawn takes e6 Ra8g8 -> Rook a8 to g8 Nb3# -> Knight to b3 mate a8=B -> Pawn to a8 promotes to Bishop Ra8xg8 -> Rook a8 takes g8 ``` [Answer] # JavaScript (ES6), 206 bytes Takes some inspiration from [Neil's Retina answer](https://codegolf.stackexchange.com/a/264563/58563). But in the end, this is quite different. ``` s=>[/O-O-/,/O-/,/.\d/g,/to (?=.*o)/,/x to/,..."=+#ORKBQN",/^.? /].map((r,j)=>s=s.replace(r,`long/short/ to $&// takes/ promotes to / check/ mate/ castle/Rook/King/Bishop/Queen/Knight/Pawn `.split`/`[j]))&&s ``` [Try it online!](https://tio.run/##dZJfb4IwFMXf9ykaXAxM7H3QKHuoJryayOTVuVCxIoqU0G7z27OWP5Mh4wFC8@Pcc87lTL@oCPM4k@OUH1hxJIUgiy14Y28MNpQ3/H6AyAbJkbkk@IVb6uyGJAcbY2yQ0cDzV@5mbdjwgZcIdvhKM9PM7bNFFoIInLMsoSFTJ0HC0wjEiecSlAB6HoJ60gsTgLKcX7lkQp8DCk8svAC6UsnUCxUyYeBzfoFVrBTcWGlksPlkLIVVGkcnCW/0O0UBFlkSywCC7XlnWcOhKEKeCp4wnPDIPJoGmxqWhcpLzS4/UgPZ9KnD@dRpQMXp0Zqjr13ueIscshlp9ldPB0KR8ydS6bWK1ZVw9/NBPUtJVNn0J/t5mb@Lq9W0nJVl1g31kKO7cJvsN6KX7lVWFK931eB9PnyV/K5eNVQnfyyJze5oqyQ26@m9kW1UqaPbeFRVaGOhjf7jYb2ftFqufpqy5UlvOuoQt2uZa/32UqtdFT8 "JavaScript (Node.js) – Try It Online") ### Decoding examples ``` e4 to e4 Pawn to e4 ``` ``` fxg8=Q+ fx to g8=Q+ f takes g8=Q+ f takes g8 promotes to Q+ f takes g8 promotes to Q check f takes g8 promotes to Queen check Pawn takes g8 promotes to Queen check ``` ``` Ra8g8 R to a8 to g8 R a8 to g8 Rook a8 to g8 ``` --- # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 144 bytes *-4 bytes thanks to @Neil* The same logic back-ported to Retina. ``` O-O- long O- short .\d to $& -2`to x to takes = promotes to \+ check # mate O castle R Rook K King B Bishop Q Queen N Knight ^.? Pawn ``` [Try it online!](https://tio.run/##FU5BCsIwELzPKwJVEUo9qGgvRejFQ8HYnEWMdW1DayJtRH8fN4ednZ0dmBnJG6vDfHm8BZnJDIOzLXhPnRs9VpcHhHditkC2vjEBfnyzpnuaUEC8R/dynqbowiWFaDpqeiQQL@0JkgU9@YGgoJzrUaEynFCiNBzxRo36Q2RxQmVN23lcVweBs/5aEQJtoXSO56/NizpFed8n3E3GSSNkMoHiJztoF61MGaNyum8S6Lwo/w "Retina 0.8.2 – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/) `-p`, 249 bytes `-p` flag loops over input, modifies it with these two fat regex functions, and spits it back out. ``` sub(/(^[a-g]?)?(.\d)?(x)?(?=.\d)|O(-O)+/){$4?%w(short long)[~/$//5]+' castle':"#{$1&&?P}#{' '+$2if$2} #{$3?:takes:'to'} "} gsub(/[#+=B-R]/){|m|m[/\W/]?' '+%w(mate promotes\ to\ _ check)[m.ord%5]:%w(King Queen Rook Bishop Pawn).find{_1[m]}||:Knight} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=LVDNaoNAGLzvUyxqoiJmSdK0IsiC19CaeOlhtUWT9YdEN-hKLGpfpJcc2r5THqW3bmoP3zB8zHzzMR-fVRO_fRPJPEnh5avhiWldf-om1pD2QiIzDbGOtVmwF9iKwc6N955merqB9E65w5OzVmes4vDIylQn70hBaBUaKtxFNT9S1ZbkTplPp3gzyJ0KVUNZ5ImyGKBYL7HNowOtbZUzdYDSANK_bCIbjmv6oUjoi74gKHhGIb6ZRVoRcQpPFSsYp3UAOQsgfIW7jO4OOilmrNpPVqEthOu8TOG2obSEPmMH6Obi0RPcROdSnyV5ue9e56QIh76312WeZnwYC_jv4XJ9TNrUcrYGcOMHGXimd5sRjZHKwBcSkLT0HviRJehTvJTBtk2EYZ3NQWQ5LvBjS6jGq78) ### Partially ungolfed ``` sub(/(^[a-g]?)?(.\d)?(x)?(?=.\d)/) { # Replace the part that says which piece moves where "#{ $1&&?P # 'P' (Pawn) if group 1 is present # (matches if input starts with /[a-g]x/ or /.\d/) }#{ ' '+$2if$2 # Group 2 with leading space if present # (for Qb3e6 -> Queen b3 to e6 etc.) } #{ $3?:takes:'to' # 'takes' if group 3 (x) is present, else 'to' # (uses label notation :takes to save bytes) } " } sub(/O(-O)+/) { # Replace castling notation (original program checks for group 4) %w(short long) # ['short', 'long'] [ ~/$/ # Index of end of input (3-4 if O-O, 5-6 if O-O-O) /5] # Divide by 5 to get correct index for short vs long + ' castle' # Add the ' castle' part } gsub(/[#+=B-R]/) {|m| # Match checkmate, check, promotes, pieces m[/\W/]? # If non-letter (checkmate, check, promote) ' '+ # Leading space ['mate','promotes to ', nil, 'check'][m.ord%5] # Match the corresponding phrase by using mod 5 # '#' -> 0, '=' -> 1, '+' -> 3 : # Otherwise (if letter) %w(King Queen Rook Bishop Pawn).find{_1[m]} # Find the piece that has that letter ||:Knight # If none found, it's a Knight (N can't match) } ``` ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~165~~ 146 bytes ``` FS≡ιx≔⊞OΦυ⊖Lκtakesυ-≔⟦⎇⊖Lυlong¦short⟧υ¿№βι≔⊞O⁺∨⁻υ⟦to⟧⟦Pawn⟧…⟦to⟧¬№υtakesιυ¿Σι⊞υ⁺⊟υι⊞υ§⪪”↶.⭆~»¤πη‽q∕¶lj,⊙↥⟲Qmº5σ¡²JN¤εlθw(LθΦG▶⁵@W|]”¶⌕KQRBNO+#ι⪫υ ``` [Try it online!](https://tio.run/##bVJLTwIxEL7zK5p6mUa4G4kHxZjgAxbw5nqoy7DbUKabdqoY42/H2QXjxdN8zUy/x7RVY2MVrD8cNiEqmFKbecXRUQ3GqPThuGoUOKO@BpVNqPReX6rrlFxNUOTUzFuMlkOEO@cZI@ShusUq4g6JcQ2PSDU3sDXGDJVmu8WkBWUzPtGN/uhenjGSjZ/wD0Hu7/tAtZaamhBZm9cj0Ro3Nnu@VG6jYBIyMbwNlRP7//ksfE4wj/DkSIDYfdEc9KvpQGE/qIeTz8rjpAktHLtDNQt84s5/QfpU7phHoZc8nYVV3kGn3sl2071iIVy5n/4d/W1f85TWuIdV6x2DfpDVl7TIiFTSMoRtSTdOArclPZCrGy5JNscepTZYSXtnWQ5tDLvAmJT4FYcldXu@c7QWysXyZjY/P9O9vGzse1DICzPcB0d9HiVZxvIF9vXF1eL8MHr3Pw "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` FS≡ι ``` Loop over the characters of the input string. ``` x≔⊞OΦυ⊖Lκtakesυ ``` For `x`, push `takes` to the result, but remove any bare letters (which will be the source file of a pawn capture). ``` -≔⟦⎇⊖Lυlong¦short⟧υ ``` For `-`, change `castle` to `short` but `short castle` to `long`. (The `castle` comes from the `O` below.) ``` ¿№βι≔⊞O⁺∨⁻υ⟦to⟧⟦Pawn⟧…⟦to⟧¬№υtakesιυ ``` For other lower case letters, this might be the source or the destination file. Remove any existing `to` and add a new `to`, unless there is a `takes` in the string. Then push the file to the result. ``` ¿Σι⊞υ⁺⊟υι ``` For digits, append the rank to the file. ``` ⊞υ§⪪”↶.⭆~»¤πη‽q∕¶lj,⊙↥⟲Qmº5σ¡²JN¤εlθw(LθΦG▶⁵@W|]”¶⌕KQRBNO+#ι ``` For other characters, push the piece name or notation to the result. ``` ⪫υ ``` Join the collected words on spaces. [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~176~~ ~~172~~ 171 bytes ``` (([A-Z])(..)?|(.?))(x)?(.\d) $2$#4$*P $3$#3$* to$5 $6 ox akes O-O- long O- short O castle # mate \+ check = promotes to K King Q Queen R Rook B Bishop N Knight P Pawn ``` [Try it online!](https://tio.run/##FY0/r4IwHEX3@ymatEOrgUF8ykKIrCTyZ1TfUPQnELQ1UCPD@@68up2c5J47kuuNXhYpz4fg9KtkGKr0T4apUnJWqQwvNwWxEXwrViUTkeCRWDFnxQ8TO9gZeqAJRVAEeFjTesLU2dGhALvqyT0IHOypHeGy9qqj64AE7DXap3U0@RRDjrz32wrVm8igRm3tgAxZ71svHJGbvu0cSpT6Y5blPrdxUq2RNXv@/UbtBe4z7VDr2OOxiTh0nGT/ "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: ``` (([A-Z])(..)?|(.?))(x)?(.\d) $2$#4$*P $3$#3$* to$5 $6 ``` Identify the piece or pawn being moved, whether there is a disambiguation square for the piece, and its destination. ``` ox akes ``` Fix up the case of a capture. ``` O-O- long O- short O castle ``` Process castling. ``` # mate \+ check = promotes to ``` Process other symbols. ``` K King Q Queen R Rook B Bishop N Knight P Pawn ``` Expand the piece names. Edit: Saved 4 bytes thanks to @Arnauld. Saved 1 byte thanks to @ValueInk. [Answer] # C# .NET console app, 333 bytes Assumes `using System; using System.Text.RegularExpressions;` ``` string m=Regex.Replace(args[0],"(?<!x)[a-h](?!.*[x|a-h])","t${0}"),r=m[0]>96?"Pawn ":m[0]<49?(m.Length>4?"long":"short")+" castle ":"";foreach(var c in m){int i="-0RNBQKx+#=t".IndexOf(c);r+=",,,Rook ,Knight ,Bishop ,Queen ,King ,takes ,check,mate,promotes to ,to ".Split(',')[i+1];if(c!=m[0]&i<0)r+=c+(c<57?" ":"");}Console.Write(r); ``` ## Commented ``` // add a 't' to the move string wherever "to" is needed string m = Regex.Replace(args[0], "(?<!x)[a-h](?!.*[x|a-h])", "t${0}"), // start with 'Pawn' if the first character is a file, to or takes r = m[0] > 96 ? "Pawn " // decode castles now so we can ignore -,0 later : m[0]<49 ? (m.Length>4 ? "long" : "short") + " castle " : ""; // iterate through the move string foreach (var c in m) { // map each code to a word, with space where needed // 0,- map to empty string int i = "-0RNBQKx+#=t".IndexOf(c); r += ",,,Rook ,Knight ,Bishop ,Queen ,King ,takes ,check,mate,promotes to ,to ".Split(',')[i + 1]; // anything that doesn't map is assumed to be a square reference and added to the result // except if it's the first character because if it's not x or t then it must be a file with no rank. // also add a space if it's a digit if (c != m[0] & i < 0) r += c + (c < 57 ? " " : ""); } Console.Write(r); ``` ]
[Question] [ Given a string `s` consisting of characters a-z lowercase, generate 5 arrays `a1`, `a2`, `a3`, `a4`, and `a5` of size `n` (length of `s`) where the `i`-th element of each array represents the index of the next occurrence of the `i`-th character in `s`, with the following conditions: * If no such occurrence exists, set the value to `n` (0-based indexing) or `n+1` (1-based indexing) depending on the indexing convention you use. * `a1` represents the 1st next occurrence of the character, `a2` represents the 2nd next occurrence, `a3` represents the 4th next occurrence, `a4` represents the 8th next occurrence, and `a5` represents the 16th next occurrence. This is a code golf challenge, so the shortest code in bytes wins. Here are some test cases. They all use 0-based indexing. **Input:** `aakakakakka` **Output:** ``` 1 3 4 5 6 7 8 10 9 11 11 3 5 6 7 8 10 9 11 11 11 11 7 10 9 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 11 ``` **Input:** `sydgdtsfixuvhdgisifdyovjcgs` **Output:** ``` 6 20 4 14 13 27 16 18 15 27 27 22 27 19 25 17 26 27 27 27 27 27 27 27 27 27 27 16 27 13 25 19 27 26 27 17 27 27 27 27 27 27 27 27 27 27 27 27 27 27 27 27 27 27 27 27 27 27 27 27 27 27 27 27 27 27 27 27 27 27 27 27 27 27 27 27 27 27 27 27 27 27 27 27 27 27 27 27 27 27 27 27 27 27 27 27 27 27 27 27 27 27 27 27 27 27 27 27 27 27 27 27 27 27 27 27 27 27 27 27 27 27 27 27 27 27 27 27 27 27 27 27 27 27 27 ``` **Input:** `qmorzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz` **Output:** ``` 59 59 59 59 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 59 59 59 59 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 59 59 59 59 59 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 59 59 59 59 59 59 59 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 59 59 59 59 59 59 59 59 59 59 59 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 59 59 59 59 59 59 59 59 59 59 59 59 59 59 59 ``` [Answer] # [BQN](https://mlochbaum.github.io/BQN/), 18 bytes[SBCS](https://github.com/mlochbaum/BQN/blob/master/commentary/sbcs.bqn) ``` -∘≠↑¨<⊒¨⍷⊸∾⍟(2⋆↕5) ``` [Run online!](https://mlochbaum.github.io/BQN/try.html#code=RuKGkC3iiJjiiaDihpHCqDziipLCqOKNt+KKuOKIvuKNnygy4ouG4oaVNSkKCnRlc3RzIOKGkCDin6ggImFha2FrYWtha2thIiwgInN5ZGdkdHNmaXh1dmhkZ2lzaWZkeW92amNncyIsICJxbW9yenp6enp6enp6enp6enp6enp6enp6enp6enp6enp6enp6enp6enp6enp6enp6enp6enp6enp6eiLin6kKCuKNieKJjeKlij7ii4jin5w+4p+cRsKodGVzdHM=) The *Progressive Index of* `⊒` does the heavy lifting here. `...⍟(2⋆↕5)` 1, 2, 4, 8 and 16 times: `⍷⊸∾` prepend the unique characters to the string. `<⊒¨` For each of the resulting strings find the progressive indices of the characters in the input string. *progressive* means that each index can only be used once. The length of the input is used as a *not found* value. `-∘≠↑` From each resulting integer list, take as many values from the back as there are characters in the input. [Answer] # Excel, ~~111~~ 109 bytes *With thanks to **JvdV** for the 2-byte save*. ``` =LET( b,LEN(A1), c,SEQUENCE(b), d,MID(A1,c,1), IFERROR(FIND(0,SUBSTITUTE(MID(A1,c+1,b),d,0,{1,2,4,8,16}))+c-1,b) ) ``` 0-based. Input in cell `A1`. Generates an *n*-row-by-5-column array, where *n* is the length of the input string. [Answer] # [J](http://jsoftware.com/), 35 bytes ``` (2^i.5){0|:i.@#+(#,~^:16[:I.{.=])\. ``` [Try it online!](https://tio.run/##y/r/P03B1kpBwyguU89Us9qgxipTz0FZW0NZpy7OytAs2spTr1rPNlYzRu9/anJGvkKagnpiYjYEZieqc4EF1aE0ULK4MiU9paQ4LbOitCwjJT2zODMtpTK/LCs5vRhTcWFuflEVeUD9PwA "J – Try It Online") * `(…)\.`: Apply the verb inside to each suffix of the string, in order of start point. + `{.` `=` `]`: Check for equality (`=`) between the first element (`{.`) and the whole suffix (`]`, identity function). This produces a list of Booleans. + (`[:` to use monadically.) `I.` produces a list of indices of the 1s. + `#` `,` `~` `^:` `16`: Take the length of the suffix (`#`) and append (`,` with `~` to reverse operands) it to the list, repeating 16 times (`^:` `16`). * `i.` `@` `#` `+`: Add (`+`) [0,1,2,3,…] (`#` gives the length of the string, and `i.` produces that many numbers). This adjusts the numbers from indices in the suffixes to indices in the whole string. * `0` `|:`: Transpose. * `(2^i.5){`: Take the rows at indices 1, 2, 4, 8, 16. [Answer] # JavaScript (ES6), 93 bytes Expects an array of characters. Returns an array of 5 arrays of integers, using 0-based indexing. ``` f=(s,k=5)=>k--?[...f(s,k),s.map(g=(c,i,q)=>!s[i]|q>>k?i:g(c,[...s,c].indexOf(c,i+1),-~q))]:[] ``` [Try it online!](https://tio.run/##nY@xbsMgEIZ3PwX1Yk7BSB26pMKZOvcBHAYEhmASiLnESqqqr@4Gp0/Qu@FO3/8Nd6OaFersz5c2JjMsixUUWRBvILrQtruec24LAYb8pM7UCaqZZ9Mjf8Hey@@p68LOb90DFxmZltxHM9w@bTE3r8DanwlAbnu5vPcVIbVS4dlB1awAvBtnLmj97TofjPPorbmnedQOn8J0Svnrf1VXsuI25Q@lDxSJ6IhOEdNx4MfkqKXr0RLW53KJMx@Tj7QhDcDfuo8NkA1ZJyy/ "JavaScript (Node.js) – Try It Online") ### Commented ``` f = ( // f is a recursive function taking: s, // s[] = input string, as an array of characters k = 5 // k = counter, initialized to 5 ) => // k-- ? // decrement k; if it was not 0: [ ...f(s, k), // append the result of a recursive call s.map( // for each entry in s[], g = ( // using a recursive callback function g taking: c, // c = current character i, // i = current position q // q = iteration counter, initially zero'ish ) => // !s[i] | // if s[i] is undefined q >> k ? // or we've done 2 ** k iterations: i // stop and return i : // else: g( // do a recursive call: c, // pass c unchanged [...s, c] // append c to a copy of s[] .indexOf( // and look in there for the position of c, // the next occurrence of c i + 1 // starting the search at i + 1 ), // -~q // increment q ) // end of recursive call ) // end of map() ] // : // else: [] // stop ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 23 bytes ``` IE⁵Eθ§⁺Φ⌕Aθλ›νμEφLθ⊖X²ι ``` [Try it online!](https://tio.run/##JYvBCsIwEER/JccE4kXw5KkoiqDQXwjb1S5sdtskrf59bOhcHryZgTEk0MC19omk2EvIxb7CZE/eNMzedOUhA/5sz0u2N@KCaYMMHXOr2XlzTxiaFm@ic/vz7c0T5VNGO7vmrggJI0rBwfb63dZHb8jtOdc6CS5RRRcuKUSCpBl0IsjEBLoqQxAFFdJMuR5W/gM "Charcoal – Try It Online") Link is to verbose version of code. 0-indexed. Outputs each index on its own line with each set of indices double-spaced from each other. Explanation: ``` ⁵ Literal integer `5` E Map over implicit range θ Input string E Map over characters ⌕A Find all occurrences of λ Current character in θ Input string Φ Filtered where ν Occurrence index › Is greater than μ Current index ⁺ Concatenated with φ Predefined variable `1000` E Map over implicit range θ Input string L Length § Indexed by ² Literal integer `2` X Raised to power ι Outer value ⊖ Decremented I Cast to string Implicitly print ``` [Answer] # [Python](https://www.python.org) NumPy, 92 bytes ``` lambda*s:clip(N:=len(s),0,x:=a(17*s,0,"s"))[2**c_[:5]+a(x)[:N]] from numpy import* a=argsort ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3Y3ISc5NSErWKrZJzMgs0_Kxsc1LzNIo1dQx0KqxsEzUMzbWKgWylYiVNzWgjLa3k-Ggr01jtRI0KzWgrv9hYrrSi_FyFvNLcgkqFzNyC_KISLa5E28Si9GIgE2pHV0FRZl6JRpqGllJiYjYEZicCDeRCSBRXpqSnlBSnZVaUlmWkpGcWZ6alVOaXZSWnF6MqLMzNL6oiDwANgrhowQIIDQA) Expects the splatted input string and returns a 2D array of integers. ### How? Repeat the input to make sure at least 16 excess copies of every letter are available. Do an indirect sort, i.e. a sort we can take back by applying the inverse permutation. Apply the sort, shift by 1,2,4,8 or 16 and unsort. Clip to range. [Answer] # [Pyth](https://github.com/isaacg1/pyth), 24 bytes ``` [[email protected]](/cdn-cgi/l/email-protection)+fgTkxbcz1mlzGz^2d5 ``` [Try it online!](https://tio.run/##K6gsyfj/P9fBWS9VOy09JLsiKbnKMDenyr0qzijF9P//xMRsCMxOBAA "Pyth – Try It Online") ### Explanation ``` # implicitly assign z = input() .e z # enumerated map b, k over z, indices xbcz1 # get all indices of b in z f # filter this on lambda T gTk # T >= k + mlzG # pad with 26 copies of len(z) C # transpose m 5 # map d over [0-4] @ # the element at the index ^2d # 2 ^ d ``` [Answer] # [Haskell](https://www.haskell.org/), 90 bytes ``` f s=[[([n|(n,x)<-z,x==c,i<=n]++l)!!(2^j)|(i,c)<-z]|let l=length s:l;z=zip[0..]s,j<-[0..4]] ``` It's got a perfectly natural typing, and uses 0-indexing as is normal for Haskell. ``` f :: String -> [[Int]] ``` [try it online, with tests](https://play.haskell.org/saved/m28fqrOb) [Answer] # Octave/MATLAB, 174 bytes Modified from [@loopy walt's answer](https://codegolf.stackexchange.com/a/259318/110802) Golfed version, [try it online!](https://tio.run/##nY5BTsMwEEX3PYXVDWNhUB0hIRUhcYJcAFWVG9upW8c2Hie4LLh6cEoQYcvM7s/7T@ObJAY1jrp3TTLekUyeiYZBRBFb4@iKlMGSSd8frIJGWVt1Iv0S9OnK1IWxyrXpCDhHr5@M5F3J0ccEUYWph4wz/kgXiHFS5X0QMVVkN8N5vmvjhN1fieI5YC5/wkuwPf7pAd/W9I4zEvy7ilAxstk@0Pub2TJ1O@OgExnyhG0oIzWFhf2WF1Y5OUqDATSshTh/71msKV39xHiRrUyoTe6Ho2wNGi0vfjg1LS6xt87Hj/9N0Yxf) ``` function x=f(varargin),s=double(cell2mat(varargin));N=numel(s);[~,x]=sort(repmat(s,1,17));[~,i]=sort(x);f_i=bsxfun(@plus,i(1:N)-1,(2.^(0:4)).');x=min(max(x-1,0),N)(f_i+1);end ``` Ungolfed version: ``` function x = f(varargin) s = cell2mat(varargin); s = double(s); N = length(s); s17 = repmat(s,1,17); [~, x] = sort(s17); x=x-1; index_part1 = power(2, 0:4).'; [~, index_part2 ]= sort(x); index_part2 = index_part2(1:N)-1; clipped = min(max(x, 0), N); sum_matrix = bsxfun(@plus, index_part2, index_part1); final_index = sum_matrix; x = clipped(final_index+1); end disp(f("aakakakakka")) disp(f("sydgdtsfixuvhdgisifdyovjcgs")) disp(f("qmorzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz")) ``` [Answer] # [Arturo](https://arturo-lang.io), 92 bytes ``` $[s][map 0..4'x[i:0map s'c['i+1(char? select.with:'j.n:2^x drop s i'm->c=m)?->j+i->size s]]] ``` [Try it](http://arturo-lang.io/playground?GRPr6p) ]
[Question] [ # Introduction Time is a really simple concept. Seconds pass, one after the other, all the same. But humans love making it hard. [This Stackoverflow question](https://stackoverflow.com/questions/6312993/javascript-seconds-to-time-string-with-format-hhmmss/43466724#43466724) has gathered many answers and even though they are surprisingly long and complex, most of them will still fail for certain inputs. Can you format a number of seconds into a timestamp for human consumption not only precisely, but correctly? # Challenge Build a human-readable timestamp from a floating point number of seconds. The timestamp must be formatted as `hh:mm:ss.zzz`. Single digit hours, minutes and seconds must be formatted with a leading zero. If the number of complete hours is zero, the hours and leading colon must be omitted, making the output format `mm:ss.zzz`. Please note that the number of hours may have more than two digits. For inputs that cannot be expressed as a finite number, the result must be `--:--.---` (see below for examples of this that probably apply to your language). This is `code-golf`, so the shortest code in bytes wins. # Example Input and Output ``` 0 -> 00:00.000 -0 -> 00:00.000 1 -> 00:01.000 -1 -> -00:01.000 0.001 -> 00:00.001 3.141528 -> 00:03.142 3600 -> 01:00:00.000 3599.9995 -> 01:00:00.000 363600 -> 101:00:00.000 17999.9999 -> 05:00:00.000 Infinity -> --:--.--- -Infinity -> --:--.--- NaN -> --:--.--- ``` [Answer] # JavaScript (ES6), 112 bytes ``` f=n=>1/n?n<0?'-'+f(-n):(n=n*1e3+.5,(k=n/36e5|0)?k>9?k:'0'+k:'')+new Date(n).toJSON().slice(13+!k,-1):'--:--.---' ``` [Try it online!](https://tio.run/##jdHBToQwEAbgu0@Bp7Z2p8wsgtLIcvGiBz34BASLQcjUCNGY@O64G2UjBIxN2kPz5Z@Z9rl4K7rytX7pgf2jG4Yq42xHIed8hbkAoSsJrKzkjM/IRdrEG9lkHEaJiz9R5c0uzRsrUOj9KZRm9x5cF72TrEzvbx/u76QyXVuXTlKkT5sNkLICwAIYABBD6bnzrTOtf5KVxGBcSgVhGCBaRIOIJ1MH@D9HC3m0lEdTB2vwUIQWCtPMRYbOKd5e/naHu@3cJYiTBsmuzRIlI/6m9IelizRNzX6nP7HxKr3hqua6/ziOPv7N/ImOcOaGLw "JavaScript (Node.js) – Try It Online") ### How? We use the `toJSON()` method to extract the minutes, seconds and milliseconds directly in the expected format. Such a date representation is always expressed as UTC, so we don't have to bother about the system time zone. ``` 1970-01-01T00:00:00.000Z \_______/ ``` Hours are formatted manually. Unless there's no complete hour and the field is not inserted at all, the leading colon in the above string is also included. [Answer] # JavaScript™, 161 bytes ``` t=n=>(f=parseInt,O='0',p=n<0?(n=-n,'-'):'',h=f(n/3600),m=f(n/60%60),s=(n%60).toFixed(3),n-n==0?p+(h?(h>9?h:O+h)+':':'')+(m>9?m:O+m)+':'+(s<10?O+s:s):'--:--.---') ``` I could save 13 bytes if I used `|0` to truncate `h` & `m`, but I think that would cause it to fail on very large numbers (e.g. `Number.MAX_SAFE_INTEGER/3600|0 === -1966140585`. Also, this is somewhat silly, but I *think* this could even work in an old ES3-only engine if the arrow function were swapped out for a normal one? (the other JS answer uses `.toJSON` which was added in ES5 I believe). ``` (n => ( // constants f = parseInt, O = '0', // variables p = n<0?(n=-n,'-'):'', h = f(n/3600), m = f(n/60%60), s = (n%60).toFixed(3), // return value n-n==0 ? p+(h?(h>9?h:O+h)+':':'')+(m>9?m:O+m)+':'+(s<10?O+s:s) : '--:--.---' ) ) ``` [Answer] # MATLAB, 114 bytes ``` function d(i),if~isfinite(i),'--:--.---',end,f='hh:mm:ss.SSS';if abs(i)<3600,f=f(4:12);end,i=seconds(i);i.Format=f ``` Using MATLAB's built in 'duration' class (and its derivative, seconds) I can convert the float input i to a duration and change the output format to the proper format for the challenge. If the input is nan or inf though, the duration will be displayed as nan or inf, so I hard-coded the exception string. TIO doesn't have MATLAB, but octave, and octave doesn't have the builtin 'seconds' class, so I can't show a TIO link. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 44 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` 3.òÄƵ/v60ym‰`}₄*ò)T‰J`₄+¦)…::..ι¬_·.$JIï'-Ãì ``` 05AB1E doesn't have `NaN` nor `Inf`. It can handle number-strings with leading 0s though, so I've added a test case to my test suite for it. Formatting takes about 2/3rd of the code, although can most likely be golfed a bit more.. [Try it online](https://tio.run/##yy9OTMpM/f/fWO/wpsMtx7bql5kZVOY@atiQUPuoqUXr8CbNECDHKwHI0T60TPNRwzIrKz29czsPrYk/tF1Pxcvz8Hp13cPNh9f8/69rbGZsZmCgZ2BgCAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeV/Y73Dmw63HNuqX2ZmUJn7qGFDQu2jphatw5s0Q4AcrwQgR/vQMs1HDcusrPT0zu08tCb@0HY9Fa/Kw@vVdQ83H17zX@d/tIGOkq6Bko6hjq6hjrGeoYmhqZGFjrGZgQGQAFMGegYGhjpKBgYGZkB1uoZGxiamZuYWlkBxSwtzM1MTYyNDHUNzS0tLPSC2jAUA). **Explanation:** Step 1: Get the individual hours, minutes, seconds, and milliseconds: ``` 3.ò # Round the (implicit) input by 3 decimals Ä # Take the absolute value of it Ƶ/ # Push compressed integer 210 v # Loop over its digits `y`: 60ym # Push 60 to the power `y` # (3600,60,1 in the three iterations respectively) ‰ # Divmod the top integer by this ` # Pop and push the quotient and remainder separately to the stack } # After the loop ₄* # Multiply the top (decimal) value by 1000 ò # (Banker's) round it to the nearest integer ) # Wrap all values on the stack into a list ``` [See this 05AB1E tip of mine (section *How to compress large integers?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `Ƶ/` is `210`. Step 2: Format and output them: ``` T‰ # Divmod all values in the list by 10 J # Then join the pairs together # (≥10 will remain unchanged; <10 will have a single leading 0) ` # Pop and push all values to the stack again ₄+ # Add 1000 to the top value ¦ # Remove the leading 1 # (to format numbers #/##/### to "00#"/"0##"/"###" respectively) ) # Wrap the stack back into a list …::. # Push string "::." .ι # Interleave the list with this as list [":",":","."] ¬ # Push the first item (without popping the list itself) _ # Check if it's 0; or technically "00" (1 if "00"; 0 otherwise) · # Double it .$ # Remove that many leading items from the list J # Join everything in the stack together I # Push the input again ï # Cast it to an integer (edge case "-0" becomes 0) '-à '# Only keep the potential "-" (or an empty string otherwise) ì # Prepend that to the string # (after which the result is output implicitly) ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 64 bytes ``` ≔∕⌊⁺·⁵×φNφθF‹θ⁰-≦↔θ⊞υ﹪%06.3f﹪θ⁶⁰F²«≧÷⁶⁰θ¿¬‹θι⊞υ﹪%02d⎇ιθ﹪θ⁶⁰»⪫⮌υ: ``` [Try it online!](https://tio.run/##ZY/dasJAEIWvzVMsC4VZ2IQYq2B7JYhgqRLEF4hm1yysu7o/gVL67NuRtLlxYG7mzHznzLlr3Nk2OqWV9@piYK161QrYaGsd1Dp6KIs5J0d1FR4kJ1tzi2EfryfhgGFxIrHv7D2T1hH4FN7DnZOSMVI7ZQLQnKK4a25/BquTtzoGMRzV0XcQOdnZNmoL9KVcFDNJxwGiFsj6x1eMfGeTEXZQly7A1oQh9WN3wE6UJLC3Ycyj2CPQk1nVotVRONO4L1B4@2SMsJ9s@OTDKgMH0QvnBUT8mr5R1FPKZ8X0dTpfVinv9S8 "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ≔∕⌊⁺·⁵×φNφθ ``` Input the number of seconds and round it to the nearest millisecond (rounding `0.5` to infinity). (Note that Charcoal only supports inputs of the form `-?\d+(.\d+)?`.) ``` F‹θ⁰- ``` If the number is negative then output a `-`. ``` ≦↔θ ``` Take the absolute value of the input. ``` ⊞υ﹪%06.3f﹪θ⁶⁰ ``` Take the seconds part of the value and format it to `6` zero-filled characters of which `3` are decimals. ``` F²« ``` Repeat for the minutes and the hours. ``` ≧÷⁶⁰θ ``` Floor divide the value by `60`. ``` ¿¬‹θι ``` If the value is not a zero number of hours, then... ``` ⊞υ﹪%02d⎇ιθ﹪θ⁶⁰ ``` ... format the minutes or hours as appropriate to `2` zero-filled characters. ``` »⪫⮌υ: ``` Correct the order of the parts of the time and join them with `:`s. I did try writing a Retina answer but implementing rounding was too arduous. Without rounding it took 135 bytes: [Try it online!](https://tio.run/##PU0xCsJAEOznG7eGu4Rd9owGuSaNIDb5QC5BRYU0KSSNiG@PlxRuMTPszOy@HtMwXueNPV1myeORwByYhZnBCkXf9tIVBMoEBFWFjZLGSQHy6C3XLt4XTRnlBtZ8ykr169LK@LAGbAoEV7vkVcnJrcldlKViykCyE8RbvLdBOihl86zLaw/2KMXv/H57wHIzwUrn8TmMw/QG/1VzbX4 "Retina 0.8.2 – Try It Online") Link includes test cases. [Answer] # [Python](https://www.python.org), 123 bytes ``` lambda x:'--:--.---'*(x*0!=x*0)or'-'*(x<0)+f'{(q:=abs(round(x,3)))/3600:02.0f}:'*(q>=3600)+f'{q//60%60:02.0f}:{q%60:06.3f}' ``` [Attempt This Online!](https://ato.pxeger.com/run?1=dY9NCsIwEEb3nkIXkkSddGo02mA9iZuIBAVNba1QKZ7ETUH0Tt7CI9jWH4LiIsm8N9_A5HTdHtJlZIuzCWeXfWpgfMvXejNf6GamCIAC4ABAOjTrYCssLxYlpOYJsq4hOY1VqOc7mkR7u6BZTzDGPCERFfY5mqMqs_E0rEydjz1PYlt-2nlcg-TCHMlrhfs2WdmUGoqMNd41uOC7DReQI7osuD_wh_2xq6pVnPEvFvJL-KMgCHh5AkcOa-MIs450SsnKGsJ-NfzxVttKP_9dFM_3AQ) ~~I don't believe Python has the concept of `Infinity` or `NaN`, so this function only accepts a floating point number.~~ TIL about `float('inf')` and `float('nan')`. ``` (x*0!=x*0) # If the input is infinite or NaN... '--:--.---'* # ...return the result filled with '-' or # Otherwise: '-'*(x<0) # Prefix with '-' if the input is negative q:=abs(round(x,3)) # Initialize q = abs(x) rounded to 3 decimals *(q>=3600) # If q >= 3600... +f'{q/3600:02.0f}:' # ...append q/3600, padded with 0s. Append ':' # Finally, append minutes (q//60%60) padded with 0s, a literal ':', # and seconds (q%60) padded with 0s and rounded to 3 decimal places +f'{q//60%60:02.0f}:{q%60:06.3f}' ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~200~~ ~~183~~ 175 bytes * -8 thanks to Juan Ignacio Díaz I round to the nearest millisecond before performing calculations to avoid incorrect displays around 3599.9995 seconds. To remove the hours part if not required and fix up spacing for negative values, I use positional formatting in `printf()`. ``` f(a,b,c,d)double a,b;{c=*(long*)&a<0;b=fabs(rint(a*1000)/1000);d=b<3600;printf(a*0?"--:--.---":"%5$0*4$.f:%0*.f:%06.3f"+d*10,c*d+2,fmod((d?a:b)/60,60),fmod(b,60),c+2,a/3600);} ``` [Try it online!](https://tio.run/##TVHLbqMwFN3zFRZtRjaxHUMKDXFo1cW0E2nEqptR1YUfOEUiUJVkVLXKr5e5JpnJLLg@j6sDBxu2MWYYHFZUU0Mtsd1eNxUCKj9NEeGmazcR@aZWQurCKd3jt7rdYRXFQggyG6e0hV7NMyHkqzchLBK3IWNLxjhjLFyGk/RSRFeX3C0nIhpnxucunFqIoSay04S6bWcxtrdqqcksEzQT5KjpERpYUTP/EiIPw0XdmmZvK7Tqd7bu@MtNcJa2avfileDCVq5uK/Tze/nw@AO/E9zXH1XnAM1OKHonJAjgo9FW1S3@3dWWoM8Aob//4em58BQhQRETnKIYTngEFwKOOY@v4jRZgL4QfiVeJCmPk3kGXprnPM/zFOT/sO/glSxJ6ZgcX@dHM/fmP9svnJLW5f26XD/@Av0My7sSOEx0kJDjO2gZAHLdG9aFkEivTs0VATKdHpshdLqlcOJQcYNCCi31M5GjB5d3Jq/7XY/DcGSH4DB8GdeoTT@wZvsH "C (gcc) – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), 162 bytes Building on [@ErickF's answer](https://codegolf.stackexchange.com/a/248174/112488), fixed the output for \$-0\$. ``` f(a,b,c)double a,b;{b=fabs(rint(a*1e3)/1e3);c=b<3600;printf(a*0?"--:--.---":"%5$0*4$.f:%0*.f:%06.3f"+c*10,a<0&c|2,fmod((c*a?a:b)/60,60),fmod(b,60),a<0|2,a/3600);} ``` [Try it online!](https://tio.run/##TVFbb5swFH7nVxzRZrIJdmwIrITQag@7RJp4qjRNUx9sg1tLXKJCpmpd/vqYTdJlDxx/l@Njf1iRR6WmSSMRylDhqj/IpgZL8ldZaCEH9Gy6EYmA1zFeuZKrQm7jlLF87yy7M2B3PiEbQighxN/4i@SaBetrqjcLFsw1pbH2lyrgLBRb9k79jkLd9hVCKhB3YiPxKmVhyvBJlTO0jbZNrNxROD9OV6ZTzaGqYTuMlenp0613kVoxPjnFu6pqbboavn4sP99/QS8Y0GB@1b12cAVnHLxg7Hn29tAK06GfvakwvHoAb/l/PBSOArAQCKMhcLvaj1HG7BJTvuZJFln9hrkWfhMllEdxar0ky2iWZYmV/8MuhlPSKAnnyfx9djIzZ/6zXcN50q78tCt399@tfoHlh9JyW@GY2zkug8w9i3T/jCQUwHKQsH37AQLnsFzKUzqA85P5Cx7RtYbiFvzQppUPOJ99@5oXsj@MA/L9mR294/RH6UY8DhNp2ol863pi2n1jlBn/Ag "C (gcc) – Try It Online") [Answer] # [Perl 5](https://www.perl.org/) `-MPOSIX=fmod -n`, 113 bytes ``` $_*=1;s/-//;$_=.001*int$_*1000+.5;printf$&.(($h=0|$_/3600)>10?"$h:":"0$h:"x!!$h)."%02d:%06.3f",$_/60%60,fmod$_,60 ``` [Try it online!](https://tio.run/##FY5NS8QwGITv/opsfOt@2CZvLA2koXr2sCh48VaK29JINilNigr@dmM7l2GGB2amfrZVStCeGqEDLzjX0DYMUZyMi2stEPGeVXqa1zzAHTscYGzwF1peSsTjo8AnCmNNa4qbfe92MB4ZzfDhUmcoWTnQfIUlZhLz4eov0OYSk9ah@9nvNQeuye3nEiLprPVfgVwXG81kexJn01ny0YU@EOOIdz2ZF5eKslKKKaVuSrldIJv@/BSNdyEV59eXt@f3ZltKxUqfK4YC/wE "Perl 5 – Try It Online") ]
[Question] [ You are probably familiar with the Cartesian product. It takes two lists and creates a list of all pairs that can be made from an element of the first and an element from the second: \$ \left[1,2\right] \times \left[3,4\right] = \left[(1,3),(1,4),(2,3),(2,4)\right] \$ Here the order of the result is such that the pairs whose first element is earlier in the first list come earlier in the result, and if the first elements come from the same element the pair whose second element comes first is earlier. Now we can also have a generalized Cartesian product which takes 3 arguments, two lists and a function to combine pairs. So for example if we wanted to find all ways to add an element of the first list to an element of the second list: \$ \mathrm{Cart} : \left((A,B) \rightarrow C, [A], [B]\right)\rightarrow[C]\\ \mathrm{Cart}\left(+,[1,2],[3,4]\right) = [4,5,5,6] \$ This is the same as taking the regular Cartesian product and then adding up each pair. Now with this generalized Cartesian product we are going to define the "product all the way down" \$ a\otimes b = \mathrm{Cart}\left(\otimes, a,b\right) \$ This recursive definition is a little bit mind bending. \$\otimes\$ takes a ragged list containing nothing but lists all the way down and combines each pair of elements using itself. Lets work through some examples. The simplest example is \$[\space]\otimes[\space]\$. Since the generalized Cartesian product of an empty list with anything is the empty list it doesn't matter that this is recursive the answer is just \$[\space]\otimes[\space] = [\space]\$. There are two elements to combine so there are no ways to combine two elements. The next example is \$[[\space]]\otimes[[\space]]\$, here we have some elements. The regular Cartesian product of these is \$[([\space],[\space])]\$, we already know how to combine \$[\space]\$ with \$[\space]\$ so we can do that. Our result is \$[[\space]]\$. Ok Let's do \$[[\space],[[\space]]]\otimes[[[\space]]]\$. First we take the Cartesian product, \$ [([\space],[[\space]]),([[\space]],[[\space]])] \$ Then we combine each with \$\otimes\$: \$ \begin{array}{ll} [[\space]\otimes[[\space]],&[[\space]]\otimes[[\space]]] \\ [[\space],&[[\space]]\otimes[[\space]]] \\ [[\space],&[[\space]\otimes[\space]]] \\ [[\space],&[[\space]]] \\ \end{array} \$ ## Task Your task is to take two finite-depth ragged lists and return their "product all the way down". Answers will be scored in bytes with the goal being to minimize the size of the source code. ## Test cases If you are having difficulty understanding please ask rather than try to infer the rules from test cases. ``` [] [] -> [] [[]] [[]] -> [[]] [[],[[]]] [[[]]] -> [[],[[]]] [[[[]]]] [] -> [] [[],[[]],[]] [[],[[]]] -> [[],[],[],[[]],[],[]] ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 17 bytes Anonymous infix lambda. ``` {0∊≢¨⍺⍵:⍬⋄,⍵∘.∇⍺} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///v9rgUUfXo85Fh1Y86t31qHer1aPeNY@6W3SAzEcdM/QedbQDxWv/pz1qm/Cob6pXsL@fxqPevkddzSB1vVsOrTd@1DYRKBMc5AwkQzw8gzUf9a4AaoWqRuH8V4@OVU8DEVzq0dGxYDaIAvN0QEyIEJgBEgSzkLWAFenAtUL1AAA "APL (Dyalog Unicode) – Try It Online") `{`…`}` "dfn"; left argument is `⍺` and right argument is `⍵`:  `0∊` Is zero a member of…  `≢¨` the length of each of…  `⍺⍵` the arguments?  `:⍬` If so, return the empty list.  `⋄` Otherwise,…  `,` ravel (flatten)…  `⍵∘.∇⍺` the Cartesian self-product of the reversed arguments. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 13 bytes ``` #0/@Tuples@#& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zg@1/ZQN8hpLQgJ7XYQVntf0BRZl5JtLKCrp1CWrRybKyCmoK@A5dCdXV1rY5CdW2tDpcCmAPiAUk4XwfCg8jBhaEcZI1ghTowAyDaamv/AwA "Wolfram Language (Mathematica) – Try It Online") Takes input as a list of two ragged lists. [Answer] # [Python](https://www.python.org), 42 bytes ``` f=lambda X,Y:[f(x,y)for x in X for y in Y] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3tdJscxJzk1ISFSJ0Iq2i0zQqdCo10_KLFCoUMvMUIhRAzEoQMzIWqqOqoCgzr0QjTSM6VkchOlZTkwsuEB0LEgKSqII6ICGwDIhGkQOLYDEHrEUHZp4OVCPEBTC3AwA) The obvious. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 4 bytes ``` λΠvx ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLOu86gdngiLCIiLCJbW1tdLFtbXV0sW11dLCBbW10sW1tdXV1dIl0=) Port of Jonathan Allan's Jelly answer. #### Explanation ``` λ # Start a lambda function Π # Cartesian product v # For each inner list: x # Do a recursive call ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~19~~ 11 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` "`â®δ.V"©.V ``` Input as a pair of ragged lists. [Try it online](https://tio.run/##yy9OTMpM/f9fKeHwokPrzm3RC1M6tFIv7P//6OjoWB0gBhJArADjxcYCAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeV/pYTDiw6tO7dFL0zp0Eq9sP86/6Ojo2N1FKJjgYQCiA3iAEkYVwfKAUvBRGHsaFRlOjDdEE2xsQA). **Explanation:** ``` "..." # Recursive string as defined below © # Store this string in variable `®` .V # Execute it as 05AB1E code, using the (implicit) input as argument # (after which the result is output implicitly) ` # Push both lists in the pair separated to the stack â # Take the cartesian product of these two lists δ # Map over each inner pair of lists: ® .V # Execute `®` as 05AB1E code, doing a recursive call ``` If only 05AB1E had a recursive function builtin.. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 34 bytes ``` ⊞υAFυ«≔⊟ιηF⊟ιFEη⟦κλ⟧«⊞ιλ⊞υλ»»⭆¹§υ⁰ ``` [Try it online!](https://tio.run/##NU4xCsMwDJztV2iUwIV27pQxQyHQMXgIaRubGjskdiiUvN2VHapB0t3pJI1mWMYwuJy7tBpMClo/p4hEV/kKC2Ai@ErRrKudPHZhRksKDKuiygdDUMFtmNEo6N8KnKZqFHWtZaJYxP9IRbvcZbdYH/EeuUzFflHQxNY/np8ydib@I@eeQ/PeXpesj/bAHPm0uR8 "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a list of two ragged lists. Explanation: ``` ⊞υA ``` Push the list of two ragged lists to the predefined empty list. ``` Fυ« ``` Loop over all the lists of ragged lists. ``` ≔⊟ιη ``` Remove the second ragged list from the list. ``` F⊟ιFEη⟦κλ⟧« ``` Remove the first ragged list from the list and loop over the Cartesian product of the lists. ``` ⊞ιλ⊞υλ ``` Push each new list of two ragged lists to the ragged list being processed and also to the predefined empty list so that it will be "recursively" processed. ``` »»⭆¹§υ⁰ ``` Pretty-print the resulting ragged list. (The default output for a ragged list is blank, so I don't have much choice here.) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 4 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` Œp߀ ``` A monadic link accepting a list of the two ragged lists that yields their product-all-the-way-down. **[Try it online!](https://tio.run/##y0rNyan8///opILD8x81rfl/uP3opIc7Z/z/Hx0dHasDxEAiNpZLB8aL5YoFAA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8///opILD8x81rfn/cPeWQ1sf7th0dFIYkHu4/eikhztnPNwx/1HjNh2HrEcNcxR07RQeNczVjPz/PzpWITqWKzo6FkgDCRBLB8QAcUEUUABMw5SBJXWgyiEqAQ) (The footer parses and reformats like the question for ease of comparison) ### How? ``` Œp߀ - Link, "f": list of lists (initially the two inputs), A: Œp - Cartesian product of A's items € - for each resulting list, a: ß - call this Link - i.e. f(a) ``` [Answer] # [Thunno](https://github.com/Thunno/Thunno), \$ 15 \log\_{256}(96) \approx \$ 12.35 bytes ``` Y"yzSeYxAv"AxAv ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72sJKM0Ly9_wYKlpSVpuhbrI5Uqq4JTIyscy5QcgQREFCq5YGd0dHSsDhADCSBWgPFiYyEKAA) Port of Kevin Cruijssen's 05AB1E answer. #### Explanation ``` Y"yzSeYxAv"AxAv # Implicit input Y # Store it in y for later "yzSeYxAv"Ax # Store the recursive string in x: yzS # Get the cartesian product of the elements of y e # Map: Y # Store the list in y xAv # And execute x as Thunno code Av # Execute x as Thunno code # Implicit output ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 28 bytes ``` f=->a,b{a.product(b).map &f} ``` [Try it online!](https://tio.run/##KypNqvz/P81W1y5RJ6k6Ua@gKD@lNLlEI0lTLzexQEEtrfZ/gUJadHSsTnRsLBeYCWTogAg4F8LTAcvExv4HAA "Ruby – Try It Online") Recursive by definition. [Answer] # JavaScript, 33 bytes ``` f=A=>B=>A.flatMap(a=>B.map(f(a))) ``` [Try it online!](https://tio.run/##TU7LDsIgELz3RyipEv0AmtS7X7DZwwbBR7A0hejn44JoetjZmckkMw96UTTrfUn7OVxszk5PejzpcVLOUzrT0hNr9WTiepJS5mRjMhRt1ACAO0A@@CI2vqHt/9g20FRLI3bxFt6a6wSIgWplceQgUHT/1upzyIQ5Bm@VD9caK/PggJLxiLIM/QA "JavaScript (Node.js) – Try It Online") Use as `f(A)(B)`, as permitted [here](https://codegolf.meta.stackexchange.com/a/8427/104752). [Answer] # [jq](https://stedolan.github.io/jq/), 24 bytes ``` def f:[combinations|f];f ``` [Try it online!](https://tio.run/##yyr8/z8lNU0hzSo6OT83KTMvsSQzP6@4Ji3WOu3//2guhehYHRDBFcsF4kTHgrlACi6gA@JBREEMmDiYA5REU6gDN0EHqhwA "jq – Try It Online") ]
[Question] [ ## Lexicographic Ordering For this challenge we will be talking about the lexicographic ordering of strings. If you know how to put words in alphabetical order you already understand the basic idea of lexicographic ordering. Lexicographic ordering is a way of ordering strings of characters. When comparing two strings lexicographically, you look at the first character of each string. If one of the strings is empty and has no first character that string is smaller. If the first characters are different then the string with the smaller first character is smaller. If the characters are equal we remove them from the strings and compare the rest of the strings Here is a Haskell program that implements this comparison ``` compare :: Ord a => [a] -> [a] -> Ordering compare [] [] = EQ compare [] (y : ys) = LT compare (x : xs) [] = GT compare (x : xs) (y : ys) = if x == y then compare xs ys else compare x y ``` Lexicograpic ordering has some interesting properties. Just like integers, every string has a next biggest string. For example after `[1,0,1,0]` there is `[1,0,1,0,0]`, and there is nothing in between. But unlike integers there are strings which have an infinite number of strings between each other. For example `[0]` and `[1]`, all strings of more than 1 `0` are greater than `[0]` but less than `[1]`. ## Challenge In this challenge you will write a program or function (from now on just called "function"), which maps binary strings (that is, strings made of an alphabet of two symbols) to ternary strings (strings made of an alphabet of three symbols). Your function should be *bijective*, meaning that every string gives a unique output, and every ternary string is the output for some input. Your function should also be *monotonic*, meaning that it preserves comparisons when applied $$ x < y \iff f(x) < f(y) $$ Where \$<\$ is the lexicographic ordering of the strings. ## Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so answers will be scored in bytes with fewer being better. ## IO You may take input and produce output as a string with chosen characters for the sets of 2 and 3 symbols, or as a list / array / vector of integers. ## Testing It's rather hard to make test cases for this. However it should be noted that when given a string of only `0`s your code must give back the same string. So I can give the following test cases ``` [] -> [] [0] -> [0] [0, 0, 0] -> [0, 0, 0] ``` However this doesn't go very far in terms of testing. So I recommend you also run a random battery of strings checking that * The monotonicity property holds * Your function preserves the number of `0`s on the end [Answer] # [Haskell](https://www.haskell.org/), 41 bytes ``` f x|sum x<1=x f(0:y:x)=y:f x f(1:x)=2:f x ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P02hoqa4NFehwsbQtoIrTcPAqtKqQtO20gooAeQagjhGIM7/3MTMPAVbhZR8LgWF3MQC33gFjYKizLwSBT2FNE2gmIJCtEJ0LJihoxBtgGDpACEqDwoNwRDCwlRhiCaCykfmIdhILBQ1YJtQeFD7UVWg2WOIcCGGmCFWMaje2P8A "Haskell – Try It Online") Here's a solution. Just to show that this is possible and give a potential starting point for others. ## Explanation The first thing we can notice is that any valid \$f\$ must preserve the number of zeros at the end of the input in the output. The proof of this is pretty simple. Lets say we have some string \$x\$. We know that there are no strings between \$x\$ and \$x\mathbin{|}0\$ (here \$\mathbin{|}\$ represents appending a character to a string). Thus there can be no strings between \$f(x)\$ and \$f(x\mathbin{|}0)\$. If there were some string \$y\$ such that \$f(x) < f(y) < f(x\mathbin{|}0)\$, then it would have to be that \$x < y < x \mathbin{|} 0\$. So since there are no strings between \$f(x)\$ and \$f(x\mathbin{|}0)\$, then \$f(x\mathbin{|}0) = f(x)\mathbin{|}0\$. So this allows us to write the first line of our program ``` f x|sum x<1=x ``` Which says if we get a list of only \$0\$s then output that list intact. It might be tempting to say that *all* zeros should be preserved in the output, not just trailing ones. However this ends up not being possible, I will leave the proof of this as an exercise for the reader. Now the task is to translate strings with no trailing zeros, while preserving order. The way I chose to do this is pretty simple. We go left to right replacing certain sequences with the correct symbols. If we see a zero we replace read it as the next symbol (and skip over that symbol), there must be a next symbol since otherwise there would be a trailing \$0\$. ``` f(0:y:x)=y:f x ``` If the symbol is \$1\$ we read it as \$2\$. ``` f(1:x)=2:f x ``` # [Haskell](https://www.haskell.org/), ~~52~~ 48 bytes *4 bytes saved by ovs* ``` f(0:x)=0:f x f(1:x)|sum x>0,z:y<-x=1+z:f y f x=x ``` [Try it online!](https://tio.run/##bY5BCsIwFET3OcUsU4ySvy3GG3iCUKSgwWJTi62QFu8eQw20aWU28yYT5t/L7nGra@8Nl7nLlMwNHDOcAny6t4U7STHmw3HvFO3G8Dqw0FDO27JqoHB9MsCW7fkC3r6qpscBJgsZoKGLyQhoOTsRlFIUTfq5bYNWScpLmv3CJZ1pKaG4nzZWOzRfuMnobxb/Fv4L "Haskell – Try It Online") This is a different bijection discovered by a friend of mine and golfed by me. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 10 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` 2ḢḢ?;ßƊ¹Ẹ? ``` A monadic Link that accepts a list (of \$\{0,1\}\$) and yields a list (of \$\{0,1,2\}\$). **[Try it online!](https://tio.run/##y0rNyan8/9/o4Y5FQGRvfXj@sa5DOx/u2mH/303ncPvRSQ93znjUtCbrUeM@KwXNyP//o6NjuXSiDcCEDhDCGVBoCIYQFoqkIYIDZ0IZYApCwATBxsAYUHPh4ghDDBH2IXMN0blAxbEA "Jelly – Try It Online")** ### How? Results in the same mapping as used by [Wheat Wizard](https://codegolf.stackexchange.com/a/229394/53748). ``` 2ḢḢ?;ßƊ¹Ẹ? - Link: list, A Ẹ? - if: any? Ɗ - then: last three links as a monad - f(A): Ḣ? - if: head (leftmost element of A (or 0 if empty); changes A in place) 2 - then: literal two Ḣ - else: head (leftmost element of augmented A (or 0 if empty); changes A in place again) ß - call this Link again -> f(augmented A) ; - concatenate ¹ - else: identity (yield A) ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 34 bytes ``` s=>s.replace(/0(?=.*2)./g,t=>t/2); ``` [Try it online!](https://tio.run/##LYxBDsIgEEX3nMJdQRHIrEwMdecFPEBDKDQ1WFqgJp4eoe3M/P8yk595q6@KOoxzuk6@N9nKHGUbWTCzU9pgLvBDsjMQxgeaZJs4kHsOZlnHYHBjY0NKVvXP0ZnXb9JY0GZN9radjxfswj8D7WSr/RS9M8z5AXf0ZHFHCMkCiTqbSgFAsX0DdFgRoNLVoarm0B6tKNwAB@AP "JavaScript (Node.js) – Try It Online") Wheat Wizard♦'s idea using the allowance of custom char [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 20 bytes ``` /0*$/%`1(.) $.($1*__ ``` [Try it online!](https://tio.run/##K0otycxLNPz/X99AS0VfNcFQQ0@TS0VPQ8VQKz7@/38DQwNDQ0MDAwA "Retina – Try It Online") Explanation: Uses @WheatWizard's friend's mapping. ``` /0*$/%` ``` Match trailing zeros and temporarily exclude them from the following substitution. ``` 1(.) $.($1*__ ``` Match a `1` followed by a digit and replace it with 1 more than the digit, i.e. `11` becomes `2`, `10` (in the middle) becomes `1`, but other digits are unaffected. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 20 bytes ``` ≔I⪪⮌S¹υWΣυ¿⊟υ2I⊟υFυ0 ``` [Try it online!](https://tio.run/##NYw7CsMwEAX7nGJxtQsJSGldhVTpjHUCYda2QJGEPs7xFdnYzTA8hjetOk5e21pfKZnF4VunjCpYk3HkjWNi/LhQssrRuAWJ7iB3FOpvv9VYBlTli4UIzAw4@HD40OqM3bOjHtgmPofj/WzawewjNL1q0epahRBSNtTHZv8 "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Uses @WheatWizard's mapping. ``` ≔I⪪⮌S¹υ ``` Reverse the input, split it into digits, and cast the digits to integer. ``` WΣυ ``` Repeat while there are still `1`s left in the input... ``` ¿⊟υ2 ``` ... if the current digit is a `1` then print a `2`... ``` I⊟υ ``` ... otherwise print the next digit. ``` Fυ0 ``` Print any trailing zeros. ]
[Question] [ A challenge many developers face when drawing a graph from scratch to plot some data is generating its ticks. In below graph, there are 6 horizontal ticks (1750, 1800, 1830, 1860, 1880 and 1900) and 11 vertical ticks (0, 10, 20, 30, 40, 50, 60, 70, 80, 90 and 100). [![Relative share of world manufacturing output](https://i.stack.imgur.com/dVOLe.png)](https://i.stack.imgur.com/dVOLe.png) The horizontal bounds of the above graph goes from 1750 to 1900, which we'll call \$x\_{min}\$ and \$x\_{max}\$, respectively. For any \$x\_{min}\$ and \$x\_{max}\$ values, using \$n\$ ticks, there is a minimum multiple \$m\$ of a value \$s\$ that satisfies the following: 1. \$m \geq x\_{min}\$ 2. \$(m + s \times (n - 1)) \leq x\_{max}\$; and 3. \$(m + s \times n) \gt x\_{max}\$. Let's suppose \$x\_{min} = 0\$, \$x\_{max} = 19\$ and \$n=4\$. * Consider \$s=4\$. The minimum multiple of \$s\$ that is greater or equal than \$x\_{min}\$ is 0, therefore \$m=0\$. While the second condition is satisfied (\$0 + 4 \times 3 = 12 \leq x\_{max}\$), the third condition is not (\$0 + 4 \times 4 = 16 \not \gt x\_{max}\$). * Consider \$s=5\$. The minimum multiple of \$s\$ that is greater or equal than \$x\_{min}\$ is 0, therefore \$m=0\$. Both the second (\$0 + 5 \times 3 = 15 \leq x\_{max}\$) and the third (\$0 + 5 \times 4 = 20 \gt x\_{max}\$) conditions are satisfied, therefore \$s=5\$. Note that we need to minimize \$s\$: \$s=6\$ also satisfies all of the conditions, but we'll use \$s=5\$. In addition, since there could be more than one multiple of \$s\$ that satisfies all three conditions, we want also to minimize \$m\$ of the minimum found \$s\$. Finding \$s\$ allows us to create \$n\$ equally-spaced ticks that can be used for our graph. The sequence goes from \$m\$ to \$m + s \times (n - 1)\$ with step \$s\$, so using \$s=5\$ as in the previous example, the generated ticks are \$\{0, 5, 10, 15\}\$. These ticks also gives the impression that our graph is sliding if we scale those properly, since they will only change if \$x\_{min}\$ is a multiple of \$s\$. Below a gif that illustrates the generated ticks for \$(x\_{min}, x\_{max})\$ going from (0, 19) to (10, 29), with \$n=4\$. [![gif](https://i.stack.imgur.com/F4um7.gif)](https://i.stack.imgur.com/F4um7.gif) Another way of thinking about this problem is generating the ticks beforehand. Let's suppose \$x\_{min} = 4\$, \$x\_{max} = 21\$ and \$n=3\$. * Consider \$s=5\$. This would generate the ticks \$\{5, 10, 15\}\$ and the next tick would be 20, which is not greater than \$x\_{max}\$ (breaking the third condition). Note that here, \$m=5\$ since it's the first multiple \$m\$ of \$s\$ such that \$m \geq x\_{min}\$. * Consider \$s=6\$. This would generate the ticks \$\{6, 12, 18\}\$ and the next tick would be 24, which is greater than \$x\_{max}\$ (satisfying all conditions). We could also use \$s = 7\$, but we want to minimize this value. ## Input * Two real numbers `min` and `max` representing the minimum and the maximum values of a range, where `max` is greater than `min`; and one positive integer (`num`) representing the number of ticks. The input is guaranteed to generate an integer `s`, so you should not handle `min = 0`, `max = 4`, and `num = 3` for example. ## Output * A sequence of equally-spaced numbers with length `num` representing the ticks of a graph based on the previous explanation. ## Test cases ``` # from gif 0, 19, 4 -> [0, 5, 10, 15] 1, 20, 4 -> [5, 10, 15, 20] 2, 21, 4 -> [5, 10, 15, 20] 3, 22, 4 -> [5, 10, 15, 20] 4, 23, 4 -> [5, 10, 15, 20] 5, 24, 4 -> [5, 10, 15, 20] 6, 25, 4 -> [10, 15, 20, 25] 7, 26, 4 -> [10, 15, 20, 25] 8, 27, 4 -> [10, 15, 20, 25] 9, 28, 4 -> [10, 15, 20, 25] 10, 29, 4 -> [10, 15, 20, 25] 11, 30, 4 -> [15, 20, 25, 30] # m can be negative -10, 1, 3 -> [-8, -4, 0] -9, 2, 3 -> [-8, -4, 0] -8, 3, 3 -> [-8, -4, 0] -7, 4, 3 -> [-4, 0, 4] -6, 5, 3 -> [-4, 0, 4] -5, 6, 3 -> [-4, 0, 4] -4, 7, 3 -> [-4, 0, 4] -3, 8, 3 -> [0, 4, 8] -2, 9, 3 -> [0, 4, 8] -1, 10, 3 -> [0, 4, 8] # num can be 1 0, 3, 1 -> [0] 1, 4, 1 -> [3] 2, 5, 1 -> [3] 3, 6, 1 -> [4] 4, 7, 1 -> [6] 5, 8, 1 -> [6] 6, 9, 1 -> [8] 7, 10, 1 -> [9] 8, 11, 1 -> [9] 9, 12, 1 -> [12] ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins. [Default I/O methods](https://codegolf.meta.stackexchange.com/q/2447/91472) apply. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 41 bytes ``` NθNηNζ≔¹ε≔…·⌈θηδW⁻Lδζ«≦⊕ε≔…·⌈∕θε∕ηεδ»I×δε ``` [Try it online!](https://tio.run/##fY0/C8IwEEdn8yk6XkAHobo4iS4FKyJ@gdgcyUF62iatUPGzx/gHFAeHGx73473KqrY6KRdjwecubLv6iC00ciG@2f7wkHjpPRmG6TjDDxVcuc5Tj3vFBmGF5IhN8o0zm06n5cWSwwxK4s7DBtkECzr9BimzqxiV6vxxtVgjB9Svxuh/ZE09aYTmMU6@N9o3PtI3sWuJA6yUD3CgGj081VIuYpzOxSwXeZz07g4 "Charcoal – Try It Online") Link is to verbose version of code. Explanation: I tried and failed to find some sort of formula, so brute force it is. ``` NθNηNζ ``` Input the minimum, maximum and ticks. ``` ≔¹ε≔…·⌈θηδ ``` Start with a step of 1 and ticks from the ceiling of the minimum to (the floor of) the maximum. ``` W⁻Lδζ« ``` Repeat until we get the desired number of ticks. ``` ≦⊕ε ``` Increment the step. ``` ≔…·⌈∕θε∕ηεδ ``` Divide the ends by the new step size and list the integers in that range. ``` »I×δε ``` Multiply those by the step to get the desired output. [Answer] # [J](http://jsoftware.com/), 30 28 38 bytes ``` 1 :'](]*i.@u+>.@%),(]+0 0-:|~)u>.@%~-' ``` [Try it online!](https://tio.run/##fZPNaoNAGEX3eYpLoajNKM6PPyOkhBa6Kl10LyENpk2h6abpquTV7Yx@MyLILEQ494z63Rk/@5ssOmLTIAJDjsZcaYbH1@ennqOJ2ri9O2Xby/o@294mLG7XOfK0@bsmF0uuadQnq@7w8Y04ZygYuLnxIkHagGvECsfEPJIUnzOIfHBETg4POJwcEXAEOTLgSHJUwFHkFM6ZBHONg4mCpDIklSRVIakiqQ5JNUk6JLmyuW97MhjkOJ70dZu@Vy8PGfCFw/6Mtw7n7n3/c/rtaPWuZtgpcybGvUQs7brd9Pi5IJygl3Ppcj/pkDGoIVYurhbjwsXlYly6uFiMKxf7jbcRQz2ktUvlUqpdKpZS04brhfo8X3yh3C1IsLHz89m/IC1VRPmMFkT9K5WlJVH/maWlFVE1ozVR30dtqSbqS9SW2hn47KCOmBOejqYYuCCu0f8D "J – Try It Online") This is a J adverb modifing `n`, the number of ticks, and taking the max and min as left and right args, respectively. Called like: ``` 19 (4 f) 0 ``` * `u>.@%~-` Calculates step size by dividing `n` into the difference between the max and min. + `,(]+0 0-:|~)` Adds one to the step size if the step size evenly divides both endpoints. * `]*` The step size times... + `i.@u` Produces range `0..n-1` + `+` Add elementwise to... + `>.@%` The ceiling of `>.@` the min divided by the step size `%` -- adjusts so the first tick starts where we want. [Answer] # [R](https://www.r-project.org/), ~~45~~ ~~69~~ 59 bytes *Edit: ~~+24~~ +14 bytes to fix bug pointed-out by Neil & ophact* ``` function(l,h,n){while((t=-l%/%T+1)+h%/%T-n)T=T+1 T*(1:n-t)} ``` [Try it online!](https://tio.run/##jVNNT4MwGL7zK5qYZeDaSD8oxWQmXj142k13QMIGkXXJZHow/nZ8i9DVbFIvZM/HHt4@vD10bV28vi27zVEXbb3XYYMrrKPPj6puyjBsl6SZ3cxWCxotKvOD6Gi1BBisrkN6q0kbfXVXaHPY79BjWTdBHxcKjFiMkYjQFSJ36CnBiAKmieHXg4mmGCWJ42ICc4ZFjIVaB0XehvNnPY@CIf5hr/O2yjW6b5pc24zE5GYxPOWYQ9OUYppmAlMFL6EKIqmSHB5KXkje1pshrs9yJgJsR7dj/@dsDAD1mTgA5jOZKrnPZIDwmSQAt@6TwwijCz4Kk16XApB6XVAlU16XYVnmt0Gf3C3@ZDHC7@@6QwVsykuJdLnN2/q9HEJInw3@MYTAfASqsy0RM/SkAQg@aTDFuAYjAmV12W/V3zqIckoHnE7pMJ1y9LgfR1kZTpdNyPRnd851t199tA3T092BF1P7N@e@CIfnzhVJLvG8P73lhXMRUoeXzu6rS7zsj2l55Sx4vwSjkDk7bXbsXDAxzBEoW3ff "R – Try It Online") **Ungolfed version** ``` ticks= function(l,h,n){ # l=low, h=high, n=n ticks d=1:(h-l+1) # d=range of possible values of s to try s=match(n,(floor(h/d)-ceiling(l/d)+1)) # calculate s by trying each value of d # until floor(h/d)-ceiling(l/d)+1 is equal to n # (golfed: match(n,h%/%d+-l%/%d+1)) a=ceiling(l/s)*s # calculate a=start value (golfed: --l%/%s*s) return(a+(1:n-1)*s) # output ticks (golfed: s*(1:n-1--l%/%s)) } ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 13 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` r/ḍ@ƇⱮJ$L⁼¥ƇḢ ``` A dyadic Link accepting a pair of numbers, `[xmin, xmax]`, on the left and an integer, `n`, on the right that yields a list of ticks. **[Try it online!](https://tio.run/##ATAAz/9qZWxsef//ci/huI1Axofisa5KJEzigbzCpcaH4bii////WzE3NTAsIDE5MDBd/zY "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##TdCxysIwFAXgV8ngWLE3bdN0EWfxBSR0dBEnNzf9FycXJwddBHERwU3BSdH3aF8knlhz80Mh/QjhnHvHo8lkZu20U11Xvfeyvpz7rUG9uD8O72V13dvX/Xns1H@n17q6bXDiG7tjvhXtrqjnu6G1xpg4ElSUkUhLERlDkZAxS0LESiDJSqGElUEpS0EZK4cUS0M5q4B0SEcZ@a8M2iShTdtduzpJQ/c2SLs/Vu4esdAnC0JXFYQ58iDMqIMwfxGENhQz4yaP/NpShmzSyC9NMX5Z5FemGapJIr@wbxD5hRGxMDTJr8oP "Jelly – Try It Online"). ### How? ``` r/ḍ@ƇⱮJ$L⁼¥ƇḢ - Link: list, bounds; integer, n: / - reduce (bounds) with: r - inclusive range -> [xmin..xmax] $ - last two links as a monad - f([xmin..xmax]): J - range of length -> [1..(xmax-xmin)+1] Ɱ - map across that with: Ƈ - filter keep those for which: @ - with swapped arguments: ḍ - divides? Ƈ - filter keep those for which: ¥ - last two links as a dyad - f(potential tick list, n): L - length (potential tick list) ⁼ - equals (n)? Ḣ - head ``` [Answer] # [Haskell](https://www.haskell.org/), 63 bytes ``` (x#y)n=[[i|i<-[x..y],mod i s<1]|s<-[1..],div y s+div(-x)s<n]!!0 ``` [Try it online!](https://tio.run/##dZJNboMwEIX3nMJJIwUUQzH/VJAT9AbICyRQa5U4UUAVRLk7HQ@FVA1ePb/vGWbs8WfZftVNM45m/zJYMi8KcReZXfSOM3B6OldEkDZj/N4CZI7DaSW@yUDaA6hp91abSb7ZuOOpFDKvzgYxBT1bmd1eSmm@5vvj3sp2x4@6exeyNkhTd0VPByp5fq3Larcv9m9Cio6Iw2HLt7iB3KasK0VD4I@Xq5Cd@dtgfqP4Pb1ZBlFFR5cSllISEPtICjAheMVCbjBKPHeOFq4gNzwQpsl8EE@TBSC@JlMSaLIIJJyzR6AoN2KQSBcmILEuhJN7iS5U3ku1KRzfX67nkSjKDRu3wxpTG2rYcDQVqJJrHJb@Gle9L1wx8IAjHNUTBhatYFjFKxgKJjN2sU4CFNpLnymbBvIPu9g1myA@mWC2Pr6S8I/1sbnJBvgW4tlGOP7kj42wi8kmOGO8UvQpjlVNYPFqrzd75vEf "Haskell – Try It Online") The function `(#)` takes the minimum value `x`, the maximum value `y` and the number of ticks `n`. ## How? The problem is equivalent to finding $$ \min\left\{s\ge 1:\left\lfloor\frac{x\_{\text{max}}}{s}\right\rfloor-\left\lceil\frac{x\_{\text{min}}}{s}\right\rceil=n-1\right\}. $$ Since we are guaranteed that an answer exists, it is sufficient to find $$ \min\left\{s\ge 1:\left\lfloor\frac{x\_{\text{max}}}{s}\right\rfloor-\left\lceil\frac{x\_{\text{min}}}{s}\right\rceil<n\right\}. $$ [Answer] # JavaScript, ~~99~~ 97 bytes ``` (a,b,n)=>(g=s=>(x=s*Math.ceil(a/s))+s*(n-1)<=b&x+s*n>b?[...Array(n)].map((_,i)=>x+s*i):g(s+1))(0) ``` I will golf this later; could not find a suitable replacement for `Math.ceil`. *-2 bytes thanks to my own golfing efforts.* # Explanation. This is an implementation which simply follows what is asked in the question. The function is recursive and will call itself with `s+1` if the conditions are not satisfied. ## commented ``` (a,b,n) // declare parameters: input a, b, n => // start of arrow function expression (g= // assign function expression to g s=> // declare parameters: s (x= // assignment expression: assign value to identifier x s*Math.ceil(a/s)) // s multiplied by ceiling of a over s +s*(n-1)<=b // speaks for itself & // bitwise and (saves one byte) x+s*n>b // speaks for itself ? // if above conditions satisfied, return [...Array(n)].map((_,i)=>x+s*i) // array of n elements each filled in with x + s times i : // otherwise return g(s+1) // call with s+1 ) // closing bracket (0) // IIFE: initial call with s=0. ``` And "fun fact": when s is 0, we get `NaN` (`Infinity * 0`) as the value for `x`, which makes it quietly fail. However, this is not noticed as the function increments `s` due to unsatisfied conditions. ]
[Question] [ **Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers. --- Questions without an **objective primary winning criterion** are off-topic, as they make it impossible to indisputably decide which entry should win. Closed 2 years ago. [Improve this question](/posts/222560/edit) This is a challenge I thought of recently which I think is not hard but allows for a wide range of possible solutions. Seems like a perfect fit for the creativity of PPCG users :) ## Your Task Define two functions which together form a lossless round-trip `String × String → String → String × String`. More specifically, define two functions `combine` and `separate` with repsective types `String × String → String` and `String → String × String` such that `separate ∘ combine = id`. Even more specifically, define two functions (or methods/procedures/etc), which I will refer to as `combine` and `separate`, and which exhibit the following characteristics: * When invoked with a single string, `separate` produces two strings as results. (You may use any reasonable string type. Most languages don't canonically allow producing multiple values, so feel free to to do something equivalent, such as returning a 2-tuple or modifying two global variables.) * When invoked with two strings, `combine` produces a single string as result. (You may accept input to `separate` in the same form that `combine` produces, or any other reasonable form.) * For any two strings `a` and `b`, `separate(combine(a, b))` must result in two strings which are (structurally) equivalent to `a` and `b`. * The above bullets are the *only* restrictions on `combine` and `separate`. So, for instance, `combine ∘ separate` need not be `id`, and `separate` can even be a partial function, if you like. (Defer to the final and more-verbose description if there are any ambiguities between the three) ## Intent My goal with this challenge is to inspire creative and interesting solutions. As such, in order to avoid priming/suggesting your thinking about how to solve this problem, I will not be providing test cases, and I **strongly** suggest that you do not look at the existing answers until you submit your own. ## Winning Criteria This challenge is a [popularity-contest](/questions/tagged/popularity-contest "show questions tagged 'popularity-contest'"); the answer with the highest score at noon on April 5th, UTC, is the winner. Guidelines for voters, included to be a valid [popularity-contest](/questions/tagged/popularity-contest "show questions tagged 'popularity-contest'"), are as follows: * Strongly prefer answers which you do not immediately comprehend, are not obviously correct, and/or surprise you * Prefer answers which go beyond strings, i.e., those which make use of more than the problem statement did (functions, strings, pairs) * Avoid answers which are similar to your own solution(s) * Avoid answers which boil down to language builtins --- Have fun! [Answer] I know this is extra credit, but your problem got me thinking a lot about this and what interested me the most was not just `separate` being the left inverse of `combine`, but having them be true inverses of each other. This ends up with us defining a bijection from `String -> String x String`. The path I took was as follows * Define a bijection from `String -> N` * Define a bijection from `N -> N x N` * Combine them to get the functions we need ### String -> N Let `r` be the size of the character set you're working with and give each character a unique value from 1 to `r`, say `f(c) = n`. Going from right to left and indexing starting from zero, create the number `f(s[0])r^0 + f(s[1])r^1 + f(s[2])r^2 ... f(s[length(s)])r^(length(s))`. The lowest number you can get this way is 1, so we let the empty string equal 0. ### N -> N x N Take `n` in any base you like. Separate even digits into one part of the tuple and the odd digits into the other to make a pair of numbers. E.g. `12345 -> (24, 135)`. To work your way back, combine the numbers in the opposite way, inserting extra zeros as necessary. ### Putting it all together # [Haskell](https://www.haskell.org/) ``` module Main where import Data.Function ((&)) -- tio is saying this isn't correct for some reason so gotta define it manually -- import Data.Functor ((<&>)) main :: IO () main = do putStrLn $ show $ separate "Hello, world!" putStrLn $ combine ("Hello, world!", "") putStrLn $ show $ separate $ combine ("Hello, world!", "") putStrLn $ combine $ separate "Hello, world!" separate :: String -> (String, String) separate str = str <&> toInt & fromNZ & split & tmap toNZ & tmap (map fromInt) combine :: (String, String) -> String combine strs = strs & tmap (map toInt) & tmap fromNZ & join & toNZ <&> fromInt base :: Int base = 95 toInt :: Char -> Int toInt c = fromEnum c - 31 fromInt :: Int -> Char fromInt i = toEnum $ i + 31 strip :: [Int] -> [Int] strip is = case is of 0 : i : tail -> strip $ i : tail _ -> is split :: [Int] -> ([Int], [Int]) split = tmap strip . fst . foldr (\a ((acc1, acc0), i) -> (if mod i 2 == 0 then (acc1, a : acc0) else (a : acc1, acc0) , i + 1 ) ) (([], []), 0) join :: ([Int], [Int]) -> [Int] join (l1, l2)= strip $ reverse $ go [] (reverse l1, reverse l2) where go :: [Int] -> ([Int], [Int]) -> [Int] go acc (l1', l2') = case (l1', l2') of (head1 : tail1, head2 : tail2) -> head2 : head1 : go acc (tail1, tail2) ([], head : tail) -> head : 0 : go acc ([], tail) (head : tail, []) -> 0 : head : go acc (tail, []) ([], []) -> acc tmap :: (a -> b) -> (a, a) -> (b, b) tmap f (a1, a2) = (f a1, f a2) fromNZ :: [Int] -> [Int] fromNZ is = if is == [] then [0] else let (result, finalCarry) = foldr (\i' (acc, carry) -> let i = if carry then i' + 1 else i' in if i >= base then (i - base : acc, True) else (i : acc, False) ) ([], False) is in if finalCarry then 1 : result else result toNZ :: [Int] -> [Int] toNZ is = if is == [0] then [] else let (result, finalUncarry) = foldr (\i' (acc, uncarry) -> let i = if uncarry then i' - 1 else i' in if i <= 0 then (i + base : acc, True) else (i : acc, False) ) ([], False) is in if finalUncarry then case result of a : tail -> if a == base then tail else result _ -> result else result m <&> f = f <$> m infixl 1 <&> ``` [Try it online!](https://tio.run/##vVVNbxw3DL3rVzCG4dXAs8Z6gx5qeHxxGzRAkx6aXOIahTyr8SqdkRaSto5/vUNSmo9d223iQ@YwI5KP5BNJadYq/KPb9uGhc6ttq@GdMhbu1tprIUy3cT7CLyqqkzdbW0fjLEh5VBRiPgeUwAQI6t7YW4hrXJtgZxFq572uIzTOQ3CdBq9VQM/g4NbFqGClG2M1mAidslvVtvcU71E2dJfy/OgC04mOaJ2dwds/QBZJqmDlBMBmG/@M/ncLhxDW7o4@eqO8ihoOfsOduRLunG9Xrw52wbXrboiF3EOVcHBQ/Hfc73Luoc/zAiEGE24RHamg8wuQaVlmVTHCQvRQYR784htrBNG9tRHXR9B4173/xMuwaU1Sxk5tEJP1LEl6ERgdscI9T2Swn5e4pOWAwsShZxD2YjKVYlROCH12xiZDokLMMwUhblTg9CTwuoKffxKCw5H@cq08USF7UtYIIfdf7bZDYQ6vT4XI8XIkciDHQW3QJzr2OEThmH1wF2ZDHlcIuSYfXmQ9TnYFNTHClWuQ9wLO0PcMojItoRPucNAh5G/Sm4CxqQk7sSWvyqQoMoCKyeVKsU6gCZHerl1RjwHkXwrPg6rr0xLwvShKMNQaNqLZNIBnGCksoaqQYVxrm21ozX7Ij32zQbdBTzDJ2sfPhpKrdJqlpE1vKa9oF9fIBNGCmsvjs7O9sZhsly2Gb5dFNdTM63@1D3RAbh0GA9krCDmsl5Qy3UuUGqHPV3RMmaG4HUo8o8yzom/mRMNN5S2ttVqd5i5ifhKXWVxy4F7TA/vw2SEB@2hUHwLmCEMAlBcTX4Kxfcoi@3CByW@Rk@7lZPs0X4YTAg8PTRT1RJHuhi1SYYPT6qZEXQI1qKfOL6k@sgESGhLTiXr/6YnjkQ0mXQU4gLSqqIk0fHC1oA7QjEGrYxoZr8O2jRjaWNVeKu/vC3amZ5z1NO9mxnNbYrsYN8w6PX3E/jFDmEHTJMdEBoONU9w/zM3MJlpjxV4MAxcV8H3EcaTBeyZdVcDkPvitLsSjqNL0gDcK5RExrrhde1ZDt2kmgcnHMqXsNHGphGLIlGVBd@oTTWL1oxYt@h79T4s@2vobm7S1L25Tdh0aNX9ho877e4@qf/yDu/RxsokM5GsmlXO8YoBv4fznEDs7UNSacdTyn2SH8KT59PBf5rmB6NL/lX6ScH54AZ0wtjFfWpwiNDw8fAU "Haskell – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal) Simply lists the code points in both strings. Within each string, code points are delimited with commas, and the two strings's code points are separated with a semicolon. The only gotcha is to ensure that empty strings decode to empty strings. ## Combine ``` ⪫E²⪫ES℅λ,¦; ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMMrPzNPwzexQMNIRwHO9swrKC0JLgEqSNfQ1FHwL0rJzEvM0cjRBHKUdJTAlDWQsv7/Pzk/NykzL5WrOLUgsSixJPW/blkOAA "Charcoal – Try It Online") Link is to verbose version of code. ## Separate ``` E⪪S;∧ι⭆⪪ι,℅Iλ ``` [Try it online!](https://tio.run/##RYzBCsIwDIZfZfSUQYRFnFp6kp08CMKeoFTRQulKjb5@TN3BHPLxfwl/ePoaFp9ErjVmhosvMJcUGc65vHlmtQ/osTPO6D7lG0TsVv3/VWWw3Set84HvFSb/Ykj9b5yItUhESINFe1SMGgclOaKxUfMW7UGxW7FvVjaf9AU "Charcoal – Try It Online") Link is to verbose version of code. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal) Works by prefixing each character of the first string with a comma, suffixing each character of the second string with a comma, and then joining the strings with a semicolon. This simplifies decoding as there are an equal number of commas and original characters. There is a slight Charcoal gotcha in that it can't chop a zero-length string, so to obtains the first string the decoder chops the original string at the semicolon before stripping the commas (still one byte shorter than slicing though), while for the second string it can strip the commas first and then slice from where the semicolon used to be. ## Combine ``` ⪫E²⭆S⎇ι⁺λ,⁺,λ; ``` [Try it online!](https://tio.run/##LchBCgIxDIXhvacIXSUQN27nBArCgF4glqKFmpZMR/D0scP4Vu/740ssVinus2XteKlZ8SoNTwy3PtJzw1nb2nciMdyTqdgXM8Nc1gULQ@BAf43LUGhs5CkQTe6xvh9Z02FJTUx68uOn/AA "Charcoal – Try It Online") Link is to verbose version of code. ## Separate ``` ≔⌕Φθ¬﹪κ²;η⟦Φ…θ⊗η﹪κ²✂Φθ﹪κ²η ``` [Try it online!](https://tio.run/##XU29CsIwGNx9itApgXNxzSQVN6XgKA5pGkzwM19NU8Gnjyk4qMMdB/dnvUmWDZWynaZwjXIf4lCJskvyAXHkLA88zMTyBrFRSkE0uqnslV51KcQsz594@7LkWs/jUtzx3JMbpF8aPwsQJwrWfZ382V5dlC4FFow7egREOD3BYYRBqshVl/WT3g "Charcoal – Try It Online") Link is to verbose version of code. [Answer] # JavaScript ``` const obfuscate = str => [...str].map(e=>e.charCodeAt(0).toString(36) + '?').join``; const combine = (first, second) => obfuscate(first) + ' ' + obfuscate(second); const separate = string => string.split(' ').map(x =>x.split('?').filter(b=>b).map(el => String.fromCharCode(parseInt(el, 36))).join``); ``` > > In this case, `separate` is a partial function because it is only defined on specially formatted strings generated by `combine`. The `obfuscate` helper function turns the input string into an array of strings composed of the base-36 representation of the current character codepoint, plus a question mark. The array is then joined and returned. Then, `combine` returns the obfuscation of the first string, a space, then an obfuscation of a second string. `separate` undoes `obfuscate` on both strings and returns the array, in essence. Upon reading the answers, I found out that I sorta ported @Neil's answer with the difference being that I used a base-36 representation. > > > [Answer] Can't let @Mason have it for free (edit 1: also @Neil posted as I write this), so I'm dropping in with answer number 4 and 5 (edit 2: goddamn someone posted another answer): the *python convertors*. # Answer One: the easy version (string conversion using split()) ``` import math def combine(stringA, stringB): stringC = stringA + "\n" + stringB len1 = len(stringC) stringD = stringC * len1 return stringD def seperate(stringE): len2 = math.isqrt(len(stringE)) stringF = stringE[0:len2] stringG, stringH = stringF.split("*", 2) return stringG, stringH ``` This functions takes two strings, combines them with an asterisk and then multiplies them by their combined length (plus the asterisk). To decode, it takes the square root of the length, splits ton the asterisk, and returns the strings (tested). Now for the *hard* version. # Answer Two: the actually hard version (hex conversion) ``` def combine2(stringI, stringJ): stringK = stringI + "\n" + stringJ integerA = stringK.encode().hex() integerB = int(integerA, 16) return integerB def seperate2(integerC): integerD = (int(integerC)) integerE = hex(integerD) stringL = str(integerE) stringM = stringL[2:] stringN = bytes.fromhex(stringM).decode('ascii') stringO, stringP = stringN.split(":") return stringO, stringP ``` Three years later and I've actually done it: this code can first convert a string to hex, return that, then take that hex string (note, leave the 0x in or the first character will be removed) and convert it to the string that you originally had (again, ***painfully*** tested). (Edit 3: now you can't break it - newlines can't appear in input) ]
[Question] [ # Golf Golf! This is my first challenge, so please be gentle! The challenge is to write a program that will output the correct score for a layout in the card game "Golf." The card game Golf has many variations. The house rules I use follow the [standard rules for Six-Card Golf](https://www.pagat.com/draw/golf.html#six) given by Pagat, with one slight difference. There is already a similar challenge [here](https://codegolf.stackexchange.com/questions/80487/golf-a-golf-scorer) but I think this one is more interesting because it requires you to take the orientation of the cards into account. Each player has a 2x3 layout of cards. By the end of each round all cards are turned face up and scored as follows: * Each ace counts 1 point. * Each two counts minus two points. * Each numeral card from 3 to 10 scores face value. * Each Jack or Queen scores 10 points. * Each King scores zero points. * A pair of equal cards *in the same column* scores zero points for the column (even if the equal cards are twos). * A set of three equal cards *in the same row* scores zero points for the row (even if the equal cards are twos). ## Input The input can be a string or array of any kind. ## Output An integer representing the score of the Golf hand. ## Examples These examples use the notation `A23456789TJQK` but you need not use that notation in your answer. ``` Layout AK3 J23 Score 9 ----------------------- Layout 25Q 25J Score 20 ----------------------- Layout T82 T8A Score -1 ----------------------- Layout QQQ 234 Score 5 ----------------------- Layout TJQ QTJ Score 60 ----------------------- Layout 888 382 Score 1 ----------------------- Layout 888 888 Score 0 ``` This is code golf, so the shortest answer in bytes wins! [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes ``` n/aEÐḟẎḞS ``` [Try it online!](https://tio.run/##y0rNyan8/z9PP9H18ISHO@Y/3NX3cMe84P///0dH6xrpKJjqKBga6BnF6iggcQ1jYwE "Jelly – Try It Online") -1 thanks to [Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan). Takes input in the form of `[[A, B, C], [D, E, F]]`, where each of `A`, ..., `F` are elements in \$(1,-2,3,4,5,6,7,8,9,10,10.1,10.2,0)\$, representing values \$A,2,3,4,5,6,7,8,9,T,J,Q,K\$ respectively. [Answer] # [Haskell](https://www.haskell.org/), ~~107~~ ~~103~~ 98 bytes ``` f m=sum[min 10k|r<-m,o<-m,any(/=r!!0)r,(j,x)<-zip o r,j/=x,(k,c)<-zip[-2..]"2 KA 3456789TJQ",c==x] ``` [Try it online!](https://tio.run/##Pc5Bb4IwHAXwr/K34QChCBZxaKgJV9wORG5AlgZqRGghFCNb@O4M47bLS94v7/CuTNW8aeb5AoKqu0hFJWHj1FMfWAK3z2DyS7dpv1o5Ro/1Gx6NwPquOmihxzebjlivcfGy1CLrdY4InEJwt97uzd8nUYxwQemYz4JVkgrWfXxCdx/OQ/8uIW2YGjSUcDVAx5TiJTqkr3phVcPLAyDTVNf2AcI0EVjHv64vj40n6XzseDHw8n/JFjbQtAxsynKYdIbF78E9Jg62NtjDOyfXHm1fqkA7NpXkCoUnFyLiZpJ4MRAvymTiE0j8MJNxvIi7XSSKIU4ilM8/ "Haskell – Try It Online") Takes advantage of the fact there are only two rows. We double iterate over the rows taking a row `r` and a row `o`. When they are the same row the result will always be zero (due to the "columns" matching) so we will only consider the two iterations in which `r` and `o` refer to distinct rows. I zero out rows by first checking whether any entries in the row are not equal to the first. If the row is all equal this will be false and the list will be empty, with a sum of 0. Otherwise I zip this row with the other and iterate over the pairs that aren't equal (this zeroes out equal columns in a similar manner). Finally I index a list of card ranks starting with -2 padding with spaces as necessary to map each rank to its score. I just have to use `min 10` to clamp that index to make jacks and queens cost 10 rather than 11 and 12. EDIT: thanks to @xnor for taking off 4 bytes! I didn't know you could put identifiers directly after number literals that's really cool! EDIT2: Thanks again to @xnor for another 5 bytes! Great idea to iterate over the rows like that [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 50 bytes ``` F²⊞υS≔⁰ζF⭆υΦι∧⊙ι¬⁼λν⊙υ¬⁼λ§νμ≡ι2≧⁻²ζA≦⊕ζKω≧⁺∨ΣιχζIζ ``` [Try it online!](https://tio.run/##ZZDBTsMwDIbvfQprJ0cK0lZpFzhVaEgFDQp7gqjN2kipuyUOY0M8e0gJhyF8iv1/@f0n7aBcOykb435ygKWAJvgBg4SaDoF37Az1KMRdUXlvesKlhEvqfuisbtVh5h@MZe3QSKiow4rO8/F5Ytwcg7IerQQSQszyeeb/ShXX1OkPJAmj@C3wJ8PtAGgEfBat8hoW5eIW0sIc5s30A@PWUPASyhwsY9U1hjW1To@aWHfX0FOCmvQCxlOadXqvguV/9o2d3V8c7sKYkkhYLUV2@Sry7XvlGS/pj2Is169FuX6MN@/2Gw "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` F²⊞υS ``` Read the layout into an array. ``` ≔⁰ζ ``` Initialise the score to zero. ``` F⭆υΦι∧⊙ι¬⁼λν⊙υ¬⁼λ§νμ ``` Filter on the input, removing characters that equal all of the characters in its row or column. ``` ≡ι ``` Switch over each remaining character. ``` 2≧⁻²ζ ``` `2` scores `-2`. ``` A≦⊕ζ ``` `A` scores `1`. (These 4 bytes could be removed if `1` was used to denote `1`, but IMHO that's an abuse of the input format.) ``` Kω ``` Do nothing for `K`. ``` ≧⁺∨Σιχζ ``` Otherwise digits score their value and other letters score `10`. ``` Iζ ``` Cast the sum to string for implicit print. [Answer] # [J](http://jsoftware.com/), ~~39~~ 28 bytes ``` [:+/@,]<.@*]+:&(1=#@~.)"1/|: ``` [Try it online!](https://tio.run/##PY5fS8MwFMXf8ykOU6xzM2vSteuKhc2BSCdCpG9SRulSWylJid2Tsq9eM2yFew@X3z33z2c/oU6JOIKDOVxENu8pdm8vT/17NFts5tkD3dxls@jmlsVXmzOdTtjiJ@qnhLw@UjzLppUGpTboTK6@mryr1QeKXGlVF3mDWrWnzmqnoU8GrZGlNEYeh4ZUhT7aCVLFFBwersFwuBRL@AiwQog1mGuDsotw@@D3Gc6We0s/WIXrNBF7BzVFRogsKm3tMUpU1rL3Eu45f5S7I@a@4H4y4AMbcRryNNwO2B@pEMIeGmjwv8MeFandQUj/Cw "J – Try It Online") Credit to Erik the Outgolfer and Jonathan Allen for the input encoding idea. ## explanation A very "J" solution. I'll explain by example... Let's take the input: ``` AK3 J23 ``` and apply this encoding: ``` ┌─┬──┬─┬─┬─┬─┬─┬─┬─┬──┬────┬────┬─┐ │A│2 │3│4│5│6│7│8│9│T │J │Q │K│ ├─┼──┼─┼─┼─┼─┼─┼─┼─┼──┼────┼────┼─┤ │1│_2│3│4│5│6│7│8│9│10│10.1│10.2│0│ └─┴──┴─┴─┴─┴─┴─┴─┴─┴──┴────┴────┴─┘ ``` which produces: ``` 1 0 3 10.1 _2 3 ``` Let's look at the first part of the solution, eliding some detail to start: ``` ] (...)"1/ |: ``` This says take the input `]` and its transpose `|:` and create a "multiplication table" of all the combinations, except instead of multiplication we'll apply the verb in parenthesis. The rank `"1` specifier ensures that we take all combinations of rows from both arguments, but since the rows of the transpose are the columns of the original matrix, this means we'll be taking all combinations of rows and columns. That is, we'll be doing: ``` Rows Cols ┌─────────┐ ┌──────┐ │1 0 3 │ │1 10.1│ ├─────────┤ "times" table ├──────┤ │10.1 _2 3│ │0 _2 │ └─────────┘ ├──────┤ │3 3 │ └──────┘ which produces: ┌───────────────────────┬─────────────────────┬────────────────────┐ │┌─────┬────┬──────┐ │┌─────┬────┬────┐ │┌─────┬────┬───┐ │ ││1 0 3│verb│1 10.1│ ││1 0 3│verb│0 _2│ ││1 0 3│verb│3 3│ │ │└─────┴────┴──────┘ │└─────┴────┴────┘ │└─────┴────┴───┘ │ ├───────────────────────┼─────────────────────┼────────────────────┤ │┌─────────┬────┬──────┐│┌─────────┬────┬────┐│┌─────────┬────┬───┐│ ││10.1 _2 3│verb│1 10.1│││10.1 _2 3│verb│0 _2│││10.1 _2 3│verb│3 3││ │└─────────┴────┴──────┘│└─────────┴────┴────┘│└─────────┴────┴───┘│ └───────────────────────┴─────────────────────┴────────────────────┘ ``` Now the `verb` we apply to each of these combos is `+:&(1=#@~.)` and this verb returns false if "either argument consists of a single repeated item" and true otherwise. It does this by taking the nub, or uniq `~.`, asking if its length is one `1=#`, and taking the nor of the result `+:`. That is, this will return a boolean mask with the same shape as the input matrix, but with zeros for any item in a row or column of all equal items. ``` 1 1 0 1 1 0 ``` Now we simply mutliply the original matrix by this mask and take the floor `]<.@*`: ``` 1 0 0 10 _2 0 ``` and then flatten and sum the result of that: `+/@,` ``` 9 ``` [Answer] # JavaScript (ES6), ~~97 95~~ 93 bytes Takes input as an array of 2 arrays of 3 characters. ``` a=>a.map((r,i)=>r.map((c,j)=>t-=c!=a[i^1][j]&r!=c+[,c,c]?{K:[],2:2,A:-1}[c]||-c||~9:0),t=0)|t ``` [Try it online!](https://tio.run/##bZBLq8IwEIX391foxjQ40bY@0EKUbuNKcBcihPFBi1qpxY3x/vXetL0GpS4OzIH55hwm1Xd9wzy5FuyS7fblgZeaL/TgrK@el0NC@SJvDEJqTcE4drmWyTZQMlW9vMuxLwEB1fKxiqSCMAohjljwlKiMYWjM7zzyKRTcp6YoMbvcstN@cMqO3sGTksQEyMpqRBRIIuwUNk5R2hkOO/OfFlItTKzWNfJywiGh32Y2dmNWH6@Yl4sdw4I2s64z3nNGVmPHTL7HCIdU8Oaj2vRLNfHPCBfTfMFVG5d/ "JavaScript (Node.js) – Try It Online") ### Commented ``` a => // a[] = input a.map((r, i) => // for each row r[] at position i: r.map((c, j) => // for each card c at position j in r[]: t -= // update t: c != a[i ^ 1][j] & // if c is not equal to the sibling card in the other row r != c + [, c, c] ? // and r is not made of 3 times the same card: { K: [], // add 0 point for a King (but [] is truthy) 2: 2, // subtract 2 points for a Two A: -1 // add 1 point for an Ace }[c] // || -c // or add the face value || ~9 // or add 10 points (Jack or Queen) : // else: 0 // add nothing ), // end of inner map() t = 0 // start with t = 0 ) | t // end of outer map; return t ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 22 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` c xÈf *YgUïUÕ me_â Ê>1 ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=YyB4yGYgKllnVe9V1SBtZV/iIMo%2bMQ&input=W1stMiwgNSwgMTAuMl0sIFstMiwgNSwgMTAuMV1d) [Answer] # [PHP](https://php.net/), ~~145~~ 109 bytes After using the default `A23456789TJQK` coding for inputs and not getting a good result, I switched to using this coding similar to other answers: ``` A | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | T | J | Q | K 1 | -2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 10.1 | 10.2 | 0 ``` Input is a two dimensional array in this format: `[[1,0,3],[10.1,-2,3]]`. Basically checks the row (using `min` and `max`) and the column for each card to not contain equal values and then adds card value to the total score and at the end prints integer portion of the total score. ``` function($a){for(;$x++<2;)for($i=3;$i--;)min($r=$a[$x-1])-max($r)&&$r[$i]-$a[$x%2][$i]&&$s+=$r[$i];echo$s^0;} ``` [Try it online!](https://tio.run/##VZDdioMwEIXvfYpQZovBpDWxXXZJZR8kmwURxVxURV0QSp/dncSfrrk4ZM58ORmmrdrp9tVWbRBAmU7lb50PtqlDyOijbLpQwRhFN6moK8CmiQLLuaJ3i0yXQqZh5MJQfs9GNOjxCJ0Ga7jvvEnjCjT7KJ0bqsirBvqfWD0nhZ8ORT/0JCU6IHi0FqgsdpKgGKZFfBKMy9UwjJzP5HOhvX91NGIS6Z0hFlrGazgGsw/XdZwPXw3xCudiw0@SbbKmuzHY5YVf/4f7aRd6ebmf5X2dxf@6CeIJ2Q034yIwuCVcfpHlFQmXdWU98TdKHj4NyrlDlS/disnhuz6o4Dn9AQ "PHP – Try It Online") *(Note: TIO for PHP is broken at the moment, because of a wrong version upgrade, but should come back OK)* [Answer] # [Python 3](https://docs.python.org/3/), 79 bytes ``` lambda d:sum([({*a}!={x}!={y})*int(x)for a,b in(d,d[::-1])for x,y in zip(a,b)]) ``` [Try it online!](https://tio.run/##VVBLCoMwFNx7iteViUQx2oII9iJpFoqVCvWDWtAGz27zEqztJswnk2HSL9Oja@Otym7bM2@KMocyHV8NEUR5@XrK1IzHslKvbicy06obIGcF1C0pWSnS1OfSiDNbtAjvuifap5Ju032cRshACMEZhAxiyUDwMNDMj5AiFwgvDLQeIT8otz7XyQQTNm3I1woim/zPxwzOR9g27v5@@7ciMY8miOO9TErHwV24AoeZNakD0A/4E5WrUFnBv4KqCGK6unT7AA "Python 3 – Try It Online") Uses the same input format as some other answers, values \$1,-2,3,4,5,6,7,8,9,10,10.1,10.2,0\$ for the cards. --- # [Python 3](https://docs.python.org/3/), 118 bytes More readable input format ``` lambda d:sum([({*a}!={x}!={y})*[10,10,10,1,0,-2,int(x,36)]['TJQAK2'.find(x)]for a,b in(d,d[::-1])for x,y in zip(a,b)]) ``` [Try it online!](https://tio.run/##LY9Bi4MwEIXv/orpKUkZlzZplyC44NWeAt6yOViyYYWtlWpBK/5216lCGPK9N8ObaYbu916rOaTf8195u/oSfNI@b9zycV9Ou3TsqQyT2NvjAbeHB4wlVnXHe1SfwllW5Ca7SPYRqtrzXrhwf0CJV6hq7tHbJImPTpDY47CI8KoavvjCibn7absWUrCWZRfFEFguFXMIlsmzIZbnfOVCS@JCZysbs/rqtPn5m02x9WutidUy5lwUUT6l0QLv1CQCaB50R2AjKRPEXzAGTn8xMTH/Aw "Python 3 – Try It Online") [Answer] # [Kotlin](https://kotlinlang.org), 159 bytes Lambda takes 1.3456789TJQ0 as input. The outer code takes A23456789TJQK as input, converts the ace, two, and king so the math works out, and displays the cards & score. ``` {d:List<String>->Int var s=0 for(r in 0..1)for(c in 0..2)if((d[r][0]!=d[r][1]||d[r][1]!=d[r][2])&&d[0][c]!=d[1][c]){ val n=d[r][c]-'0' s+=if(n>9) 10 else n} s} ``` [Try it online!](https://tio.run/##jVhdb9u4En33r5gYi9bGOoo/mm5ibApku92LJL23N9u8FXlgJNoWIksuScXxTfPbe8/MSLLcNN0WBWyTh8PhzJnDYW6LkKX514MDOstXZZhSXoRFms9pVjhK7MyUWaBgfaDYeOupcB1gfXpP8cI4EwfrPHmbWXxLaOaKJZ2OJ68OX/92dHx1fnkRMfw/RbBTWrkUNkMBS1lGcZHfYW1a5LRO8TuYW8vYVWZiS71TBo4GNObPaEAmT@iCvw@jfodxb501siXbXKQeBhNL8yKbsWdZZvO5nTJwEcLKTw8OeJ6nIx9MfGvvgQIkiovlweeD0fFkfDRh@L/YQu/1fmxc0pdfe9RpJuS3/LziPfF/uaFZ6jg@9a4D8gWOYREvupEzzW0eMruHNXYL48U4z9qlwZKRo7ti7swSxzFBg1KUAUnBANYVziHI5PFFjPLBDWVmAxCluYLgNM3N0lKXPY266ml7Qo6xMHDc5Bu6My41AUnwUQ1dFCUcd2WGbJ8Rf58VWVasZQPELk9gi8EKYTc@pvf7b3kHMT5P72xONxv6r5mbMGDoOg0LKnKsz9L5IlCSzmbW2Ty2Ee/pOBiMMxmymmxwLp8u08y4VrgEdoOznjGSSXqriWe7nIiCzeQgJNjKDL6xsYH7jE4DOfu5TDFFiBfHnfkmRypcivRIEKiYqW0NmGdzBZk4Lso8RMRz70y8YI5urJMoGhrfT@osFDNdF9Efm9qQBXExbnmdg52EhP1i3sDjULrcSjxnTPxyJVSXLAPqq@D7aafZnWHikacRrQr4GG0nw7qoJ5dpXnoZEJBvofJyaZ1RN7RoJ1JvQ93Yiy@MvjNZaVsLz1E6iBhdlhY5rsBY9mSHC85ANf8/63Z9OKWVSZ2E5XNpsibYSjFmaVxk5TIXqXlioyr5GkQ9y3xLm9S1bUqE14Xv1xt7K2kKC2fts7u7Yv0PWwPR7MsDDP/BvqKtnbrCUv4FIIrEMtWD42BxOTtnNuweSpPBt2meqIEPIgR6hlxYPgcBnV3BQbCX14v37LGezzaaBZ2rrLy7N0sIk689QW3bakgKnU1A/6UWZKu2kkvtcfHkFswErFpiAkPrZRxHgHCW3K@tE1V5L9UhBi9EY8/H8vFRvD3mr/vf/7e7enx4qR/n29Xj4Q@WE@0auDoa68fp1sD@6Kf3v7zU/SevtssPf3o1YihGrlrevx7@9PKjoyP@mOgRdPmI2jdRcwHKBSR0WBRO7m5NBnLD@JsNxiDJud@rWLECQ/gqLfM46IUMucbFuLTM@S2dMrO8SUzUAZAvq9h630tMMFN6n/rw@0ch8pv@FHwP9NDpEGHRn1UTwaTw5VJZArHhsoroL9CetVGxXFYsf1rZAy0uHG13XLGsvixuMCDSX98pgdCNiOcDWtsae8eVBtm7sdKCmCRRca@8ihT3VpoS9bXpbwRfrY3obKZQXClwbC5dCGsCqjlPc1z@OmHQNOWV1Q8In1unvpncl67mmNPENWQ4fRX2DKJQcPS522qMJZyeXW9xc/NXOqEhfrEu9ThKKL9hFI36GKtGK5XUibFOEEe2J7n7hFXXn4bXtHdC29@ja/rypYLyv52ZHeT4uk8vXnwLHV5/0n236FEz1Ac3ajQumDotbasVcv/l8GUD5dP@etLaSU9RrX5Dx/2dOcK9tDNgM2@/QejaavBR0srpdZZvZd6wI4MV16Va/qqLBOlAA5MVSCCnRWuj6nRUrYHW2qkUn48nNK7aOmg3CkPLKUk9dxXfK6emkt7rFti4cqjVqbDZAA3OFIqJZUQfrWq6fVLhYIYC6ypXSmW0ohOdGB0eq1J8fUimbX/236C6O0K/k2EHhnquYR3/ihuqpTNQ7JNjdu2dyJfR9Zcv1ZdqBPR58SIRvsgQs@S6/9ARXigkVhr4X09gMH@DNCOxksz8seMfv6rKaPxa0Za4DNqhWg70aByrpIWv80D8REGnnvcqDve/HRrtDHVVhX95WMls/7Hbnu0rd6qNhDv/NghNk4P4yQum7nWVEkuge8bN/ZROuTF4SogrtyFumOvrH2LiXvrtc42PFIARvKz4G2iBssMRvTWiPzkYEtuVtsB5ja0611ma8ZNGmxShdygKfT0UrsbO7Lr1INTnWpojiWnSGo86WvJOS@FEnH8P1ez19/Y6dUGLaxwHbAXxeN1WIpmDR6y5D7tSII@g7k7L0qXHtqFaH9D8QSnPEOu5yU7dvOQKeFdHoNcy2/3DJEqnPeR2G0R9pAZ9zjWvYL10ccMtauS6cLeeyx21uMrSUL2hJJTwFvme1VDsoa8WVv9VakHa7Q2Vof5qILZZW@keE52sGCYa0FhT1sOgxryKt4TPqfu9v9FD3ve6p93@gLqjbj9qDv4NYiyI6AeIC0EMuxrhWsvY6w8zzacvb/TcPZGGwW5Gt7OTKDrs9/sVwT@0mDlgrYJdxI3ZVdc1IlBJXvNHCnlTtv9oIS8c7mFU8ponZSXWrn4cJvW5Gkl8hIWA50zPOle4KQyDOuYms/Ud1mhBwxRUIeex@tuJ3/t@ULqj4aSLmJ1Hk27/@4jo8JIR0eH5c4iro4gRV0ej5xBoWcXG5NWzNs4Fgbb0OQQ6T0ZMsJkgRNYgK6pvrFJf/w8 "Kotlin – Try It Online") ]
[Question] [ An [H tree](https://en.wikipedia.org/wiki/H_tree) is a fractal tree structure that starts with a line. In each iteration, T branches are added to all endpoints. In this challenge, you have to create an ASCII representation of *every second* H tree level. The **first level** simply contains three hyphen-minus characters: ``` --- ``` The next levels are constructed recursively: * Create a 2x2 matrix of copies from the previous level, separated by three spaces or lines. * Connect the centers of the copies with ASCII art lines in the form of an H. Use `-` for horizontal lines, `|` for vertical lines, and `+` whenever lines meet each other. ### Second level ``` -+- -+- | | +-----+ | | -+- -+- ``` ### Third level ``` -+- -+- -+- -+- | | | | +--+--+ +--+--+ | | | | | | -+- | -+- -+- | -+- | | +-----------+ | | -+- | -+- -+- | -+- | | | | | | +--+--+ +--+--+ | | | | -+- -+- -+- -+- ``` ## Rules * Input is an integer representing the level of the ASCII art H tree as described above (*not* the actual H tree level), either zero- or one-indexed. * Output is flexible. For example, you can print the result or return a newline-separated string, a list of strings for each line, or a 2D array of characters. * You must use `-`, `|`, `+` and space characters. * Trailing space and up to three trailing white-space lines are allowed. This is code golf. The shortest answer in bytes wins. [Answer] # [Canvas](https://github.com/dzaima/Canvas), ~~20~~ 19 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md) ``` ø⁸«╵[↷L⇵;l⇵└┌├-×╋‼│ ``` [Try it here!](https://dzaima.github.io/Canvas/?u=JUY4JXUyMDc4JUFCJXUyNTc1JXVGRjNCJXUyMUI3JXVGRjJDJXUyMUY1JXVGRjFCJXVGRjRDJXUyMUY1JXUyNTE0JXUyNTBDJXUyNTFDLSVENyV1MjU0QiV1MjAzQyV1MjUwMg__,i=Mw__,v=8) Explanation: ``` ø push an empty canvas ⁸«╵[ repeat input*2 + 1 times ↷ rotate clockwise L⇵ ceil(width/2) ;l⇵ ceil(height/2); leaves stack as [ ⌈½w⌉, canvas, ⌈½h⌉ ] └┌ reorder stack to [ canvas, ⌈½w⌉, ⌈½h⌉, ⌈½w⌉ ] ├ add 2 to the top ⌈w÷2⌉ -× "-" * (2 + ⌈w÷2⌉) ╋ in the canvas, at (⌈w÷2⌉; ⌈h÷2⌉) insert the dashes ‼ normalize the canvas (the 0th iteration inserts at (0; 0) breaking things) │ and palindromize horizontally ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 22 bytes ``` P-²FNF²«⟲T²+×⁺²κX²ι←‖O ``` [Try it online!](https://tio.run/##RYxBDoIwEEXXcIqG1UyEDe7wBCaCDeEClQyxsVBSpnVhPHstbFy@l//f@FRutMrE2HrDenV6YWiqUtR4ySfrBFyX1XPn5wc5QBSHq1F88qy3rJgGp5Yt2Rn2SyaPQnEq/jDomTaQxm9Ql@KFpZD2nWoJNOK@a20gaG408U49TYZGvgdyRq2Q1DfGc6yC@QE "Charcoal – Try It Online") Link is to verbose version of code. 0-indexed. Explanation: ``` P-² ``` Print the initial three `-`s, leaving the cursor in the middle. ``` FN ``` Repeat for the number of times given. ``` F²« ``` Repeat twice for each `H`. Each loop creates a slightly bigger `H` from the previous loop, but we only want alternate `H`s. ``` ⟲T² ``` Rotate the figure. ``` +×⁺²κX²ι← ``` Draw half of the next line. ``` ‖O ``` Reflect to complete the step. The result at each iteration is as follows: ``` --- | | +---+ | | -+- -+- | | +-----+ | | -+- -+- | | | | +-+-+ +-+-+ | | | | | | | | +-------+ | | | | | | | | +-+-+ +-+-+ | | | | -+- -+- -+- -+- | | | | +--+--+ +--+--+ | | | | | | -+- | -+- -+- | -+- | | +-----------+ | | -+- | -+- -+- | -+- | | | | | | +--+--+ +--+--+ | | | | -+- -+- -+- -+- ``` [Answer] # [Python 2](https://docs.python.org/2/), 227 bytes ``` L=len def f(n): if n==1:return[['-']*3] m=[l+[' ']*3+l for l in f(n-1)];w=L(m[0]);y=L(m)/2;x=w/4-1;m=map(list,m+[' '*w,' '*x+'-'*(w-x-x)+' '*x,' '*w]+m) for i in range(y,L(m)-y):m[i][x]=m[i][w+~x]='|+'[m[i][x]>' '] return m ``` [Try it online!](https://tio.run/##RY9BbsMgEEX3nGJ2gIGkdrKyRU6QVbaIRaTaLRGMLeoKLFW9umucSN0Mw2fmff60zJ8jNut61b5H8t4PMDDkLQE3AGpdt7GfvyMaQxW11ckSCNp4YSiUq/AwjBE8OCx7qua2S/rKgnmzvFtKx49Nl3U6nlXdBR3uE/Pua5ZhR1RJlprFRq9YUlllLnZl15MVgZPdwhWLeMePni2yYNXC22CcNdnq/Uzid2vpj6DmpV/KJwk8E0BYCwcLp5aNPMnzlnKKDmdAAjddcpP/OLf2@Ubp4TE6ZJ6/ptc/ "Python 2 – Try It Online") [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 118 bytes ``` {map ->\y{map {' |-+'.comb[:2[map {$^b%%1*$b&&6>=$^a/($b+&-$b)%8>=2},$^x/¾,y/2,y,$x/3-$_]]},2..^$_*6},2..^$_*4}o*R**2 ``` [Try it online!](https://tio.run/##PcjPCoIwHMDxe08x5OfUuT@0RKJwD9FVnbhIKNKJXRzmq3XoxRZ46PLlw3e8Tc/c9w7hDhV@6dsRMVW5DUuE3iyN@NX2pjzJcnugTRjuCRiMc1WAbkUMJsUMTBIeVSFXCnoW3w91QlJHYRYHBk1dr1RyrqEh@V/ZasmFEOnPu1frUBdDkyjFH/Y@bImDaggS1NkJ6cz/AA "Perl 6 – Try It Online") 0-indexed. Returns a 2D array of characters. The basic idea is that the expression ``` b = y & -y // Isolate lowest one bit b <= x % (4*b) <= 3*b ``` generates the pattern ``` --- --- --- --- ----- ----- --- --- --- --- --------- --- --- --- --- ----- ----- --- --- --- --- ``` ### Explanation ``` { ... }o*R**2 # Feed $_=2**$n into block map ->\y{ ... },2..^$_*4 # Map y=2..2**n*4-1 map { ... },2..^$_*6 # Map $x=2..2**n*6-1 ' |-+'.comb[:2[ ... ]] # Choose char depending on base-2 number from two Bools map { ... } # Map coordinates to Bool # Horizontal lines ,$^x/¾ # Modulo 8*¾=6 ,y/2 # Skip every second row # Vertical lines ,y # Modulo 8 ,$x/3 # Skip every third column -$_ # Empty middle column # Map using expression $^b%%1*$b&& # Return 0 if $b is zero or has fractional part 6>=$^a/($b+&-$b)%8>=2 # Pattern with modulo 8 ``` ]
[Question] [ This challenge is for the largest finite number you can get BrainFuck programs of given lengths to contain in memory. We must use one of the BF versions that uses big integers for the cells rather than byte values as not to be capped at 255. Do not use negative positions and values in memory. Do not use the BF instruction to input memory, also the output instruction is not needed. --- Challenge: Write Brainfuck programs with lengths from 0 to 50. Your score is the sum of each programs maximum value in memory. --- As they may well be trivial feel free to omit the programs listed below and start from a length of 16, I'll use the following for the smaller sizes: Length, Score, Program ``` 0, 0 1, 1, + 2, 2, ++ 3, 3, +++ Pattern Continues 10, 10, ++++++++++ 11, 11, +++++++++++ 12, 12, ++++++++++++ 13, 16, ++++[->++++<] 14, 20, +++++[->++++<] 15, 25, +++++[->+++++<] ``` Total Score: 139 --- Related but different: [Large Numbers in BF](https://codegolf.stackexchange.com/questions/115272/large-numbers-in-bf) [Largest Number Printable](https://codegolf.stackexchange.com/questions/18028/largest-number-printable) [Busy Brain Beaver](https://codegolf.stackexchange.com/q/4813/194) See the comments below for more info. --- --- The combined results so far, being the sum of the best of each size: ``` length: 16 to 24 by sligocki 100, 176, 3175, 3175, 4212 4212, 6234, 90,963, 7,467,842 ``` --- ``` length: 25 to 30 by sligocki ``` 239,071,921 --- ``` length: 31, 32, 33, (34 to 37) by sligocki 380,034,304 30,842,648,752 39,888,814,654,548 220,283,786,963,581 ``` --- ``` length: 38 based on code by l4m2, by alan2here ``` (4 ^ 1366 - 4) / 3 [!["(4 ^ 1366 - 4) / 3" in full](https://i.stack.imgur.com/G1gAE.gif)](https://i.stack.imgur.com/G1gAE.gif) --- ``` length: 39 to 47 based on code by l4m2, by alan2here ``` Σ (n = 4 to 12) of (fn(0) | f(x) := (4x+2 - 4) / 3) --- ``` length: 48 based on code by l4m2, by alan2here ``` (172) - 2 --- ``` length: 49, 50 by l4m2 (<sup>21</sup>2) - 2 (<sup>26</sup>2) - 2 ``` [Answer] # (262)-2 ``` +++++[->+++++<]>[->+[->+[->++<]>[-<+>]<<]<[->+<]>] ``` Where (42) = 2222 # f20(0), where f(x):=(4x+2-4)/3 ``` ++++[->+++++<]>[->+[->+[->++<]>[-<++>]<<]<[->+<]>] ``` [Answer] There's been a lot posted about the top of the range (size ~ 50). But here are some high-scoring programs near the bottom: * Size 16: `+[->++++++[-<]>]` scores 100 * Size 20: `+[->++++++++++[-<]>]` scores 4,212 * Size 28: `+[->++++++++++++++++++[-<]>]` scores 804,576 In general, if we parameterize it so that there are N+1 `+`s in the middle, then this simulates the "Collatz-like" iteration: * $$C(2k) \to Halt(Nk)$$ * $$C(2k+1) \to C(N(k+1))$$ Where C(m) = `[0, *m*, 0 ...]` (Data pointer looking at value m, at least one zero to the left, infinite 0s to the right). It turns out that for $$N = 2^m + 1$$ this iterates exactly m+2 times (starting from C(1)) and scores $$\frac{N}{2} (\frac{N^{m+1} - 2^{m+1}}{N - 2} + 1) \approx \frac{N^{m+1}}{2} \approx N^{\log\_2(N)}$$ points using N + 12 size. [Answer] total: (≈ & >) 172 more detail: ``` length: 0 to 12 see question total: 78 ``` --- ``` length: 13 to 24 N × N (N + 1) × N 16, 20, 25, 30, 36, 42, 49, 56, 64, 72, 81, 90 ++++[->++++<] +++++[->++++<] +++++[->+++++<] Pattern Continues +++++++++[->++++++++<] +++++++++[->+++++++++<] ++++++++++[->+++++++++<] total: 581 ``` total so far: 659 --- each yeild: fn(0) | f(x) = x × m + 1 ``` length: 25 (m, n) = (5, 4) 156 >+>+>+>+<[>[-<+++++>]<<]> length: 26 (m, n) = (4, 5) 341 >+>+>+>+>+<[>[-<++++>]<<]> total: 497 ``` total so far: 1156 --- each yeild: fr or (r × s)(0) | f(x) = (x + 1) × (p × q) ``` length: 27 (p, q, r) = (2, 2, 5) 1364 +++++[->+[->++<]>[-<++>]<<] length: 28 (p, q, r) = (2, 2, 6) 5460 ++++++[->+[->++<]>[-<++>]<<] length: 29 (p, q, r) = (2, 2, 7) 21,844 +++++++[->+[->++<]>[-<++>]<<] length: 30 (p, q, r) = (2, 2, 8) 87,380 ++++++++[->+[->++<]>[-<++>]<<] total: 116,048 ``` total so far: 117,204 ``` length: 37 (p, q, r, s) = (2, 3, 4, 4) (≈ & >) (6 ^ 16 = 1,721,598,279,680) ++++[->++++<]> [->+[->+++<]>[-<++>]<<] total: (≈ & >) 1,721,598,279,680 ``` total so far: (≈ & >) 1,721,598,396,884 --- Based a design by l4m2 each yeild: fn(0) | f(x) = (4x + 2 - 4) / 3 ``` length: 38 n = 4 +++[->+[->+[->++<]>[-<++>]<<]<[->+<]>] length: 39 n = 4 ++++[->+[->+[->++<]>[-<++>]<<]<[->+<]>] length: 40 n = 5 +++++[->+[->+[->++<]>[-<++>]<<]<[->+<]>] length: 41 n = 6 ++++++[->+[->+[->++<]>[-<++>]<<]<[->+<]>] length: 42 n = 7 +++++++[->+[->+[->++<]>[-<++>]<<]<[->+<]>] length: 43 n = 8 ++++++++[->+[->+[->++<]>[-<++>]<<]<[->+<]>] length: 44 n = 9 +++++++++[->+[->+[->++<]>[-<++>]<<]<[->+<]>] length: 45 n = 10 ++++++++++[->+[->+[->++<]>[-<++>]<<]<[->+<]>] length: 46 n = 11 +++++++++++[->+[->+[->++<]>[-<++>]<<]<[->+<]>] length: 47 n = 12 ++++++++++++[->+[->+[->++<]>[-<++>]<<]<[->+<]>] ``` --- ``` Based a design by l4m2 length: 48 ++++[->++++<]>[->+[->+[->++<]>[-<+>]<<]<[->+<]>] total: <sup>17</sup>2 - 2 ``` --- --- ``` Honorary Mention (3 × 3) ^ 4 >+<++++[->[->+++<]>[-<+++>]<<] ``` [Answer] # Revision! Even bigger numbers now! ``` ++++++++[>+>>++++++++[<<[>+++<-]>[<++++>-]>-]<<<-] ``` Result: 1.1684220603446423e+69 or 116842206034464220000000000000000000000000000000000000000000000000000 (At least that's what the compiler says) # How? How this works is that repeats the assignment v=v(4\*3)^v 8 times(At least that's what I intended it to do. [Answer] Just found a more powerful family of programs in the 16-33 size range. These are programs that look like `++[>+++++[-<]>>]` (M+1 `+`s at start and N+1 `+`s in middle). Here are all the ones that beat existing champions (IIUC). ``` Size 16 / Params M= 1 N= 4 / Score = 176 / ++[>+++++[-<]>>] Size 17 / Params M= 1 N= 5 / Score = 3,175 / ++[>++++++[-<]>>] Size 21 / Params M= 2 N= 8 / Score = 6,234 / +++[>+++++++++[-<]>>] Size 22 / Params M= 2 N= 9 / Score = 90,963 / +++[>++++++++++[-<]>>] Size 23 / Params M= 2 N=10 / Score = 7,467,842 / +++[>+++++++++++[-<]>>] Size 24 / Params M= 2 N=11 / Score = 239,071,921 / +++[>++++++++++++[-<]>>] Size 30 / Params M= 3 N=16 / Score = 380,034,304 / ++++[>+++++++++++++++++[-<]>>] Size 31 / Params M= 3 N=17 / Score = 30,842,648,752 / ++++[>++++++++++++++++++[-<]>>] Size 32 / Params M= 3 N=18 / Score = 39,888,814,654,548 / ++++[>+++++++++++++++++++[-<]>>] Size 33 / Params M= 3 N=19 / Score = 220,283,786,963,581 / ++++[>++++++++++++++++++++[-<]>>] ``` Note: These programs all go one spot to left of the starting memory location ... if you want to disallow that, you'll need to prepend them with `>`. This program follows the recurrence: ``` Start -> [M, N*] [b+k, b*] -> Halt(max(Nb, k)) [a, a+k+1*] -> [k, N(a+1)*] ``` In other words: if the register to the left has an equal or larger value, it will halt. If current register has greater value, iterate like the second line. All of these recurrences seem to eventually halt, but I don't have any deeper insight yet ... ]
[Question] [ A function is said to have a *cycle of length n* if there exists an *x* in its domain such that *fn(x) = x* and *fm(x) ≠ x* for *0 < m < n*, where the superscript *n* denotes *n*-fold application of *f*. Note that a cycle of length *1* is a fixed point *f(x) = x*. Your task is to implement a [*bijective* function](https://en.wikipedia.org/wiki/Bijection) from the integers to themselves, which has exactly one cycle of every positive length *n*. A bijective function is a one-to-one correspondence, i.e. every integer mapped to exactly once. Having exactly one cycle of length *n* means that there are exactly *n* distinct numbers *x* for which *fn(x) = x* and *fm(x) ≠ x* for *0 < m < n*. Here is an example of what such a function might look like around *x = 0*: ``` x ... -7 -6 -5 -4 -3 -2 -1 0 1 2 3 4 5 6 7 ... f(x) ... 2 4 6 -3 -1 1 -4 0 -2 5 7 -7 -6 3 -5 ... ``` This excerpt contains cycles of length *1* to *5*: ``` n cycle 1 0 2 -2 1 3 -4 -3 -1 4 -5 6 3 7 5 -7 2 5 -6 4 ... ``` Note that above I'm using "function" only in the mathematical sense. You may write either a function or a full program in your language of choice, as long as it takes a single (signed) integer as input and returns a single (signed) integer. As usual you may take input via STDIN, command-line argument, function argument etc. and output via STDOUT, function return value or function (out) argument etc. Of course, many languages don't (easily) support arbitrary-precision integers. It's fine if your implementation only works on the range of your language's native integer type, as long as that covers at least the range *[-127, 127]* and that it would work for arbitrary integers if the language's integer type was replaced with arbitrary-precision integers. Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. [Answer] ## Python 2, 55 bytes ``` g=lambda n,k=1:n/k and~g(~n+k*(n>0),k+1)+k*(n>0)or-~n%k ``` --- **59 bytes:** ``` g=lambda n,k=1:n<0and~g(~n,2)or n/k and k+g(n-k,k+2)or-~n%k ``` Creates the cycles ``` [0] [-1, -2] [1, 2, 3] [-3, -4, -5, -6] [4, 5, 6, 7, 8] ... ``` Modified from [my solution on the earlier challenge](https://codegolf.stackexchange.com/a/53668/20260), which is modified from [Sp3000's construction](https://codegolf.stackexchange.com/a/53648/20260). The function ``` g=lambda n,k=1:n/k and k+g(n-k,k+2)or-~n%k ``` makes odd-size cycles of non-negative numbers ``` [0] [1, 2, 3] [4, 5, 6, 7, 8] ... ``` To find the correct cycle size `k`, shift the input `n` down by `k=1,3,5,7,...` until the result is in the interval `[0,k)`. Cycle this interval with the operation `n->(n+1)%k`, then undo all the subtractions done on the input. This is implemented recursively by `k+g(n-k,k+2)`. Now, we need the negative to make the even cycles. Note that if we modify `g` to start with `k=2` in `g`, we'd get even-size cycles ``` [0, 1] [2, 3, 4, 5] [6, 7, 8, 9, 10, 11] ... ``` These biject to negatives via bit-complement `~`. So, when `n` is negative, we simply evaluate `g(n)` as `~g(~n,2)`. [Answer] # [MATL](https://github.com/lmendo/MATL), 47 bytes ``` E|G0<-QXJ:tQ*2/0hStJ<f0))Q2MQ)&:J6M-)2/ttk>Eq*k ``` [**Try it online!**](http://matl.tryitonline.net/#code=RXxHMDwtUVhKOnRRKjIvMGhTdEo8ZjApKVEyTVEpJjpKNk0tKTIvdHRrPkVxKms&input=Mw) ### General explanation *Function 2 below is the same as used in [@Sp3000's answer](https://codegolf.stackexchange.com/a/53648/36398) to the related challenge. Thanks to @Agawa001 for noticing.* The function is the composition of three: 1. Bijection from **Z** (the integers) to **N** (the naturals). 2. Bijection from **N** to **N** with the desired characteristic (one cycle of each length). 3. Inverse of function 1. Functions 1 and 3 are used because it's easier (I think) to achieve the desired behaviour in **N** than in **Z**. Function 2 is as follows: upper line is domain, lower line is codomain. Commas are used for clarity: ``` 1, 2 3, 4 5 6, 7 8 9 10 ... 1, 3 2, 6 4 5, 10 7 8 9 ... ``` The first block (from upper `1` to lower `1`) is a cycle of length 1. The second (from `2 3` to `3 2`) is a cycle of length 2, etc. In each block, the lower part (image of the function) is the upper part circularly shifted one step to the right. Function 1 is as follows: ``` -5 -4 -3 -2 -1 0 +1 +2 +3 +4 ... +10 +8 +6 +4 +2 +1 +3 +5 +7 +9 ... ``` Function 3 is the same as 1 with the two lines swapped. ### Examples The image of `3` is `-5`. First `3` is mapped to `7` by function 1; then `7` is mapped to `10` by function 2; then `10` is mapped to -5` by function 3. The length-1 cycle is `0`. The length-2 cycle is `-1 1`. The length-3 cycle is `-3 2 -2`, etc. ### Code explained Functions 1 and 3 are straightforward. Function 2 works by finding the lower endpoint of the corresponding input block. For example, if the input to this function is `9` it finds `7` (see blocks above). It then picks the upper endpoint, which is `10` in the example. The circular shift of the block is achieved thanks to MATL's 1-based, modular indexing. ``` % FUNCTION 1 % Implicit input E| % Multiply by two. Absolute value G0< % 1 if input is negative, 0 otherwise - % Subtract Q % Add 1 XJ % Copy to clipboard J. Used as input to the next function % FUNCTION 2 : % Range [1 2 ... J], where J denotes the input to this function tQ* % Duplicate, increment by 1, multiply 2/ % Divide by 2 0hS % Prepend a 0. This is needed in case J is 0 tJ<f % Duplicate. Find indices that are less than the input J 0) % Pick the last index. ) % Apply as index to obtain input value that ends previous block Q % Add 1: start of current block 2M % Push the two arguments to second-to-last function call Q) % Add 1 and use as index: end of current block &: % Inclusive binary range: generate input block J % Push J (input to function 2) 6M- % Subtract start of block ) % Apply as index (1-based, modular). This realizes the shifting % FUNCTION 3 2/ % Divide by 2 ttk> % Duplicate. 1 if decimal part is not 0; 0 otherwise Eq % Multiply by 2, add 1 * % Multiply k % Round down % Implicit display ``` [Answer] # Pyth, ~~27~~ 18 bytes ``` _h?gQ0^2Q*.5@,Q-xh ``` Explanation (Pyth initializes `Q` to the input integer): ``` _ negative of ( ( ?gQ0 if Q >= 0: ^2Q 2**Q else: *.5 half of @ Q element Q (modulo list length) in , the two element list [ Q Q, hQ ((Q plus 1) x Q XOR Q) - Q minus Q ] h ) plus 1 ) ``` This has cycles (−1) (0, −2) (1, −3, −4) (2, −5, −7, −6) (3, −9, −13, −11, −8) (4, −17, −25, −21, −15, −10) (5, −33, −49, −41, −29, −19, −12) (6, −65, −97, −81, −57, −37, −23, −14) (7, −129, −193, −161, −113, −73, −45, −27, −16) (8, −257, −385, −321, −225, −145, −89, −53, −31, −18) (9, −513, −769, −641, −449, −289, −177, −105, −61, −35, −20) ⋮ The cycle of length *n* is given by (*n* − 2, −2^(*n* − 2)⋅1 − 1, −2^(*n* − 3)⋅3 − 1, −2^(*n* − 4)⋅5 − 1, …, −2^2⋅(2·*n* − 7) − 1, −2^1⋅(2·*n* − 5) − 1, −2^0⋅(2·*n* − 3) − 1). Each integer *k* ≥ −1 appears as the first element of the (*k* + 2)-cycle. For each integer *k* < −1, we can uniquely write 1 − *k* = 2^*i* ⋅ (2⋅*j* + 1) for some *i*, *j* ≥ 0; then *k* appears as the (*j* + 2)th element of the (*i* + *j* + 2)−cycle. [Answer] ## Python 3, 110 bytes *I still have not figured out how to get a lambda in there* if n is a triangle number [1,3,6,10,15,21,28,etc...] then f(n) is the order in the list multiplied by negative one. if the number is negative, give it 1+the next smallest triangle number. else, increment. Example: 5 is not a triangle number, so add 1. Next iteration, we have 6. 6 is a triangle number, and it is the 3rd in the list, so out comes -3. The program gives these lists length 1:[0] length 2:[1,-1] length 3:[2,3,-2] length 4:[4,5,6,-3] length 5:[7,8,9,10,-4] ``` x=int(input()) if x<0:print((x**2+x)/2+1) else: a=((8*x+1)**.5-1)/2 if a%1:print(x+1) else:print(-a) ``` Edit: Thanks again to @TuukkaX for removing excess charcters. [Answer] ## Python 3, 146 bytes For every number greater than 0, there are even loops (len 2,4,6,8...), and less than 0, odd loops (1,3,5,7). 0 maps to 0. (-3,-2,-1),(0),(1,2),(3,4,5,6) maps to (-2,-1,-3),(0),(2,1),(6,3,4,5) ``` f=lambda x:1+2*int(abs(x)**.5)if x<1 else 2*int(x**.5+.5) x=int(input());n=f(x) if x>0:b=n*(n-2)/4 else:b=-((n+1)/2)**2 print(b+1+(x-b-2)%n) ``` Edit: @TuukkaX took off 8 bytes from the previous solution. And another 3. [Answer] ## Matlab(423) ``` function u=f(n),if(~n)u=n;else,x=abs(n);y=factor(x);for o=1:nnz(y),e=prod(nchoosek(y,o)',1);a=log(x)./log(e);b=find(a-fix(a)<exp(-9),1);if ~isempty(b),k=e(b);l=fix(a(b));break;end;end,if(abs(n)==1)k=2;l=0;end,if(k==2)l=l+1;x=x*2;end,e=dec2base(l,k)-48;o=xor(e,circshift(e,[0 1]));g=~o(end);if(~o|nnz(o==1)~=numel(e)-g),u=n*k;else,if((-1)^g==sign(n)),u=sign(n)*k^(base2dec([e(2:end-1) 1]+48,k)-(k==2));else,u=n*k;end,end,end ``` * Non-competing because it breaks a good record of being condidate for the last ranking, whilst I am struggling to shorten it as possible as i can. * Some nonesensical bugs concerning accuracy in matlab that I couldnt find any way out except making my code sarcatistically big, in other hand the mapping I opt for was in terms of prime facors and n-ary logarithm. **Execution** ``` f(2) 1 f(1) 2 f(-2) -4 f(-4) -8 f(-8) -1 f(0) 0 ---------------------------- ``` ## Explanation * Knonwing, first off, that any number can be written as product of exponents of primes `N=e1^x1*e2^x2...` from this base i chose to map images of cycles `C` which are extracted from the biggest exponent of the smallest factor (not necessarily prime) that N is a perfect power of. * in simpler words, let `N=P^x` where P is the smallest perfect root, `x` denotes precisely two essential terms for the cycle : `x=Ʃ(r*P^i)`, a term `P` is the base of cycle as well a perfect root for the main number N, and `k` is the degree of the cycle `C=p^k`, where `i` varies between 1 and k, the coeffecient `r` is incremented by 1 and bounded by P-1 for any following pre-image until all coeffecients are set to r=1, so we move to the start of that cycle. * To avoid collisions between cycles the choice of exponentiation of primes rather than their products is accurate, because as an example of two cycles of bases `3` and `2` a meetpoint between them can be `3*2`, so this is avoided since a cycle is defined by its degree more than its base , and for the meetpoint there is another cycle of base `6` and degree 1. * Negative numbers place an exception, as for it, i reserved odd degrees for negative numbers, and even degrees for the rest. How so ? for any number N embedded within a cycle `P^k`, is written as `P^(a0*P^i0+a1*P^i1+...)`, the amount `(a0*P^i0+a1*P^i1+...)` is transalted in P-ary base as `a0,a1,....` , to clarify this point if (p=2) the sequence must be in binary base. As is known prealably without setting the condition of positive/negative degrees and the (+/-1) exception, a number N is on the edges of a cycle of degree `k` if and only if the sequence `A` is written as `1111..{k+1}..10` or `111..{k}..1` for all bases, otherwise no rotation is needed, thus assigning negative/positive condition for a respective odd/even degrees `k/k'` for both makes an odd sequence written in the form `101..{k}..100`, an even sequence is written in the form `101..{k'}..10` for a beginning edge of a respectively negative/positive number-cycle. **Example:** Taking a number `N=2^10`, `x=10=2^1+2^3` , the sequence A is written `A=1010`, this type of sequence symptomizes a finite edge of positive number-cycle, which is `C=2^3`, so the next image is that of beginning edge `A=011` which is `8`, **But**, by standarizing this result to (+/-)1 exception `2^10/2` maps to `8/2` and the previous image mustnt be rotated. Taking a number `N=-3^9`, `x=9=3^2` , the sequence A is written `A=100`, this type of sequence symptomizes a finite edge of negative number-cycle, which is `C=3^1`, so the next image is that of beginning edge `A=01` which is `3`, But, by adapting this result to negative/positive condition `-3^9` maps to `-3` . * for the couple `(-/+)1`, i envisaged to intrude it within numbers of cycle-bases `2`, in a guise that an ordinary sequence of cyclic groups `{2,4}{8,16,32,64}..` are made up in another form `{1,2}{4,8,16,32}..`, this prevents any loss of previous elements, and the opeation done is just shifting with popping a new element in. --- **Results:** running this little code-sheet to verify the first reasonable ranges of cyclic numbers: ``` for (i=1:6) index=1;if(max(factor(i))>=5) index=0;end for ind=0:index j=f(((-1)^ind)*i); while(((-1)^ind)*i~=j)fprintf('%d ',j);j=f(j);end,fprintf('%d \n',(-1)^ind*i),pause,end, end ``` This leads to this results ``` 2 1 -2 -4 -8 -1 1 2 -4 -8 -1 -2 9 27 3 -9 -27 -81 -243 -729 -2187 -6561 -19683 -3 8 16 32 64 128 256 512 4 -8 -1 -2 -4 25 125 625 3125 5 36 216 1296 7776 46656 6 -36 -216 -1296 -7776 -46656 -279936 -1679616 -10077696 -60466176 -362797056 -2.176782e+009 -1.306069e+010 ??? Error using ==> factor at 27 ``` The last one is segmentation-error but it fits the [-127,127] standard signed-integer range. [Answer] ## JavaScript (ES6), 73 bytes ``` f=(n,i=0,j=0,k=0,l=1,m=i<0?-i:~i)=>n-i?f(n,m,k++?j:i,k%=l,l+!k):++k-l?m:j ``` Works by enumerating the sequence (0, -1, 1, -2, 2, -3, 3, ...) until it finds `n`, counting cycles as it goes. `i` contains the current entry; `j` contains the start of the current cycle, `k` the index within the cycle, `l` the length of the current cycle and `m` the next entry in the sequence. Once we find `n` we then take `j` if we're at the end of a cycle or `m` if not. ]
[Question] [ # The Challenge In this challenge you have to do two different (but related) tasks depending of the order of the input. Your program will recieve a string `s` and an integer `n` as input and will * split `s` into pieces of length `n` if `s` comes first. The last element will be shorter if necessary. * split `s` into `n` pieces of equal length if `n` comes first. If `len(s)` is not a multiple of `n` the first `len(s) mod n` elements will be one longer. You may only take those 2 inputs. `s` will never contain only digits. ### Notes * You may use the reverse mapping. Note this in your answer if you do that. * `s` will only contain [printable ASCII characters](https://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters) (no newlines). * You may not use any builtins that solve either those two tasks directly. All other builtins are allowed. * You have to take both arguments from the same source. * You may take the arguments in an ordered list or any other format which clearly indicates their order as long as it is unambiguous. * You may take the input as one string/ stream and use a character which is not a valid input (like a nullbyte) to separate them. * `n` will always be equal or less than the length of `s` and greater than zero. * You may output the resulting list in any resonable format as long as it clearly indicates the particular pieces and their order. # Example **Input:** `programming, 3` The last element contains only 2 characters, because 11 is not divisible by 3. **Output:** `["pro", "gra", "mmi", "ng"]` **Input:** `3, programming` 11 is not a multiple of 3, so the first 2 elements will be one longer: **Output:** `["prog", "ramm", "ing"]` # Rules * Function or full program allowed. * [Default rules](http://meta.codegolf.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) for input/output. * [Standard loopholes](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so lowest byte-count wins. Tiebreaker is earlier submission. # Test cases The test cases got generated with this [Pyth program](http://pyth.herokuapp.com/?code=jk%5BJw%22%2C%20%22Kw%22%20-%3E%20%22.xcsJKcJsK&input=12%0Aprogramming&test_suite=1&test_suite_input=3%0Ahelloworld%0Ahelloworld%0A3%0A1%0Aprogramming%0Aprogramming%0A1%0A8%0Aprogramming%0Aprogramming%0A8%0A9%0Acode%20golf%0Acode%20golf%0A9&debug=0&input_size=2) (uses builtins, so no valid answer). Thanks to @FryAmTheEggman for providing the base version of that! ``` 3, helloworld -> ['hell', 'owo', 'rld'] helloworld, 3 -> ['hel', 'low', 'orl', 'd'] 1, programming -> ['programming'] programming, 1 -> ['p', 'r', 'o', 'g', 'r', 'a', 'm', 'm', 'i', 'n', 'g'] 8, programming -> ['pr', 'og', 'ra', 'm', 'm', 'i', 'n', 'g'] programming, 8 -> ['programm', 'ing'] 9, code golf -> ['c', 'o', 'd', 'e', ' ', 'g', 'o', 'l', 'f'] code golf, 9 -> ['code golf'] 4, 133tspeak -> ['133', 'ts', 'pe', 'ak'] 133tspeak, 4 -> ['133t', 'spea', 'k'] ``` **Happy Coding!** [Answer] # JavaScript (ES6), 132 bytes ``` (s,t)=>+t?[...Array(-~(~-s.length/+t))].map((_,i)=>s.substr(i*t,t)):[...Array(s=+s)].map(_=>t.slice(p,p-=~((t.length-p-1)/s--)),p=0) ``` This is probably hopelessly over-engineered. [Answer] # JavaScript (Firefox), ~~88~~ 87 bytes ``` a=>b=>(s=+b?a:b,i=x=0,l=s.length,[for(c of s)if(r=s.slice(x,x+=+b||l/a+(i++<l%a)|0))r]) ``` Call it like `(...)("programming")(3)` using Firefox 30+. [Answer] # MATL, ~~46~~ ~~26~~ ~~21~~ ~~27~~ ~~29~~ 42 bytes ``` jtU?jtbUe!tn2Gn>?0t(]tgbw(}ie]!2t$X{Oc''Zt ``` [**Try it Online!**](http://matl.tryitonline.net/#code=anRVP2p0YlVlIXRuMkduPj8wSihddGdidyh9aWVdITJ0JFh7T2MnJ1p0&input=OApwcm9ncmFtbWluZw) (Updated slightly to work with the latest version of the language) **Explanation** ``` j % Explicitly grab the first input as a string t % Duplicate U % Attempt to convert it to a number ? % If the conversion to a number was successful j % Explicitly grab the second input as a string t % Duplicate the value b % Bubble-up the first element in the stack U % Convert to a number from a string e % Reshape the string into a nGroup x nPerGroup matrix ! % Take the transpose t % Duplicate the result n % Number of characters in the repmat result 2Gn % Number of characters in the string >? % If chars in repmat > chars in string O % Zero t % Duplicate ( % Assign the last element to a null character (bug in MATL) ] % End if statement t % Duplicate this matrix g % Convert to a logical matrix b % Bubble-up the original string w % Flip the top two elements ( % Assign the non-empty characters to the chars from the input string } % Else the string comes first i % Explicitly grab the second input (the number) e % Reshape the characters into an nPerGroup x nGroup 2D array ] % End of if statement ! % Take the transpose so it reads left-to-right 2 % Number literal t % Duplicate $X{ % Call num2cell to convert to a cell array Oc % Null character '' % Empty string Zt % Replace null chars with empty strings % Implicit display of stack contents ``` [Answer] # Ruby, 119 bytes ``` ->x,y{r=[t=0];x.to_s==x ?(r.push x[t...t+=y]while x[t]):x.times{r.push y[t...t+=y.size/x+(r[y.size%x]? 0:1)]};r[1..-1]} ``` And I take first place by 2 bytes... [Answer] ## AWK, 121 130 128 122 Bytes ``` $1~/^[0-9]+$/{s=1}{a=$(s+1) b=s?$1:$2 $0="" for(j=-b;j<=c=length(a);)$0=$0 substr(a,j+=b+s,b+(s=s&&j<c%b*(b+1)?1:0))" "}1 ``` The only issue is if the first entry is a string that starts with a numeric value. This would cause `AWK` to see the string as that number and the second entry as the string. OK... fixed the numeric issue, but it added 9 bytes :(. Reworked a bit to save a couple bytes. Almost back to the original length. :) [Answer] ## Haskell, 131 bytes ``` import Data.Lists q(d,m)=splitPlaces$(d+1<$[1..m])++[d,d..] a#b|all(`elem`['0'..'9'])a=q(divMod(length b)$read a)b|1<2=q(read b,0)a ``` Usage example: ``` *Main> "8" # "programming" ["pr","og","ra","m","m","i","n","g"] *Main> "programming" # "8" ["programm","ing"] ``` How it works: the main work is done by the helper function `q` which takes a pair of numbers `(d,m)` and a string `s`. It first builds a list of `m` times `d+1` followed by infinite many `d` (e.g `(1,3)` -> `[2,2,2,1,1,1,1,1,...]`). It then uses `splitPlaces` to split `s` into chunks of lengths given by the list. `splitPlaces` stops if `s` runs out of elements, so an infinite list is fine. The main function `#` checks which parameter is the number `n` / string `str` and calls `q` with either `(div (length str) n, mod (length str) n)` or `(n, 0)` plus `str`. [Answer] # C# (LINQPAD) - 335 bytes ``` var y=Util.ReadLine().Split(',');int x,j=0;var t=int.TryParse(y[0].Trim(),out x);x=x==0?int.Parse(y[1].Trim()):x;var i=t?y[1].Trim():y[0];var z="";if(!t){while(i.Substring(j).Length>x){z+=i.Substring(j).Length>x?i.Substring(j,x)+", ":"";j+=x;}z+=i.Substring(j);}else z=string.Join(", ",i.Split(x).Select(s=>string.Concat(s)));z.Dump(); ``` The input reading part took up a bit of space. Winner of longest answer. Usage #1: ``` $ 3, helloworld >> hell, owo, rld ``` Usage #2: ``` $ helloworld, 3 >>hel, low, orl, d ``` [Answer] ## Pyth, 181 bytes Let's pretend the longest code in bytes wins \o/ ``` DyGK@G0J:@G1"."1=YJV%lJKW<[[email protected]](/cdn-cgi/l/email-protection)=YXYN+@YN@YhN=Y.DYhN)FNr%lJK/-lJ%lJK/-lJ%lJKKW<l@YNsclJK=YXYN+@YN@YhN=Y.DYhN))RY)DPG=K@G1=J:@G0"."1=YJV/lJKW<l@YNK=YXYN+@YN@YhN=Y.DYhN))RY).xyQPQ ``` [Try it here !](https://pyth.herokuapp.com/?code=DyGK%40G0J%3A%40G1%22.%221%3DYJV%25lJKW%3Cl%40YN.EclJK%3DYXYN%2B%40YN%40YhN%3DY.DYhN%29FNr%25lJK%2F-lJ%25lJK%2F-lJ%25lJKKW%3Cl%40YNsclJK%3DYXYN%2B%40YN%40YhN%3DY.DYhN%29%29RY%29DPG%3DK%40G1%3DJ%3A%40G0%22.%221%3DYJV%2FlJKW%3Cl%40YNK%3DYXYN%2B%40YN%40YhN%3DY.DYhN%29%29RY%29.xyQPQ%0A&input=%5B3%2C%20%20%22helloworld%22%5D&test_suite_input=%5B3%2C%20%20%22helloworld%22%5D&debug=0) (The online interpreter seem to have a bug, it displays the input while it should not) Here's the output from the terminal: ``` » pyth split.pyth <<<'["helloworld", 3]' ['hel', 'low', 'orl', 'd'] » pyth split.pyth <<<'[3, "Helloworld"]' ['Hell', 'owo', 'rld'] ``` Seriously, I am open to new approach. I'm new to python, so I probably missed a few shorthands. I mean, I think my answer is deseperate from the point it is longer than the javascript answer... [Answer] # PHP, 114 bytes ``` [$t,$n,$p]=$argv;for(@+$p?$s=$n:$f=$n*($p=strlen($s=$p)/$n)%$n;$t;)echo$t=substr($s,$a+=$e,$e=$p+($i++<$f)|0)," "; ``` * String should not start with digits. (Replace `+@$p` with `is_numeric($p)` to fix.) * Output should not contain a chunk "0". (Insert `~` for printable ASCII, `a&` for any ASCII before `$t;` to fix.) * Run with `-nr` or [try it online](http://sandbox.onlinephpfunctions.com/code/69f2fd868a9a43c7bfe7d72f517c2694fab9300a). [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~122~~ 118 bytes ``` param($a,$b)if($a-is[int]){$a,$b=$b,((($l=$b|% Le*)-($c=$l%$a))/$a)}$a-split("(..{$b})"*$c+"(.{0,$b})"*$a.Length)-ne'' ``` [Try it online!](https://tio.run/##jVLRaoMwFH33Ky4hnUkXuxX70A4K/YD@wRgjtdHKUnWa0YH1291N7KIbDJaHm9xz7jk3N6QqL6puTkrrnqawhbavZC3PjEpBDzxP8RDlzXNemBfeOnBLD4IxRjUerjPYqzmPGE22VM@o5PwBQ4eiptK5YYQtFi09dJzMaXKPWfsobqlc7FWRmROPChWGfRcEOxYALhYLCO2NyktZ62MIIGDHHBIig6jdLMO5GBTTcgHxqLCVSDhd7bKJaolpVZcZznvOiywcVFNkbDBFBSxvpe4iztyGzKfShrMPuQ3FUOIt1390d3aD1X9sft1s/XMIJ5sOskEgKY8KslKn@LRDeeJnsO8XKhvAj@QI93jppO/oImDjjTzoC1eoW8axaSol33xHRKyhaWysXENkR/dRIWA1ERlbaQm7W0HA4QozaJ3OfVBB1WelEqOO@J/p60DUqvnQBoE7/OZUAj04nFBGbhyJ1DvxUsKfvkUk6Pov "PowerShell – Try It Online") Less golfed: ``` param($a,$b) if($a-is[int]){ $length=$b|% Length $c=$length%$a $a,$b=$b,(($length-$c)/$a) # recalc length and swap } $pattern="(..{$b})"*$c+"(.{0,$b})"*$a.Length $parts=$a -split $pattern # pattern like '(..{3})(..{3})(.{0,3})(.{0,3})(.{0,3})' $parts -ne '' # output not empty parts ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 69 bytes ``` ->a,b{a.scan /.{1,#{b}}/ rescue b.scan /.{1,#{b.size.fdiv(a).ceil}}/} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsEiN9ulpSVpuhY3XXXtEnWSqhP1ipMT8xT09aoNdZSrk2pr9RWKUouTS1MVklBl9Iozq1L10lIyyzQSNfWSUzNzgGproYZpFyi4RSsVFOWnFyXm5mbmpSvpKBjHcoFEjXUUUCRiIVoWLIDQAA) ]
[Question] [ ## Background The Fibonacci tiling is a tiling of the (1D) line using two segments: a short one, *S*, and a long one, *L* (their length ratio is the golden ratio, but that's not relevant to this challenge). For a tiling using these two prototiles to actually be a Fibonacci tiling, the following conditions have to be fulfilled: * The tiling must not contain the subsequence *SS*. * The tiling must not contain the subsequence *LLL*. * If a new tiling is composed by performing all of the following substitutions, the result must still be a Fibonacci tiling: 1. *LL* → *S* 2. *S* → *L* 3. *L* → *(empty string)* Let's look at some examples: ``` SLLSLLSLLSLS ``` This looks like a valid tiling, because it doesn't contain two \*S\*s or three \*L\*s but let's perform the composition: ``` LSLSLSLL ``` That still looks fine, but if we compose this again, we get ``` LLLS ``` which is not a valid Fibonacci tiling. Therefore, the two previous sequences weren't valid tilings either. On the other hand, if we start with ``` LSLLSLSLLSLSLL ``` and repeatedly compose this to shorter sequences ``` LSLLSLLS LSLSL LL S ``` all results are valid Fibonacci tilings, because we never obtain *SS* or *LLL* anywhere inside those strings. For further reading, there is [a thesis](http://www.math.yorku.ca/~ejross/math/thesis.pdf) which uses this tiling as a simple 1D analogy to Penrose tilings. ## The Challenge Write a program or function which, given a non-negative integer *N*, returns all valid Fibonacci tiling in the form of strings containing *N* characters (being `S` or `L`). You may take input via function argument, STDIN or ARGV and return or print the result. This is code golf, the shortest answer (in bytes) wins. ## Examples ``` N Output 0 (an empty string) 1 S, L 2 SL, LS, LL 3 LSL, SLS, LLS, SLL 4 SLSL, SLLS, LSLS, LSLL, LLSL 5 LLSLL, LLSLS, LSLLS, LSLSL, SLLSL, SLSLL ... 8 LLSLLSLS, LLSLSLLS, LSLLSLLS, LSLLSLSL, LSLSLLSL, SLLSLLSL, SLLSLSLL, SLSLLSLL, SLSLLSLS ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 43 [bytes](https://github.com/abrudz/SBCS) ``` (1+∘÷⍣=1){'LS'[∪2</⍺|(⍺×(⍳÷⊢)2*⍵)∘.+⍳⍵]}1∘+ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkG/zUMtR91zDi8/VHvYltDzWp1n2D16Ecdq4xs9B/17qrRABKHpwPJzUAVXYs0jbQe9W7VBGrQ0waKAdmxtYZAnvb/NKBhj3r7HnU1H1pv/KhtItCC4CBnIBni4Rn8P03BkEtXV5crTcEIShtDaRMobQqlLbg089PSuAwVwCBYR8GHywjK9gFyQAI@XMYQER@QUDBELBjE8uEygamFSIHlgqGkD1idD5cpVDdCCCoPVQzVCTEbaKaenh6XBZIemI0ILSgsiDt94EagsMBWQiURrGAA "APL (Dyalog Unicode) – Try It Online") This uses the alternative formulation (actually the first one) shown in the linked paper: the closest integer staircase to the line \$y = x/\phi\$, where \$\phi\$ is the golden ratio \$\frac{\sqrt5+1}{2}\$. Given the initial vertical offset from the line \$h\$ (which can be positive or negative), the next term (one of `LS`) can be determined by the following rule: * If \$h<0\$ (below the line), \$h←h+1\$ and emit `S`. * Otherwise (over the line), \$h←h-(\phi-1)\$ and emit `L`. Since \$h-(\phi-1) = h+1-\phi\$, we can always increment and take modulo \$\phi\$ of it. Then the condition \$h<0\$ changes to \$h<\phi-1\$, but it doesn't affect the resulting sequence of terms. Then the problem becomes to sample enough values for initial \$h\$ so that we can get all possible sequences of `SL` for any given length \$n\$. I choose \$2^{n+1}\$ points uniformly spaced over the interval \$[0,\phi)\$, which works for small \$n\$, and the gap size reduces faster than that induced by the collection of lines \$y=x/\phi+c\$, each passing through some lattice point inside \$0 \le x \le n\$. Finally, I determine the actual `SL` terms by checking each consecutive pair: `S` if `left < right`, `L` otherwise, and take unique sequences. ``` (1+∘÷⍣=1){'LS'[∪2</⍺|(⍺×(⍳÷⊢)2*⍵)∘.+⍳⍵]}1∘+ ⍝ Input: n (1+∘÷⍣=1){...}1∘+ ⍝ Pass n+1 and phi to the inner dfn... ⍳⍵ ⍝ Range 0..n ∘.+ ⍝ Outer product by addition... (⍺×(⍳÷⊢)2*⍵) ⍝ 2^(n+1) uniformly separated numbers in [0,phi) ⍺| ⍝ Modulo phi 2</ ⍝ Pairwise comparison in row direction ⍝ (1 if right is higher, 0 otherwise) ∪ ⍝ Take unique rows 'LS'[...] ⍝ Map 0, 1 to L, S ``` [Answer] # CJam, ~~70~~ ~~62~~ 59 bytes ``` Qali{_'L:Xf+\'S:Yf++}*{{_X2*/Xf-Yf/Xf*Y*}h]N*_X3*#\Y2*#=},p ``` Reads from STDIN. [Try it online.](http://cjam.aditsu.net/ "CJam interpreter") ### Example run ``` $ cjam tilings.cjam <<< 5 ["LLSLL" "SLSLL" "SLLSL" "LSLSL" "LSLLS" "LLSLS"] ``` ### How it works The idea is to push all strings of L's and S's of the proper length, successively apply the transformation to each until the result is an empty string, concatenate the sequences of strings and search for the forbidden substrings. ``` Qa " Push R := [ '' ]. "; li{ " Do the following int(input()) times: "; _'L:Xf+ " Append (X := 'L') to a copy of all strings in R. "; \'S:Yf+ " Append (Y := 'S') to all original strings in R. "; + " Concatenate the arrays into R. "; }* " R now contains all strings of L's and S's of length int(input()). "; { " For each S ∊ R: "; { " "; _ " Push a copy of S. "; X2*/ " Split S at 'LL'. "; Xf- " Remove 'L' from the chunks. "; Yf/ " Split the chunks at 'S'. "; Xf* " Join the chunks, separating by 'L'. "; Y* " Join, separating by 'S'. "; }h " If the resulting string is non-empty, repeat. "; ]N* " Join the array of resulting strings from S to '', separating by linefeeds. "; _X3*# " Push the index of 'LLL' a copy in the resulting string (-1 if not present). "; \Y2*# " Push the index of 'SS' in the original string (-1 if not present). "; = " Check if the indexes are equal; this happens if and only if both are -1. "; }, " Filter: Keep S in R if and only if = pushed 1. "; p " Print a string representation of R. "; ``` [Answer] ## GolfScript (86 bytes) ``` ~:|'LS'1/\{{.{1&!'LLS'2/=}%'SS'/'SLS'*[.(1&{'LS'\+}*]{.)1&{'SL'+}*}/}%.&}*['']+{,|=},p ``` This is an inflationary approach: it starts with `L` and `S` and expands them using the rules `LL -> SLS`, `L -> S`, `S -> LL`, and leading or trailing `S` can have an `L` added at the word boundary. [Online demo](http://golfscript.apphb.com/?c=Oyc0JwoKfjp8J0xTJzEvXHt7LnsxJiEnTExTJzIvPX0lJ1NTJy8nU0xTJypbLigxJnsnTFMnXCt9Kl17LikxJnsnU0wnK30qfS99JS4mfSpbJyddK3ssfD19LHA%3D) [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 69 bytes ``` ~{Ėl|l.&ċ∈ᵛ"LS"&~c=ᵐ{¬{s₂tʰhᵗ=}&}cᵐ{"LL"∧"S"|"S"∧"L"|"L"∧""}ᵐcẹ↰∧}ᵘcᵐ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/6htw6Ompoe7Omsfbp3wv676yLScmhw9tSPdjzo6Hm6dreQTrKRWl2wLlKw@tKa6GKi25NSGjIdbp9vWqtUmg4SVfHyUHnUsVwpWqgFiEMsHyIKIKYFMTX64ayfImo7lQN4MkJ7//6MNdAx1jHSMdUx0TGMB "Brachylog – Try It Online") ### How it works First define a predicate, that has a valid fibonacci tiling as input (as a list of `"L"` and `"S"`), and its length as output. ``` Ėl| ``` It's either an empty list `Ė`, returning it's length `l` or … ``` l.&ċ∈ᵛ"LS" ``` Something which length is the output and is a list which elements all are elements of `"LS"`. (This part was rather annoying for how simple it should be; I couldn't generate *strings* up to length `N` consisting of `"LS"`.) ``` &~c=ᵐ ``` Also, the input splitted in groups where each group has only one unique element, e.g. `[S, LL, S]` or `[S, L, L, S]` or `[LLLL]` … ``` {¬{s₂tʰhᵗ=}&} ``` Has no two consecutive groups where the first group's last element and the second group's first element are the same – to filter out `[S, L, L, S]`. (Is there a way to drop `{…&}` here?) ``` cᵐ{"LL"∧"S"|"S"∧"L"|"L"∧""}ᵐcẹ↰∧ ``` Those groups are then replaced. If a group doesn't match one of the three rules, the whole partition of the string gets thrown out, i.e. `[LLLL]` isn't valid. The replaced groups then, converted to a list, must also fulfill this predicate. ``` ~{…}ᵘcᵐ ``` We now find all unique fibonacci tilings that have the length of the input and convert the lists back to strings. [Answer] Haskell, 217 ``` import Control.Monad data F=L|S deriving (Eq) f n=filter s$replicateM n [L,S] r (L:L:m)=S:r m r (S:m)=L:r m r (L:m)=r m r []=[] s []=True s m|v m=s$r m s _=False v (L:L:L:_)=False v (S:S:_)=False v (_:m)=v m v []=True ``` Explaination: I define 4 functions: * `f` takes an integer and returns the result `replicateM n [L,S]` creates all possible permutations of `[L,S]` with the length `n` `filter s ...` will filter this list (of lists) with the function `s` * `r` reduces a a given list by 1 level. This is simply done by pattern matching. A list starting with 2 `L` will become a list starting with `S` and the reduced remaining * `v` validates a given list by the rules given (no 3 continuous L, no 2 continous S) if the list starts with one of the 2 illegal sequences (L,L,L or S,S) the result is `False`, an empty list is valid, and an non-empty list is checked again with the first element removed * `s` checks if a list and all reduced lists are valid. Again: an empty list is valid (and can't be reduced further). If the list given as argument is valid then the list is reduced ad checked with `s` again. Otherwise the result is `False` ]
[Question] [ Your job is to take this number as input (although it should work with any other number too): ``` 18349570345710975183495703457109751834957034571097518349570345710975183495703457109761834957034571097518349570345710975183495703457109751834957034571097518349570345710976183495703457109751834957034571097518349570345710975183495703457109751834957034571097618349570345710975183495703457109751834957034571097518349570345710975183495703457109761834957034571097518349570345710975183495703457109751834957034571097518349570345710976183495703457109751834957034571097518349570345710975183495703457109751834957034571097618349570345710975183495703457109751834957034571097518349570345710975183495703457109761834957034571097518349570345710975183495703457109751834957034571097518349570345710976183495703457109751834957034571097518349570345710975183495703457109751834957034571097618349570345710975183495703457109751834957034571097518349570345710975183495703457109761834957034571097518349570345710975183495703457109751834957034571097518349570345710976183495703457109751834957034571097518349570345710975183495703457109751834957034571097618349570345710975183495703457109751834957 ``` and find the smallest period, which is in this case: ``` 1834957034571097518349570345710975183495703457109751834957034571097518349570345710976 ``` Good luck and have fun! --- **Clarifications**: * The input number has in minimum one period and one partial period * The period always starts at the beginning of the input number * Period means in this case a sequence of numbers which repeats itself. [Answer] ## Regex (.NET flavour), ~~23~~ 22 bytes ``` .+?(?=(.*$)(?<=^\1.*)) ``` This will match the required period as a substring. [Test it here.](http://regexhero.net/tester/?id=d2f91dfc-88ff-4a21-824a-b49512d0ce5d) How does it work? ``` # The regex will always find a match, so there's no need to anchor it to # the beginning of the string - the match will start there anyway. .+? # Try matching periods from shortest to longest (?= # Lookahead to ensure that what we've matched is actually # a period. By using a lookahead, we ensure that this is # not part of the match. (.*$) # Match and capture the remainder of the input in group 1. (?<= # Use a lookahead to ensure that this remainder is the same # as the beginning of the input. .NET lookaheads are best # read from right to left (because that's how they are matched) # so you might want to read the next three lines from the # bottom up. ^ # Make sure we can reach the beginning of the string. \1 # Match group 1. .* # Skip some characters, because the capture won't cover the # entire string. ) ) ``` [Answer] # CJam, ~~20~~ 16 bytes ``` Ll:Q{+_Q,*Q#!}=; ``` Reads from STDIN. [Try it online.](http://cjam.aditsu.net/ "CJam interpreter") The above code will require **O(n2)** memory, where **n** is the length of the input. It *will* work with 216 digits, as long as you have enough memory. This can be fixed the the cost of five extra bytes: ``` Ll:Q{+_Q,1$,/)*Q#!}=; ``` ### Example run ``` $ cjam <(echo 'Ll:Q{+_Q,*Q#!}=;') <<< 18349570345710975183495703457109751834957034571097518349570345710975183495703457109761834957034571097518349570345710975183495703457109751834957034571097518349570345710976183495703457109751834957034571097518349570345710975183495703457109751834957034571097618349570345710975183495703457109751834957034571097518349570345710975183495703457109761834957034571097518349570345710975183495703457109751834957034571097518349570345710976183495703457109751834957034571097518349570345710975183495703457109751834957034571097618349570345710975183495703457109751834957034571097518349570345710975183495703457109761834957034571097518349570345710975183495703457109751834957034571097518349570345710976183495703457109751834957034571097518349570345710975183495703457109751834957034571097618349570345710975183495703457109751834957034571097518349570345710975183495703457109761834957034571097518349570345710975183495703457109751834957034571097518349570345710976183495703457109751834957034571097518349570345710975183495703457109751834957034571097618349570345710975183495703457109751834957; echo 1834957034571097518349570345710975183495703457109751834957034571097518349570345710976 $ cjam <(echo 'Ll:Q{+_Q,*Q#!}=;') <<< 12345123451; echo 12345 $ cjam <(echo 'Ll:Q{+_Q,*Q#!}=;') <<< 1234512345; echo 12345 $ cjam <(echo 'Ll:Q{+_Q,*Q#!}=;') <<< 123451; echo 12345 ``` ### How it works For input Q, the idea is to repeat the first character len(Q) times and check if the index of Q in the result is 0. If it isn't, repeat the first *two* characters len(Q) times, etc. ``` L " Push L := []. "; l:Q " Read one line from STDIN and save the result in Q. "; { }= " Find the first element q ∊ Q that yields a truthy value: "; + " Execute L += [q]. "; _Q,*Q# " Push (L * len(Q)).index(Q). "; ! " Compute the logical NOT of the index. "; ; " Discard the last q. This leaves L on the stack. "; ``` [Answer] # Python 60 `s` is the string of digits ``` [s[:i]for i in range(len(s))if(s[:i]*len(s))[:len(s)]==s][0] ``` eg: ``` >>> s = '18349570345710975183495703457109751834957034571097518349570345710975183495703457109761834957034571097518349570345710975183495703457109751834957034571097518349570345710976183495703457109751834957034571097518349570345710975183495703457109751834957034571097618349570345710975183495703457109751834957034571097518349570345710975183495703457109761834957034571097518349570345710975183495703457109751834957034571097518349570345710976183495703457109751834957034571097518349570345710975183495703457109751834957034571097618349570345710975183495703457109751834957034571097518349570345710975183495703457109761834957034571097518349570345710975183495703457109751834957034571097518349570345710976183495703457109751834957034571097518349570345710975183495703457109751834957034571097618349570345710975183495703457109751834957034571097518349570345710975183495703457109761834957034571097518349570345710975183495703457109751834957034571097518349570345710976183495703457109751834957034571097518349570345710975183495703457109751834957034571097618349570345710975183495703457109751834957' >>> [s[:i]for i in range(len(s))if(s[:i]*len(s))[:len(s)]==s][0] '1834957034571097518349570345710975183495703457109751834957034571097518349570345710976' ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 14 characters ``` hf}z*lzTm<zdUz ``` Explanation: ``` implicit: z = input() h head( f filter(lambda T: }z z in *lz len(z) * T T, m map(lambda d: <zd z[:d], Uz range(len(d))))) ``` Essentially, it generates all of the initial sequences of the input, repeats each one `len(z)` times, and sees whether `z`, the input, lies within the resultant string. --- This is not a valid answer, but a feature was recently added to Pyth, after the question was asked, that allows a 12 character solution: ``` <zf}z*lz<zT1 ``` This uses the filter on integer feature. [Answer] # [Japt](https://github.com/ETHproductions/japt), 8 bytes ``` å+ æ@¶îX ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVI=&code=5Ssg5kC27lg=&input=WyIxIiwiMTEiLCIxMTEiLCIxMiIsIjEyMTIiLCIxMjEyMTIiLCIxMjMiLCIxMjMxMjMiLCIxMjMxMjMxMjMiLCIxODM0OTU3MDM0NTcxMDk3NTE4MzQ5NTcwMzQ1NzEwOTc1MTgzNDk1NzAzNDU3MTA5NzUxODM0OTU3MDM0NTcxMDk3NTE4MzQ5NTcwMzQ1NzEwOTc2MTgzNDk1NzAzNDU3MTA5NzUxODM0OTU3MDM0NTcxMDk3NTE4MzQ5NTcwMzQ1NzEwOTc1MTgzNDk1NzAzNDU3MTA5NzUxODM0OTU3MDM0NTcxMDk3NjE4MzQ5NTcwMzQ1NzEwOTc1MTgzNDk1NzAzNDU3MTA5NzUxODM0OTU3MDM0NTcxMDk3NTE4MzQ5NTcwMzQ1NzEwOTc1MTgzNDk1NzAzNDU3MTA5NzYxODM0OTU3MDM0NTcxMDk3NTE4MzQ5NTcwMzQ1NzEwOTc1MTgzNDk1NzAzNDU3MTA5NzUxODM0OTU3MDM0NTcxMDk3NTE4MzQ5NTcwMzQ1NzEwOTc2MTgzNDk1NzAzNDU3MTA5NzUxODM0OTU3MDM0NTcxMDk3NTE4MzQ5NTcwMzQ1NzEwOTc1MTgzNDk1NzAzNDU3MTA5NzUxODM0OTU3MDM0NTcxMDk3NjE4MzQ5NTcwMzQ1NzEwOTc1MTgzNDk1NzAzNDU3MTA5NzUxODM0OTU3MDM0NTcxMDk3NTE4MzQ5NTcwMzQ1NzEwOTc1MTgzNDk1NzAzNDU3MTA5NzYxODM0OTU3MDM0NTcxMDk3NTE4MzQ5NTcwMzQ1NzEwOTc1MTgzNDk1NzAzNDU3MTA5NzUxODM0OTU3MDM0NTcxMDk3NTE4MzQ5NTcwMzQ1NzEwOTc2MTgzNDk1NzAzNDU3MTA5NzUxODM0OTU3MDM0NTcxMDk3NTE4MzQ5NTcwMzQ1NzEwOTc1MTgzNDk1NzAzNDU3MTA5NzUxODM0OTU3MDM0NTcxMDk3NjE4MzQ5NTcwMzQ1NzEwOTc1MTgzNDk1NzAzNDU3MTA5NzUxODM0OTU3MDM0NTcxMDk3NTE4MzQ5NTcwMzQ1NzEwOTc1MTgzNDk1NzAzNDU3MTA5NzYxODM0OTU3MDM0NTcxMDk3NTE4MzQ5NTcwMzQ1NzEwOTc1MTgzNDk1NzAzNDU3MTA5NzUxODM0OTU3MDM0NTcxMDk3NTE4MzQ5NTcwMzQ1NzEwOTc2MTgzNDk1NzAzNDU3MTA5NzUxODM0OTU3MDM0NTcxMDk3NTE4MzQ5NTcwMzQ1NzEwOTc1MTgzNDk1NzAzNDU3MTA5NzUxODM0OTU3MDM0NTcxMDk3NjE4MzQ5NTcwMzQ1NzEwOTc1MTgzNDk1NzAzNDU3MTA5NzUxODM0OTU3MDM0NTcxMDk3NTE4MzQ5NTcwMzQ1NzEwOTc1MTgzNDk1NzAzNDU3MTA5NzYxODM0OTU3MDM0NTcxMDk3NTE4MzQ5NTcwMzQ1NzEwOTc1MTgzNDk1NyJdCi1tUg==) -2 bytes thanks to Shaggy! Transpiled JS Explained: ``` // U is the input string representation of the number U // cumulative reduce using the '+' operator // the result is an array of strings length 1, 2, ..., N // all substrings start with the first character from input .å("+") // find the first match .æ(function(X, Y, Z) { // repeat the substring until it is as long as the input // and compare it to the input return U === U.î(X) }) ``` [Answer] # Java 8, 125 bytes Takes input as a string since there is no reasonable way to represent a 1000+ digit number in Java other than a string (No BigInteger please). ``` s->{String o="";for(int i=0;java.util.Arrays.stream(s.split(o+=s.charAt(i++))).filter(b->!b.isEmpty()).count()>1;);return o;} ``` [Try it online!](https://tio.run/##7Y4xb4MwFIR3foXLZAthgRJKIwukDM3WKWPVwRDcPmpsZD8iIcRvpx7Sf9CpYrrT6b3vrpd3mfa3763V0nvyJsEsERjsnJJtRy7LFR2YT6Low3gm1micGg0t8SgxyN3CjQzh83Hz/iHZEl2IItXm0/oXYas4Fso6GvAEqkz0oZtPCJqfnZOz5x5dJwcazKgBqU0qz9sv6c5IIUkYY1yBDtNok9ZPDQf/Oow405C3djJIWZ0LJlyHkzPEinUT0XX22A3cTsjHsAK1oYorGucvh@OpKLPDsSjz7FQWfxA879AdukP/DzRmTETruv0A) ]
[Question] [ This is a model of a forgiving HTML parser. Instead of parsing HTML and extracting attributes, in this code golf, the tag parser will be simple. Write a function that parses a tag structure and returns its parenthized form. An opening tag consists of one lowercase letter, and a closing tag consists of one uppercase letter. For example, `aAbaAB` parses into `(a)(b(a))`, or in HTML, `<a></a><b><a></a></b>`. Of course, tags can be in juxtaposition and nest. "Prematurely" closed tags must be handled. For example, in `abcA`, the `A` closes the outermost `a`, so it parses into `(a(b(c)))`. Extra closing tags are simply ignored: `aAB` parses into `(a)`. Overlapping tags are NOT handled. For example, `abAB` parses into `(a(b))`, not `(a(b))(b)`, by the previous rule of extra closing tags (`abAB` -> `abA` (`(a(b))`) + `B` (extra)). Assuming no whitespaces and other illegal characters in the input. You are not allowed to use any library. Here is a reference implementation and a list of test cases: ``` #!/usr/bin/python def pars(inpu): outp = "" stac = [] i = 0 for x in inpu: lowr = x.lower() if x == lowr: stac.append(x) outp += "(" + x i = i + 1 else: while len(stac) > 1 and stac[len(stac) - 1] != lowr: outp += ")" stac.pop() i = i - 1 if len(stac) > 0: outp += ")" stac.pop() i = i - 1 outp += ")" * i return outp tests = [ ("aAaAbB", "(a)(a)(b)"), ("abBcdDCA", "(a(b)(c(d)))"), ("bisSsIB", "(b(i(s)(s)))"), ("aAabc", "(a)(a(b(c)))"), ("abcdDA", "(a(b(c(d))))"), ("abcAaA", "(a(b(c)))(a)"), ("acAC", "(a(c))"), ("ABCDEFG", ""), ("AbcBCabA", "(b(c))(a(b))") ] for case, expe in tests: actu = pars(case) print "%s: C: [%s] E: [%s] A: [%s]" % (["FAIL", "PASS"][expe == actu], case, expe, actu) ``` Shortest code wins. [Answer] ## Haskell, 111 characters ``` s@(d:z)§c|c>'^'=toEnum(fromEnum c-32):s++'(':[c]|d<'='=s|d==c=z++")"|1<3=(z++")")§c p=tail.foldl(§)"$".(++"$") ``` This one's pretty golf'd for Haskell. Fun feature: The stack and the accumulating output are kept in the same string! Test cases: ``` > runTests Pass: aAbaAB parsed correctly as (a)(b(a)) Pass: abcA parsed correctly as (a(b(c))) Pass: aAB parsed correctly as (a) Pass: abAB parsed correctly as (a(b)) Pass: aAaAbB parsed correctly as (a)(a)(b) Pass: abBcdDCA parsed correctly as (a(b)(c(d))) Pass: bisSsIB parsed correctly as (b(i(s)(s))) Pass: aAabc parsed correctly as (a)(a(b(c))) Pass: abcdDA parsed correctly as (a(b(c(d)))) Pass: abcAaA parsed correctly as (a(b(c)))(a) Pass: acAC parsed correctly as (a(c)) Pass: AbcBCabA parsed correctly as (b(c))(a(b)) ``` --- * Edit: (113 → 111) used an `@` pattern as suggested by FUZxxl [Answer] # Z80 Machine Code for TI-83+, 41 bytes This is an implementation in hexadecimal machine code for a z80 cpu running on a TI-83+. `11XXXX131AFE61380F6FE53E28CD9DB47DCD9DB4188EE1BDC03E29CD9DB4189BEF4504E5214CE1C9` The XXXX (3 - 6 inclusive) is the 16-bit address of the string you are parsing, minus 1 byte. Encoded in Z80-ASCII: `¹XX≤¯•⟙8𝑭o↥>(ˣïÑ}ˣïÑ≠á↑γ∊>)ˣïÑ≠Ì⬆︎E𝑤↥!₄L↑Φ` (Approximate, because TI calculators have their own character set.) NOTE THAT THE `AsmPrgm` IS NOT INCLUDED IN THE ABOVE [Answer] ## Windows PowerShell, 142 ~~146~~ ~~147~~ ~~152~~ ~~156~~ ~~169~~ ``` {$s='' -join([char[]]"$args "|%{if(90-ge$_){')'*(($x=$s.indexOf("$_".ToLower())+1)+$s.Length*!$x) $s=$s.substring($x)}else{"($_" $s="$_$s"}})} ``` Some things to note: This is just a script block. It can be assigned to a variable or given a function name, if necessary. You can also run it by putting `.` or `&` in front of it and the arguments at the end. Uses a final space to terminate unclosed tags. Passes all tests. Test script: ``` $tests = ("aAaAbB","(a)(a)(b)"),("abBcdDCA","(a(b)(c(d)))"),("bisSsIB","(b(i(s)(s)))"),("aAabc","(a)(a(b(c)))"),("abcdDA","(a(b(c(d))))"),("abcAaA", "(a(b(c)))(a)"),("acAC","(a(c))") "function f " + ((gc ./tags.ps1)-join"`n") | iex $tests | %{ $result = f $_[0] ("FAIL: $($_[0]):$($_[1]) - $result", 'PASS')[$result -ceq $_[1]] } ``` [Answer] # Python - 114 113 153 192 174 159 characters ``` from sys import * s="";c=a=argv[1] for f in a: o=c.find;p=f.lower if '@'<f<'\\': \td=o(f)-o(p()) \ts+=")"*d \tc=(c[:o(p())]+c[o(f)+1:]) else:s+=("("+f) print s ``` Abuses python's indentation parser to use one space for a full tab, five for two tabs. **Edit 1** - saved an unneeded space in the range() function **Edit 2** - fixed to deal with improper parse grammars, unterminated tags. **Edit 3** - fixed a bug whereby "incorrect" parses could be generated by ambiguity in the tag tree. Implemented a stack-based strategy, rather than a counter. **Edit 4** - renamed s.find to o to prevent save the chars used to repeatedly call it. did the same for f.lower. **Edit 5** - added the space/tab hack, saving three chars. **Edit 6** - ditched the loop in favor of ")"\*d. [Answer] ## Golfscript, 54 chars ``` {[]:|\{.96>{.|+:|;40\}{32+|?).')'*\|>:|;}if}%|,')'*}:$ ``` Tests ``` ;["aAaAbB" "abBcdDCA" "bisSsIB" "aAabc" "abcdDA" "abcAaA" "acAC" "aAB" "abAB" "AbcBCabA"]{.' '\$n}% aAaAbBaAaAbB (a)(a)(b) abBcdDCA (a(b)(c(d))) bisSsIB (b(i(s)(s))) aAabc (a)(a(b(c))) abcdDA (a(b(c(d)))) abcAaA (a(b(c)))(a) acAC (a(c)) aAB (a) abAB (a(b)) AbcBCabA (b(c))(a(b)) ``` ]
[Question] [ Following the great advice (what do you mean *it's not advice*?!) on [Adding unnecessary fluff](https://codegolf.meta.stackexchange.com/a/9384) we can devise the following task: * Take a list of positive integers and a positive integer \$m\$ as input. * Only keep the prime values from the list. * Define \$f(n) = F\_{n^2 + 1}\$ (the \$n^2+1\$-th element in the Fibonacci sequence, starting from \$F\_0=0, F\_1=1\$), \$g(n) = \underbrace{f(f(\cdots f(n)\cdots))}\_{m\text{ applications of }f}\$, and \$h(n) = \begin{cases}h(g(n) \mod n) + 1&n\neq0\\0&n=0\end{cases}\$. * Apply \$h\$ to each element on the list. * Return the median (you can assume the input contained an odd number of primes). ## Test cases ``` [2,7,11,10,14,4,9], 1 -> 2 [2,7,11,5,13,10,14,4,9], 1 -> 2 [5,5,11,5,13,93,94,95,9], 1 -> 3 [5,7,11], 2 -> 2 [5,5,11], 2 -> 1 [5,43,67], 2 -> 3 [5,43,67], 2 -> 3 [977], 2 -> 5 [719, 727, 733, 739, 743], 2 -> 4 [967], 10 -> 4 [977], 10 -> 3 [5], 10 -> 1 ``` [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. You can use any reasonable I/O format. This is code golf, so the shortest answer in each language wins. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 28 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` DpÏε"ÐĀiIFn>Åf}s%®.V>"©.V}Åm ``` Times out for the \$m\geq2\$ test cases, but works in theory. [Try it online](https://tio.run/##AUIAvf9vc2FiaWX//0Rww4/OtSLDkMSAaUlGbj7DhWZ9cyXCri5WPiLCqS5WfcOFbf//WzIsNywxMSwxMCwxNCw0LDldCjE) or [verify all `m=1` test cases](https://tio.run/##yy9OTMpM/V9WGZRgr6SQmJeikGurZA9kPmqbpKBkX5kQ@t@l4HD/ua1KhyccaciMcMuzO9yaVlusemidXpid0qGVemG1h1tz/@v8j46ONtIx1zE01DE00DE00THRsYzVMYzVUYCLm@oYGmNKmoLEoZKWQASUMoXIxgIA). **Explanation:** ``` DpÏ # Only keep the primes of the first (implicit) input-list ε # Map over each prime: "..." # Define recursive string `h` explained below © # Store this string in variable `®` (without popping) .V # Execute it as 05AB1E code, with the current prime as argument }Åm # After the map: Pop and push its median # (which is output implicitly as result) Ð # Triplicate the current value Āi # Pop one, and if it's NOT 0: IF # Loop the second input-integer `m` amount of times: n> # Square the current value, and then increase it by 1 Åf # Pop and push the 0-based Fibonacci number }s # After the loop: swap so a copy of the triplicated number is at the top % # Modulo ®.V # Then do a recursive call to `®` > # And increase it by 1 # (implicit else:) # (implicitly use the triplicated 0) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 20 bytes ``` ²‘ÆḞƊ⁴¡%⁸ßẸ¡‘ ẒƇÇ€Æṁ ``` [Try it online!](https://tio.run/##y0rNyan8///QpkcNMw63Pdwx71jXo8YthxaqPmrccXj@w107Di0EynA93DXpWPvh9kdNa4CKdjb@f7hzn/WjhjkKunYKjxrmWh9u5wJLRv7/H22kY65jaKhjaKBjaKJjomMZqwMTMtUxNEYRNwUJQcUtgQgoagqU@G8IAA "Jelly – Try It Online") A full program taking the list of integers as the first argument and \$m\$ as the second. Prints the result to STDOUT. The TIO link includes a footer that evaluates the first three examples. Times out where \$m \ge 2\$. ## Alternative approach [Jelly](https://github.com/DennisMitchell/jelly), 36 bytes ``` ẒƇµØ.;S$%ḊɗƬLƊ⁹СḊU²‘%ÆḞʋƒ%µ¹Ð¿)ẈÆṁ’ ``` [Try it online!](https://tio.run/##y0rNyan8///hrknH2g9tPTxDzzpYRfXhjq6T04@t8TnW9ahx5@EJhxYCBUIPbXrUMEP1cNvDHfNOdR@bpHpo6yGQ3H7Nh7s6gKI7Gx81zPz/cOc@60cNcxR07RQeNcy1Prxcn@vh7i2Hth6d/HDnYoTEwx2LHu6Y/6hxW9jhds3I//@VlJSijXTMdQwNdQwNdAxNdEx0LGN1FAxByo24YFKmOobGWOVNQVJQeUsgAsqaIhQYgxSADAAKGKHogAkYggRMjHXMzGEixthELM3hPFOuaHNDSx0FcyNzIGFsDCJAXBNjmAoToHqwbkMDGNccwQWZD@cYAr0PAA "Jelly – Try It Online") A dyadic link taking the list of integers as its left argument and \$m\$ as its right, and returning the result. Works for all of the examples in under two seconds total. Full explanation to follow, but in brief: 1. For a given integer \$n\$: 1. Generate \$\pi(n)\$, \$\pi(\pi(n))\$, \$\pi(\pi(\pi(n)))\$ … so we have \$m\$ levels of this. Here \$\pi(n)\$ is the Pisano period which is the period of the Fibonacci sequence \$\mod n\$. 2. Reverse these. So for example where \$n = 977\$ and \$m = 5\$, we have a list of `[120, 120, 120, 984, 652]`. 3. Starting with \$n\$, reduce using each member of the list with the following dyadic function: \$ F((x ^ 2 + 1) \bmod y) \$ where \$F(z)\$ is the zth Fibonacci sequence member. 4. Take the result of this reduction \$ \bmod n\$ 2. If the result is non-zero, repeat the above using the result as the new \$n\$. 3. Count how many steps it takes to get to zero. 4. Repeat for all of the other prime integers, and take the median. ### Line by line explanation ``` ẒƇµØ.;S$%ḊɗƬLƊ⁹СḊU²‘%ÆḞʋƒ%µ¹Ð¿)ẈÆṁ’­⁡​‎‎⁡⁠⁡‏⁠‎⁡⁠⁢‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁣‏⁠‎⁡⁠⁢⁤⁤‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁢⁣⁤‏⁠‎⁡⁠⁢⁤⁡‏⁠‎⁡⁠⁢⁤⁢‏⁠‎⁡⁠⁢⁤⁣‏‏​⁡⁠⁡‌⁤​‎⁠‎⁡⁠⁤⁢‏⁠‎⁡⁠⁤⁣‏⁠‎⁡⁠⁤⁤‏⁠‎⁡⁠⁢⁡⁡‏‏​⁡⁠⁡‌⁢⁡​‎‎⁡⁠⁤‏⁠‎⁡⁠⁢⁡‏⁠‎⁡⁠⁣⁣‏⁠‎⁡⁠⁣⁤‏‏​⁡⁠⁡‌⁢⁢​‎‎⁡⁠⁢⁢‏⁠‎⁡⁠⁢⁣‏⁠‎⁡⁠⁢⁤‏‏​⁡⁠⁡‌⁢⁣​‎⁠‎⁡⁠⁣⁡‏‏​⁡⁠⁡‌⁢⁤​‎⁠‎⁡⁠⁣⁢‏‏​⁡⁠⁡‌⁣⁡​‎‎⁡⁠⁤⁡‏‏​⁡⁠⁡‌⁣⁢​‎‎⁡⁠⁢⁡⁢‏‏​⁡⁠⁡‌⁣⁣​‎‎⁡⁠⁢⁡⁣‏‏​⁡⁠⁡‌⁣⁤​‎‎⁡⁠⁢⁣⁡‏⁠‎⁡⁠⁢⁣⁢‏‏​⁡⁠⁡‌⁤⁡​‎‎⁡⁠⁢⁡⁤‏‏​⁡⁠⁡‌⁤⁢​‎‎⁡⁠⁢⁢⁡‏‏​⁡⁠⁡‌⁤⁣​‎‎⁡⁠⁢⁢⁢‏‏​⁡⁠⁡‌⁤⁤​‎‎⁡⁠⁢⁢⁣‏⁠‎⁡⁠⁢⁢⁤‏‏​⁡⁠⁡‌⁢⁡⁡​‎‎⁡⁠⁢⁣⁣‏‏​⁡⁠⁡‌⁢⁡⁢​‎‎⁡⁠⁣⁡⁡‏‏​⁡⁠⁡‌⁢⁡⁣​‎‎⁡⁠⁣⁡⁢‏⁠‎⁡⁠⁣⁡⁣‏‏​⁡⁠⁡‌⁢⁡⁤​‎‎⁡⁠⁣⁡⁤‏‏​⁡⁠⁡‌­ ẒƇ # ‎⁡Keep primes µ ) # ‎⁢Start a new monadic chain and apply it to each of the primes: µ¹Ð¿ # ‎⁣- Repeat until zero, collecting up intermediate results: Ɗ⁹С # ‎⁤ - Do the following the number of times indicated by the link’s right argument, collecting up intermediate results (argument starts as one of the primes): Ø. ɗƬ # ‎⁢⁡ - Do the following starting with [0, 1] and with the current value of n as the right argument until no new values are seen (I.e. we’ve reached [0, 1] again): ;S$ # ‎⁢⁢ - Concatenate the sum to the end % # ‎⁢⁣ - Mod n Ḋ # ‎⁢⁤ - Remove first value L # ‎⁣⁡ - Length (which will be Pisano period) Ḋ # ‎⁣⁢ - Remove first value U # ‎⁣⁣ - Reverse order ʋƒ # ‎⁣⁤ - Reduce this list using the following, and starting with the current n ² # ‎⁤⁡ - Squared ‘ # ‎⁤⁢ - Increment by 1 % # ‎⁤⁣ - Mod the current Pisano period ÆḞ # ‎⁤⁤ - Fibonacci number % # ‎⁢⁡⁡ - Mod n Ẉ # ‎⁢⁡⁢Lengths Æṁ # ‎⁢⁡⁣Median ’ # ‎⁢⁡⁤Decrement by 1 💎 ``` Created with the help of [Luminespire](https://vyxal.github.io/Luminespire). [Answer] # [Raku](https://raku.org), 107 bytes ``` ->\v,\m{v.grep(&is-prime).map(->\n{n&&&?BLOCK(([o] &{(0,1,*+*...*)[$^n**2+1]} xx m)(n)%n)+1}).sort[*div 2]} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=ddDdSsMwFAfw6_UpDqOGJE3D0ll0DCfopYIP0HVQXDvKTFrSDzpCn8SbXuiND7H38G3M3HDsQjh_TiA_OJzz_qGTbTN8yR2grFFwB59Nnfm331t_sWzZUpqWb3RaYpRXfqlzmRIukxLbX2UUQuj-4fnl8QnjqIgBGTxhglGPcs4pidyVojTwRNxD14EkWJErRTzRE14Vuo7oOm8hiPvTyP3cyQoNOAoY3DAQwmZic83A1iy2TwYBYRcitG36PwyP4gxnhxxU-CenBPwFYLdN3ioGrrRJu5KAcUZVshuNN0UNxh7nLEjPwJL0tU7Xv3g8d05bDMOx_wA) * `.grep(&is-prime)` filters the prime numbers (&is-prime is a built-in function) * `(0, 1, * + * ... *)` constructs the Fibonacci sequence * `&?BLOCK` is a compile-time variable referring to the current block, so we can recurse with even anonymous functions * `o` is the function composition operator; `[o]` says "reduce with `o`", so we can compose `m` functions with it * `[* div 2]` as an array subscript passes the array length to `*` there, effectively getting the middle element without hussle (`div` is doing floor division) [Answer] # [R](https://www.r-project.org), 241 bytes ``` \(x,m,`~`=sapply,`&`=c,f=`for`,`-`=sum)median(x[x~\(z)2>-!z%%(2:z)]~\(n){while(n){p=n f(i,1:m,{x=1&1 j=2 while(-((x=x[2]&-x%%p[1])>0:1))j=j+1 p=j&p}) f(i,1:m,n<-`if`((n=(n^2+1)%%p[i])<2,n,{x=0:1 f(l,2:n,x<-x[2]&-x%%p[i+1]) x[2]})) F=F+1} F}) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=bVJtitswEKV_dQrXkKBpxkskO3UTIv_MJWwXpa29cXBUEydU9SZ7kVJICz1Ue4u9wY42cXYLC2akeV9g9H782p5-r9Sf_a4MPvx9yLjFDep7rdpl09TfUQ-1-oyl0uXXrUYdELHfwKb4Ui0Nt6m9z3gHMgnedoMBl7MOckIM3H1bVXXhLo0yrOQVitkG76wSQ8HWSrIzH3BulU1lPgzsYNCkIodkPBMAa7UeCdao9bA5wtVv5oGuSs25Udx8lCMBzlTlMJdoXDp5SVyjnBm08-BFcjWibOaAIwBbqMVIHNniCOcf__fmZ2GVn0qMUQgUYxQRRjjN0RNekHiS9dQERfgqP3HUhZ_SR-zkWRA6gQsgQP7n6AHhgCjE93GPhK8h0_i6TVgaiyl6sYxphKEbbo3CXhGR_sktxv0aP68u_7oI_5C0u23b1NWO-5nx4ZAUNafJqRNw2-4_cZ-EN-8OWZb66PtoARz_wpVRnDPWT93hrhqX61XUIXkBvWV7U5ldcVts6TnOXeOFRc95VrxLqQoURqfMc7i80ul0Ph8B) A function taking the vector of integers as its first argument and \$m\$ as its second. Returns an integer. This uses the same methodology described in [my second Jelly answer](https://codegolf.stackexchange.com/a/269010/42248), but uses no built-ins for checking primes or the Fibonacci sequence. [Answer] # [Wolfram Language(Mathematica)](https://www.wolfram.com/wolframscript/), 132 bytes 132 bytes, it can be golfed much more. ``` g[0,n_]:=n g[m_,n_]:=g[m-1,Fibonacci[n*n+1]] h[m_,0]=0 h[m_,n_]:=h[m,g[m,n]~Mod~n]+1 F[l_,m_]:=Median[Map[h[m,#]&,Select[l,PrimeQ]]] ``` [Try it online!](https://tio.run/##bY5Nq8IwEEX3/RXBB6J1hLZaeTxx9aCuiorLYaixBg0kU9G4Ev3rNVU3fmyGwz33wljpdspKp0tZ/xslD9iammotzSps0bjeYgRc0N@Egy3a4sGe@jFkel2xLEuNHHIvJgp2TSOiSfSge9cT@D4wXfNqc2XqxUGGpgDb2FxttGTM5R6b4g@1YamMKh0amB@0VQsiqjuhmJ3c/uSOIuwGPmeHGZ4TEAMQQxApiNEFhH9h/G7T@02@WT8cgfj1JvI6edHp5@CZ1Dc) [Answer] # [Python 3](https://docs.python.org/3/), 252 bytes ``` from statistics import* f=lambda n:f(n-1)+f(n-2)if n>1else n g=lambda m,n:g(m-1,f(n*n+1))if m>0else n h=lambda m,n:h(m,g(m,n)%n)+1if n>0else 0 F=lambda l,m:median(map(lambda n:h(m,n),filter(lambda n:0not in map(lambda m:n%(m+2),range(n-2))and n!=1,l))) ``` [Try it online!](https://tio.run/##Zc7BjoIwEAbgO0/RPZh0ZExoFWNI9OhLGA91aaFJZyClF58ekV13cffQTPr3m@bv76nteDuOLnYkhmSSH5L/HISnvotpnbljMHSrjeDKSd4oyJ9Dg3eCT8qGwQrOmhci5KqRtFE4qTXnCp6QTsU3bJewlYQTRoYVQ67mH79gkZ1fMCBVZGtvWJLp5U@Zdl5E50Oy8TcuuEvCs1hYqnglKdeA0XBj5/ZguBb8cVQYAGDso@ckz/KicYs7LHF/xal69paX09H/8h3u8YCquKJePpR/4XwfHw "Python 3 – Try It Online") ]
[Question] [ [The explanations of the algorithm come from [here](https://publications.mfo.de/bitstream/handle/mfo/3940/snapshot-2022-002.pdf?sequence=1&isAllowed=y). I recommend reading it for a beautiful description of the algorithm.] This challenge is to implement the Robinson Schensted correspondence. # Input A permutation \$\pi\$ of the integers \$\{1, \dots, n\}\$. # Output A pair of Young Tableaux corresponding to the Robinson Schensted correspondence of \$\pi\$. # Explanation A Young Tableau of size \$n\$ is a two-dimensional arrangement of the numbers from \$1\$ to \$n\$, in which each number appears exactly once. They are arranged in left-justified rows, one below the other, and no row has more entries than the one above it. Also, the entries in each row are in increasing order as you read them from left to right, and the entries in each column are in increasing order as you read them from top to bottom. [citation](https://publications.mfo.de/bitstream/handle/mfo/3940/snapshot-2022-002.pdf?sequence=1&isAllowed=y) The Robinson-Schensted algorithm takes a permutation of the numbers \$1\$ to \$n\$ and produces two Young Tableaux from it. We call these two tableaux \$P\$ and \$Q\$. I will describe how to make \$P\$ first. Given a permutation \$a\_1, \dots, a\_n\$, we process the numbers in the permutation from left to right. We try to insert them one after another into a growing Young tableau, making new rows where we can't do it while satisfying the conditions that the entries in each row are in increasing order as you read them from left to right. We start with \$a\_1\$ and place it in the top left. We then try to place \$a\_2\$ to its right. If \$a\_2 < a\_1\$ then we make a new row, place \$a\_1\$ in the new row on the left and place \$a\_2\$ in the top left. If \$a\_2 > a\_1\$ then we simply append it to the first row. Now consider \$a\_3\$. If it is larger than all the numbers in the first row we simply append it to the first row. If not, we find the first number in the first row that is larger than it and replace that number with \$a\_3\$. We now take the number that we replaced, and we insert it into the second row, in the same way as before. This may cause a number to be "bumped" out of the second row and inserted into the third row. We keep going in the same way all through the permutation, always inserting the next number from our permutation starting at the first row of the tableau. \$Q\$ has the same shape as \$P\$, but we just number the boxes by the step at which that box appeared in \$P\$. # Examples ``` pi = [2 1 3] P = [[1, 3], [2]] Q = [[1, 3], [2]] pi = [1 3 2 4] P = [[1, 2, 4], [3]] Q = [[1, 2, 4], [3]] pi = [5 3 4 1 2] P = [[1, 2], [3, 4], [5]] Q = [[1, 3], [2, 5], [4]] pi = [1 5 6 4 2 3] P = [[1, 2, 3], [4, 6], [5]] Q = [[1, 2, 3], [4, 6], [5]] pi = [4 2 6 5 7 3 1] P = [[1, 3, 7], [2, 5], [4], [6]] Q = [[1, 3, 5], [2, 4], [6], [7]] ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 66 bytes ``` ≔Eθ⟦⟧ηFθ«≔⁰ζWΦ§ηζ›λι«§≔§ηζ⌕§ηζ⌊κι≔⌊κι≦⊕ζ»⊞§ηζι⊞υζ»E⟦η⊕Eθ⌕Aυκ⟧⭆¹Φιν ``` [Try it online!](https://tio.run/##XZA9a8MwEIZn@1fcqIMrNOnX4MlLQoZAoKPxYGw1OiIrjSy3pSW/XZVUuy1e73mfl5drVWPbc6O9L4eBj0bsm1dxIahqJFBY5C9nC@KC8JVnU@KW4DOA7F2xliA2rJ20onQ708kPoSIl2FrZxLMmYMSkT/4cXAgbNt3ytmfD/diLE2KsKX47xB@ZQdg9sZ1preylcbKbll7z7DAOalmfxATGn@A1P1g2Lv2gCqF/TfNf4sxS62iEVVgTPLvgHCNeRZyewQQmUCy8r6p7gjXBI8EDwRPBHcGqrv3Nm/4G "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ≔Eθ⟦⟧η ``` Create `P` with an array for each entry, just in case. ``` Fθ« ``` Loop over the input list. ``` ≔⁰ζ ``` Start at the first array of `P`. ``` WΦ§ηζ›λι« ``` Repeat while the current array of `P` has elements greater than the current value. ``` §≔§ηζ⌕§ηζ⌊κι ``` Replace the next greater element with the current value. ``` ≔⌊κι ``` Replace the current value with the next greater element. ``` ≦⊕ζ ``` Move to the next array of `P`. ``` »⊞§ηζι ``` Append the current value to the current array of `P`. ``` ⊞υζ ``` Keep a record of the insertion indices. ``` »E⟦η⊕Eθ⌕Aυκ⟧⭆¹Φιν ``` Build `Q` from the list of insertion indices, then trim trailing empty elements from both `P` and `Q` and pretty-print them at a cost of 1 byte (the default output format isn't terribly readable). [Answer] # JavaScript (ES12), 124 bytes Returns `[P, Q]`. ``` a=>a.map(g=v=>(p=P[y]||=[]).some((V,k)=>V>v?p[n=V,k]=v:0)?g(n,y++):y=(Q[y]||=[]).push(++j)^p.push(v),y=j=0,Q=[],P=[])&&[P,Q] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=bZLfboIwFMaTXfoU52IxbehQUXHRFK92s4sNssSbrovEAeoUiCgJUZ9kN2bZHmp7mrUFNzD0on_Od87vfG36_hlGr97pw6dfu61_c_t9cKnl6ms3RgFNqYViarOMHw6Ucawn0dpDaELeMLUmVjqOWUjFidN02MbjAIUk0zQ8zChy_oviXTJHmrbEL3G-TzHJ6JK2iSN0YsukZpPZxOG5h58rGLEGADMIdAh0OYHSaLXABgqMFRIzOIcWOJcxCZBHAgLTKzHKgEJi3SqjFJaYvsL0lBvjTKpgVHJR1K_zQ6Av196fL8E0FdM43_DCl6oTulnDrJElNqeZCj5Qnju8-l4iXrUjJvPCb6Gd30A1GIgGvKH70ebOnc2RC9SCvWi58rbAwCainAuAj1w8EuFZFCbRytNXUYCmIhmu9_dPjw96st0swmDhZyLv-BzadYotFadOcaQyFQ2OOP8op1O-_gI) ### Commented ``` a => // a[] = input array a.map(g = // using a recursive callback function g, v => // for each value v in a[]: ( p = // p[] is the entry at position P[y] ||= [] // y in P[] (initialized to [] if undefined) ) // .some((V, k) => // for each value V at index k in p[]: V > v ? // if V is greater than v: p[n = V, k] // save V in n = v // set p[k] to v and trigger the some() : // else: 0 // keep searching ) // end of some() ? // if found: g(n, y++) // do a recursive call with v = n // and y incremented : // else: y = // save in y: (Q[y] ||= []) // initialize Q[y] to [] if undefined .push(++j) ^ // increment j and push it in Q[y] p.push(v), // push v in p[] // p[] and Q[y] have the same length L, // so this resets y to (L xor L) == 0 y = j = 0, // start with y = 0 and j = 0 Q = [], // initialize Q[] P = [] // initialize P[] ) && [ P, Q ] // end of map(); return [ P, Q ] ``` [Answer] # [R](https://www.r-project.org), 115 bytes ``` \(x){P=Q=!x%o%x;for(i in x){r=1;while(i<-P[r,w<-which.min(P[r,]%in%1:i)]-!(P[r,w]=i))r=r+1;Q[r,w]=F=F+1};list(P,Q)} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=PY3BCoJAEIbvPYUeFnZwN1hTi3SvXtNzeZIWB0xhNRTCJ-liQQ_V27SmeJr_-_5h5vnS41vJz71V_PBtLrSHRyJTafekJn2oak3RwsoyWksRdgWWV4oRT86adRE3nBfbG1Z0EhnBiogjQsbtv-gyiQBaakeE6cyxjB0xhCU2LU1YCsPy-qRoTl0m2A5gM2WTmMu8hXxDnmndtfVZYIy77k85MHZvNgXAfHYc5_kD) For an input vector of length \$n\$, this returns a pair of \$n \times n\$ matrices initialized with zeros and the actual content of tableaux filled in. I hope, that's an acceptable output format. ### Explanation ``` \(x) { P=Q=!x%o%x # Initialize the matrices for (i in x) { # Loop through the elements r=1 # Start at row 1. We can't abuse built-in T here # as it has to be reset on each iteration while ({ w=which.min(P[r,]%in%1:i) # Find the first element in the current row that is >i or 0 i=P[r,w]-!(P[r,w]=i) # Swap the found element with i i}) # While we are not on 0 (empty space) r=r+1 # Go to the next row Q[r,w]=F=F+1 # When finished, increase the turn number and store it in Q } list(P,Q) #... and return } ``` [Answer] # Python3, 559 bytes ``` E=enumerate from itertools import* Z=zip_longest W=lambda x:[[*filter(None,i)]for i in x] V=lambda X:all(all(x[i]<x[i+1]for i in range(len(x)-1))for x in X) def U(p,a):p[0]+=[a] def G(P,a,I):P[I-1]=[*P[I-1][:len(P[I])],P[I][-1],*P[I-1][len(P[I]):]];P[I]=[a,*P[I][:-1]] def f(l): p,q=[[l.pop(0)]],[[1]] for i,a in E(l,2): F=1 for I,v in E(p[0]): if v>a: F=0;P=W(Z(*p));Q=W(Z(*q));P[I]=[a,*P[I]];Q[I]=[i,*Q[I]] if V(W(Z(*P)))==0:P[I]=P[I][1:];Q[I]=Q[I][:-1];G(P,a,I);G(Q,i,I) p=W(Z(*P));q=W(Z(*Q)) break if F:U(p,a);U(q,i) return p,q ``` [Try it online!](https://tio.run/##XVHLbtwgFN37K1iCQ6qxM00rXLpLqtlU40UeCkIVUXCLyhiGOJHbn59eLnGqmYXx8Xn5@jr@mX6F8eJzTIfDlbTjy84mM9lqSGFH3GTTFIJ/Jm4XQ5rq6kH@dfGHD@NP@zxVd9Kb3eOTIbNQqh6cBz/9HkbLHdNDSMQRN5JZV7eL8V4Y72m@ZuX0FzjOmv/OZKCXejvSmZ03jGVhzsI9q57sQG5o5IaJqFb6TCqjkfxGt9zwDRNbtTlvtFR1AUrkIsCaaZ5vCki@iO@a0LrLAPpQhBzopXqgnomKRL6XSvkPMUS6YlpzpbKD4Nzc5AGvqOdt9pJr2cCZpQ1/LVKeFzXiBvL61SAE46rbyjv6QOvIWNcXuAd4NI7uenx0vM5AYxZ6bin6t4wxKVcCMzh@I94i/fIx3bIiAD13ALAkyqWh2xfYs6I8Jmt@V/iaa1GW3t3QPfzViiQ7vaQx7@QQkxsnOlDVctJwcqEh/s5lghNQ1kf0R6TXGGhPAyBeotiethXuEi2fsKI5rW2X2uNkiZXydREP/wA) [Answer] # [J](https://www.jsoftware.com), 60 bytes ``` g=.<`(/:~(-.;$:@])&;2<@-./\_"+]F:.(]`I.`[}~)])@.(1<#) ,:&g/: ``` [Attempt This Online!](https://ato.pxeger.com/run?1=TZFNTsMwEIXF1qd4AlQlauO06Q_gBlQ2lUBIXcCuRDRt7BAwNrhJo0qlF2FTFhwKToNDhFSvPG_G730af3w-7XZfRS680-8wPafhzPHZ1vHo8JiNIrcxDMKRR_37h8NmNGbUiWZXdDZ937qRO6JOJzxySYs1Up_VHj8H4zZYm0wULu8mLZQcKc8RK3BjtEFScOQaMZxXw5fFSzyXa9eW8yJFppA_cmiZcINrrLhZZloxQjZKFwrVvMxRxkt7fSsywxMGQTaojyiTpuErspl6_Qi-TfcXOuGE3Nr8yjdQCWSmbID4q6surFEsKyLRspBJ1bBJRU0itJS6zFQKqRexlGtoZcHOaI8G9XhmeTIpUWrzDGHNLe0Fu2FtCIQMfXTRQwfBvtix8sDKAbr7ciUMbOvEvukQt17n_9f8Ag) (*Note: code won't actually run because ATO's J isn't new enough. See below for how to run locally.*) ## The idea Consider input `4 2 6 5 7 3 1`: * Fold forward through the input, collecting results. Seed the fold with a list of infinity repeated `n` times, where `n` is the input length. The fold logic is... * At each step, find the "insert before" point for the next element (where you'd need to insert it to maintain ascending order), but instead of inserting, overwrite the list at that position. For our example input, the result would be: ``` 4 _ _ _ _ _ _ 2 _ _ _ _ _ _ 2 6 _ _ _ _ _ 2 5 _ _ _ _ _ 2 5 7 _ _ _ _ 2 3 7 _ _ _ _ 1 3 7 _ _ _ _ ``` * Notice the final row `1 3 7` already contains the first row of the `P` Young tableaux. We also need the 4 evicted elements, in order of eviction, to call the function recursively and so build the entire tableaux. * To find them, take the set difference of every pair of rows. This difference will be empty when the fold appends an element, and it will be the evicted element when the fold overwrites: ``` ┌─┬┬─┬┬─┬─┐ │4││6││5│2│ └─┴┴─┴┴─┴─┘ ``` * Next, append to `1 3 7` the result of running the above procedure recursively on `4 6 5 2`. This gives us the `P` tableaux. * Finally, to get the `Q` tableaux, we do everything again on the "grade up" of the input, rather than the input itself. ### Alternate way to find evicted elements It's worth pointing out this alternate approach to finding the evicted elements from the cumulative fold result, since it may help submissions in other languages. * Take the fold result above, remove the infinity placeholders, and flatten it: ``` 4 2 2 6 2 5 2 5 7 2 3 7 1 3 7 ``` * Remove the final row elements `1 3 7`: ``` 4 2 2 6 2 5 2 5 2 ``` * Take the uniq, but start at the right side instead of the left: ``` 2 5 6 4 ``` This is exactly the reverse of what we need. So uniq "under" reverse `~.&.|.` produces the evicted elements in the correct order: ``` 4 6 5 2 ``` The full J code for this approach is: ``` g=.<`([:({:,~.&.|.&;$:@-.;@{:)_"+<F:.(]`I.`[}~)])@.(1<#) ,:&g/: ``` ## Local tests These tests require J 9.4.2. The code expects 0-indexed input and produces 0-indexed output. However, to keep the test readable, we do pre- and post-processing below so that the actual input/output is 1-indexed. ``` g=.<`(/:~(-.;$:@])&;2<@-./\_"+]F:.(]`I.`[}~)])@.(1<#) f=.,:&g/: >:L:0 f <: 5 3 4 1 2 >:L:0 f <: 1 5 6 4 2 3 >:L:0 f <: 4 2 6 5 7 3 1 >:L:0 f <: 1 2 3 4 >:L:0 f <: 4 3 2 1 ``` Running the above produces: ``` >:L:0 f <: 5 3 4 1 2 ┌───┬───┬─┐ │1 2│3 4│5│ ├───┼───┼─┤ │1 3│2 5│4│ └───┴───┴─┘ >:L:0 f <: 1 5 6 4 2 3 ┌─────┬───┬─┐ │1 2 3│4 6│5│ ├─────┼───┼─┤ │1 2 3│4 6│5│ └─────┴───┴─┘ >:L:0 f <: 4 2 6 5 7 3 1 ┌─────┬───┬─┬─┐ │1 3 7│2 5│4│6│ ├─────┼───┼─┼─┤ │1 3 5│2 4│6│7│ └─────┴───┴─┴─┘ >:L:0 f <: 1 2 3 4 ┌───────┬─┐ │1 2 3 4│_│ ├───────┼─┤ │1 2 3 4│_│ └───────┴─┘ >:L:0 f <: 4 3 2 1 ┌─┬─┬─┬─┐ │1│2│3│4│ ├─┼─┼─┼─┤ │1│2│3│4│ └─┴─┴─┴─┘ ``` Note the 2nd to last test case contains an extraneous blank, but this is allowed. [Answer] # [Haskell](https://www.haskell.org), 177 bytes ``` import Data.List h([],_,n)x=([[x]],[[n]],n+1) h(p:w,q:z,n)x|(t,y:d)<-span(x>)p,(w,z,m)<-h(w,z,n)y=((t++x:d):w,q:z,m) h(p:w,q:z,n)x=((p++[x]):w,(q++[n]):z,n+1) f=foldl h([],[],1) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=bVJNb4JAEE2v_Io56W4Ym4CijZGeeuw_2GwMaSGSwrrANqLxn_Tipem5f6T39td0WD6iRgLDY96b9yZhP742UfUWZ9np9PluksnD73ea621p4Cky0f1zWhlnw4TENSpeh0yIWkoUQlFVrseJ1MsdFstDwx-Zwf3yla8mlY4Uqx-5RrbDA-bU2lik-D5kzLhuTbpuMr-yIYF2XUpqBKwgqAge2sAkTLbZawZ2K7o93i7-d_cTl2UFIQidwhGYThE0QsFhNQETV-YlquIKiRhTl561ZUQCOpUIamuIgjAEPYbRCIoGFmMunTxKFdnqMlUGbIbjDH5NngN0MeEjeAhT8hKiB768_uTYyZseAg3NekmPp_JGZ5gL7NzMhvmD0Ko6dXAVihA079llOPnMrY9_tnSPqT2_tLrBDG6tydx6Lux63rABdS6XoDKXZ3TQ0R1DZUHW0ml_a38u_wE) ]
[Question] [ # Let's go for a rollercodester ride The objective of this challenge is to create a program that is run recursively through several languages of your choice. The output of the first iteration becomes the code for the second iteration, et. cetera. * You choose the language sequence, but each **unique** language may be used only once. Unique languages will be determined using CGCC standards (different compiler flags => different languages!) * Each step must be a complete program that terminates before the next step will be executed. * The entire output of stdout (not including stderr) will be considered code for the next step. * Other than executing and producing output, your programs can do whatever they want but every byte that your program reads contributes a byte to it's scored code length. * Each step executes in a theoretically clean environment, no actions of prior steps can be accessed by the current step. * Please score your submission as best as you can, I anticipate some difficulty validating submissions (no fancy scoring tool yet...). ## Scoring Thanks to ovs for creating a score calculator: [TIO Link](https://tio.run/##Tc7LCoMwEAXQ/XzFIG1JUIPU6qK03yJ5SYWaSB6C4L@nIatuZnHPvTAuiiMlcQTt8Y2XF1v5hrdnsNMC4KV1OseFmebyM0lrPOkp83FFZfHkDYoG5QmIMrqdh1gWhPBW0JaIVlLKuPDZgw38m43Xopb/fTarZSeFKXM2GoUjaKMANreYMGN1ZeNcNVj@SWno4D5Avo8O@u4H) * The curvature of any three consecutive steps in the submission is the difference of the difference of each step's code length. * Any three consecutive steps in the submission earn score points equal to their absolute curvature divided by the total source length of all three steps. * Each scored step will be rounded (x>=5e-7 becomes 1e-6, x<5e-7 becomes 0) to the nearest 1e-6, to make scoring exact. * The goal is to achieve the highest score. * In the unlikely event of a tie, the shortest initial (just the first step) submission in bytes wins (it's gotta have some sort of golf, right???). To discuss scoring consistently we can call the first step "Step 1", and assign scored points to the last step that contributes to those points. The first two steps (1 and 2) are not scorable because there isn't enough data to calculate a score, then each step after that has a score calculated from itself and the two prior steps. i.e. in the working example below, step 3 scores .566038, step 4 scores .536082 ## Scoring example * Step 1 (original submission) : 50 bytes * Step 2: 25 bytes -25 change * Step 3: 50 bytes +25 change +50 curvature / 50+25+50 bytes = 0.4 score * Step 4: 40 bytes -10 change -35 curvature / 25+50+40 bytes = 0.304348 score * Step 5: 30 bytes -10 change +0 curvature / 50+40+30 bytes = 0 score total score: (0.4+0.304348+0) = 0.704348 ## Working example Here's a working example, code is below the score. I can maximize my score by increasing the repeating parts of the Octave and Python 1 code, but can never get more than a score of 2 in any step. 4 steps: 1. Python 3 - 107 2. Octave - 166 3. C (gcc) - 45 4. Python 1 - 80 scoring: ``` step diff curve total_len score 107 - - 166 +59 - 45 -121 -180 318 0.566038 80 +35 +156 291 0.536082 total: 1.102120 ``` # [Python 3](https://docs.python.org/3/), 107 bytes ``` print(f"""disp("main(){'{for(int i=0;i<10;i++)puts(""print 1"");}'}") {''' '''.join(['%commented']*10)}""") ``` [Try it online!](https://tio.run/##HYxLCsJAEAX3OUV4IN1tQDK4jJ5EXIhJsIX5kIwLGebsY@Pi1aaol775FcO5tbRpyLwCmHVPDP/QwFKorHFjU71ex0kvzjAMkj55Z@Af9Q6QqVKFdIWIOtvpHS2/0eEZvV9CXma6H90o1f6ltR8 "Python 3 – Try It Online") # [Octave](https://www.gnu.org/software/octave/), 166 bytes ``` disp("main(){for(int i=0;i<10;i++)puts(""print 1"");}") %commented %commented %commented %commented %commented %commented %commented %commented %commented %commented ``` [Try it online!](https://tio.run/##y08uSSxL/f8/JbO4QEMpNzEzT0OzOi2/SCMzr0Qh09bAOtPGEEhoa2sWlJYUaygpFRSBZAyVlDSta5U0uVST83NzU/NKUlPowfz/HwA "Octave – Try It Online") # [C (gcc)](https://gcc.gnu.org/), 45 bytes ``` main(){for(int i=0;i<10;i++)puts("print 1");} ``` [Try it online!](https://tio.run/##S9ZNT07@/z83MTNPQ7M6Lb9IIzOvRCHT1sA608YQSGhraxaUlhRrKBUUgSQMlTSta///BwA "C (gcc) – Try It Online") # [Python 1](https://www.python.org/download/releases/1.6.1/), 80 bytes ``` print 1 print 1 print 1 print 1 print 1 print 1 print 1 print 1 print 1 print 1 ``` [Try it online!](https://tio.run/##K6gsycjPM/z/v6AoM69EwZCLWvT//wA "Python 1 – Try It Online") [Answer] # 9 langs, score 7.090470. ## [Deadfish~](https://esolangs.org/wiki/Deadfish%7E), 10000001377 bytes ``` {{i}}iic{i}dciiic{{d}iii}ddddc{iiiiii}iiiiic{dddd}ddddc{d}dddc{i}ic{iiii}iiiiiic{dddd}dddddc{d}dcdcc{i}ic{iiii}iiiiiic{dddddd}ddccddcdc{iiiiii}dc{dddd}iic{iiii}ddc{i}iicdciiiiicddddcdddc{d}iiic{ddddd}dddddc{iiiiii}iiciiic{d}iic{dddddd}ddcdcdcddddc{iiiiii}iiiic{i}iicddcc{d}iic{i}dciiiiiic{{d}ii}iiiciic{ii}ddc{iiii}c{dddddd}icdc{iiiii}iic{ii}iciic{d}iciiiiiciiiiiic{{d}iii}ddddddcddddddcic{iiiiii}iiiic{i}iicddcc{d}iic{i}dciiiiiic{{d}ii}ddc{i}dddc{d}ic{{i}ddd}c{i}dciiic{{d}ii}ddc{{i}ddd}iiic{{d}iii}dddc{{i}ddd}iiiciiiiic{{d}ii}iic{{i}dd}iic{dd}iiic{i}iiic{d}iiicddc{dddddd}dc{i}dcdccc{d}iiic{iiiii}iic{ddd}ddddc{ddd}iiic{{i}dd}ciic{d}iciiiiiciiiiiic{{d}iii}ddddddcddddddc{iiiiii}iic{ddddd}icdddddc{iiiii}iiiic{ddddd}ddc{iiiiii}iiic{dddddd}iic{d}ic{iiiii}iiiiiic{ii}iiiic{dd}ddddc{i}ic{dddddd}iic{d}iiiciicdddc{iiiii}iiiiic{ddddd}ddddciiiiic{iiiii}dc{ddddd}ddc{iiiii}iic{dddddd}dc{{i}ddd}ciiiiic{d}dc{i}dc{i}dc{dd}iiicic{{d}iii}ic{iii}ddc{iiiii}iiiiicic{d}ddddddciiiiiciiiiiic{dddddd}dddddc{iiiiii}ddc{dddd}ddc{iii}iiiic{ddddd}ddc{iiiii}iic{i}dciiiiiciiiiiic{{d}ii}ddddc{{i}dd}dddc{d}ddc{i}ddciiiiic{{d}iii}cic{{i}dd}iic{d}dciiiiicdcdc{{d}iii}dddddc{iiiii}iicc{dddddd}iic{{i}dd}ddciiiiicdcdc{{d}ii}dddciiiiic{{i}ddd}iiiiiic{dd}ddc{ddddd}iic{iiiii}ddc{ddddd}iiciiic{iiiii}dddccdcc{dddddd}iic{i}dddc{ii}ddc{iiiiii}iiiiiic{ddd}ic{ddddd}ddc{d}c{i}dddcddciiciiiiiicc{iii}iiiicccccc ``` [Try it online!](https://deadfish.surge.sh/#WlZFjXu+9z/Nz7Dd14+q3AeDdVfVbr6tz24PA3VX1Vuvtbc9uDwN1VX1tWtwH26q83B9bnmsDVWq3XjdVX1VuA8w3Xm6qr61rVW4Dw3PNW3Xm59gN3XnjG4+twfuqq9rcDzcexuvYGA3dePqq1VWbgPDc81bdebn2A3defW59W69u59X7n2G7rz63c+rxu68fVu59XjA3deebufXm6vG543XjVuqq+3PtbbrxuB5uq+q3VeN3Pr8br2BgN3Xj6qtVVuA83VV7VVuB4bqq+twHjdVV5uvbgeBuPDdX1W57dVV5uvGNVuB4N1VfVYG4H26qvrcDzdVV9u59X4G6+3Ptz7dXjN3Xj24fW4HgzdfVVgYDdVV9VbgPrdVfW4eG6qvrcDzc+wMBu68+q3c+vq3X1ufWBu68fm7n15uvsDWt3Xj6q3A826qrzdz6+sDWt3Xn1YG7n1eBur63VV5uB9bqq8w3A+ra26qrzc+rcfW4DwN1Xt1VfW6/c+rVjAbcPDbbYA=) With \$10^{10}\$ `h` at the end. ## [HQ9+](https://esolangs.org/wiki/HQ9%2B), 192 bytes ``` for(i=0;i<100;i++)(c=console.log)('#comment');c('[print("#comment") for i in range(1000)]; print("`/*`,k1(`x`k1*,)`*/`,`#include <stdio.h>`,`int main(){puts(\\"puts %q[+[+.]]\\");}`,")')//QQQQQQ ``` [Try it online!](https://dso.surge.sh/#hq9+) (code will need to be pasted in) Note: Extraneous content has been simplified in the below snippets, and removed from the TIOs - if you add it back it'll work fine. ## [JavaScript (Node.js)](https://nodejs.org), 1164 bytes ``` for(i=0;i<100;i++)(c=console.log)('#comment');c('[print("#comment") for i in range(1000)]; print("`/*`,k1(`x`k1*,)`*/`,`#include <stdio.h>`,`int main(){puts(\\"puts %q[+[+.]]\\");}`,")')//QQQQQQ ``` Repeated 6 times. [Try it online!](https://tio.run/##NYzbDoIwEER/pYEYdgG5PBf8B5@BpKRUXYEWoRgT47djNToPM8nJyVzbe7vImSa716ZT23YyM1CZcSryzHUUIchSGr2YQSWDOSMEvjTjqLQNkEsIqmkmbcH7Uw@Z@2DESLO51WcF7ijDhrOfKNJQxH0O4iH6PIxRhKmIhU9aDmunWLHYjkxyOTjofDa2pAGf02oXqGvvs2x3q6IqSprGAeQvEXsYYJoev9m2Nw "JavaScript (Node.js) – Try It Online") ## [Python 3](https://docs.python.org/3/), 1033 bytes ``` #comment [print("#comment") for i in range(1000)]; print("`/*`,k1(`x`k1*,)`*/`,`#include <stdio.h>`,`int main(){puts(\"puts %q[+[+.]]\");}`,") ``` [Try it online!](https://tio.run/##LcrtCoIwFIDhWzlMgm0OP@in0o3o4IhaDtvZmhOK6NqXQb9eeHn8Ky6Ozil1PhiKnGWjs3amyARcXQADhiAMdJt5XVWV0A38IZYS1VpzfOJaSyVQlqgwMzTe92mGdouTccVyOebhwQ6GuHj7PW68Z7/A6dHlXV5o3TPRfFAxkdIX "Python 3 – Try It Online") The `#comment` is repeated 100 times. ## [Vyxal](https://github.com/Vyxal/Vyxal), 9081 bytes ``` #comment `/*`,k1(`x`k1*,)`*/`,`#include <stdio.h>`,`int main(){puts("puts %q[+[+.]]");}`, ``` The `#comment` is repeated 1000 times. [Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%60%2F*%60%2Ck1%28%60x%60k1*%2C%29%60*%2F%60%2C%60%23include%20%3Cstdio.h%3E%60%2C%60int%20main%28%29%7Bputs%28%22puts%20%25q%5B%2B%5B%2B.%5D%5D%22%29%3B%7D%60%2C&inputs=&header=&footer=) ## [C (gcc)](https://gcc.gnu.org/), 914699 bytes ``` /*x*/ #include <stdio.h> int main(){puts("puts %q[+[+.]]");} ``` [Try it online!](https://tio.run/##S9ZNT07@/185My85pzQlVcGmuCQlM18vw44rM69EITcxM09Ds7qgtKRYQwlEKqgWRmtHa@vFxippWtf@/w8A "C (gcc) – Try It Online") The `x` is actually 1000 newline-separated copies of 1000 more `x`. ## [Ruby](https://www.ruby-lang.org/), 14 bytes ``` puts %q[+[+.]] ``` [Try it online!](https://tio.run/##KypNqvz/v6C0pFhBtTBaO1pbLzb2/38A "Ruby – Try It Online") ## [brainfuck](https://github.com/TryItOnline/brainfuck), 5 bytes ``` +[+.] ``` [Try it online!](https://tio.run/##SypKzMxLK03O/v9fO1pbL/b/fwA "brainfuck – Try It Online") ## [PHP](https://php.net/), 382 bytes ```    !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ ``` [Try it online!](https://tio.run/##BcGJNxMAAAdgT6WSp6LDleTsoCRnSIdUChWVlEqO0GGlkNvM7osdZhg2ZuZmmLne@/3@sPk@Qb3A6/U9cvSY3/ETJ/1PBfgHnj5zNij43PkLF0NCw8IjLkVejroSHRMbF59w9dr1G4lJN28l3065k5qWnpGZdTc7J/de3v0HDx/lPy548vRZ4fMXRcUlL1@9Li178/Zd@fuKDx8rP33@UvW1uqa27lt9Q@P3Hz9/NQl@/2n@@6@lte1/e0dnV3cPetEHIfohwgDEkEAKGeRQQAkV1NBAi0EMQQc9DDBiGCaMwIxRjGEcFkxEYQpW2DCNGdgxCwfm4MQ8FrCIJSxjBatYwzpc2MAmtuDGNjzYwS72sI8D9rKPQvZTxAGKKaGUMsqpoJIqqqmhloMcoo56GmjkME0coZmjHOM4LZzgJKdopY3TnKGds3Rwjk7Oc4GLXOIyV7jKNa7TxQ1ucotubtPDHe5yj/s88PF6DwE "PHP – Try It Online") ~~No idea what my score is.~~ Thanks to @ovs for calculating my score. [Answer] # [Score 20](https://tio.run/##ZY7LCsIwFET39ysuopLQNtQHXYh@S7l5FAs2KXkUCv33WOtGcDMDc2ZgfJJzznKOJuAD93cx0IjHW3RtDxCU82aNNywMqWernA3swkVIA2qHC5UoS1QLIKrkJ4ppWzBGleQVk5XiXJAMK48u0mtlVMhC/fZFp/uJbZgL75LV2ICxGmD0vY0d7g6i6XYlbn9yrqGGE/zp@Wv19eNv) ~~Have I misunderstood this question? I'm not quite sure what's happening here. Please leave a comment if this is not allowed by the rules, and I will then delete it.~~ The basic idea is try to find out if any languages accept an empty program and output something (non-empty stdout). And this could be extended as long as you spend some more time on esolang wiki and find out more languages and append them to this chain... * [Pyth](https://github.com/isaacg1/pyth), 0 bytes, [Try it online!](https://tio.run/##K6gsyfgPBAA "Pyth – Try It Online") * [sed](https://www.gnu.org/software/sed/), 0 bytes, [Try it online!](https://tio.run/##K05N0U3PK/0PBAA "sed – Try It Online") * [Python 3](https://docs.python.org/3/), 1 byte, [Try it online!](https://tio.run/##K6gsycjPM/7/n@v/fwA "Python 3 – Try It Online") * [Python 3 (Cython)](http://cython.org/), 0 bytes, [Try it online!](https://tio.run/##K6gsycjPM9ZNBtP/gQAA "Python 3 (Cython) – Try It Online") * [,,,](https://github.com/totallyhuman/commata), 0 bytes, [Try it online!](https://tio.run/##S87PzU0sSfwPBAA ",,, – Try It Online") * [Python 2](https://docs.python.org/2/), 1 byte, [Try it online!](https://tio.run/##K6gsycjPM/r/n@v/fwA "Python 2 – Try It Online") * [Python 2 (Cython)](http://cython.org/), 0 bytes, [Try it online!](https://tio.run/##K6gsycjPM9JNBtP/gQAA "Python 2 (Cython) – Try It Online") * [Retina](https://github.com/m-ender/retina/wiki/The-Language), 0 bytes, [Try it online!](https://tio.run/##K0otycxLNPwPBAA "Retina – Try It Online") * [Python 1](https://www.python.org/download/releases/1.6.1/), 1 byte, [Try it online!](https://tio.run/##K6gsycjPM/z/H4gA "Python 1 – Try It Online") * [Pyt](https://github.com/mudkip201/pyt), 0 bytes, [Try it online!](https://tio.run/##K6gs@Q8EAA "Pyt – Try It Online") * [A Pear Tree](https://esolangs.org/wiki/A_Pear_Tree), 0 bytes, [Try it online!](https://tio.run/##S9QtSE0s0i0pSk39DwQA "A Pear Tree – Try It Online") * [brainfuck](https://github.com/TryItOnline/brainfuck), 12 bytes, [Try it online!](https://tio.run/##SypKzMxLK03O/v8/UaEgsaikKDMlPZXr/38A "brainfuck – Try It Online") * [JavaScript (Node.js)](https://nodejs.org), 0 bytes, [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Q8EAA "JavaScript (Node.js) – Try It Online") * [Husk](https://github.com/barbuz/Husk), 0 bytes, [Try it online!](https://tio.run/##yygtzv4PBAA "Husk – Try It Online") * [SuperMarioLang](https://github.com/charliealejo/SuperMarioLang), 104 bytes, [Try it online!](https://tio.run/##JchBCsIwEEbhfU7xMxsrFDEoUjxLN6UZw0A6CTGB3j6mdfPxeN@aOG9LlhgW9a0NQZRhR6wx1E1hr29TlffEa2EHVof4gWiqxfyvqAeBRtDQceKl9L4d43Iw06l9TYSYez3uTzKt/QA "SuperMarioLang – Try It Online") * [JavaScript (V8)](https://v8.dev/), 0 bytes, [Try it online!](https://tio.run/##y0osSyxOLsosKNEts/gPBAA "JavaScript (V8) – Try It Online") * [JavaScript (SpiderMonkey)](https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey/Releases/45), 0 bytes, [Try it online!](https://tio.run/##y0osSyxOLsosKNEtLshMSS3Kzc/LTq38DwQA "JavaScript (SpiderMonkey) – Try It Online") ]
[Question] [ **This question already has answers here**: [[Br]eaking Code Golf [Ba]d](/questions/112608/breaking-code-golf-bad) (3 answers) Closed 3 years ago. The TV series "Breaking Bad" replaced the letters Br and Ba with a periodic-table like representation, printing `[Br35]eaking [Ba56]d`. Create a program that takes a string input, does a replacement and prints an output. The replacement shall subsidize any substring that matches an element symbol with the notation demonstrated in `[Br35]eaking [Ba56]d`. That is, add the atomic number to the element symbol and enclose in square brackets. All elements start with a capital letter and consist of either one or two letters. The highest element to be considered is Og118. From wikipedia: > > 1 H, 2 He, 3 Li, 4 Be, 5 B, 6 C, 7 N, 8 O, 9 F, 10 Ne, 11 Na, 12 Mg, 13 Al, 14 Si, 15 P, 16 S, 17 Cl, 18 Ar, 19 K, 20 Ca, 21 Sc, 22 Ti, 23 V, 24 Cr, 25 Mn, 26 Fe, 27 Co, 28 Ni, 29 Cu, 30 Zn, 31 Ga, 32 Ge, 33 As, 34 Se, 35 Br, 36 Kr, 37 Rb, 38 Sr, 39 Y, 40 Zr, 41 Nb, 42 Mo, 43 Tc, 44 Ru, 45 Rh, 46 Pd, 47 Ag, 48 Cd, 49 In, 50 Sn, 51 Sb, 52 Te, 53 I, 54 Xe, 55 Cs, 56 Ba, 57 La, 58 Ce, 59 Pr, 60 Nd, 61 Pm, 62 Sm, 63 Eu, 64 Gd, 65 Tb, 66 Dy, 67 Ho, 68 Er, 69 Tm, 70 Yb, 71 Lu, 72 Hf, 73 Ta, 74 W, 75 Re, 76 Os, 77 Ir, 78 Pt, 79 Au, 80 Hg, 81 Tl, 82 Pb, 83 Bi, 84 Po, 85 At, 86 Rn, 87 Fr, 88 Ra, 89 Ac, 90 Th, 91 Pa, 92 U, 93 Np, 94 Pu, 95 Am, 96 Cm, 97 Bk, 98 Cf, 99 Es, 100 Fm, 101 Md, 102 No, 103 Lr, 104 Rf, 105 Db, 106 Sg, 107 Bh, 108 Hs, 109 Mt, 110 Ds, 111 Rg, 112 Cn, 113 Nh, 114 Fl, 115 Mc, 116 Lv, 117 Ts, 118 Og > > > Additional rules: * As this challenge is about compression as much as about code golf, so you have to provide the element list yourself. You **must not use any build in periodic tables** provided by our language. * Work case-sensitive. That means "Breaking Bad" has 2 replacements, "Breaking bad" has one. The input can be arbitrary and won't always follow English grammar. fOoBar shall become f[O8]o[Ba56]r. * Search greedy, [He] takes precedence over [H]. **Shortest code in bytes wins.** [Answer] # JavaScript (ES6), 327 bytes ``` s=>s.replace(RegExp([...a="HHeLiBeBCNOFNeNaMgAlSiPSClArKCaScTiVCrMnFeCoNiCuZnGaGeAsSeBrKrRbSrYZrNbMoTcRuRhPdAgCdInSnSbTeIXeCsBaLaCePrNdPmSmEuGdTbDyHoErTmYbLuHfTaWReOsIrPtAuHgTlPbBiPoAtRnFrRaAcThPaUNpPuAmCmBkCfEsFmMdNoLrRfDbSgBhHsMtDsRgCnNhFlMcLvTsOg".match(/.[a-z]?/g)].sort(s=>-!!s[1]).join`|`,'g'),s=>`[${s+-~a.indexOf(s)}]`) ``` [Try it online!](https://tio.run/##bZHfbtsgHIXv9xRpNKm21lDtAbLJkDiOahMEbF0bRQq2f8a0GCKwq3b/Xj3L9dTb853v5pwn9aJiE8xpXDjfwrlbnuPyS0QBTlY1kHDQ69dTskcIqeW8KKA0GDChu5wCVZXOrDBMEJuFO6JEI813EiqXA/HUkOnRbdQGsigAh7vAaxEeHgOtKy8bPvGetZkm7dYJJ2oJ2x9AIlalIsACbdkghvW0aWW9eiv8OsjhoS6nopPqnsMubgMbs6nQ0rIaG@azkbs8cJU1smfqGz2xKRvIgJ9Jt475ULXUl4F3q1po3BexGleRa@Jon9uqKV9k3Ok5GtTY9Mkt2qvFz8PXW50eUPRhTC6TLK6u4v7zIUVP3rjj7@PNtb5Oby7guP/4K35a/FXIuBZed10S0z@HY3puvIveArJeJ10yxwHUs3F6hlU7T9MP/@HCvBeCtX5274N9TyGXw2Ybb7sZnyzES@P8Dw "JavaScript (Node.js) – Try It Online") ### How? The data string consists of all element symbols concatenated together, from lowest to highest atomic number. ``` "HHeLiBeBCNOFNeNaMg...LvTsOg" ``` We split it into a list `a[]` of 118 entries with the following regular expression: ``` +------> any character (always a capital letter) | +--> optionally followed by a letter in lower case | __|_ |/ \ /.[a-z]?/g ``` We create a copy of `a[]`, put all single-character elements at the end of the list and join with pipes: ``` [...a].sort(s => -!!s[1]).join('|') ``` Which gives: ``` "Og|Ts|Lv|Mc|Fl|Nh|...|He|H|B|C|N|O|F|P|S|K|V|Y|I|W|U" ``` We turn this string into a regular expression and apply it to the input string. Each matched sub-string `s` is replaced with the pattern: ``` `[${s + -~a.indexOf(s)}]` ``` [Answer] # [Python 3.8](https://docs.python.org/3.8/), ~~454~~ \$\cdots\$~~409~~ 385 bytes Saved a whopping ~~38~~ ~~40~~ ~~45~~ 69 bytes (and fixed a bug) thanks to [ovs](https://codegolf.stackexchange.com/users/64121/ovs)!!! ``` eval("lambda s:_]and_<b][-1]".replace('_',"[(s:=re.sub(f'(?<!\[){b}',f'[{b}{e}]',s))for e,b in p if b[1:]")) import re p=[*enumerate(re.split("(?=[A-Z])","HHeLiBeBCNOFNeNaMgAlSiPSClArKCaScTiVCrMnFeCoNiCuZnGaGeAsSeBrKrRbSrYZrNbMoTcRuRhPdAgCdInSnSbTeIXeCsBaLaCePrNdPmSmEuGdTbDyHoErTmYbLuHfTaWReOsIrPtAuHgTlPbBiPoAtRnFrRaAcThPaUNpPuAmCmBkCfEsFmMdNoLrRfDbSgBhHsMtDsRgCnNhFlMcLvTsOg"))][1:] ``` [Try it online!](https://tio.run/##ZVLbbptAFHz3V2x4ASocyXHTRlbcCLAdrBiMgF5ivLJ2zQGjcNPZJVJk@dtdcKpGavdlZ2dGo3PZ5k0e6mp81@A5nW7P8MoKTSlYyRNGxGRHWZXs7jmNhyOqXCM0BduDpu5UQ4k1MZkiXIuWa6mqPdxfbWP9yE@qkapxdx/hRFVD6HpaIwGDk7wiDclTwuPRhCq6PsjLpkZJEAbNNP4EVVsCMglaH9oUudQU7WEam8MN1RVDcRxY5RZYtrdeeOAxNzOLMPdDuzDxyWbhPsp/2OhWC7BrL7fbTfXIHsEUIVj4hAEP8XmDHnfraB@0wcFPzMxOllVYhTyC5S@whcVWzAYfvcQvw3LePiYRn7059Ryj8pmvWieN2M8A1mKJvjRbJ4sKn1u5X5syqBYYMHMfHXz23Wv81izt0nqx07lYlG7i1SsM0hkPM@vgCFfORJDZlXdYFO5@9RqJddbNg/ZzOUsQUpAp0QakO5piIbCXvMqIxZJuCrGF41v6h4otdvuFJopu/Gvm/5t76q8xXdcWw86Sxus7Wr8H4YfuQFHUfYIDN7SHH0p@pRikE0a0Qx2tD7Avt1W37c3Xz3vVIO9wNFb1Qb97aUC/@0tjk0tK31@qSf3yaDCvZPeDjvJEht/IUZzIEePOMiVAT6p@/g0 "Python 3.8 (pre-release) – Try It Online") First goes through all two letter chemicals and then single letter ones. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 217 bytes ``` F⪪”}∨"²Q/QH▷⊕Ff←SγG¤º&ρωVφ∨]›¶⁻Nr*Sψ⦄π⁶&U⊞jεJκκH‹ι7◧"↷⌊Rι¦◧◧‽3▷↨↑´^@➙⊙×π+sQ⌈⊙▷TQ|ⅉB{_Π"⪪η(⁵AxQWW/⁻∨8▶u…κ¹*ITλ_⟧‽Hj.⊞;r⬤|›∧7ψjêÞζp⸿⊖¿⊖Q℅↷Hb↨“↔=bY⁵⌈↷¬δ⎚⪫:D₂↓;≦?⁺[‴.t4r±,s^)↗τ”²⊞υΦι›κ ≔⪪⮌S¹θW∧θ⭆⊕№υ⭆²§⮌θκ⊟θ¿№υι«[ιI⊕⌕υι]»ι ``` [Try it online!](https://tio.run/##VVJLj5swED43v2LECSR66F57Mk4IaIFYmD52qx4MDGDFmMQ2aauqvz3raFcb1ZI1M57vMbLdTcJ0i1DX67AYCPlJSRcGGWRYyAQToFDBAVKosBLlSBSXDDhQRcwjUMG7Rn4FakqdIl0qSddnvRd7JJZjYh5N3XLzBM@masul6eq1nlhPRtrnmmveNpjDd6Q2EYWgyEzVs5nPu3XfN@32T7bsTDM/tcWaDY34BjUebG6YI2s2Noq1iWQLcbVOTS1I10xMfIHqxFYy0zk50mFn07nsq6Uw9bBt@ZhMmS3d1tYj1dWUqrIrLo09jEEMD1EEbLVTuMaQSuXQhDKGvUFxS48xBBBEUfR5Q6yVo367pRovaCyGuT6tjjsj9RhGUQyf/D578K9JKoSQ6D48x/AKKMXJ4zuDM2qHfUiXVbub7b39EANxue7x97vD2Sse/QA@sOXkS79ADnCnS3/wd/OBeRH/fD8Cb/9WyHtKhXX/uafSz/bKju6w4OeN/m@DyiK8i/gPclgSYa4fL@oF "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` F⪪”...”²⊞υΦι›κ ``` Split a list of element names into pairs of letters and delete the spaces. ``` ≔⪪⮌S¹θ ``` Reverse the input and split it into characters. ``` W∧θ⭆⊕№υ⭆²§⮌θκ⊟θ ``` While there is still input, remove the last 2 characters if there is a matching element, otherwise remove the last character. ``` ¿№υι« ``` If there is a match in the array, then... ``` [ιI⊕⌕υι] ``` ...print the match and its atomic number inside `[]`s. ``` »ι ``` Otherwise just print the current character. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~183~~ 181 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` .œʒ.•2вy>ÖΘZθÒ7ßΩ¨ÑÝ (Îiþ∍ćf=ÆΛ}’.мιoiFδC¸Γ=¢`Ÿíнp»ΛÑzðÿ®ÄÄ‘Â@Âη+(Óûò‘8нKKK#â<Ù#<“râµ5£”м}ÓæuüåÈZµ-ΔÈ;VzeY¯õnK§ÁÚ¡[θƶη„Gp©6›mðÿāε1ΛÎíγJò~܉cT¢Œƶʒ˜•2ô™ðм©såüαP}Σ€g{ygš}θ®DεN>«…[ÿ]}‡J ``` Pretty slow for long inputs. [Try it online](https://tio.run/##FY/NSgJhGIX33YYbIRIK@oFMwqLAgWgRQUqQlYlEPygtKowvkXJT4BjRjxZOZElpZk5ONRW8x3FR8DLX8N2ITdvDged5NhLhxVik0/FYuR/VI4XWZ9e3fTjlsyAbUAdxzWW6RxaFLjeOY/iSmaPW4coIDvgyKcW5xzb5bSM2wY0xMjg3QtqCZaBif27SB18iu4MavqmKNNJSnCE1ihQ3u93I4QN1ZxmyPxVFcUHz4tzllSIfh0Z6P91IUbDNpPMrbcHELTJB0nv4BJnh2Z3IHD1BX1foDvu4oGKIjfYrN6W4mtyk8oAU72v/2NY@672OxDEq/BJAfQ95KWpLM6RZavv1R/3N//eiIdMaarZJ5YTDMfl5Osk3MvUY3d2OWsUkG1QdZ33KRw9SlEL4nne6i4FOxx@PhFf94eU/) or [verify a few more short test cases](https://tio.run/##FY9fK0NxHMbvvYp1dqOwovwpMxohK1xI2VKGbS1/pokaTb@tNbux2pm0MbQjYzFmnDk4qN9jLqhv5zX83sgcV089PfV5PqFN72LQ19yODEoWkZQtFmkw0rQ1sj@yTTCly6hFHDiinJs0yL04pzK/RganLa1IB/EhUgdf@/4BJOkkKljeZuj0EgqO0tMw1yg7wJWFhoaK8b7B3@gEmR1U8cnvkEBCsBziQ4jTc1srsnhDzWz6jHeXy2WFYkfeahesEIbC1W5@IdipoUfNXWkLOi6RcnO1gw6R6p/d8c3xe6jrLn6FGI550UPad52eBTsb2@DlHsFe1/6xXzFSO80TaVTocQK1PRQEqy7NcKUhf9d/5N/Cvy@eREJB1dB5edPk6PQwHaULEb8N7EYCjWKUNH43Quqkg98IVvLgc970Lk4025seyRn2eVec3mWpXRr3ra6GzPRPhZzesDT/Bw). **Explanation:** ``` .œ # Get all partitions of the (implicit) input-string ʒ # Filter these list of parts by: .•2вy...ƶʒ˜• # Push compressed string "h helibeb c n o f nenamgalsip s clark casctiv crmnfeconicuzngageassebrkrrbsry zrnbmotcrurhpdagcdinsnsbtei xecsbalaceprndpmsmeugdtbdyhoertmybluhftaw reosirptauhgtlpbbipoatrnfrraacthpau nppuamcmbkcfesfmmdnolrrfdbsgbhhsmtdsrgcnnhflmclvtsog" 2ô # Split it into parts of size 2: ["h ","he","li","be","b "...] ™ # Titlecase each string: ["H ","He","Li","Be","B ",...] ðм # Remove all spaces from each string: ["H","He","Li","Be","B",...] © # Store this list in variable `®` (without popping) s # Swap so the current partition is at the top of the stack å # Check for each inner part whether it's in the element-list # (1 if truthy; 0 if falsey) ü # For each overlapping pair: α # Get the absolute difference P # Get the product of those to check if all are truthy (1) # (partitions in the form of [0,1,0,1,...] or [1,0,1,0,...] are left) }Σ # After the filter: sort any remaining partition by: € # Map each part in the list to: g # Pop and push its length { # Sort this list of lengths y # Push the current partition again g # Pop and push its length to get the amount of parts in this partition š # And prepend it at the front of the other lengths }θ # After the sort by: only leave the last partition, # which will have the most parts, as well as the longest individual parts ® # Push the list of elements from variable `®` again D # Duplicate it ε # Map the copy to: N> # Push the 0-based map index, and increase it by 1 « # Append it to the element-string …[ÿ] # Push string "[ÿ]", where the `ÿ` is automatically filled with the # element name and number }‡ # After the map: transliterate all elements to the formatted elements in # the partition J # And join it back together to a single string # (after which it is output implicitly as result) ``` [See this 05AB1E tip of mine (section *How to compress strings not part of the dictionary?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `.•2вy>ÖΘZθÒ7ßΩ¨ÑÝ\n(Îiþ∍ćf=ÆΛ}’.мιoiFδC¸Γ=¢`Ÿíнp»ΛÑzðÿ®ÄÄ‘Â@Âη+(Óûò‘8нKKK#â<Ù#<“râµ5£”м}ÓæuüåÈZµ-ΔÈ;VzeY¯õnK§ÁÚ¡[θƶη„Gp©6›mðÿāε1ΛÎíγJò~܉cT¢Œƶʒ˜•` is `"h helibeb c n o f nenamgalsip s clark casctiv crmnfeconicuzngageassebrkrrbsry zrnbmotcrurhpdagcdinsnsbtei xecsbalaceprndpmsmeugdtbdyhoertmybluhftaw reosirptauhgtlpbbipoatrnfrraacthpau nppuamcmbkcfesfmmdnolrrfdbsgbhhsmtdsrgcnnhflmclvtsog"`. [Answer] # [Perl 5](https://www.perl.org/) `-p`, 313 bytes ``` map$k{$_}=++$j,HHeLiBeBCNOFNeNaMgAlSiPSClArKCaScTiVCrMnFeCoNiCuZnGaGeAsSeBrKrRbSrYZrNbMoTcRuRhPdAgCdInSnSbTeIXeCsBaLaCePrNdPmSmEuGdTbDyHoErTmYbLuHfTaWReOsIrPtAuHgTlPbBiPoAtRnFrRaAcThPaUNpPuAmCmBkCfEsFmMdNoLrRfDbSgBhHsMtDsRgCnNhFlMcLvTsOg=~/.[a-z]?/g;for$a(sort{$b=~y///c-length$a}keys%k){s/(?<!\[)$a/[$a$k{$a}]/g} ``` [Try it online!](https://tio.run/##FdDdToMwGADQe59Ck5podOKNV3MxtBtjEbqG1p9tGvMBpSDQkhZM5jIfXYznEU4nbXM3ji10qD6gj@Ps6gp9XoehjCosMaHrgEoKsfIbXjFOGt8@EuCZqJ6JjXUgiaEVGbZ6CUvpOy6xfbRJyu1ma2kaG5ElQ1Ky3FckX2mueSrk6lUShyECIpmlOWt5uxiWuUjn@9AsrGg3aTSEhYCXRK7dyrLeH0IlGpbiihm/T3RgE/AzUTJ4oh0b/Ja0uCbFwgVtnFMT2aSYp1zhMnRxP3eJIpqWQRNn0ZdwazX78W52MPl@f/DUtDAWwYUztj@gdPaz9zwvmzRSq75EcKzl3p3XlwfnXTzcn73tLhF4OwT/V3B899RxnKLP2e10xFZCXWl1iiE/KdYGg/01XV8Z7cZJ1/wB "Perl 5 – Try It Online") ]
[Question] [ # Input The input will be a year between 1583 and 2239. We just want to know when [Hannukah](https://en.wikipedia.org/wiki/Hanukkah) was or will be in that year. This is information used by millions of people every year and put in calendars across the world. What could be easier? # Output The Gregorian date of the first **evening** of Hannukah that year. That is the day before the first full day of Hannukah. Your code should output the month and day of the month in any easy to understand human readable form of your choice. # Examples ``` 1583 December 9 2013 November 27 2014 December 16 2015 December 6 2016 December 24 2017 December 12 2018 December 2 2019 December 22 2020 December 10 2021 November 28 2022 December 18 2023 December 7 2024 December 25 2025 December 14 2026 December 4 2027 December 24 2028 December 12 2029 December 1 2030 December 20 2031 December 9 2032 November 27 2033 December 16 2239 December 21 ``` It could hardly be simpler. We start with a couple of definitions: We define a new inline notation for the division remainder of \$x\$ when divided by \$y\$: $$(x|y)=x \bmod y$$ For any year Gregorian year \$y\$, the *Golden Number*, $$G(y) = (y|19) + 1$$ For example, \$G(1996)=2\$ because \$(1996|19)=1\$. To find \$H(y)\$, the first evening of Hannukah in the year \$y\$, we need to find \$R(y)\$ and \$R(y+1)\$, the day of September where *Rosh Hashanah* falls in \$y\$ and in \$y+1\$. Note that September \$n\$ where \$n≥31\$ is actually October \$n-30\$. $$R(y)=⌊N(y)⌋ + P(y)$$ where \$⌊x⌋\$ denotes \$x-(x|1)\$, the integer part of \$x\$, and $$N(y)= \Bigl \lfloor \frac{y}{100} \Bigr \rfloor - \Bigl \lfloor \frac{y}{400} \Bigr \rfloor - 2 + \frac{765433}{492480}\big(12G(y)|19\big) + \frac{(y|4)}4 - \frac{313y+89081}{98496}$$ We define \$D\_y(n)\$ as the day of the week (with Sunday being \$0\$) that September \$n\$ falls on in the year \$y\$. Further, Rosh Hashanah has to be postponed by a number of days which is $$P(y)=\begin{cases} 1, & \text{if } D\_y\big(\lfloor N(y)\rfloor \big)\in\{0,3,5\} & (1)\\ 1, & \text{if } D\_y\big(\lfloor N(y)\rfloor\big)=1 \text{ and } (N(y)|1)≥\frac{23269}{25920} \text{ and } \big(12G(y)|19\big)>11 & (2)\\ 2, & \text{if } D\_y\big(\lfloor N(y)\rfloor \big)=2 \text{ and } (N(y)|1)≥\frac{1367}{2160} \text{ and } (12G(y)|19)>6 & (3)\\ 0, & \text{otherwise} & (4) \end{cases}$$ For example, in \$y=1996\$, \$G(y)=2\$, so the \$N(y)\approx13.5239\$. However, since September 13 in 1996 was a Friday, by Rule \$(1)\$, we must postpone by \$P(y)=1\$ day, so Rosh Hashanah falls on Saturday, September 14. Let \$L(y)\$ be the number of days between September \$R(y)\$ in the year \$y\$ and September \$R(y+1)\$ in year \$y+1\$. The first evening of Hannukah is: $$ H(y)=\begin{cases} 83\text{ days after }R(y) & \text{if } L(y)\in\{355,385\}\\ 82\text{ days after }R(y) & \text{otherwise} \end{cases} $$ # Notes and thanks Your code may not access the Internet to get the answer using e.g. an online Hebrew calendar calculator. Thank you to @Adám for pointing me to the rules and for a great deal of help. To keep things simple, this challenge assumes the location to be Jerusalem. For those now intrigued by the math of the Hebrew calendar, see <https://docs.microsoft.com/en-us/dotnet/api/system.globalization.hebrewcalendar?view=netframework-4.8> . [Answer] # JavaScript (ES6), ~~188 ... 168~~ 160 bytes *Assumes that the system is set up to UTC time (as the TIO servers are)* Returns a Date instance. ``` y=>(D=d=>new Date(y,8,n+=d))(((g=y=>D((n=80,d=D((3*-~(y/100)>>2)+1.554*(x=12*-~y%19)+y%4/4-y/314.6-.9).getDay())%2+2*(n%!d>.63&x>6))/864e5)(++y)-g(--y)+5)%30<1) ``` [Try it online!](https://tio.run/##HdCxboNADIDhPU9BBxo7xx2cDygovZvo0iEd2i3KgAKhqSKIEtTmVLWvTnGXX5bsb/FH/Vlf95fjeZT90LTTwU7eOqhsY13ffgVVPbbgoyLqhW0QAaCz80EF0NsiiRo7T2Ylf8HHOknQOUKhVZalK7hZTfPGh7pE4cM0TqWPjU5VLlWJqmvHqvaAGJKgFfThXeNUbu5vLkeMizxtMwQhPMoOpPQoMgxN8qhxWm91VpiIEv2flJNxcs4Dp@CUcyjhaA5xWBALYkEsiAWxIBaGhWFhWJhZkCl3C3UYLk/1/h18YF3wvQiC/dBfh1OrTkM3vyg4gEc1Ds@vLxtAdT2fjiMs35a4TXa4XvzgevoD "JavaScript (Node.js) – Try It Online") Or [test it against a more literal implementation](https://tio.run/##dVJdb9pAEHznVyyRjG/xB3fnj9gl56oSRWpVtVLSN8QDwobSIhvZTorVJH@d7tk1pUh9sLQ3O3czO@vvq6dVtS53h9rJizQ7bdSpUQmbqVQlefYTZqs6Y40d2bmlUkTG2FYRYcZYriJup4oqb@y8smYiOMckkWgJNwj8MTsqIanTGCJGqzH8ie80E0/4bui4MbrbrJ6tGoZoSEuOWW4M08QNvdExCREnUehnATLLatDZMsdp0ArQ8PidwFNZVN9AQQMqgV8DgH1Ww7YFDBAxWCCmf9AjoULCmNq61cM5wa9kGSagTYPTn/zuJOmN2zDwPU9jsfQjTm8cCdUSvgaJxTzhEdwQHMU8Ekh4HPlx2MukJHORIUQ26eR/J@95B@IxIivg8PwMbeWdqwB12fUFjEbknmaBRIH0ZBiTqAxiyXXnCAkI8vGW@m@62/KfG8ILb/UFEZ75IbElsXnvpmzDyWmqg4bKrH4sc1hcT1IifbCcDl4Gg/n1NhZQ2qS6JFwvizXnWRdwfwHrXeFlXOyegi11kvQDcN4tiF/4uHKhbUZ6XV0@XhBAH2AUILbuNkXJih/0eF0@ZrY2CmEYTKm4o3QDwam0LGzN7zaMlZwYG/KM9K5pwpBslYKw@RnryADrIq@Kfebuiy0z5@8@fHo/M0mBkuFuXXx8@PKZoVsd9ruamV9NXPAltcR/Wm0QAK3VzWpfZfr8QhMQQsu61Lp5eFyvs6oa3uD09Bs) ### How? The approximations described below are guaranteed to work for \$665\le y\le 5510\$, which is a significantly larger interval than the requested one. * Instead of computing: $$k=\left\lfloor\frac{y}{100}\right\rfloor-\left\lfloor\frac{y}{400}\right\rfloor-2$$ we compute \$k+2\$ with: ``` 3 * -~(y / 100) >> 2 ``` This off-by-two error is left uncorrected. We just need to adjust the final offset accordingly, as well as the tests about the day of the week. It has no impact on \$L(y)\$. * An offset of \$80\$ days is added right away to all date calculations, which introduces an additional shift of \$3\$ more days (\$80\bmod7\$) in the days of the week. Therefore, the index \$d\$ for the day of the week is \$5\$ for Sunday, \$6\$ for Monday, \$0\$ for Tuesday, \$1\$ for Wednesday, \$2\$ for Thursday, \$3\$ for Friday, or \$4\$ for Saturday. Very conveniently, it leads to the following properties: + rule \$(1)\$ for \$P(y)\$: the day is either Sunday, Wednesday or Friday iff \$d\$ is odd + rule \$(3)\$ for \$P(y)\$: the day is Tuesday iff \$d=0\$ * We use \$1.554\$ as an approximation of \$\dfrac{765433}{492480}\$. * We use \$\dfrac{y}{314.6}+0.9\$ as an approximation of \$\dfrac{313y+89081}{98496}\$. * The test about \$D\_y(\lfloor N(y)\rfloor)\$ being equal to \$1\$ is ignored entirely, as the result cancels out with the other criteria. * We use \$0.63\$ as an approximation of \$\dfrac{1367}{2160}\$. * Instead of testing \$L(y)\in\{355,385\}\$, we test \$\big(L(Y)+5\big)\bmod30=0\$. [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 108 bytes An alternate version suggested by @Adám, with a distinct output format for the edge case 2239. ``` using System.Globalization;string f(int y)=>y<2239?new DateTime(y+3761,3,24,new HebrewCalendar())+"":"1221"; ``` [Try it online!](https://tio.run/##NY7dCsIgAIXvewrxSnFFav9udVFQl0G9gFsawuZAjWEvb5PY3Xc4P5zGzxtvUvp4Y9/gEX1Q3eLa9rVszVcG01vhg8ueRsYGEHF1jCVjfH@yagAXGdTTdApFwrcbWvCCrYps3FTt1HCWrbIv6RDGBMIDpIxRKNJ9HAxII7recYzFTPfuPw4qwJaUi5HKjDwjIRhMjZjjk8gvRp1@ "C# (Visual C# Interactive Compiler) – Try It Online") --- # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), ~~134 130 122~~ 121 bytes *Saved 8 bytes thanks to @Hedi* *Saved 1 byte thanks to @Adám* My first C# program either... \o/ Returns a DateTime instance. ``` using System.Globalization;dynamic f(int y)=>y<2239?new DateTime(y+3761,3,24,new HebrewCalendar()):new DateTime(y,12,21); ``` [Try it online!](https://tio.run/##VY7NDsIgEITvPsUeIUUj4D@tHjTRo4m@AG2pIWlpApgGXx5LTA/evsnOzE7l5pXTMb6dNi94BOdVt7i2fSlb/ZFe90bUwchOV9AgbTwEXBxDzhjfn4wa4CK9eupOoZDx7YYSTtiKpMNNlVYNZ9kqU0uLMD782wllhFEs4t2OtahBdL3jGItZ09vfIyiALSkXI@UJecIswzAlQrJPIi0adfwC "C# (Visual C# Interactive Compiler) – Try It Online") [Answer] # [Perl 5](https://www.perl.org/), ~~313~~ 278 bytes ``` sub f{sub t{timegm_nocheck(0,0,0,pop,8,pop)}$Y=pop;eval'(R,N,Q)=map{X=12*(_%19+1)%19;N=1.554*X-2.9-_/314.4+_%4/4+_/100%99-_/400%9;I=intN;D=t(_,I)/86400%7;M=N-I;P=D=~/[361]/||D==4&&M>1?1:D==5&&M>=.63&&X>6?2:0;t(_,I+P),I+P}Y,Y+1;t(Y,N+82+((Q-R)/432e3)=~/1|7$/)'=~s/[A-Z_]/\$$&/gr} ``` [Try it online!](https://tio.run/##dVNtb9owEP7OrzhNBmyS4NhOQkJkukkVUqUVtWgfyhiKWBsoGm8K6TQE9K@zc6DNkFajHJfnuTufn3PWaTb3j8fNy0@Y7IzNd/lskU4XyXL1@Jw@/qKubX7r1doOjWUHMtD4H6e/x/M67ds9@57pxXi9e9BCNmhSFZElGNq4p0XT973GgyObkZNwJbymZyVVj6PlwnWrkYE948Q3erbMe/G1zmli3zAeBgZvxbe659zEd/pav/KhCsSI7/fXWnu12m1HXIk2@r7xdTNQtdpDJ7iSbTcuilh3zJjDwB5YAqGB3bNCaVF67/QZ95RMFcOqYt8inNX164YPvzjfkxH/QUiNT7PD8WWTwjeUo93@unocz6F@qU09rhjJFmJHkqE7AgfwDLTw2aGg8tmHclJ2EpSyc2y22jzDrgK4Flsg20Ll99epJttC2hL6YwQnUyP1O7bURQtbIy97a2hrNDZvEixoBb6nFPci6YUuNLAMgmQLVfCA4@MAVUIZYotEGLmhYEhEoRcF5T5Pms6NJOZ0NJ/hHjZuRZaMsWEwKuPWGopFnkBrcGG/P7uqdP0K/LsQpydCQK2G6lIsCx0NUskg4tKPpGsIbLwDApu7wsD2uZa8TBEqaHEpgjIhwHCJ4W7ZY3bSbMkschb8fCKSMRtpVjkNqPvRdCjJbEzXZoKYx0q8/w7iN3GhHuk7WPl0zU/Eec9lcUcx5JWroR@OfM5MA8VVTDd5u327ylLI0d3ojpQqcoQfKnMvJquMGr/ZNDB7a5YCmeAxugw04HcKO/ic63J4JGExkMXiCfUDvDUWPg2SD72RhVaN4HA5nmJNTJr9H6Jb1CuI2YaewgrM/rRNxxmQxGRrMjGxmnQ/YfDh@Bc "Perl 5 – Try It Online") Based on @Arnauld's javascript answer. Slightly ungolfed: ``` sub f{ sub t{timegm_nocheck(0,0,0,pop,8,pop)} #xth sep y => secs after jan 1 1970 $Y=pop; #input year eval' #eval code string to use code without $ (R,N,Q) = map { #R,N=rosh for curr Y. Q for Y+1 X=12*(_%19+1)%19; N=1.554*X-2.9-_/314.4+_%4/4+_/100%99-_/400%9; #%99 cuts decimals, int() for small nums I=intN; D=t(_,I)/86400%7; #D=weekday - 4, 3=sun 6=wed 8=1=fri ... M=N-I; #M=N%1 (perl dont support P=D=~/[361]/||D==4&&M>1?1:D==5&&M>=.63&&X>6?2:0; t(_,I+P),I+P } Y, Y+1; t(Y,N+82+((Q-R)/432e3)=~/1|7$/) ' =~ s/[A-Z_]/\$$&/gr #inserts $ before every uppercase A-Z and _ } ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~86~~ 85 [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") Now that Arnauld has posted [his C# solution](https://codegolf.stackexchange.com/a/197753/43319), I can reveal my equivalent anonymous tacit prefix function. ``` ⎕NEW{⎕USING←'System'⋄0::1221⋄⍺⍺DateTime((3761+⍵)3 24,⍺⍺Globalization.HebrewCalendar)} ``` Can't try it online as this only works under Windows. (.NET Core support is planned for this year!) `⎕NEW{`…`}` function derived from monadic operator with `⎕NEW` (create new instance of object) as operand:  `⎕USING←'System'` make the members of .NET's root namespace's immediately available  `⋄0::1221` upon any error, return this number  `⋄` Try:   `⍺⍺DateTime(`…`)` create a new DateTime object with the following constructor arguments:    `⍺⍺Globalization.HebrewCalendar` create a new HebrewCalendar object    `(`…`)3 4,` prepend the list ending with `[`…`,3,4]` where the first element is:     `3761+⍵` the argument adjusted for the difference between the civil and Hebrew calendars' years ]
[Question] [ [Shikaku](https://en.wikipedia.org/wiki/Shikaku) is a 2D puzzle. The basic rundown of it is that a rectangular grid has some numbers in it, and you want to partition the grid into rectangular components such that each component contains exactly one number which is the number of grid squares in that component. This challenge involves a 1D simplification of this: it is a line of N squares with K numbers \$\{a\_1, a\_2, \cdots, a\_K\}\$, and a solution would be a division of the line into K partitions such that each partition contains \$a\_i\$ squares. However, in this simplification, *not all squares need to be used*. # Challenge Given a list of N numbers (where 0 is an empty square), determine if a valid solution to that problem exists. # Truthy Cases (\_ is a blank; it will be given as 0 in the input. you may not take the input as an index:element mapping) ``` _ _ 3 _ _ 5 _ _ 3 _ _ ([ ] [ ] [ ]) 2 _ _ _ _ 6 _ _ _ 4 _ _ ([ ] [ ] [ ]) _ 5 _ _ _ 3 _ _ _ _ _ 4 ([ ] [ ] [ ]) _ _ 2 _ _ _ _ 4 _ _ ( [ ] [ ]) ( [ ] [ ] ) just to give 2 examples ``` # Falsy Cases ``` _ _ 2 _ 4 _ _ 3 _ _ 5 _ _ 3 _ _ _ 5 _ _ _ 3 _ 2 _ 2 _ 2 _ 3 ``` # Rules and Specifications Input can be taken as any convenient way to take a list of numbers. You can input it as a string with `_` for blanks as well; etc. Any reasonable method; however, you may not change the general structure of the input as a list. Output is a true/false value. Any truthy/falsy value is acceptable. The true/false value does not have to be consistent across cases, but your program must give the same exact answer for the same test case every run, and please specify how truthy/falsy is distinguished if it's not conventional. For example, you can output 1 for a true case and 2 for another, and 0 for false cases, but the first case must always yield 1 every time, and the second must give 2 every time. To prevent a loophole brought up thanks to @xnor, your output must be successful / failed completion as a result, numbers, booleans, or other similar "primitive-like" datatypes (basically, you cannot submit the identity function and say that the Truthy/Falsy sets are divided by this problem's specifications). * Standard loopholes are forbidden. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), therefore the shortest answer in each language wins. No answer will be accepted. [Answer] # JavaScript (ES6), ~~56~~ 52 bytes Returns a Boolean value. ``` a=>![...a,1].some(x=>t>0/x?1:(t+=x-1)*x<0?t=0:0,t=0) ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/R1k4xWk9PL1HHMFavOD83VaPC1q7EzkC/wt7QSqNE27ZC11BTq8LGwL7E1sDKQAdIav5Pzs8rzs9J1cvJT9dQjw4pKi3JqIxV1@RCFk/TiDbQMdAx1gGRpjpwdqwmhjojsCwImkFpExwqYSbBzIWqxqrSQAdhLtw8FGXqMXnRbok5xbjcbgTRidV0NH/hcAHctVjljXQQGKTiPwA "JavaScript (Node.js) – Try It Online") ### Commented The accumulator \$t\$ is decremented whenever an empty slot is encountered. For each non-zero value \$x\$, we update \$t\$ to \$max(t+x-1,0)\$. The test fails if we reach a non-empty slot (or the end of the list) with \$t>0\$. ``` a => // a[] = input ![...a, 1] // append a '1' at the end of a[] to force a last test .some(x => // for each value x in the updated array: t > 0 / x ? // if x = 0, this test is always falsy (0 / 0 -> NaN) // if x ≠ 0 and t is greater than 0: 1 // failed: yield 1 : // else: (t += x - 1) // add x - 1 to t * x < 0 ? // if t is negative and x ≠ 0: t = 0 // we have accumulated more empty slots than // we can consume here: set t to 0 : // else: 0, // do nothing t = 0 // start with t = 0 ) // end of some(); return the opposite result ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~96~~ ~~87~~ 85 bytes ``` def f(a): c=p=0 for x in a: if p*x:return p|=x;c+=1 if c>=p>0:c=p=0 return p ``` [Try it online!](https://tio.run/##LUtBCsMwDDunr/DR3XpIKbtkuH8JWUwDwzUhHRns71lYJ4GQbEnfZdtlae0RGRj96AYTSMkOhvcMFZKA7zeTGPRSXY7lyNKzfqjew5Xm8xdW0tW6//RsgTbNSQoyxpd/YhI9Co4dzU7LZDtvP@3@Cw "Python 3 – Try It Online") -5 bytes thanks to 79037662. -6 bytes thanks to HyperNeutrino. None and positive are falsy, 0 is truthy. [Answer] # [Python 2](https://docs.python.org/2/) via exit code, 52 bytes ``` n=0 for x in input()+[1]:x*n<0>_;n+=x<1or-max(x-1,n) ``` [Try it online!](https://tio.run/##bU6xDoIwFNz5ihcmUEhoRQcENx2d3AgxBGsggZbUEsvXYxWoxZhcXu7d3bu27UXJKB4KdiOJbdsDTQLrzjhIqKhC2wnHXacoi@SKxsHhuqfrRMaIcb/JpSN95FF3UIfWs6xqAiiyQPBeTSCSFPDuVbzlFRVw4Z1aiCxIK@CcN@TIOeOR9k95/SBDGnigsPlMhe1MJiWzUjxLI3YGD3XIPDX7vtExpPDTt@jQdqil/1/T8cWro4qNHjwZLw "Python 2 – Try It Online") Successful completion for True, error for False. *-1 byte thanks to Arnauld.* [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~56~~ ~~55~~ ~~54~~ 47 bytes *inspired by Arnauld's [one accumulator code](https://codegolf.stackexchange.com/a/195521/80745).* ``` !($args+1|?{$_;$t+=$_-1}|?{$t-ge$_;$t*=$t-ge0}) ``` [Try it online!](https://tio.run/##bVHvCoIwEP@@p1hyhUuFMutDIfUOPYBInRYJmU4K1Ge3tZot2zjG7X5/7sbl1zsW5QmzrIOEhrTuRjbERVo682ZbQ7QB7oQQefP29eReirI2DWU@a1nXErKzCRXHtYEXFbp0JmOhkuWgwn7ZvoLfsdLywCjQLfU@XxkzzTPo03srbhJn5YAc6M2/uPlnzGj0M6mB4v/dgsVoQ8e0lmzAR44HjkeXwv50vsSXSuwJojdYYFllXBQmYn27Dy4hC@wP6uGtN2FrpbFI2z0B "PowerShell – Try It Online") [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 34 bytes ``` ^ , \d+ $* \b ; +1`,;1|1;, ; ^\W*$ ``` [Try it online!](https://tio.run/##K0otycxL/K@q4Z7wP45LhysmRZtLRYsrJonLmkvbMEHH2rDG0FoHyImLCddS@f/fQMdAx1gHRJrqwNlcRmA2CJpBaROwOEwVTA9UjgtEIvTA1ELETMBsNDu4EDwgnwuiEoaNAQ "Retina 0.8.2 – Try It Online") Explanation: ``` ^ , ``` Prepend a `,` so that there's one `,` for each square. ``` \d+ $* ``` Convert the entries to unary. ``` \b ; ``` Surround each non-empty square with `;`s. ``` +1`,;1|1;, ; ``` Each `;` in turn starts eating away at the adjacent empty squares. ``` ^\W*$ ``` Check that there were no `1`s left. After adding the prefix and the unary conversion, .NET is actually able to solve the problem in a single regex, although it weighs in at a massive 58 bytes: ``` ^ , \d+ $* ^(,*(,)*(?<-2>1)*(?(2)^)(1)*(?<-3>,)*(?(3)^))*$ ``` [Try it online!](https://tio.run/##XU27CoAwDNzzHRXSGkFbdZI6@hNSFHRwcRD/v/apICGXu8uFXPt9nKstcFqsAYJ5K4EJMEgCiQsch0rqxhOU3HBsoqd0WKJyHhfM2ppqUuSxo5eDDNxXn2Yb/JzKN2kHHr@bnI1eG/jvB3zKaYjJ3OoB "Retina 0.8.2 – Try It Online") [Answer] # [J](http://jsoftware.com/), 47 bytes ``` [:*/2(>+.0>:[)/\[:(++(0>.0-+)*0<+-])/@|.\<:@,&1 ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/o6209I007LT1DOysojX1Y6KtNLS1NQzs9Ax0tTW1DGy0dWM19R1q9GJsrBx01Az/a3JxpSZn5CsopAENMVAwBpOmCDZc1ggsBoJmUNoETCJpN4VKGMOVAhWhGI8wxARhuLo6hEYoMYFJpWE6CVkt3EKEoBESNv4PAA "J – Try It Online") Credit to Arnauld for the high-level idea. I'll add explanation and golf more soon. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 20 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ŒṖT€ẈỊẠƲƇðẈẋ`€F⁹a⁼ðƇ ``` A monadic Link accepting a list of non-negative integers which yields a list. An empty list is falsey, a non-empty list is truthy. (The list is actually all ways which work). **[Try it online!](https://tio.run/##y0rNyan8///opIc7p4U8alrzcFfHw91dD3ctOLbpWPvhDSDuru4EoITbo8adiY8a9xzecKz9////0QY6CkY6CgZgZAJhxAIA "Jelly – Try It Online")** Or see a [test-suite](https://tio.run/##y0rNyan8///opIc7p4U8alrzcFfHw91dD3ctOLbpWPvhDSDuru4EoITbo8adiY8a9xzecKz9v46hgsHhdnuQrhlAOU33//@jow10FIDIGEwCkSmMARWJ5dKJNoKJQZAZEtsEoQpZM7KJCLVQVUCEZiKqKXB5E4QYdvchNKDYDBU2QjLKCCYTCwA "Jelly – Try It Online"). ### How? ``` ŒṖT€ẈỊẠƲƇðẈẋ`€F⁹a⁼ðƇ - Link: list, S ŒṖ - all partitions (of S) Ƈ - filter keep those for which: Ʋ - last four links as a monad: € - for each: T - truthy indices Ẉ - length of each Ị - insignificant (for our purposes: is in (0,1)?) Ạ - all truthy? Ƈ - filter keep those for which: ð ð - the dyadic link - i.e. f(partition, S) Ẉ - length of each € - for each: ` - use left as both arguments of: ẋ - repeat (i.e. 5 -> [5,5,5,5,5]) F - flatten ⁹ - chain's right argument (S) a - logical AND (vectorises) ⁼ - is equal to (S)? ``` [Answer] # [J](http://jsoftware.com/), 28 bytes ``` [:*/1>1&,*([0&>.<:@+)/\.@,&0 ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/o6209A3tDNV0tDSiDdTs9GysHLQ19WP0HHTUDP5r/k8DKjVQMAaTpgg2V5qCEZgHgmZQ2gQqA1MJ0weV5YKYhdCHUA8RNYHy0GyDqoCbCeYbIWGQiDGqGAA "J – Try It Online") Inspired by [Arnauld's algorithm](https://codegolf.stackexchange.com/a/195521/78410). 1 if a solution exists, 0 otherwise. ### How it works In order to retain intermediate values of `t`, I chose to use "Reduce on suffixes" `/\.` with the initial value appended. Given a function `f`, the result of `f/\.` looks like this: ``` Input array: 0 0 2 2 2 0 0 0 Index 0: 0 f 0 f 2 f 2 f 2 f 0 f 0 f 0 (right-assoc for everything) Index 1: 0 f 2 f 2 f 2 f 0 f 0 f 0 Index 2: 2 f 2 f 2 f 0 f 0 f 0 ... Index 6: 0 f 0 Index 7: 0 ``` Explanation of full code: ``` [:*/1>1&,*([0&>.<:@+)/\.@,&0 Right argument: 1D Shikaku grid ex. 0 0 2 2 2 0 0 (expected: falsy) ,&0 Append the starting value of t=0 ex. 0 0 2 2 2 0 0 0 /\.@ Reduce from right and keep intermediate values... ( ) (left: x, right: t, output: t') <:@+ Compute y = x + t - 1 [0&>. Compute max(0, y) x times; simply y if x = 0 ex. 0 1 2 1 0 -2 -1 0 1&,* For each element, match the current value of x with the previous value of t (including the finish), counting from the right ex. 0 0 0 2 0 -4 0 0 [:*/1> Check if all of them are zero or less ``` ### Golfing the next-`t` algorithm ``` If x is empty, decrement t; otherwise compute max(t+x-1, 0) -> If x is empty, compute t+x-1; otherwise compute max(t+x-1, 0) -> Compute t+x-1; if x is nonempty, apply (y => max(y, 0)) -> Compute t+x-1; apply (y => max(y, 0)) x times (assume x >= 0) ``` ]
[Question] [ Inspired by [*Display a chain of little mountains with an odd number on the top of it!*](https://codegolf.stackexchange.com/questions/100858/display-a-chain-of-little-mountains-with-an-odd-number-on-the-top-of-it) by [@sygmei](https://codegolf.stackexchange.com/users/62626/sygmei). Why have a chain of mountains when you can have one massive one? Make a program that takes an input number and prints a mountain with every odd number up to the input number. (Where "south west" means `directly below and to the left`, and "south east" means `directly below and to the right`) Every number will have a `/` south west of it, and a `\` south east. It starts from `1` at the top, and the next number will go south west of a `/` or south east of a `\`. The next number will go in the line closest to the top and to the left most possible. For a multidigit number, just the 1st digit needs to be in the right place with the other digits directly after, and only the first digit should have `\` and `/` coming out from it. The mountain up to 1 or 2 is just: ``` 1 / \ ``` A mountain up to 3 or 4 is just: ``` 1 / \ 3 / \ ``` For 25 or 26: ``` 1 / \ 3 5 / \ / \ 7 9 11 / \ / \ / \ 13 15 17 19 / \ / \ / \ / \ 21 23 25 / \ / \ / \ ``` Last two lines where the input is 121: ``` 111 113 115 117 119 121 / \ / \ / \ / \ / \ / \ ``` And the last two lines where the input is 1019: ``` 993 995 997 999 1001100310051007100910111013101510171019 / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ ``` You may assume that the input will be greater than 0 and less than 10001 (exclusive). Trailing spaces are OK, and extra leading spaces are alright as long as there is the same on all lines. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest program in bytes wins. An ungolfed answer to this can be found online [here](https://repl.it/E6aT/0) (In Python on repl.it) if you need more test cases. [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), ~~54~~ ~~52~~ ~~47~~ 46 bytes ``` ÅɹL£D€g__ÏRv"/ \ "yg×N·©úˆyvy4yg-ð×}J®>úˆ}¯R» ``` [Try it online!](http://05ab1e.tryitonline.net/#code=w4XDicK5TMKjROKCrGdfX8OPUnYiLyBcICJ5Z8OXTsK3wqnDusuGeXZ5NHlnLcOww5d9SsKuPsO6y4Z9wq9Swrs&input=MTAyMA) **Explanation** ``` # implicit input n ÅÉ # push a list of uneven numbers up to input ¹L£ # divide into sublists of length 1,2,3...n D€g__Ï # remove empty sublists R # reverse list v # for each sublist "/ \ " # push the string "/ \ " yg× # repeat it len(sublist) times N·©ú # prepend (sublist index)*2 spaces ˆ # add to global list yv # for each number in sublist y4yg-ð× # prepend spaces until length is 4 } # end inner loop J # join to string ®>ú # prepend (sublist index)*2+1 spaces ˆ # add to global list } # end outer loop ¯ # push global list R # reverse it » # join rows by space and columns by newline # implicitly print ``` I could have saved 5 bytes with `ÅɹL£D€g__ÏRv"/ \ "yg×N·©úˆy4jJðÛ®>úˆ}¯R»` if only I'd pushed that bugfix for **j** I wrote several weeks ago **:/** [Answer] ## Batch, 335 bytes ``` @echo off set i= set/ac=w=0 :l set i= %i% set/aw+=2,c+=w if %c% lss %1 goto l set s= set t= set/ac=w=1 for /l %%a in (1,2,%1) do call:c %%a echo %s% echo%t% exit/b :c if not %c%==0 goto g echo%i%%s% set i=%i:~2% echo%i%%t% set s= set t= set/aw+=1,c=w :g set n=%1 (three trailing spaces) set s=%s%%n:~0,4% set t=%t% / \ set/ac-=1 ``` [Answer] ## Python 2, ~~160~~ ~~149~~ 143 bytes *Thanks TFeld for saving 11 bytes and Artyer for saving 6 bytes* ``` x=range(1,input()+1,2);y=[];i=1 while x:y+=[''.join('%-4d'%j for j in x[:i]),'/ \ '*len(x[:i])];x=x[i:];i+=1 while y:print' '*~-len(y)+y.pop(0) ``` [Answer] ## Perl, 134 **133 bytes + 1 for `-p` option** ``` $l="/ \\ ";$t=" ";while($c++<$_) {$t.=sprintf'%-4d',$c++;$v.=$l;if ($i++>=$j){$t=~s/^/ /gm;$t.=" $v ";$i=$v="";$j++}}$_="$t $v"; ``` Formatted version (original golfed version uses real "new lines" instead of \n) ``` $l="/ \\ "; $t=" "; while($c++<$_) { $t.=sprintf'%-4d',$c++; $v.=$l; if ($i++>=$j){ $t=~s/^/ /gm; $t.="\n $v\n "; $i=$v=""; $j++ } } $_="$t\n$v"; ``` [Answer] # Bash, 425 bytes ``` f() { k=0; o=""; l=1; for (( c=1; c<=$1; c++ )); do o="$o$c "; let c++ k++; if [ $l -eq $k ]; then o=$o"\n"; k=0; let l++; fi; done; s=$[$(echo -e $o | wc -l)*2-1]; p() { for c in $(seq $1); do echo -n " "; done }; IFS=$'\n'; for n in $(echo -e $o); do unset IFS; p $s; let s--; for w in $n; do echo -n "$w"; p $[4-${#w}]; done; echo; p $s; for c in $(seq $(echo $n|wc -w)); do echo -n "/ \ "; done; echo; let s-- j++; done } ``` Formatted: ``` l=1 k=0 o="" for (( c=1; c<=$1; c++ )) do o="$o$c " let c++ k++ if [ $l -eq $k ] then o=$o"\n" k=0 let l++ fi done s=$[$(echo -e $o | wc -l)*2-1] p() { for c in $(seq $1) do echo -n " " done } IFS=$'\n' for n in $(echo -e $o) do unset IFS p $s let s-- for w in $n do echo -n "$w" p $[4-${#w}] done echo p $s for c in $(seq $(echo $n|wc -w)) do echo -n "/ \ " done echo let s-- j++ done ``` ]
[Question] [ Given a directory (such as `C:/`), given from stdin or read from a file, produce a directory tree, with each file/folder indented based on its depth. ### Example If I have a `C:/` drive which only contains two folders `foo` and `bar`, and `bar` is empty while `foo` contains `baz.txt`, then running with input `C:/` produces: ``` C:/ bar/ foo/ baz.txt ``` while running with input `C:/foo/` should produce ``` foo/ baz.txt ``` As this is codegolf, lowest byte count wins. The file extensions (such as `baz.txt`) are optional. Extra notes: hidden files can be ignored, directories must actually exist, it can be assumed that files do not contain unprintable characters or new lines but all other printable ASCII characters are fine (file names with spaces must be supported). Output can be written to file or stdout. The indentations can be made up of either a tab character or 4 spaces. [Answer] ## bash, ~~61~~ ~~58~~ 54 bytes ``` find "$1" -exec ls -Fd {} \;|perl -pe's|.*?/(?!$)| |g' ``` Takes input as a command line argument, outputs on STDOUT. Note that the spaces near the end before the `|g` are actually a tab character (SE converts them to spaces when displaying posts). ``` find crawl directory tree recursively "$1" starting at the input directory -exec and for each file found, execute... ls -Fd {} \; append a trailing slash if it's a directory (using -F of ls) |perl -pe pipe each line to perl ' s| replace... .*?/ each parent directory in the file's path... (?!$) that doesn't occur at the end of the string... | | with a tab character... g globally ' ``` Thanks to [@Dennis](https://codegolf.stackexchange.com/users/12012/dennis) for 4 bytes! [Answer] # [Dyalog APL](http://goo.gl/9KrKoM), 48 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319) ``` (⊂∘⊃,1↓'[^\\]+\\'⎕R' ')r[⍋↑r←⎕SH'dir/s/b ',⍞] ``` `⍞` prompt for character input `'dir/s/b ',` prepend text `⎕SH` execute in shell `r←` store in *r* `↑` make list of strings into character matrix `⍋` indices for ascending sorting `r[`...`]` reorder *r* [sorted] `(`...`)` on the standard out of the shell command, do: `'[^\\]+\\'⎕R' '` regex replace backslash-terminated runs of non-backslashes by four spaces `1↓` drop the first line `⊂∘⊃,` prepend the enclosed first [line] Result of inputting "\tmp" to the prompt begins as follows on my computer: ``` C:\tmp\12u64 keyboards64.msi netfx64.exe setup.exe setup_64_unicode.msi setup_dotnet_64.msi AdamsReg.reg AdamsReg.zip qa.dws ride-experimental win32 d3dcompiler_47.dll icudtl.dat libEGL.dll ``` ⋮ [Answer] ## [SML](https://en.wikipedia.org/wiki/Standard_ML), 176 bytes ``` open OS.FileSys;val! =chDir;fun&n w=(print("\n"^w^n);!n;print"/";c(openDir(getDir()))(w^"\t");!"..")and c$w=case readDir$of SOME i=>(&i w handle _=>();c$w)|x=>()fun%p=(&p"";!p) ``` Declares (amongst others) a function `%` which takes a string as argument. Call with `% "C:/Some/Path";` or `% (getDir());` for the current directory. I'm using the normally rather functionally used language StandardML whose `FileSys`-Library I discovered after reading this challenge. The special characters `!`, `&`, `$` and `%` have no special meaning in the language itself and are simply used as identifiers; however they can't be mixed with the standard alphanumeric identifiers which allows to get rid of quite some otherwise needed spaces. ``` open OS.FileSys; val ! = chDir; define ! as short cut for chDir fun & n w = ( & is the function name n is the current file or directory name w is a string containing the tabs print ("\n"^w^n); ^ concatenates strings ! n; change in the directory, this throws an exception if n is a file name print "/"; if we are here, n is a directory so print a / c (openDir(getDir())) (w^"\t"); call c with new directory and add a tab to w to print the contents of the directory n ! ".." we're finished with n so go up again ) and c $ w = 'and' instead of 'fun' must be used because '&' and 'c' are mutual recursive $ is a stream of the directory content case readDir $ of case distinction whether any files are left SOME i => ( yes, i is the file or directory name & i w handle _ => (); call & to print i an check whether it's a directory or not, handle the thrown exception c $ w ) recursively call c to check for more files in $ | x => () no more files, we are finished fun % p = ( % is the function name, p is a string containing the path & p ""; call & to print the directory specified by p and recursively it's sub-directories ! p change back to path p due to the ! ".." in & ) ``` Can be compiled like this with [SML/NJ](http://smlnj.org/) or with Moscow ML\* by prefixing with `load"OS";`. \*See `mosml.org`, can't post more than 2 links. [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 222 bytes ``` namespace System.IO{class P{static int n;static void Main(String[]a){Console.WriteLine(new string('\t',n++)+Path.GetFileName(a[0]));try{foreach(var f in Directory.GetFileSystemEntries(a[0])){a[0]=f;Main(a);}}catch{}n--;}}} ``` [Try it online!](https://tio.run/##NY7LasMwEEV/RbtIOHa6N131RSFtA1l0kWYxTMf1gDMK0uDECH@7qibp6nLhPg7GGn2gnAUOFI@AZLZTVDo0rx8JB4jRbFJUUEbDokbamxk9f5s3YLFbDSw/uz249OAl@oGaz8BKaxayQicTLwG7@NLFUqrKVRvQvnkhfeaB3suvhd3d3rlWw5S6QgPY2xGC6cqleeRAqD5M/40r35OUVYq3avqT@669AIFr5xlBsU@z1HUxc855RYorpfPAI/0C "C# (.NET Core) – Try It Online") --- The ungolf: ``` using System.IO; using System; class P { static int n=0; static void Main(String[] a) { for (int i=0;i<n;i++) Console.Write("\t"); Console.WriteLine(Path.GetFileName(a[0])); n++; if(Directory.Exists(a[0])) foreach (String f in Directory.GetFileSystemEntries(a[0])) Main(new String[]{f}); n--; } } ``` First time I ever recursed a `Main` function! I believe a person that has fresher knowledge of C# can golf it more, as I didn't program on C# for some time! [Answer] # PHP, 180 bytes * first argument: path must have a trailing slash (or backslash) * second argument: level defaults to `NULL` and will be interpreted as `0` by `str_repeat`; will throw a warning if not provided ``` function d($p,$e){$s=opendir($p);echo$b=str_repeat("\t",$e++),$e?basename($p)."/":$p," ";while($f=readdir($s))echo preg_match("#^\.#",$f)?"":is_dir($p.$f)?d("$p$f/",$e):"$b\t$f ";} ``` * displays hidden files and directories, but does not recurse hidden directories add parentheses around `is_dir(...)?d(...):"..."` to remove hidden entries from output (+2) replace `"#^\.#"` with `#^\.+$#` to display/recurse hidden entries but skip dot entries (+2) * may throw errors when directories are nested too deep. Insert `closedir($s);` before the final `}` to fix (+13) * will fail if a directory contains an entry with no name, prepend `false!==` to the while condition to fix (+8) **with glob, 182 bytes** (probably 163 in future php) ``` function g($p,$e){echo$b=str_repeat("\t",$e),$e++?basename($p)."/":$p," ";foreach(glob(preg_replace("#[*?[]#","[$1]",$p)."*",2)as$f)echo is_dir($f)?g($f,$e):"$b\t".basename($f)." ";} ``` * does not display or recurse hidden files/directories * `2` stands for `GLOB_MARK`, will append a slash to all directory names, as does `ls -F` * the `preg_replace` escapes glob special characters I could have abused `preg_quote` for this (-19); but that would fail on Windows systems, as the backslash is the directory separator there. * php *may* soon include a function [glob\_quote](https://github.com/hholzgra/glob-quote), which will allow the same golfing as `preg_quote` and work on all systems. **with iterators, 183 bytes** (well, not purely iterators: I used implicit `SplFileInfo::__toString()` to golf `$f->getBaseName()` and `$f->isDir()` to the old PHP 4 functions.) ``` function i($p){echo"$p ";foreach($i=new RecursiveIteratorIterator(new RecursiveDirectoryIterator($p),1)as$f)echo str_repeat("\t",1+$i->getDepth()),basename($f),is_dir($f)?"/":""," ";} ``` * no trailing slash required * displays and recurses hidden entries (`ls -a`) * insert `,4096` or `,FilesystemIterator::SKIP_DOTS` before `),1` to skip dot entries (+5) (`ls -A`) * flag `1` stands for `RecursiveIteratorIterator::SELF_FIRST` [Answer] # PowerShell, 147 bytes ``` param($a)function z{param($n,$d)ls $n.fullname|%{$f=$_.mode[0]-ne"d";Write-Host(" "*$d*4)"$($_.name)$(("\")[$f])";If(!$f){z $_($d+1)}}}$a;z(gi $a)1 ``` Man, I feel like PS should be able to do something like the bash answer, but I'm not coming up with anything shorter than what I've got here. Explanation: ``` param($a) # assign first passed parameter to $a function z{param($n,$d) ... } # declare function z with $n and $d as parameters ls $n.fullname # list out contents of directory |%{ ... } # foreach $f=$_.namde[0]-ne"d" # if current item is a file, $f=true Write-Host # writes output to the console (" "*$d*4) # multiplies a space by the depth ($d) and 4 "$($_.name)$(("\")[$f])" # item name + the trailing slash if it is a directory ;if(!$f){z $_($d+1)} # if it is a directory, recursively call z $a # write first directory to console z(gi $a)1 # call z with $a as a directoryinfo object and 1 as the starting depth ``` [Answer] # Python 2, 138 bytes Modified from [this SO answer](https://stackoverflow.com/a/9728478/2415524). Those are tabs for indentation, not spaces. Input will be taken like `"C:/"`. ``` import os p=input() for r,d,f in os.walk(p): t=r.replace(p,'').count('/');print' '*t+os.path.basename(r) for i in f:print' '*-~t+i ``` [**Try it online**](http://ideone.com/4P9uWR) - *It's pretty interesting that I'm allowed to browse the directory on Ideone...* Same length: ``` from os import* p=input() for r,d,f in walk(p): t=r.replace(p,'').count(sep);print' '*t+path.basename(r) for i in f:print' '*-~t+i ``` [Answer] ## Batch, 237 bytes ``` @echo off echo %~1\ for /f %%d in ('dir/s/b %1')do call:f %1 %%~ad "%%d" exit/b :f set f=%~3 call set f=%%f:~1=%% set i= :l set i=\t%i% set f=%f:*\=% if not %f%==%f:*\=% goto l set a=%2 if %a:~0,1%==d set f=%f%\ echo %i%%f% ``` Where \t represents the literal tab character. This version includes trailing `\`s on directories but 41 bytes can be saved if they are not needed. [Answer] # Perl, 89 bytes It's useful when there's a find module in the core distribution. Perl's File::Find module does not traverse the tree in alphabetic order, but the spec didn't ask for that. ``` /usr/bin/perl -MFile::Find -nE 'chop;find{postprocess,sub{--$d},wanted,sub{say" "x$d.$_,-d$_&&++$d&&"/"}},$_' ``` The script proper is 76 bytes, I counted 13 bytes for the command-line options. [Answer] # [Tcl](http://tcl.tk/), 116 bytes ``` proc L f {puts [string repe \t [expr [incr ::n]-1]][file ta $f];lmap c [glob -n -d $f *] {L $c};incr ::n -1} L $argv ``` [Try it online!](https://tio.run/##NctBCoMwEAXQfU/xF64KQdzqFbxBmkU6TkIgjWGciiCePXXT7YOnlFurshJmBJz1qxvsppJKhHBlvBSWjyqwqZBgHIszg3M2pMxQjy64KX98BcHGvL5hCsxyM54O54yOruk/YYbrcZOXuLfWelbqlY@cdv4B "Tcl – Try It Online") [Answer] # Java 8, 205 bytes ``` import java.io.*;public interface M{static void p(File f,String p){System.out.println(p+f.getName());if(!f.isFile())for(File c:f.listFiles())p(c,p+"\t");}static void main(String[]a){p(new File(a[0]),"");}} ``` This is a full program submission which takes input from its first command-line argument (not explicitly permitted, but done by many others) and prints output to standard out. [Try It Online](https://tio.run/##TY69csIwEIRfRXElBUdQx306aFwSF4o5kTOWdCOdYRiPn13I0FDut7M/g7mar0Dgh9MlZ3QUIouhQI1BfzY0/Y3YC/QM0ZoexN6gnxMbLvQa8CRI/uAIwtYtR/RnQWpu74nB6TCxpsJ49JI2Vp@BD8aBVKpBKz@sxrRGi7Yhvlr6b6tHTLyKVAySfU2b6pcr1Szvq67ckK/FY2fUTNLDTTzrzHHXqbpaE0vOefsfHGzj5D3EBw) (note different interface name) ## Ungolfed ``` import java.io.*; public interface M { static void p(File f, String p) { System.out.println(p + f.getName()); if (!f.isFile()) for (File c : f.listFiles()) p(c, p + "\t"); } static void main(String[] a) { p(new File(a[0]), ""); } } ``` ]
[Question] [ For each integer *n*, 0 or higher, output the lowest power of 2 that has two identical sub-strings of *n* digits in decimal, and the two indices where the digit sub-strings start (0-based). > > **n      Output      Proof (don't output this)** > > 0 => 0 [0 1]        (**\_**1 & 1**\_**) > > 1 => 16 [0 4]      (**6**5536 & 6553**6**) > > 1 => 16 [1 2]      (6**5**536 & 65**5**36) > > 2 => 24 [0 6]      (**16**777216 & 167772**16**) > > 2 => 24 [2 3]      (16**77**7216 & 167**77**216) > > > The possible outputs for the first three inputs are given above. When there is more than one output for a given input, either is acceptable. Only the digit positions will be different. Just output the numbers, the brackets are for clarity only. You don't need to output *n*. Output a list of as many as you can find in one minute, or your code runs out of resources, whichever comes first. Please include the output with your answer. If the list is huge, just restrict it to the first and last 5. Your code must be able to find up to *n* = 9 in under a minute. I've written a Perl program that finds *n* = 9 after about 20 seconds, so this should be easy to do. Your code doesn't need to halt itself. It is acceptable if you manually break out if it after a minute. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so lowest number of bytes wins! [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 68 bytes ``` '01'(0{x≢`∪x←⍺⍺,/⍺:⍺((⍺⍺+1)∇∇)⊃⎕←⍵,⊃a/⍨</¨⊢a←⍸∘.≡⍨x⋄(+⌂big⍨⍺)∇1+⍵})0 ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qG@qp/@jtgkG/9UNDNU1DKorHnUuSnjUsaoCKPiodxcQ6egDCSsg1tCACGgbaj7qaAcizUddzUADwCq36gA5iUClK2z0D6141LUoESy841HHDL1HnQuB4hWPuls0tB/1NCVlpgO5QINAxhhqA/XWahr8/w8A "APL (Dyalog Extended) – Try It Online") APL is not known for big integer arithmetic, infinite output, or interpreter speed (and using Extended incurs even more overhead), yet it outputs successfully up to `n=9` barely under a minute. ### How it works The code is basically an infinitely running recursive operator. The left argument is the string representation of the power of 2, the right argument is the corresponding exponent (which was needed to meet the speed requirement), and the left operand is the current value of `n`. ``` { x←⍺⍺,/⍺ ⍝ Extract length-n segments of given number x≢`∪x: ⍝ If it has duplicates... a←⍸∘.≡⍨x ⍝ Construct the pairs of indices of equal slices ⊃a/⍨</¨⊢a ⍝ Keep the ones (L,R) where L<R and take the first one ⊃⎕←⍵,... ⍝ Concat with the exponent, print it, extract ⍵ back ⍺((⍺⍺+1)∇∇)... ⍝ Continue running with n+1 ⋄ ⍝ Otherwise... (+⌂big⍨⍺)∇1+⍵ ⍝ Recurse with next power of two, using same n implicitly } '01'(0{...})0 ⍝ Invoke the dop with starting values ``` [Answer] # Mathematica, 109 bytes ``` f@n_:={NestWhile[#+1&,0,Length[p=Position[#,#&@@Commonest@#,1,2]-1]&@Partition[IntegerDigits[2^#],n,1]<2&],p} ``` --- ``` n output 0 {0, {{0},{1}}} 1 {16, {{0},{4}}} 2 {24, {{0},{6}}} 3 {41, {{8},{9}}} 4 {73, {{10},{18}}} 5 {130, {{14},{17}}} 6 {371, {{8},{52}}} 7 {875, {{68},{101}}} 8 {2137, {{12},{240}}} 9 {2900, {{270},{355}}} 10 {7090, {{803},{1123}}} 11 {12840, {{1672},{3185}}} ``` [Answer] # Python2, ~~137~~ 119 bytes It's pretty straightforward: ``` i=m=0 while 1: n=`2**i` for k in range(len(n)-m+1): q=n.find(n[k:k+m],k+1) if-1<q:print i,k,q;m+=1;break else:i+=1 ``` and the output: ``` n output 0 0 0 1 1 16 0 4 2 24 0 6 3 41 8 9 4 73 10 18 5 130 14 17 6 371 8 52 7 875 68 101 8 2137 12 240 9 2900 270 355 10 7090 803 1123 ``` 18 bytes saved by btwlf [Answer] # Perl - 99 bytes ``` use bigint;%_=$_+=$_//1;$%+=($s=$_{$1}//=pos)<pos&&print"$- $s $-[0] "while/(?=(.{$%}))/g;$-++;do$0 ``` Trading bytes for efficiency. *n = 9* finishes in about 25s, around 15x slower than the version below. --- ### Perl - 120 bytes ``` use bigint;for$i(0..2e4){$_==($s=$_{$_[$_]}//=$_)or($%+=print"$i $s $_ "),last for 0..(@_=/(?=(.{$%}))/g);%_=$_+=$_//=1} ``` The regex `/(?=(.{$%}))/g` returns all substrings of the current value of length `$%`. The list is iterated, and if a value is seen twice, it is reported. --- **Output** ``` 0 0 1 16 1 2 24 2 3 41 8 9 73 10 18 130 14 17 371 8 52 875 68 101 2137 12 240 2900 270 355 7090 803 1123 12840 1672 3185 ``` Output for *n = 10* at about 9s, for *n = 11* at 30s. [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~168~~ ~~158~~ ~~139~~ 135 bytes slow ``` param($l)for(--$p;!"$j"){if(!$d){$m=@{};$i=-1 $n='1'*!$l+[bigint]::Pow(2,++$p)}$d=''+$n[++$i..($i+$l-1)] $j=$m.$d;$m.$d=$i}"$p [$j $i]" ``` [Try it online!](https://tio.run/##TU5Ra4MwGHz3V6Th2zRzhlroSyWjUPa4TbZHkWGX2EYSDRrpg8tvd07bsXv44L477s40F9F2Z6HUCCUbRlO0hQ5AkbJpgygCk6wwVJgMsgxWwMkAmu0Hl4BkUexBzfzYf1iBCrOjPMna5rtd2lyCzWMYgiEOOPP9EOpsopLSAGQIKopJ7kHFQFPgyXwZSIfBoAwqBDLHo/PWlG6/7wYPTYC614gh@PQWKlRhOsGn14sour4V0aHRuqg5WvyzqRVdr@zkuYdyTpgld41Y1FvBL7L049B3ttFvx0p82Xw/oOe/nltlgvxXn6YFf5ensw22ZNLwMu8JT2LTW9Pbf47NmszL3bXdeeMP "PowerShell – Try It Online") Less golfed: ``` param($l) for(--$p;!"$j"){ if(!$d){ $m=@{} $i=-1 $n='1'*!$l+[bigint]::Pow(2,++$p) # if($l -eq 0){'11'}else{'[bigint]'} } $d=''+$n[++$i..($i+$l-1)] $j=$m.$d $m.$d=$i } "$p [$j $i]" ``` output from my notebook: ``` Elapsed N output ------- ----- ------------------------------ 00:00:00.0659394 0 => 0 [0 1] 00:00:00.0227806 1 => 16 [1 2] 00:00:00.1038194 2 => 24 [2 3] 00:00:00.3169680 3 => 41 [8 9] 00:00:01.0266805 4 => 73 [10 18] 00:00:03.3426611 5 => 130 [14 17] 00:00:34.3156609 6 => 371 [8 52] 00:04:23.3928567 7 => 875 [68 101] ``` --- # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~187~~ 194 bytes Add some bytes to remove redundant iterations. Thanks @CJ Dennis ``` param($l)for($p=0;!($a=0..($l-1)-ge0|%{[bigint]::Pow(2,$p)-replace"^.{$_}",('-'*$_)}|sls('\d'*$l+'\b'*!$l)-a|% m*|group|? c* -ge 2|%{$i,$j=($_|% Gr*|% I*)[0,1] ,"$p [$i $j]"*($i-ne$j)})){++$p}$a ``` [Try it online!](https://tio.run/##TVDBaoNAEL37FRuZ1F2jYgKlkGBbCKX00Da0R2NlEzdGWXVZlRx0v91uYlI6h4GZ93jvzYjqxGR9ZJwPcEAB6gZBJS0wcHKoJAYR@KsJBhr4nqeX7py4KfP7aRfusjQrm2i53FQnvHBAEFcywememT9eB7EyHWy5lg0xUX3Na2xtEz3xmbXdWfZEG7i0n6LC7lNZtaJ/QnsbaXG00OqQOZAHGGLNeJW27m82CX1nHhmOCQKFkCHII9PGkLklg5woQrrZDIQCOihDp33QMgbSBWVb6MsgNsaRcSpqlujVO6N1K5m7roqClgka@ReSZHXLG8250285K1wgdZUY0ZvBucLN97qtm6r43OVs30TPHXr587lZrpD1YXkbmnxl6bHB90Rj5hjv0dRg1Taibf4xFj65JFdXd2UMvw "PowerShell – Try It Online") Less golfed and slightly faster code: ``` param($l) $regexp = '\d'*$l+'\b'*!$l # digits or boundary $range = 0..($l-1) -ge 0 $power = 0 do{ $n = [bigint]::Pow(2,$power) $s = $range|%{$n-replace"^.{$_}",('-'*$_)} $m = $s|Select-string $regexp -AllMatches|% Matches # $s contains strings in which a regexp captures all substrings of $l digits # $m contains the captured matches # example with $l=3 and $p=43: # # $s matches after $regexp # ============= ===================== # 2199023255552 -> 219 902 325 555 # -199023255552 -> 199 023 255 552 # --99023255552 -> 990 232 555 $a = $m|Group|? Count -ge 2|%{ $i,$j = $_|% Group|% Index|Select -First 2 if($i -ne $j){ "$power [$i $j]" } } ++$power } until($a) write-output $a ``` [Try it online!](https://tio.run/##TZJRb9owEMff/SluqWmSghFDmia1arcJbdUeuqL1kTJkiBuMHDuyHdEpyWdnlxgYfohyvt/d/f@XlGYvrNsKpQ70De6hPpTc8iKhKiWEWpGL9xKv49csvqFqGL@u45sPVAFcQSZz6R0YC2tT6Yzbv1jAdS6Qn4zH2IJ9TIFhPCG07OZ0CUIyUxPAQzXGizV20X55ezs3@2Q6CmAaAIdAaNkMaqqZFaXiGxH9Gdd01UajJGaoapW2AS863DUvQomNZ85bqXM4eWDflHrifrMVrhnA8S3U8a6uaB6tqcrmC8zQje91T3Fsj/SYHNFdR66wPrAD@Kkz8X6cCOyHtM7D9Fwi3xIqgWkBdJf@79Sd6LiRBQJ0t4zOyeAlPIfDQJGWoCSpEsrxq@yt9IKZypeVR/GHlhBc9@eTVqqrfhErEkKheOlEhldPgrvKCjYzRcF1BhferHCV8shc41/QdTiqIBfZy2Us5i@zynlTPK93aH35tYbv5zmnkXcQ/4rHc579lvnWJ59SzEVB3kOEyWDhgphO0l75aQft4R8 "PowerShell – Try It Online") The output on my notebook: ``` Elapsed N output ------- ----- -------------------- 00:00:00.1183433 0 => 0 [0 1] 00:00:00.0135382 1 => 16 [1 2] 00:00:00.0135382 1 => 16 [0 4] 00:00:00.0224871 2 => 24 [0 6] 00:00:00.0224871 2 => 24 [2 3] 00:00:00.0353316 3 => 41 [9 8] 00:00:00.0649162 4 => 73 [10 18] 00:00:00.1572769 5 => 130 [17 14] 00:00:00.7403980 6 => 371 [8 52] 00:00:02.6019309 7 => 875 [101 68] 00:00:15.8726659 8 => 2137 [240 12] 00:00:30.0988879 9 => 2900 [270 355] 00:03:20.7172180 10 => 7090 [803 1123] ``` [Answer] # JavaScript (ES6), 111 bytes ``` n=>(C=i=>(I=S.indexOf(S.slice(i,i+n)))==i?S[i+n]?C(i+1):-1:i,P=p=>(z=C(0,S=(2n**p+'')))<0?P(++p):p,[P(0n),I,z]) ``` It calculates the first 9 fairly quickly, but then reaches the maximum call stack size for `n=10`; ``` [0n, 0, 1] [16n, 0, 4] [24n, 0, 6] [41n, 8, 9] [73n, 10, 18] [130n, 14, 17] [371n, 8, 52] [875n, 68, 101] [2137n, 12, 240] [2900n, 270, 355] ``` Here's how it works: ``` n=>( // take n as input C=i=> // C finds recurring match in string S (I=S.indexOf(S.slice(i,i+n))) // calculate the first index of a substring ==i // the index of the substring being tested ? // if those are equal, no match S[i+n] // if we're not at end of string, ?C(i+1) // continue recursing :-1 // otherwise, return -1 (no match) :i, // we have a match, return i P=p=> // loops over powers of 2 and check matches (z=C(0,S=(2n**p+'')))<0 // check 2^p for match ?P(++p), // if no match, continue recursing :p // if we find a match, return the power [P(0n),I,z] // return power, first and last index ) ``` ]
[Question] [ ## Challenge In the shortest amount of code: 1. Compute the length of the permutation cycle of a perfect shuffle on a deck of cards of any size *n* (where *n* ≥ 2 and *n* is even). 2. Output a table of all cycle lengths for 2 ≤ *n* ≤ 1000 (*n* even). Note that there are two basic ways of defining a perfect shuffle. There is the ***out-shuffle***, which keeps the first card on top and the last card on bottom, and there is the ***in-shuffle***, which moves the first and last cards one position toward the center. You may choose whether you are doing an out-shuffle or an in-shuffle; the algorithm is almost identical between the two. * **out-shuffle** of 10-card deck: [1,2,3,4,5,6,7,8,9,10] ↦ [1,6,2,7,3,8,4,9,5,10]. * **in-shuffle** of 10-card deck: [1,2,3,4,5,6,7,8,9,10] ↦ [6,1,7,2,8,3,9,4,10,5]. ## Graphical example Here, we see that an *out-shuffle* on a 20-card deck has a cycle length of 18 steps. (This is for illustration only; your solution is not required to output cycles graphically.) The classic 52-card deck, on the other hand, has an out-shuffle cycle length of only 8 steps (not shown). [![Out-shuffle cycle for 20-card deck](https://i.stack.imgur.com/qd3ie.png)](https://i.stack.imgur.com/qd3ie.png) An *in-shuffle* on a 20-card deck has a cycle length of only 6 steps. [![In-shuffle cycle for 20-card deck](https://i.stack.imgur.com/ZgCOZ.png)](https://i.stack.imgur.com/ZgCOZ.png) ## Tabular example of output Your program should output something similar to this, although you may choose any tabular format that you like best. This is for an out-shuffle: ``` 2 1 4 2 6 4 8 3 10 6 12 10 14 12 16 4 18 8 20 18 22 6 24 11 26 20 28 18 30 28 32 5 34 10 36 12 38 36 40 12 ...many lines omitted... 1000 36 ``` ## Questions 1. Does there seem to be any connection between the number input *n* and its cycle count, when *n* is a power of 2? 2. How about when *n* is not a power of 2? 3. Curiously, a 1000-card deck has an out-shuffle cycle count of only 36, while a 500-card deck has an out-shuffle cycle count of 166. Why might this be? 4. What is the largest number you can find whose cycle count *c* is vastly smaller than *n*, meaning that ratio *n*/*c* is maximized? [Answer] # Haskell, ~~47~~ ~~46~~ 44 (in shuffle) ``` [[i|i<-[1..],mod(2^i)n<2]!!0|n<-[3,5..1001]] ``` the basic realization is that this is the order of 2 in the multiplicative group of modulus `n+1`. [Answer] # Pyth, 16 bytes ``` mfq1%^2T+3yd)500 ``` In-shuffle using [A002326](http://oeis.org/A002326). [Answer] # Pyth, 22 bytes ``` V500,JyhNl{.u.iFc2NJUJ ``` Try it online: [Demonstration](http://pyth.herokuapp.com/?code=V500%2CJyhNl%7B.u.iFc2NJUJ&debug=0). Replace 500 with a smaller number, if it is too slow. ### Explanation: ``` V500 for N in [0, 1, ..., 499]: yhN (N + 1) * 2 J assign to J .u JUJ apply the following expression J times to N, starting with N = [0, 1, ..., J - 1], and return all intermediate results: c2N split N into 2 halfs .iF and interleave them l{ remove duplicates and give length , make a pair and print ``` [Answer] ## Mathematica, 53 (in-shuffle) ``` Grid[{2#,MultiplicativeOrder[2,2#+1]}&/@Range[1,500]] ``` or, not antagonistically spaced ``` Grid[{2 #, MultiplicativeOrder[2, 2 # + 1]} & /@ Range[1, 501]] ``` Output: ``` 2 2 4 4 6 3 8 6 10 10 12 12 14 4 16 8 18 18 20 6 (* digits, digits, bo bidgits, banana fana, ... *) 498 166 500 166 (* skip a bit, brother ... *) 998 36 1000 60 ``` Every entry in both columns is horizontally centered in their columns, but I don't have the fractional spaces `&#8194;` ... `&#8202;` here to replicate that. Observations: * Out-shuffle is in-shuffle on a deck two cards smaller. (Note that the first and last cards are in fixed position throughout the out-shuffle demonstration.) Consequently, the two choices will lead to similar output lists -- the second column will be shifted by one row. Regarding the "powers of two" hint, the in-shuffle of power of two decks has the pattern `{2^n - 2, n}`, `{2^n, 2n}`. (Out-shuffle pairs `2^n` with `n`.) * Observe in the in-shuffle example that the distance of `2` from the closest end of the deck doubles at each step. `{2, 4, 8, 15 = -5, -10, -20}`. In fact, this is true for *every* card. We therefore only need to know which power of `2` is congruent to `1` mod `n+1` where `n` is the number of cards. (Note that in the example, the cards in the last column, column `-1`, are doubled to the penultimate column, `-2`, meaning that `0` is congruent to one more card than is in the deck, thus "mod `n+1`".) Therefore, the MultiplicativeOrder[] function is the way to go (in Mathematica). * By default, one would try TableForm[] instead of Grid[], but the output is similar. [Answer] # C,86 (or 84) Score excludes unnecessary whitespace, included for clarity. ``` i,j,n; main(){ for(;n<1002;printf("%d %d\n",n,j),n+=2) for(i=n,j=1;i=i*2%(n+1),i-n;)j++; } ``` This is an in-shuffle, which as pointed out by others, is just the out shuffle with the stationary cards at both ends removed. As pointed out by others, in the in-shuffle, the position of each card doubles each time, but this must be taken modulo `n+1`. I like to think of the extra card position being position zero to the left of the table (you can think of this as holding both the stationary cards from the out-shuffle too). Obviously the position of the card must always be positive, hence the zero position always remains empty for the in-shuffle case. The code initialises `i` to the value of `n`. Then it multiplies by 2, takes the result mod `(n+1)` and checks to see if `i` has returned to its initial value (`i-n` is zero.) It increments `j` for each iteration, except the last one (hence the need initialise `j` to 1.) In principle, `i` could be with any value in the range `1..n`, so long as the comparison at the end checked if it was intialised to the same number. The reason for picking `n` was to make sure the program works for the case `n==0`. the problem was that any number modulo `(0+1)` is zero, so the loop never terminated in this case if `i` was initialised to a constant such as 1. The question examples includes the equivalent case `n==2` for the out shuffle, so it was interpreted that this case is required. If it isn't, two bytes `n,` could be saved by initializing `i` to 1, the same value as `j`. ]
[Question] [ In the spirit of the holidays, and as someone already started the winter theme([Build a snowman!](https://codegolf.stackexchange.com/questions/15648/build-a-snowman)) I propose a new challenge. Print the number of days, hours, minutes, and seconds until Christmas(midnight(00:00:00) December 25th) on a stand alone window(not a console) in any unambiguous format you see fit, and continually update it as these values change. Input - nothing, must read system time. Shortest code wins :) The strings "Days", "Hours", "Minutes", "Seconds", and "Until Christmas" are free code. You can also flavour them up if you like. Flavouring them up is sheerly for the purpose of producing a nice output. You can not flavour strings for the purpose of making a magic number to save code. [Answer] # Ruby with [Shoes](http://shoesrb.com/), 96 - 33 = 63 ``` Shoes.app{p=para animate{p.text="0 days 0 hours 0 minutes #{1387951200-Time.new.to_f} seconds"}} ``` Well, you never said we *couldn't*. ;) ![screenshot](https://i.stack.imgur.com/d33Aj.png) Updates once every frame. The magic number `1387951200` is Christmas - Dec 25, 2013 00:00. Sample IRB session for where I got the numbers: ``` irb(main):211:0> "0 days 0 hours 0 minutes seconds".size => 33 irb(main):212:0> Time.new(2013,12,25,00,00,00).to_i => 1387951200 irb(main):213:0> ``` [Answer] # PowerShell: 279 *Character count does not take into account any freebies. @Cruncher - please adjust accordingly.* ## Golfed ``` ($t=($a='New-Object Windows.Forms')+".Label"|iex).Text=($i={((New-TimeSpan -en 12/25|Out-String)-split"`n")[2..6]});$t.Height=99;($x=iex $a".Form").Controls.Add($t);$x.Text='Time Until Christmas';($s=iex $a".Timer").add_tick({$t.Text=&$i;$x.Refresh()});$s.Start();$x.ShowDialog() ``` This ain't the prettiest thing, either as code or as a window, but it works. One nice bit is that this isn't just good for 2013 - it'll work in any year, from 00:00 on January 1 until 00:00 on December 25th. ***Warning: The window may become unresponsive - it will continue to update, but you might not be able to move or close it.*** ![enter image description here](https://i.stack.imgur.com/9VPG1.jpg) ## Un-golfed with comments ``` ( # $t will be the label that displays our countdown clock on the form. $t=( # $a is used as a shortcut to address the Forms class later. $a='New-Object Windows.Forms' # Tack ".Label" onto the end with iex to finish making $t. )+".Label"|iex # Set the text for our label. ).Text=( # $i will be a script block shortcut for later. $i={ ( ( # Get the current "Time until Christmas", and output it as a string. New-TimeSpan -en 12/25|Out-String # Break the string into newline-delimeted array. )-split"`n" # Only output elements 2..6 - Days, Hours, Minutes, Seconds, Milliseconds. )[2..6] } ); # Make sure the label is tall enough to show all the info. $t.Height=99; ( # Use iex and $a as shortcut to make $x a "New-Object Windows.Forms.Form". $x=iex $a".Form" # Add the label to the form. ).Controls.Add($t); # Put 'Time Until Christmas' in the title bar for flavor. $x.Text='Time Until Christmas'; ( # Use iex and $a as shortcut to make $s a "New-Object Windows.Forms.Timer". $s=iex $a".Timer" # Tell the timer what to do when it ticks. ).add_tick( { # Use the $i script block to update $t.Text. $t.Text=&$i; # Reload the form so the updated text displays. $x.Refresh() } ); # Start the timer. $s.Start(); # Show the form. $x.ShowDialog(); # Variable cleanup - omit from golfed code. rv t,a,x,i,s ``` [Answer] # Mathematica 167 - 44 = 123 The following continually updates a table showing the days, hours, minutes and seconds (in thousandths) until the beginning of Christmas day. I am unsure how to count discount for the free strings. ``` Dynamic[Grid[Join[{{"Countdown", "until Christmas"}}, {DateDifference[Date[], {2013, 12, 25, 0, 0, 0}, {"Day", "Hour", "Minute", "Second"}], Clock[{1, 1}, 1]}[[1]] /. d_String :> d <> "s"]] ] ``` ![countdown](https://i.stack.imgur.com/JkKfj.png) --- **A quick and dirty solution**: 104-19 = 85 chars ``` Dynamic@{DateDifference[Date[], {2013, 12, 25, 0, 0, 0}, {"Day", "Hour", "Minute", "Second"}], Clock[{1, 1}, 1]}[[1]] ``` > > {{17, "Day"}, {10, "Hour"}, {59, "Minute"}, {51.4011, "Second"}} > > > [Answer] # Python 136 I'm sure someone can do this better - I've never used Tkinter before. In particular I bet the `l.pack()` and `l["text"]` can are avoidable. ![tk](https://i.stack.imgur.com/Nq18F.png) ## Golfed ``` from Tkinter import* from datetime import datetime as d r=Tk() l=Label(r) l.pack() while 1: l["text"]=d(2013,12,25)-d.now() r.update() ``` [Answer] # R Here is a solution for R using GTK+ via the gWidgets package. This is pretty ugly code since I am not familiar with the gWidgets/GTK+ package at all. ## Code Here is the code: ``` library(gWidgets) options(guiToolkit="RGtk2") # FUNCTION compute the hours minutes and seconds from time in seconds fnHMS = function(timeInSec) { hours = timeInSec %/% 3600 minutes = (timeInSec %% 3600) %/% 60 seconds = (timeInSec %% 3600) %% 60 return(list(hours = hours, minutes = minutes, seconds = seconds)) } # test the function fnHMS(1478843) # container for the label and the button widget christmasCountdownContainer = gwindow('Christmas Countdown!!', visible = TRUE) christmasCountdownGroup = ggroup(horizontal = FALSE, container = christmasCountdownContainer) ccWidget1 = glabel(sprintf('%4.0f hours, %4.0f minutes, %4.0f seconds till Christmas!!', (liHMS <- fnHMS(as.double(difftime(as.POSIXct(strptime('25-12-2013 00:00:01', format = '%d-%m-%Y %H:%M:%S')), Sys.time(), units = 'secs'))))[[1]], liHMS[[2]], liHMS[[3]]), container = christmasCountdownGroup) ccWidget2 = gbutton("Update!", handler = function(h, ...) { # retrieve the old value of the ccWidget1 oldValue = svalue(ccWidget1) liHMS = fnHMS(as.double(difftime(as.POSIXct(strptime('25-12-2013 00:00:01', format = '%d-%m-%Y %H:%M:%S')), Sys.time(), units = 'secs'))) svalue(ccWidget1) = sprintf('%4.0f hours, %4.0f minutes, %4.0f seconds till Christmas!!', liHMS[[1]], liHMS[[2]], liHMS[[3]]) }, container = christmasCountdownGroup) ``` ## Output Here is what the output looks like: ![enter image description here](https://i.stack.imgur.com/MAUw4.png) [Answer] ## Dyalog APL, 61 ``` {⎕SM[1;]←1 1,⍨⊂⍕(1 4⍴2↓2013 12 24 23 59 59 1000-⎕TS)⍪'Days' 'Hours' 'Minutes' 'Seconds'⋄∇1}1 ``` [Answer] # C# 128 Golfed ``` using D=System.DateTime;using System.Windows.Forms;class C{static void Main(){MessageBox.Show(""+(new D(2013, 12, 25)-D.Now));}} ``` Ungolfed ``` using D=System.DateTime; using System.Windows.Forms; class C { static void Main() { MessageBox.Show(""+(new D(2013,12,25)-D.Now)); } } ``` [Answer] ## Python 2, 115 ``` from datetime import datetime as d n=d.now() print str(24-n.day),str(23-n.hour),str(59-n.minute),str(60-n.second) ``` This counts newlines as 2 characters. ]
[Question] [ ## Task > > Make a simple IRC bot which does simple task like greeting user. > > > ## Detail (You may see [this RFC document](https://www.rfc-editor.org/rfc/rfc2812).) Write a complete program that perform these: 1. The program inputs `nickname` and `realname` from the user. * All `nickname` and `realname` which form is `[A-Za-z0-9]+` should be allowed, but it isn't important whether other forms are allowed. For example, if the user wants `1234qwerty` as `nickname` and `5319009` as `realname`, the program should use those names, but it isn't important whether the program can use `^^☆Rick Astley☆^^` (which includes non-alphabet&decimals) as (`nickname` or `realname`) or not, even thought this name may be rejected by the server. 2. The program inputs `serverAddress` from the user. * The form of `serverAddress` is `serverIP:serverPort`, where `serverIP` is the IP address of the server and `serverPort` is the port num of the server. 3. The program connects to port `serverPort` at IRC server `serverIP`, and it should set it's nickname as `nickname` and realname as `realname` by sending `USER realname 0 * :realname` and `NICK nickname`. 4. The program inputs a single `channelName` which doesn't include `#`, and join to the channel `#channelName`. 5. Send a private message `Hello, world!` to the `#channelName` channel like this: `PRIVMSG #channelName :Hello, world!` 6. Then, the program does these: A. If someone joins, greeting him by saying `Hello, @!` to `#channelName`, where @ is the nickname of him/her. B. If the program is kicked, try re-joining. C. If a person is kicked or banned, say `POW HAHA`. D. If a person leaves (`PART` or `QUIT`), say `Goodbye, @!`, where @ is the nickname of him/her. E. If someone says some text including `Turing test` or `turing test`, say `I'm a human!`. F. If someone says some text including `6*9`, quit by sending `QUIT :42` to the server. G. If someone says some text including `all your base are belong to us`(case-insensitive), quit by sending `QUIT :What you say!` to the server. H. If someone says some text preceding with a space and above acts aren't performed by the text, say the sum of charcode of all (except the first space) chars in the text. ## If an error is occurred If an error (such as connection error or invalid `nickname`) is occurred, you can do what you want to do. For example, if the `nickname` is already in use, the program may stop, gets a new `nickname` from the user, or automatically change the `nickname` and retry. ## Restriction The program * Should not use any internal functions or libraries which is for IRC client/bot making. i.e. something like IRC client libraries * Should **prompt what it'll input, before it gets an input**. For example, before inputs `serverAddress`, it should prompt `Write the address of server:`, `serverIP:serverPort >` , `serverAddress >`, or some text that the user can recognize. * Should work on several IRC servers using UTF-8. (i.e. not for single server) * 's messages send to server shouldn't be `NOTICE`. (RFC 2812, 3.3.2 Notice : The difference between `NOTICE` and `PRIVMSG` is that automatic replies MUST NEVER be sent in response to a `NOTICE` message.) * Should send a message where the request came from (`#channelName` or `nickname`). * Should `PONG` when `PING`ed, of course. ## PS Well, I just made this, because there was no puzzle about IRC bot. ## Edit After reading @dmckee's comment, I changed the rule for choosing winner. 1. Default `bonus` = +0 2. If somehow the program can connect to a channel (even if it's not `#channelName`), `bonus` = 1 3. If the program can perform step 1~5, `bonus` \*= 2. 4. For each tasks A~H in step 6, if the program implements, `bonus` \*= `1.2`. 5. For each six restrictions, if the program follows that, `bonus` \*= `1.05`. and `score = int(codelength/bonus)`. Program with lowest score is winner. If two answers have same score, then the answer with highest votes wins. EDIT Edit : I think `1.2` and `1.05` in step 4 and 5 should be adjusted slightly bigger.. What do you think about this? The winner is decided, however, I think there was too few entries. Anyone still may submit the code.. :P [Answer] # Python - 125 points * 304 chars * follows steps 1-5 (works for me on irc.freenode.net:6667. if you try there, remember IDENT might take a while, so give it 20+ seconds to connect and speak) * follows 4 restrictions (assuming the NOTICE restriction which is a bit unclear. the UTF restriction counts because python won't choke if it doesn't need to parse any UTF). ## score math (python): ``` bonus = 1 # connects to channel bonus *= 2 # steps 1-5 for i in xrange(4): bonus *= 1.05 # 4 restrictions int(304.0/bonus) > 125 ``` ## code: ``` import socket i=raw_input u=i('user# ') n=i('nick# ') h,p=i('host:port# ').split(':',1) p=int(p) c='#'+i('chan# ') z=0 while 1: try: def s(m): z.send(m+'\r\n') z.recv(9) except: z=socket.socket();z.connect((h,p));s('USER '+n+' 0 * :'+n);s('NICK '+n);s('JOIN '+c);s('PRIVMSG '+c+' :Hello, world!') ``` [Answer] # Perl, 66 points * 666 characters * all substeps * half of the restrictions ## Score ``` use 5.010; $bonus = 1; # connects to channel $bonus *= 2; # steps 1 to 5 $bonus *= 1.2 for 1..8; # substeps A to H $bonus *= 1.05 for 1..3; # restrictions 3, 4, 6 say int(666 / $bonus); > 66 ``` ## Code (newlines for presentation only, not counted let alone acceptable) ``` use POE"Component::IRC";$_='sub _start{Zregister,all);Z"connect")}subX001{ Zjoin=>$c);ZY"Hello, world!")}*Xquit=*Xpart=*Xjoin=sub{$g=$_[STATE]=~/t/?G oodbye:Hello;$_=$_[ARG0];/\w+/;ZY"$g, $&!")};subXkick{$_=$_[ARG2];/\w+/;Z$ &eq$n?"join":Y"POW HAHA")}subXpublic{$_=$_[ARG2];if(/turing test/i){ZY"I\' m a human!")}elsif(/6\*9/){Zquit,42)}elsif(/all your base are belong to us /i){Zquit,"What you say!")}elsif(/^ /){$t=-32;$t+=ord for/./g;ZY$t)}}chop( ($n,$r,$s,$c)=<>);$c="#$c";$i=POE::Component::IRC->spawn(nick,$n,ircname,$ r,server,$s)';s/Z/\$i->yield(/g;s/Y/privmsg,\$c,/g;S/X/ irc_/g;eval;POE::S ession->create(package_states,[main,[grep*$_{CODE},%::]]);POE::Kernel->run ``` **Side Note** The "ALL YOUR BASE ARE BELONG TO US" substep is most probably not worth its character count, but if I dropped it I wouldn't have the nice character count. Bugger. [Answer] # Ruby, 28 points * 249 Chars * Same bot as my other solution, but slightly cheating maybe by applying compression. * <http://coolfire.insomnia247.nl/golfbot-inflate.rb> (As pasting this code probably won't work too well.) # Score ``` bonus = 0 # We've done nothing yet bonus += 1 # Connects to channel bonus *= 2 # Step 1 - 5 for n in 1..7 bonus *= 1.2 # A - G end for n in 1..4 bonus *= 1.05 # 4 constraints end puts (249/bonus).to_i > 28 ``` # Code ``` require 'zlib' b=<<'E' x�]�_o�0���)��q�-KFBcdf��߃�P�S�B�����(N�Л��s~�� ��(�_$U6��5G�)�r�BB������J�{��� nNhlO�f)QQdJ�g��'�yP�!!����K�ɫ��[Ё�Ə{0�F]ѽ�m�2���GŐP��p` ��I����E�+�* z� )jrmKR�ˮ�%� #��nQaJ�H��<�ZT���虦T3.�$D('�hw��a�/'��&�_ei�}o��1���M$����H��J�$��������V"���"��'��|A�`<��3L)Y��Z|� e�� ���m�é��ǚ�ڎu��J�����Vq~(ح� E eval Zlib::Inflate.new.inflate b ``` [Answer] # Ruby, 65 points * 574 Chars * Steps 1-5, 6(A-G) and restrictions on libs, UTF-8, no NOTICE & PONG * Takes commandline args in the form of server:6667 botnick botuser channel # Score ``` bonus = 0 # We've done nothing yet bonus += 1 # Connects to channel bonus *= 2 # Step 1 - 5 for n in 1..7 bonus *= 1.2 # A - G end for n in 1..4 bonus *= 1.05 # 4 constraints end puts (574/bonus).to_i > 65 ``` # Code ``` require'socket' a=ARGV c="##{a[3]}" h,p=a[0].split':' s=TCPSocket.open(h,p) m="PRIVMSG #{c} :" s.puts"USER #{a[2]} 0 * :#{a[2]}\nNICK #{a[1]}\nJOIN #{c}\n#{m}Hello, world!" while l=s.gets case l when/\:(.+?)!(.+)JOIN/ s.puts"#{m}Hello, #{$1}!" when/KICK (.+?) (.+?) \:(.+)/ if $2==a[1] s.puts"JOIN #{c}" else s.puts"#{m}POW HAHA" end when/\:(.+?)\!(.+)(PART|QUIT)/ s.puts"#{m}Goodbye, #{$1}!" when/turing test/i s.puts"#{m}I'm a human!" when/6\*9/ s.puts"QUIT :42" when/all your base are belong to us/i s.puts"QUIT :What you say!" when/PING \:(.+)/ puts"PONG #{$1}" end end ``` [Answer] # PHP - 121 points * 1396 characters * Follows all steps (including extra) and restrictions ## Score ``` <?php $bonus = 1; //connects to channel $bonus *= 2; //completes steps 1-5 for ($x=0;$x < 8;$x++) $bonus *= 1.2; //all 8 extra steps for ($y=0;$y < 6;$y++) $bonus *= 1.05; //all 6 restrictions echo (int)(1396 / $bonus); > 121 ``` ## Code ``` <?php function w($t){global$s;echo$t."\n";socket_write($s,$t."\r\n");}function m($c,$t){w("PRIVMSG $c :$t");}@$y=fgets;$z=STDIN;echo"nickname>";$n=trim($y($z));echo"realname>";$r=trim($y($z));echo"serverIP:Port>";$a=explode(":",trim($y($z)));$s=socket_create(2,1,6);socket_connect($s,$a[0],$a[1]);w("NICK $n");w("USER $n 0 * :$r");while(1){if((!($l=trim(socket_read($s,512,1))))||(!preg_match("/^(?:\:(\S+)[ ]+)?([^: ][^ ]*)(?:[ ]+([^:].*?))?(?:[ ]+:(.+))?$/",$l,$m)))continue;echo$l."\n";if(preg_match("/(.+)!(.+)@(.+)/",$m[1],$o))$m[1]=$o;if(!empty($m[3]))$p=explode(" ",$m[3]);else$p=array();if(isset($m[4])) $p[]=$m[4];$p=array($m[1],$m[2],$p);$b=$p[2][0];@$e=$p[0][1];@$f=$p[2][1];if($p[1]=="PING")w("PONG :".$b);elseif($p[1]=="376"){echo"#channel>";$c=trim($y($z));$c=(!empty($c))?$c:"#rintaun";w("JOIN $c");}elseif($p[1]=="JOIN")if($e!=$n)m($b,"Hello, $e!");else m($b,"Hello, world!");elseif($p[1]=="KICK")if($f!=$n)m($b,"POW HAHA");else w("JOIN ".$b);elseif(($p[1]=="PART")&&($e!=$n))m($b,"Goodbye, $e!");elseif(($p[1]=="QUIT")&&($e!=$n))m($c,"Goodbye, $e!");elseif($p[1]=="PRIVMSG")if(preg_match("/[Tt]uring test/",$f))m(($b==$n)?$e:$b,"I'm a human!");elseif(strstr($f,"6*9")){w("QUIT :42");break;}elseif(stristr($f,"all your base are belong to us")){w("QUIT :What you say!");break;}elseif($f[0]==" "){$q=str_split(substr($f,1));$u=0;foreach($q AS $d)$u+=ord($d);m(($b==$n)?$e:$b,$u);}} ``` ### Side Note My answer actually differs from the instructions very slightly; the instructions say to use the `realname` as the first parameter to the `USER` command when registering, but I used the nickname instead. This is because the `realname` is allowed to have spaces, while this parameter is not. It's something of a moot point, though, since switching in the variable for `realname` would be the exact same character count. ]
[Question] [ In R print(x, digits=n) does something a little complicated. It always shows all the digits to the left of the decimal point and then, if there are any digits to the right it rounds the whole number so that at most n digits are shown. However, leading 0s are not counted. Here are examples to show how the function works. ``` print(2,digits=2) 2 print(23,digits=2) 23 print(23.12,digits=2) 23 print(2.12,digits=2) 2.1 print(0.126,digits=2) 0.13 print(23236.12,digits=6) 23236.1 print(123,digits=2) 123 print(0.00, digits=2) 0 print(23236.12,digits=1) 23236 print(1.995,digits=3) 2 print(0.0336, digits=3) 0.0336 ``` Given decimal number \$0 <= x <= 2^{40}\$ and \$n \leq 22\$ as inputs, your code should mimic R's print(x, digits=n) function. # Rounding This is different from my comment below, apologies. I didn't understand the problems with rounding before. It turns out rounding has no easily understandable rule in R (or Python for that matter). For example, ``` print(0.05, digits=1) 0.05 print(0.15, digits=1) 0.1 print(0.25, digits=1) 0.2 print(0.35, digits=1) 0.3 print(0.45, digits=1) 0.5 print(0.55, digits=1) 0.6 print(0.65, digits=1) 0.7 print(0.75, digits=1) 0.8 print(0.85, digits=1) 0.8 print(0.95, digits=1) 0.9 ``` As a result, you can round either up or down as you choose in your answer. If you can follow what R does, all the better, but it is not a strict requirement. [Answer] # [Desmos](https://desmos.com/calculator), 44 bytes ``` f(x,n)=round(x,max(0,n-floor(log(x+0^x))-1)) ``` [Try It On Desmos!](https://www.desmos.com/calculator/7zaf5yw46f) [Try It On Desmos! - Prettified](https://www.desmos.com/calculator/zgevubb4ja) I think this should work??? Tell me if there's anything wrong. [Answer] # [R](https://www.r-project.org), 5 bytes ``` print ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGiNNulpSVpuhZLC4oy80og7Jtf0zSMdFIy0zNLim2NNLmMuIB8Y2QBY7CInqERhiCamJ4hUNAAKGiGJArkQwwwMjZDUm8GMgMsBJQ0RLHQEGy4gZ6BgY4CkjlYDDHUVICYAjJDz9LSFCZhDPEH0AxjYzO4KcYg14BEFBQUIJ5fsABCAwA) Somebody had to do it. [Answer] # [Python](https://www.python.org), 52 bytes ``` lambda n,d:(f'{n:.{d}g}',s:=str(round(n)))[d<len(s)] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3TXISc5NSEhXydFKsNNLUq_Os9KpTatNr1XWKrWyLS4o0ivJL81I08jQ1NaNTbHJS8zSKNWMhem8xqhYUZeaVaKRpGOkoGGlqcsG5xuh8PUN0JRgiBkARM3R9RsZmYIVmSKKG6MYb6BkY4NJoiKxRz9LSVEfBGFWrsbEZqhjQfBNToFJLVDMhwiZYRU0NsIoagkUhobVgAYQGAA) [Answer] # [Python](https://www.python.org), ~~77 84 81 67~~ 66 bytes -3 thanks to solid.py ``` lambda n,d:len(str(n).split('.')[0])<d and f"{n:.{d}g}"or round(n) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3nXISc5NSEhXydFKsclLzNIpLijTyNPWKC3IySzTU9dQ1ow1iNW1SFBLzUhTSlKrzrPSqU2rTa5XyixSK8kvzUoCKoSaVFxRl5pVopGkYGesZGukoGGlqciGEjIzNwKKGSKIGegYGqOoM9SwtTXUUjFEUGRuboQoZGhmbmAJVWoI1Q6xfsABCAwA) [Answer] # [R](https://www.r-project.org), 34 bytes ``` \(n,d)round(n,max(d-log10(n)-1,0)) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGagqLMvJL43MzczGTbpaUlaboWN5ViNPJ0UjSL8kvzUoCs3MQKjRTdnPx0QwONPE1dQx0DTU2oSn-wbg1DI2M9E1MzHSNNLiTjMIThAqbY1ZlCjV2wAEIDAA) The answer is 29 bytes longer than the question... [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 116 bytes ``` ^\d+ $* (1)+,([.0]*(?<-1>\.?\d)+((?<=\..*)|\d*))\.?([5-9])?.* $2$#4$*# ^[.9]*# 0$& T`#9d`_d`.[.9]*# \.?(?<=\..*)0+$ ``` [Try it online!](https://tio.run/##PYw5DsIwEEX7OQVSDPKSjLwQS5aAlFyALk4wkiloKBAldzeDAxQzT//N8rg@b/dLWfNjKnPMCpgEboRq@Yh6knzYdeYQcYhZKE5pHxGleMUshSDNx74LkxhQArOs2TLZwDximIiabeCUmpDTOSf8ys/N74tWDEqxrQUqVxuaGhZoggdP2jq/KFP3NGoN5u9X4FqDIfREGjnn3w "Retina 0.8.2 – Try It Online") Link includes test cases. Takes input in the order `n,x`. Explanation: ``` ^\d+ $* ``` Convert `n` to unary. ``` (1)+,([.0]*(?<-1>\.?\d)+((?<=\..*)|\d*))\.?([5-9])?.* $2$#4$*# ``` Capture `n` in `$#1`, so that a balancing group can be used to count significant digits, but if we don't pass a decimal point, capture all the digits before the decimal point. Also note whether the next digit (if any) is at least `5`. Keep only the counted or integer digits and the next digit flag. ``` ^[.9]*# 0$& ``` If the value is all `9`s and the next digit was at least `5` then prefix a `0` for the overflow. ``` T`#9d`_d`.[.9]*# ``` If the next digit was at least `5` then increment the captured digits. ``` \.?(?<=\..*)0+$ ``` Remove any trailing zeros in the decimal part. ]
[Question] [ The [Fabius function](https://en.wikipedia.org/wiki/Fabius_function) is an example of a function that is infinitely differentiable everywhere, yet nowhere analytic. One way to define the function is in terms of an infinite number of random variables. Specifically, given a sequence of independent random variables \$\{U\_n\}\$, where each \$U\_n\$ is uniform on the interval \$[0,2^{-n}]\$, the Fabius function \$f\$ is defined on \$[0,1]\$ as the cumulative distribution function of their sum \$\displaystyle\sum\_{i=1}^\infty U\_i\$ : [![Plot of successive sums of the series of cdfs](https://i.stack.imgur.com/74eUe.png)](https://i.stack.imgur.com/74eUe.png) # Task Given a number \$x\in[0,1]\$, compute \$f(x)\$. Your answer should be accurate to within \$2^{-16}\approx0.00001526\$ on the given test cases. ## Test cases ``` x f(x) 0 0 0.163 0.012220888930835 0.3 0.129428260311965 0.5 0.5 0.618 0.733405658665583 0.75 0.930555555555556 1 1 ``` [Answer] # [Python](https://www.python.org), 94 bytes (@att) ``` lambda x:B.c[int(x*4**9)]/8**57 from numpy import* B,*A=a=1,1. exec('A*=2;B*=poly1d(A)*a;'*18) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=RY5NboMwFIT3PoV3sZ8I9bNjxyRlEQ7QC_RHchJQifixCKngBD1EN5Gq9k65TSEg9a3m6RvNzNev79v3urp-Z_HLz6XNlvb2Vrhyf3S02yTh4TmvWtbBCiDirw8WQK9J1tQlrS6l72le-rppgSQB7GIXY4AhSbv0wBY7iOU2gdjXRY9HtuPgtgtAy-eWp6xuaEHzitY-rZjgG0Lz4ERjWjrP0g9XBEV49kXeMs4J9c04xO3P7LTMWM75owRYoglOwf2dUq-3T0GnE0SEaNSoQoFSSmGtjZSwSg9ETZ4QZbSSVhqhECMzEj2TURu0d71WaiW00dYYra0ayFpPriFQ_58hOLfjtOcP) ## [Python](https://www.python.org), 99 bytes ``` lambda x:B.c[int(x*4**9)]/max(B.c) from numpy import* B,*A=a=1,1. for i in a*9:A*=2;B*=poly1d(A)*a ``` [Attempt This Online!](https://ato.pxeger.com/run?1=RU5LboQwFNvnFFkmEaT5kEygZQEH6AXaLjIf1CA-EcNUcIIeopuRqvZOc5uSAale-T1btr9-_Ty-9931u8pffy5jFZvbobHt_mjhlJX08OK6EU0kISTFbw-tndDyxBBUQ9_C7tL6GbrW98NIQBmRIrc5jzgFVT9AB10HLUmzguTisSS575uZH1GBid2qnoOvCb7enzrEcAagi2qYw9Z6dPqwTdTQs2_ciDAG0A9hjd2fUR1XyGH8JAiJuY7q6H6uqdfbJ4MrGGCUaxkYZVwIwYwxqWRGqkWRq4dykSbCCM0k56kOitqUwDU3d76TMmFKK6O1UkYuyk6triVQ_UMDvrXzdc8f) ### -13 thanks @att ### [Python](https://www.python.org), 133 bytes ``` lambda x:interp(x,r_[:2:len(B)+0j],B/max(B)) from numpy import* A=a=poly1d([1,0]) B=prod([((A:=A*A)/(a-1))[0]*(a+1)for i in[0]*17]).c ``` [Attempt This Online!](https://ato.pxeger.com/run?1=RY5NbsIwEIX3OYWXdnCCf7AxUbMIB-gFaFSZQlRHTmyZUMEBqh6iG6SqvRO3qUOQmNV7843mve8_fx7eXX_5acqX3-PQZOr6aXW33WlwKkw_7IOHJxxeNwUr7L6HazQjbY3X806fokFJE1wH-mPnz8B03oUhTapSl97ZM93BDcWkRsm69MFFB2FVlFVaoTnUGUVoQ-oU6hlFjQvAANOPC7qsUf52L_M8EhsJcD7GE1QkwOAWlKDTHu4_tMU2P3hrBhjLAB9iZ6i3B9hmDTQIPbE0zajELb7Z6evl-kXANCQhOZV8VDmhjDGilFpxoriIhE83OWWrBVNMEk7pSo5E3MmoJVU3veR8QYQUSkohFI9kKaar-FA8Rib0nk6nPv8) Brute-force computation of the convolution of the given uniform densities. Uses polynomials to get convolution through the `*` symbol. Two little tricks: 1) x^n / (x-1) generates (discarding the residual 1) the "flat" polynomials we need 2) convolution with a constant is essentially prefix sum up to the middle, saving us a `cumsum`. [Answer] # [PARI/GP](https://pari.math.u-bordeaux.fr), 56 bytes -1 byte thanks to [@att](https://codegolf.stackexchange.com/users/81203/att), ``` x->sum(i=0,x<<=20,(-1)^sumdigits(x\1-i,2)*i^20)/20!/4^95 ``` [Attempt This Online!](https://ato.pxeger.com/run?1=LYxdCsIwEISvsvYpKUm7ibZWaHsG39VKQVoWqoT-QDyLLwURz-RtTKwv880sO_N4m7qnc2vmZwPFaxobmX0yK8thujIqUNg8LzQKJhWv3O1CLY0Ds0clSWgeUqWRxxpX8abaJf_-vjamuzMLsgTT0210NvAhgIZZDiGoCLmAA0YoACOVrj1-knhJVeaxdcF9nviyO88Lvw) Returns a fraction. Based on [this answer on Mathematics SE](https://math.stackexchange.com/a/3522865/99103) [found by mousetail](https://codegolf.stackexchange.com/questions/252009/compute-the-fabius-function#comment561127_252009): $$\begin{align} F(x)&=\lim\_{n\to\infty} F\_n(x)\\ F\_n(x)&=\frac{2^{n(n+1)/2}}{n!}\,\sum\_{y\in D\_{n,x}}(-1)^{s(y)}\big(x-y\big)^n \end{align}$$ where \$D\_{n,x}\$ is the set of all dyadic numbers in \$[0,x]\$ of the form \$m2^{-n}\$ for integers \$m\$, and \$s(y)\$ is the sum of the binary digits of \$y\$. It seems that \$n=20\$ is sufficient for this challenge. [Answer] # [Pyth](https://github.com/isaacg1/pyth), 41 39 bytes ``` J*hK20]ZV*^2KQ=JsM._XZJ^_1sjN2;ceJ^2sUK ``` [Try it online!](https://tio.run/##K6gsyfj/30srw9vQNDYqTCvOyDvQ1qvYVy8@IsorLt6wOMvPyDo51SvOqDjU@/9/Az1DM2MA) Note that in the try it online link, I have decreased the accuracy from 20 to 15 so that it finishes running in time. You'll have to take my word that I've tried it on my machine and the above code meets the given accuracy requirement. This program essentially does N summations along the [Thue–Morse sequence](https://en.wikipedia.org/wiki/Thue%E2%80%93Morse_sequence). This can be thought of as a sort of "discrete integral", in which case the fact that \$f'(x)=2f(2x)\$ tells us that each time we do this, we get our function back but with half the interval, half the magnitude, but twice the accuracy. We can easily deal with the magnitude at the end, and by starting with \$2^N\$ terms of the sequence, we end with the range from 0 to 1 with whatever accuracy we desire, No floating point or overflow errors occur along the way since all of this is done on python ints. \$N=20\$ is about right to hit the accuracy required. [Answer] # [APL (Dyalog Classic)](https://www.dyalog.com/), 27 bytes ``` {⊃(⌊⍵×8*7)↓(+\⊢,-)⍣22÷8*70} ``` [Try it online!](https://tio.run/##RY49bsJAEIWv4s4/xNbOLDseNzkJjeWIyJIlR6KKwBWRCydGSAjRJ006KpQebjIXMYsXkVe9N9@b0eRvVfzynlf1a1xU@WJRFsMwl3a7lG4dyFcn/ely4CgNpd0Fk5l0309xKP0P4uXPjlUzLEuvtgu2KJ8fstlbj9H5CPTswqqOnZl75aPh@8351wuU56RC6xMgffOJAkRUzJxpxdqMTLteAphNkZGUBsjIMXNnLhHwmFKtp8qQYSJjWI8sNa5pD5t/kWVw/wTC4Qo "APL (Dyalog Classic) – Try It Online") As noted by [CursorCoercer](https://codegolf.stackexchange.com/a/252179), the identity \$f'(x)=2f(2x)\$ holds when \$0<x<\frac12\$, and can be used to characterize a unique extension of \$f\$ to \$[0,4]\$. Specifically, noting the symmetry of \$f\$ about \$x=0.5\$, we have \$f(x)=f(2-x)\$ for \$x\in[1,2]\$, then \$f(x)=-f(x-2)\$ when \$x\in[2,4]\$. [![Plot of the extension of f from 0 to 4](https://i.stack.imgur.com/xmtGk.png)](https://i.stack.imgur.com/xmtGk.png) From here, we can iterate \$\displaystyle f(x)=\int\_0^{2x}f(t)\,dt\$ until we attain the desired precision: ``` ÷8*70 start: 2^-210 one sample of an approximate-f on [0,2], times a multiplicative factor. ( )⍣22 repeat (22x) until precision goal reached: ⊢ from n samples on [0,2], ,- append its negation => 2n samples on [0,4] +\ cumulative sum take the discrete integral. the introduced multiplicative term of 1/∆x is cancelled by the start value. => 2n samples on [0,2] of a better approximation ⊃(⌊⍵×8*7)↓ index into the samples ``` ]
[Question] [ ## Challenge Create the image of a [progress pride flag](https://en.wikipedia.org/wiki/Rainbow_flag_(LGBT)#Variations). ## Output [![Progress pride flag](https://i.stack.imgur.com/kuKsw.png)](https://i.stack.imgur.com/kuKsw.png) ## Dimensions [![Dimensions](https://i.stack.imgur.com/GNIbl.png)](https://i.stack.imgur.com/GNIbl.png) ## Rules * Your program must create the image and not just load it from a website * The colours can be just your language's default if it is very difficult / impossible to load RGB values, else they should be: `red: (255,0,0)`, `orange: (255,140,0)`, `yellow: (255,240,0)`, `green: (0,138,40)`, `(dark) blue: (0,80,255)`, `purple: (120,0,140)`, `black: (0,0,0)`, `brown: (100,50,20)`, `(light) blue: (110,220,240)`, `pink: (255,180,200)`, `white: (255,255,255)` * The flag can be a scaled up version of the one shown, but the dimensions given are the smallest size allowed. An error of 1 pixel is allowed. * Please include an image of the output of your program. This post was (somewhat) inspired by [this one](https://codegolf.stackexchange.com/questions/230438/create-a-pride-flag). [Answer] # [C (GCC)](https://gcc.gnu.org), ~~192~~ 176 bytes ``` char*r="binary stuff (see ATO)";i,j;main(x){write(1,"P6 1059 672 255 ",16);for(;i<672;++i)for(j=0;j<1059;++j)write(1,r+((x=abs(i-336)+j)<504?6+x/84:i/112)*3,3);} ``` *-16 bytes thanks to [@ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)* [Attempt this online!](https://ato.pxeger.com/run?1=NVDLTsMwALv3X9DWdBrhwCEoFYQsfZBW0BPK2i59QaKlpUt_hcsu45_4Cn6BFTFLvtiWJfvzlL_KPD8eT0O_u4LfPxmoqrzWNuKbBUJ40ZwJEUJ1LVEa3awQmRYX9KwavOiuZVWM5kgIWiOavs-eu4E-SO2UXmHFy1NHsW9IhwDB_hgkrQya3BJM3ICjeoN9QJP-besRdS6Asxdasxe8-9NEsxxDoKDDEuSGidlToHThPeriPlWMHyy1UpXYrbJ3pgRfTmzK9JyJcDoGGALqyY8Qx2vB4YElRNOGGYfZ9noXq9uvrTDlevU__3LDLw) (you must set encoding to Base64) Outputs a [PPM](http://netpbm.sourceforge.net/doc/ppm.html) image. [![](https://i.stack.imgur.com/Mw1bo.png)](https://i.stack.imgur.com/Mw1bo.png) [Answer] # Java 17, 475 bytes ``` import java.awt.*;v->new Frame(){public void paint(Graphics g){int i=0;for(;i<6;g.fillRect(168,i++*112+25,891,112))g.setColor(new Color(i<3?255:i/5*120,i%5<1?0:i<3?140+i/2*100:i<4?138:80,i<3?0:i<4?40:i<5?255:140));for(i=0;i<4;g.fillPolygon(new int[]{0,0,(i+2)*84,i/3*84,i<1?0:~-i*84,(i+3)*84},new int[]{109-i*84,193-i*84,361,(i<3?6+i:8)*84+25,i++<1?613:697,361},6))g.setColor(new Color(i<1?255:i<2?110:i<3?100:0,i<1?180:i<2?220:i<3?50:0,i<1?200:i<2?240:i<3?20:0));}{show();}} ``` [![enter image description here](https://i.stack.imgur.com/EgP6c.png)](https://i.stack.imgur.com/EgP6c.png) **Explanation:** *TODO: Will try to golf it some more first.* [Answer] # BBC Basic ~~210~~ 190 bytes Golfing mainly comprises removal of unnecessary whitespace and use of abbreviations for keywords. At one point `VDU25,0` is condensed to a single 16-bit value `V.25;` (the `;` delimiter denotes that the preceding value is a 16-bit value instead of 8-bit.). At another, `VDU25,101` is replaced with the higher level command `PLOT101` ``` MODE27h=672F.i=1TO33j=i MOD3IFj=1V.19,7,16 V.(ASCM."8 < 0S o(SP S< S 4*$6LPSDHSSS",i,1)-32)*5MOD257 IFj N. IFi<19PLOT101,i MOD2*1782+336;h*i/9ELSEV.25;h;-h;25,81,-h;-h;25,97,-168;h*2; N. ``` Download interpreter at <https://www.bbcbasic.co.uk/bbcwin/download.html> This interpreter has certain features not included in the original BBC basic. It allows for larger screen modes and more colours. `MODE 27` is 1280x960 pixels but the coordinate system is double that at 2560x1920. The original BBC basic had (depending in screen mode) a maximum of 16 logical colours displayed at one time (to save memory) but there was facility to change these colours to any 18-bit physical colour using `VDU19`. This would instantaneously change the colour of all pixels of that colour on the screen (which was useful for fast animation.) This interpreter works differently. On execution of a `VDU19` colours of existing pixels do not change, only newly drawn ones, and full 24-bit colour is supported. Selecting the colour is a major part of this code, with 33 different RGB values. Most of them are divisible by 5, so I compressed them into printable ASCII by dividing by 5 and adding 32. The one exception is `138` for the green, which is taken as a larger number mod `257` Stripes are drawn using absolute coordinates with `x=1059*2=2118` at the right and `x=168*2=336` at the left. This leaves the graphics cursor in the correct position at the top right of the black chevron. `19VDU25,101,i MOD2*1782+336` causes the graphics cursor to zigzag from the default location in the bottom left corner of the screen to the top left corner of the red bar. The code 101 is for a rectangle defined by its opposite corners. Chevrons are drawn using relative coordinates as a house-shape rotated 90 degrees, comprising a triangle and a rectangle. Subsequent chevrons overdraw the house shape to produce the correct chevron shape. The graphics cursor is already at top right from the previous operation. It moves diagonally to the centre right point `VDU25,0,h;-h;`, then a triangle is drawn linking the last two positions of the graphics cursor to the bottom right `VDU25,81,-h;-h;`. The shape is completed by drawing a rectangle to the top left `VDU25,97,-168;h*2;` which leaves the cursor in the correct position for the next chevron. After the brown chevron, certain parts of the final three chevrons are off the left side of the screen and are therefore not plotted. **First working version** ``` MODE27 h=672 FORi=1TO33 j=i MOD3 IFj=1VDU19,7,16 VDU(ASCMID$("8 < 0S o(SP S< S 4*$6LPSDHSSS",i,1)-32)*5MOD257 IFj NEXT IFi<19VDU25,101,i MOD2*1782+336;i/9*h;ELSEVDU25,0,h;-h;25,81,-h;-h;25,97,-168;h*2; NEXT ``` **Commented Code** ``` MODE27 :REM select screen mode with 2560x920 logical coordinates, 1280x960 pixels h=672 :REM half the logical height of the flag FORi=1TO33 :REM iterate R,G,B through 11 colours j=i MOD3 :REM if i MOD 3 = 1 tell VDU controller to expect a redefiniton of default logical colour 7 IFj=1VDU19,7,16 :REM (below) extract R,G or B value from 1-indexed string, send to VDU controller VDU(ASCMID$("8 < 0S o(SP S< S 4*$6LPSDHSSS",i,1)-32)*5MOD257 IFj NEXT :REM if i MOD 3 is not 0 draw nothing yet IFi<19VDU25,101,i MOD2*1782+336;i/9*h;ELSEVDU25,0,h;-h;25,81,-h;-h;25,97,-168;h*2; NEXT :REM (above) if i MOD 3 = 0 draw a bar if i<19, otherwise draw a chevron. ``` [![enter image description here](https://i.stack.imgur.com/j2keW.png)](https://i.stack.imgur.com/j2keW.png) [Answer] ## PostScript, ~~156~~ ... 115 bytes ``` 00000000: 3020 3087 6101 3232 3492 7f28 ffff ffff 0 0.a.224..(.... 00000010: b4c8 6edc f064 3214 0000 00ff 0000 ff8b ..n..d2......... 00000020: 00ff f000 0089 4800 50ff 7800 8b29 7b32 ......H.P.x..){2 00000030: 3535 9236 7d92 4936 7b92 9d30 2030 8761 55.6}.I6{..0 0.a 00000040: 0133 3892 8030 8870 3392 3692 ad7d 9283 .38..0.p3.6..}.. 00000050: 3136 3888 9092 ad31 3335 9288 357b 929d 168....135..5{.. 00000060: 3020 3087 e703 9238 9280 8814 3230 92ad 0 0....8....20.. 00000070: 7d92 83 }.. ``` Before tokenization: ``` 0 0 353 224 rectclip <FFFFFFFFB4C86EDCF0643214000000FF0000FF8B00FFF0000089480050FF78008B>{255 div}forall 6{setrgbcolor 0 0 353 38 rectfill 0 112 3 div translate}repeat 168 -112 translate 135 rotate 5{setrgbcolor 0 0 999 dup rectfill 20 20 translate}repeat ``` [![output](https://i.stack.imgur.com/YZGc3.png)](https://i.stack.imgur.com/YZGc3.png) ]
[Question] [ **Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/235843/edit). Closed 2 years ago. This post was edited and submitted for review 2 years ago and failed to reopen the post: > > Original close reason(s) were not resolved > > > [Improve this question](/posts/235843/edit) Inspired by `How to write down numbers having an infinity of decimals?` [Link 🇫🇷](https://www.youtube.com/watch?v=CwqoAVMzgp4) ## Background From [Wikipedia](https://en.wikipedia.org/wiki/Khinchin%27s_constant): for almost all real numbers \$x\$, coefficients \$a\_i\$ of the continued fraction expansion of \$x\$ have a finite geometric mean that is independent of the value of \$x\$ and is known as `Khinchin's Constant`. [Khinchin's Constant](https://mathworld.wolfram.com/KhinchinsConstant.html) can be calculated using the following method: 1. Using the \$n\$ first terms of the `simple continued fraction` of a real number ([For example Pi](https://oeis.org/A001203)). 2. Compute their product 3. Apply the \$n^{\text{th}}\$ root on the absolute value of product calculated above ## What is a simple continued fraction It can be expressed as: $$x=[a\_0; a\_1, a\_2, \dots, a\_n]$$ Or $$ x=a\_0+ \cfrac{1}{a\_1+ \cfrac{1}{a\_2+ \cfrac{1}{\ddots{+ \cfrac{1}{a\_n}}}}} $$ And can be calculated using the following: 1. Separate \$x\$ into its integer part \$a\_n\$ and decimal part \$d\$ * \$a\_n = \lfloor x \rfloor\$ * \$d = x - \lfloor x \rfloor\$ 2. Repeat using the inverse of \$d\$ in place of \$x\$ while \$d\$ is not 0 It is a `simple` continued fraction because the numerator is always 1. For negative numbers, the same rule applies, the first term of the sequence will be negative. For example for \$Ï€\$: $$ Ï€ = [a\_0; a\_1, a\_2, a\_3, \dots] = [3; 7, 15, 1, 292, \dots] $$ $$ Ï€=3+\cfrac{1}{7+ \cfrac{1}{15+ \cfrac{1}{1+ \cfrac{1}{292+ \cdots}}}} $$ And \$-Ï€ = [-4; 1, 6, 15, 1, 292, \dots]\$ ## Challenge Using the method used to approximate `Khinchin's Constant` described above: Given a number of terms \$n\$ and a real number \$x\$, compute the geometric mean of the coefficients of the continued fraction expansion of \$x\$. Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. ## Test cases: | Terms to use | Real number | Expected Result | Note | | --- | --- | --- | --- | | 1 | [Ï€](https://en.wikipedia.org/wiki/Pi "Pi") | 3 | | | 2 | [Ï€](https://en.wikipedia.org/wiki/Pi "Pi") | 4.5825... | | | 3 | [Ï€](https://en.wikipedia.org/wiki/Pi "Pi") | 6.8040... | | | 7 | [Ï€](https://en.wikipedia.org/wiki/Pi "Pi") | 5.1179... | | | 7 | -[Ï€](https://en.wikipedia.org/wiki/Pi "Pi") | 5.2165... | | | 15 | [ℯ](https://en.wikipedia.org/wiki/E_(mathematical_constant) "Euler's number") | 1.8156... | | | 15 | -[ℯ](https://en.wikipedia.org/wiki/E_(mathematical_constant) "Euler's number") | 1.9164... | | | 20 | -[φ](https://en.wikipedia.org/wiki/Golden_ratio "Golden Ratio") | 1.0717... | | | 20 | [φ](https://en.wikipedia.org/wiki/Golden_ratio "Golden Ratio") | 1 | | | 100 | [φ](https://en.wikipedia.org/wiki/Golden_ratio "Golden Ratio") | 1 | Optional, might not work because of consecutive floating point errors | # Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the answer with the least amount of bytes wins. [Answer] # [Husk](https://github.com/barbuz/Husk), 14 bytes ``` ^\¹Π↑¡§,o\%1⌊² ``` [Try it online!](https://tio.run/##vY27CUJREESrMRPcz9z99PIwFgwMxBYMxMQONDI3M70FWISNrFuFw4GBw8DsTsd91XaZ78/9e77Nx3yuD8uKv9fLfFUVGwepZoQjIxEIIYywUKgN02B2F1JK9gwabhImrAPoFqchRmjJkSRAOvW8QQtNZnVsmP6Q6pcf "Husk – Try It Online") for the last test case (or [try it here](https://tio.run/##vcutDQJREEbRanAkzP/M18sGvQkCQWgBQTB0AAqPw74CKGIbGbYKrjnqzufToXs/jc/3sVzu4zle2@O04eV2He/uVjZ2SLh6IaGiZSFhqqWScJIqYyQHFNB0Ji8hpMFsHZWyOIxCKoQKWClSK3E1YU6KxI7pD3X@AA) for n=7, number=pi). ``` ¡ # Apply function repeatedly to first results, # collecting second results into infinite list: §, ² # combine pair of results of functions applied to arg 2: ⌊ # floor o\%1 # reciprocal of fractional part ↑ # Now take arg1 elements from list, Π # calculate the product, ^ # and raise to the power of \¹ # reciprocal of arg1 ``` [Answer] # [Factor](https://factorcode.org/) + `math.continued-fractions math.unicode`, 66 bytes ``` [ 1vector over [ dup next-approx ] times 1 head* Π abs nth-root ] ``` [Try it online!](https://tio.run/##ZZBBS8NAEIXv@RXv4ElIMYoICl6ll17EU@lh3UzMYjK7zs6WSsh/6S/qX4pbUqnFuX3z3jx40xirXqa31@Xq5REmRm8jPkmYOmzpqEX0Rlt0TklMN9PCeo5qWM@ojhPVZSM50GUVkb4SsaWTpUl8EoKQ6ncQxzpLiZ31NeGpKIYCea4GVAgO4y/dXtDdBT38J6aP86a6B/1JukFoj/5inNao5orwWxKsUaeQb3damhDE77CBuj4XqNCSqa9x2MO8R7C2pXiv2EwDxvlpz70JWEw/ "Factor – Try It Online") ## Explanation It's a quotation (anonymous function) that takes an integer signifying the number of terms to use and a real number and returns a real number. Assuming `3 3.141592653589793` is on the data stack when this quotation is called... | Snippet | Comment | Data stack (top on right) | | --- | --- | --- | | `1vector` | Make a vector out of the object on top of the data stack. This is how `next-approx` expects to take its input. | `3 V{ 3.141592653589793 }` | | `over` | Put a copy of the object second from the top on top of the data stack. | `3 V{ 3.141592653589793 } 3` | | `[ dup next-approx ]` | Push a quotation to the data stack for `times` to use later. | `3 V{ 3.141592653589793 } 3 [ dup next-approx ]` | | `times` | Take an integer and a quotation and call the quotation that many times. In this case, equivalent to `dup next-approx dup next-approx dup next-approx` | | | | Inside the quotation now... | `3 V{ 3.141592653589793 }` | | `dup` | Copy the top data stack object | `3 V{ 3.141592653589793 } V{ 3.141592653589793 }` | | `next-approx` | Add the next term in the continued fraction to our vector. `next-approx` has stack effect `( seq -- )` so we made a copy so we don't lose it | `3 V{ 3 7.062513305931052 }` | | `dup next-approx` | Iteration 2 | `3 V{ 3 7 15.9965944066841 }` | | `dup next-approx` | Iteration 3 | `3 V{ 3 7 15 1.003417231015 }` | | `1 head*` | Remove last element | `3 V{ 3 7 15 }` | | `Î` | Take the product | `3 315` | | `abs` | Take the absolute value | `3 315` | | `nth-root` | Take the nth root of a number. In this case, take the cube root of 315 | `6.804092115953367` | [Answer] # [Mathematica](https://www.wolfram.com/mathematica/), 42 38 bytes ``` N@1##&@@ContinuedFraction[#2,#]^(1/#)& ``` Corrected formatting and size reduced by @theorist. Inputting n=100 and variable as Pi we get the output as ``` 2.69405 ``` You can save 2 bytes by removing N@ but this will give an exact expression and not numeric. The code also passes all the tests giving the exact value for each number except for -Pi for which it returns a complex number. However the magnitude of this complex number is exactly the same as that given in the expected value. [Answer] # JavaScript (ES7), 47 bytes Expects `(n)(real)`. ``` n=>v=>(g=n=>n?~~v*g(n-1,v=1/(v%1)):1)(n)**(1/n) ``` [Try it online!](https://tio.run/##bYzNCsIwEITveYq9CLvR/mylCJbUU6E9CHmFUm1VSiK25NhXj/HgRXub@eZjHq1rp@51f86RsZer75U3qnSqxEGFYE7L4uSAJuKdU5yg2zDRkQkNSYmcGPK6AQXndr7FuilE9S1VIXT9mZBhCzlICWmcEySQFUJ01kx2vMajHbDH8Kcboh@ardL9Kj2sUs4Jq/@HNMh1sP0b "JavaScript (Node.js) – Try It Online") Note: With 40+ terms, the last test case will diverge from 1 because of cumulated floating point errors. [Answer] # [Ruby](https://www.ruby-lang.org/), 57 bytes ``` ->n,l,r=1{n=n.abs;l.times{r*=n.to_i**(1.0/l);n=1/n%=1};r} ``` [Try it online!](https://tio.run/##bY3RCoIwGIXve4puArd@535DBGXdddkTyIgJWcJcMhcY02dfol0G5xz4vptj3/UnNCLEZwMarEBvhGGqHkrNXNvdB2/pItzr1lIaIeOJJqURmJiDwLm0c6gQUjhBDsiXrN3mt1yyTvV@Gqd@31QxMmUfMMp5t2K0CQK5XMVVuWdRXACzjaOMUs6yI5JkeeF/JKZchi8 "Ruby – Try It Online") ]
[Question] [ ## Background We all know about distributivity, i.e. \$a(b+c) = ab + ac\$. This is a property on *2* different operations, namely addition and multiplication. But indeed, nothing can stop us from studying distributivity of 1 operation. In this challenge, you will be studying a kind of left-distributive operation. ## Task Given a positive integer \$N\$. Consider an operation \$p \star q\$ where \$p, q\in\{0, 1,\dots, N-1\}\$, such that \$ p \star 1 \equiv p + 1 \pmod N\$ and \$p \star (q \star r) = (p \star q) \star (p \star r)\$. In essence, you are making an \$N\times N\$ table. For instance, if \$N = 4\$, a possible \$\star\$ is: ``` ⋆ q 0 1 2 3 p-+--------- 0 | 0 1 2 3 1 | 0 2 0 2 ← 2 | 0 3 0 3 3 | 0 0 0 0 ↑ ``` Note that the marked column satisfies \$ p \star 1 \equiv p + 1 \pmod N\$. In this challenge, we are interested in the marked *row*. It seems to be periodic, and the challenge is to find its period. The smallest positive period for a sequence \$a\_0, \dots , a\_{N-1}\$, is defined to be the smallest positive integer \$k\$, such that \$k\$ divides \$N\$, and \$a\_i = a\_{i + k}\$, for \$i=0..(N-k-1)\$. However, there may be many possible \$\star\$'s for a given \$N\$, or there may be none. So you need to compute the (smallest positive) periods for all of them. > > Task: given a positive integer `N`, compute all the possible smallest positive periods of `1 ⋆ q`. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). > > > ## Details and clarifications In the case `N = 4`, the given table turns out to be the only possible one, so you should output a list (or a set, etc.) consisting only of the number `2`. But for `N = 3`, no operation satisfies all the requirements, so you can output an empty list, or 0, or some falsy value. The smallest positive period will always be between 1 and \$N\$, if the sequence `1 ⋆ q` (`0 <= q < N`) doesn't repeat at all, it is of period \$N\$. `N` will range from 1 to \$2^{32}-1\$. So it is almost [kolmogorov-complexity](/questions/tagged/kolmogorov-complexity "show questions tagged 'kolmogorov-complexity'"). But note that a formula or recurrence relation of this is unknown. ## Test cases ``` In : N = 1 Out: [1] In : N = 2 Out: [1] In : N = 3 Out: [] In : N = 4 Out: [2] ``` [Answer] # [Python 2](https://docs.python.org/2/), 113 bytes ``` N=input() f=lambda p,q:f(f(p,q-1),-~p%N)if p*q else q print([i for i in range(1,N)if N%i+f(1,i)<1]+[N])[:N&N-1<1] ``` *-2 bytes thanks to @Jakque* [Try it online!](https://tio.run/##bVHBbsMgDL3zFRZTV1hopPQYLfuEXHbMqiproLOUAgUq1st@PXPTtdqkcTG233t@YH9OH86uJ/2pd9uYAtp9wzmf2gatPyUhmWnG/vA@9ODVsTbCCIqrSqrVl1@0Eg34pyPoMWo4Mk/8JDoE4wIgoIXQ270WlZqR7QILQwnK52pTdO1GdnX72K4qSieayljSMUVoYMSYxI1bVVIy9gCveDiNfdIQ00DS84wfk3jwLiRwUcVzZEFBJhEXS49eU9vqvL2S5qoZnNdWEGwZlpK5cbh2FRC7vAHvdwV3Pst/FDIpZFK4P3f2XzOgk8scMGkRtA8CJRTA3yyXLJe70cWLq39p8xcCKt68cDVXLqsRv/Yjp28 "Python 2 – Try It Online") The short, recursive approach is slow since it repeats computation of many entries, so I've made an [iterative, memoized approach](https://tio.run/##bVPLbtswELzzKxYKWpMxY0QO0EMB9RN86dEVAsVa2UQtkibpqEbRb3eXlPUIHAICxJ3Z4XB3aS/hYPTLFf/g7tUHp/S@yLLsuimUDlxpew5cCNZiW/z9x1iNDTTcypP4zoCWasAWxXO/icthODsNpxm6ecrv8OcBP32WPUfvc7ld5uLLhs1CZG@bXJW9RYtOmZpPJjdfo4uBvi1T/AGw3iPsKo9@JMYTR15ezuLrKb4eBHyoXIDGmRbCAeHNhGDaJ6f2hwCVrqEz7jeYs4OuusDZSmiU8wGO2ISYoFNM4zs6sJX3VH2o3sw7JrW2UhpqVe2Nro7pwHRPuomkT5RFX6fGUDIQ1VV6jwSvZS4Jnwp3K89alFDcNstcxjKWIyeqnCaVlwRPEjOZU5Jp@LCNVhI7kcPMlZr0cgmbmVwoGh7I0BigEocPozDr7lZRW62LAzk0VlxpSBkL6IMnM9v146O6O/JbHIcH@Kna87EKSM2qCUysfq6Zaq2h/hkv/cUzJ6EjMeNXVlkkWGP32ielaFMbi5oTbeEWgplj3aMSKHs1EMf/2NhbPus@KHSk0JHCaDjdo797t@qcCsgdWseVgCVkv3QmWLfaHY2Prj5N68ujZFb8yCTquljAoq9ufNl89rzF9T8) which is much faster (quadratic in `N`) and can compute up to `N=4096` within 60 seconds on TIO. # How it Works The algorithm assumes that \$\star\$ is unique, if it exists (proof below). It uses recursion, setting \$p\star q=\begin{cases} q, &p=0 \\ p+1 \mod n, &q=1 \\ (p \star (q-1 \mod n))\star (p+1 \mod n), &\text{otherwise} \end{cases}\$ The first case (\$p=0\$) is Lemma 1 in the uniqueness proof: \$0\star q=q\$. The second case (\$q=1\$) is given. The third case has a simple proof despite its complex self (assuming addition and subtraction are mod \$N\$: \begin{align\*} &p \star q\\ =&p \star ((q-1)+1) \\ =&p \star ((q-1)\star 1) \\ =&(p \star (q-1))\star(p\star 1) \\ =&(p \star (q-1))\star(p+1) \end{align\*} This is enough to determine the unique \$\star\$ (The proof shows that the third case will not recurse indefinitely). The period is the minimum \$i\$ such that \$1\star (i+1) = 1\star 1 = 2\$. If this \$i\$ doesn't divide \$N\$, then it is not a period. ### Ungolfed code: ``` # f(p,q,N) = p⋆q def f(p,q,N): if p==0: return q if q==1: return (p+1)%N return f(f(p,(q-1)%N,N),(p+1)%N, N) def period(N): if any(f(p,f(q,r,N),N) != f(f(p,q,N),f(p,r,N),N) for p in range(N) for q in range(N) for r in range(N)): # The f does not exist return [] for i in range(1, N): # period is i if f(1,i+1)=f(1,1)=2 if f(1,i+1,N) == 2: # might not be divisible, in which case it is not the period if N%i: return [N] return [i] ``` This could be sped up immensely by memoization utilizing \$ a \star 2 = a \star (1 \star 1) = (a\star 1)\star (a\star 1) = (a+1)\star(a+1) \$ and \$1 \star a = (1\star (a-1))\star 2\$. # Proof of Uniqueness of \$\star\$ For this section, we assume all addition/subtraction is mod \$N\$. **Lemma 1**: For all \$a\$, \$0 \star a = a\$ *Proof*: Induction Base case: \$a=1\$. Given since \$0\star 1=1\$. Step: Assume this lemma holds for \$a=k\$. Then \begin{align\*} &0 \star (k + 1)\\ =& 0\star (k\star 1) \\ =& (0\star k)\star (0\star 1) \\ =& k \star 1 \\ =& k+1, \end{align\*} so this holds for \$a=k+1\$. Since this addition is mod \$N\$, this will "wrap around" back to \$0\$, so it applies for \$a=0\$ too, not just \$a\geq 1\$ **Theorem**: If an operation \$\star\$ is valid for a given \$N\$, then it the unique \$\star\$ that is valid for that \$N\$. *Proof:* We use strong induction to show that, for all \$0\leq a,b\leq N-1\$, \$a\star b\$ is uniquely determined by \$N\$. In addition, for each \$a\$ and \$b\$ in the same set, either (1) \$a\star b=0\$ or (2) \$a<a\star b<N\$ 1. Base case: \$a\star b\$ is uniquely determined and equal to \$0\$ for \$a=N-1\$ and for all \$b\$. We prove this base case with induction too. 1. Base case: \$b=1\$. We are given \$a\star 1=a+1\$, so \$(N-1)\star 1=0\$, uniquely determined. 2. Step: Given \$(N-1)\star b=0\$ for \$b=k\$, then \begin{align\*} &(N-1)\star (b+1)\\ =&(N-1)\star (b\star 1)\\ =&((N-1)\star b)\star((N-1)\star 1)\\ =&0\star0 \\ =&0, \end{align\*} where we use Lemma 1 to show \$0\star 0=0\$, so \$(N-1)\star b\$ is uniquely determiend to be \$0\$. 2. Assume \$a\star b\$ is uniquely determined and either (1) or (2) hold for all \$k<a\leq N-1\$ and for all \$b\$. Then for \$a=k\$, we will show \$a\star b\$ is uniquely determined and either (1) or (2) hold for all \$b\$, again with induction. 1. Base case: \$k\star b\$ is uniquely determined and either (1) or (2) hold for \$b=1\$. This is trivial since \$k\star 1=k+1>k\$, so \$k\star 1\$ is unique and (2) holds 2. Step: Assume \$k\star b\$ is uniquely determined and either (1) or (2) hold for \$b=j\$. Then: \begin{align\*} &k\star (b+1)\\ =&k\star (b\star 1)\\ =&(k\star b)\star(k\star 1)\\ =&(k\star b)\star(k+1) \end{align\*} If (1) holds, then \$k\star b=0\$, so \$k\star(b+1)=k+1>k\$ by Lemma 1. Thus \$k\star(b+1)\$ is uniquely determined and satisfies (2). If (2) holds, then \$k<k\star b\leq N-1\$,so by the outer inductive assumption, \$k\star(b+1)=(k\star b)\star (k+1)\$ is uniquely determined and either (1) or (2) holds for it. In either case, \$k\star(b+1)\$ is uniquely determined and either (1) or (2) hold for it, completing the inductive step. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~106~~ ~~90~~ 42 bytes ``` AtomQ@#&&2^Tr@UnitStep[#-{2,3,5,9}]&@*Log2 ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b737EkPzfQQVlNzSgupMghNC@zJLgktSBaWbfaSMdYx1THsjZWzUHLJz/d6H9AUWZeCVDGLs1BOVatzrGoKLGyzszkPwA "Wolfram Language (Mathematica) – Try It Online") Returns the period if it exists, or `False` otherwise. [Laver Tables](https://en.wikipedia.org/wiki/Laver_table) exist iff \$N\$ is a power of 2. The sequence of periods is [A098820](https://oeis.org/A098820) on the OEIS. Assuming the l3 rank-into-rank cardinal exists, it's been shown that the first \$N\$ for which the period is greater than 16 is at least \$2^{A(9,A(8,A(8,255)))}\ggg2^{31}-1\$, where \$A\$ is the Ackermann function. John Baez has a relatively accessible layman's explanation [here](https://johncarlosbaez.wordpress.com/2016/05/06/shelves-and-the-infinite/). ]
[Question] [ A *wave* of power \$k\$ is an infinite array that looks like \$1,2,\dots,k,k-1,\dots,1,\dots,k,\dots,1,\dots\$, and so on. For example, a wave of power 3 starts with \$1,2,3,2,1,2,3,2,1,...\$, and repeats indefinitely. A wave of power 1 is an infinite array of ones. They happen to be beautifully expressed as $$w\_k[t] = k - |(t - 1)\bmod(2k - 2) - k + 1|\text{, 1-indexed}$$ In this challenge, all waves are trimmed to their first \$n\$ elements, where \$n\$ is the length of the input array. A *decomposition of an array into waves* is an array of coefficients of length \$n\$ such that the original array equals the sum of the waves multiplied by their corresponding coefficients. Formally, if the original array is \$A\$, the decomposition is an array \$B\$ such that for any \$i\$ (\$1 \le i \le n\$) the following equality holds: $$A[i] = \sum\_{j=1}^\infty B[j] \cdot w\_j[i]\text{, 1-indexed}$$ The *waviness* of an array is the index of the last non-zero value in its decomposition into waves. The task is, given a positive integer array of length \$n\$, to calculate its waviness. Note that the decomposition can still include non-integer and negative numbers. ## Test cases All test cases below are 1-indexed. Your solution may use 0-indexing instead. ``` [1, 1, 1] -> 1 (decomposition: [1, 0, 0]) [1, 2, 1] -> 2 (decomposition: [0, 1, 0]) [1, 2, 3] -> 3 (decomposition: [0, 0, 1]) [1, 1, 2] -> 3 (decomposition: [1, -0.5, 0.5]) [1, 3, 3, 3, 1] -> 3 (decomposition: [-1, 1, 1, 0, 0]) [1, 2, 2, 4] -> 4 (decomposition: [0, 0.5, -0.5, 1] [4, 6, 9, 1, 4, 3, 5] -> 7 (decomposition: [2, -0.5, 5, -5, 6.5, -1, -3] [4, 6, 9, 1, 4, 3, 5, 7] -> 8 (decomposition: [2, -0.5, 5, -5, 6.5, -1, -10.5, 7.5]) ``` This is tagged [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") an uncommon justification, so the shortest answer wins. [Answer] # JavaScript (ES6), ~~172 171~~ 169 bytes The output is 0-indexed. ``` a=>a.map((_,i)=>(D=m=>+m||m.reduce((s,[v],i)=>s+(i&1?-v:v)*D(m.map(([,...r])=>r).filter(_=>i--)),0))(a.map((v,y)=>a.map((_,x)=>x-i?x-~-Math.abs(y%(2*x)-x):v)))&&(j=i))|j ``` [Try it online!](https://tio.run/##lY5da4MwFIbv@ytyMzmnTdL50XUbxN70dr9ApGRWu4jWEp2kIPvrLnMrDFthC@9NOM/L8@aylXWi1alhx2qf9pnopQglL@UJYEcVihC2ohThouy6kut0/56kADWN2ni41gtQjrth7XOL8y2U382Ics51bO8aeaaKJtWwE6FiDJHeI8KPoaVn/KUz9mOY2hj2wV5k88blaw3nO/DmBplBq0B0HMiFQuzyPqmOdVWkvKgOkEHkUvKVGJGM33JJ3Nk17k3j3m3cn8D92c0x3j9w/5LRpAncGxJcCSwejPGAkgdKnoZJweBYXXoWX/8Bp2Q9NCz@2H8C "JavaScript (Node.js) – Try It Online") ### How? This is essentially an implementation of [Cramer's rule](https://en.wikipedia.org/wiki/Cramer%27s_rule), except that the denominator is not computed. Given the input vector of length \$n\$, we define \$W\_n\$ as the matrix holding the waves, stored column-wise. *Example:* $$W\_5=\begin{pmatrix} 1&1&1&1&1\\ 1&2&2&2&2\\ 1&1&3&3&3\\ 1&2&2&4&4\\ 1&1&1&3&5\end{pmatrix}$$ We compute all values \$v\_i=\det(M\_i)\$ with \$0\le i<n\$, where \$M\_i\$ is the matrix formed by replacing the \$i\$-th column of \$W\_n\$ with the input vector. *Example:* For the 5th test case and \$i=3\$, this gives: $$v\_3=\det(M\_3)=\begin{vmatrix} 1&1&1&\color{red}1&1\\ 1&2&2&\color{red}3&2\\ 1&1&3&\color{red}3&3\\ 1&2&2&\color{red}3&4\\ 1&1&1&\color{red}1&5\end{vmatrix}=0$$ We return the highest index \$j\$ such that \$v\_j\neq0\$. ### Commented The helper function \$D\$ uses [Laplace expansion](https://en.wikipedia.org/wiki/Laplace_expansion) to compute the determinant: ``` D = m => // m[] = matrix +m || // if the matrix is a singleton, return it m.reduce((s, [v], i) => // otherwise, for each value v at (0, i): s // take the previous sum s + (i & 1 ? -v : v) // based on the parity of i, add either v or -v * D( // multiplied by the result of a recursive call: m.map(([, ...r]) => r) // pass m[] with the 1st column removed .filter(_ => i--) // and the i-th row removed ), // end of recursive call 0 // start with sum = 0 ) // end of reduce() ``` The matrix \$M\_i\$ is computed with: ``` a.map((v, y) => // for each value v at position y in the input vector a[]: a.map((_, x) => // for each value at position x in the input vector a[]: x - i ? // if this is not the i-th column: x - // compute the wave of power x+1 at position y: ~-Math.abs( // x - (|y mod (2*x) - x| - 1) y % (2 * x) - x // (where y mod 0 is coerced to 0) ) // : // else: v // append the value a[y] of the input vector ) // end of inner map() ) // end of outer map() ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~34~~ ~~33~~ 27 [bytes](https://codegolf.meta.stackexchange.com/questions/9428/when-can-apl-characters-be-counted-as-1-byte-each) ``` ⊢{⊢/⍋0≠⍺⌹⍉↑(1+⍵⍴⍳,⊢-⍳)¨⍳⍵}≢ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkG/9OB5KOuRdVArP@ot9vgUeeCR727HvXsfNTb@ahtooah9qPerY96tzzq3awDVKMLpDUPrQCSQOHaR52LQEYBjUhXMOSCs0AQiWeExjNGUWmExDMGQ1TVRgomcL6JgpmCJVDUBKjKFLuogjlUXMMQYhkYmiiYK1ho6hr@BwA "APL (Dyalog Unicode) – Try It Online") Lots of golfing thanks to [ngn](https://chat.stackexchange.com/transcript/message/52223665#52223665). ### How it works ``` g←⊢{⊢/⍋0≠⍺⌹⍉↑(1+⍵⍴⍳,⊢-⍳)¨⍳⍵}≢ Accept a vector V of length N ⊢{ }≢ Call the inner function with ⍺=V, ⍵=N ⍳⍵ Make 0..N-1 ( ⍳,⊢-⍳)¨ For each i of above, make 0..i-1,i..1 and 1+⍵⍴ repeat/truncate to length N and +1 ⍺⌹⍉↑ Reform above as matrix and solve equations 0≠ Test nonzero on each item (nonzero→1, zero→0) ⊢/⍋ Find the last index of 1 ``` --- # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~34~~ 33 [bytes](https://codegolf.meta.stackexchange.com/questions/9428/when-can-apl-characters-be-counted-as-1-byte-each) ``` ⍴-0(⊥⍨=)⊢⌹∘⍉∘↑1+⍴⍴¨(⊢,1+⌽)∘⍳¨∘⍳∘⍴ ``` [Try it online!](https://tio.run/##nZDBSsNAEIbP3aeYY5Ya2E2i1UMewJPPUBD20kavIr0GWxpRRPDipSDk5qH14MFLHmVeJP67q6GJtrUyMLP/8M83ww4vR@H51XB0YWqjOL@7Fr0MhYsVF2@iN3bvKef3GVpVGfBscaA5f6hebeb5h@SbJy6WVYmUYTjk2QsXpUoxz/P3sZgIo3@Cu759lkwEF88UeJQMyZNIpeRZKFMCrbE4Km3BYmJJX6dZtsGlZBshqcDjYU0lVi2wILDXYhQrrMml7Qt8dXklhYn8T4Tf8FR2we6YHX/RZsYbmM7wP6rg28fTM3BVbf5A1/02v7@JW4MLniENoUWjbKypqKPiljNaU7GLtjuipNEJHdEJuglch793aSAC7de4SGhAx7L@BA "APL (Dyalog Unicode) – Try It Online") Uses `⎕IO←0` and an alternative way to generate the matrix W. ``` g←⍴-0(⊥⍨=)⊢⌹∘⍉∘↑1+⍴⍴¨(⊢,1+⌽)∘⍳¨∘⍳∘⍴ Accept a vector of length n ⍳∘⍴ Make a vector 0..n-1 (⊢,1+⌽)∘⍳¨ For each k of above, chain 0..k-1 and k..1 ⍴⍴¨ and repeat or truncate to length n The first row has 0 elements, repeat gives n zeros 1+ Increment all elements ⍴-0(⊥⍨=)⊢⌹∘⍉∘↑ The rest is the same as the previous answer ``` --- # [APL (Dyalog Unicode)](https://www.dyalog.com/), 34 [bytes](https://codegolf.meta.stackexchange.com/questions/9428/when-can-apl-characters-be-counted-as-1-byte-each) ``` ⍴-0(⊥⍨=)⊢⌹∘⍉∘↑⍴⍴¨(⊢,1↓¯1↓⌽)∘⍳¨∘⍳∘⍴ ``` [Try it online!](https://tio.run/##nZDBSsNAEIbPnaeY4y64kKTR6iEPUyjspY29ivQa2tIVSxG89FIQcvPQevDgJY8yL5LOzmqNUSuWgZnM5J/vH7Y/HprBTX94bWsbUXF/C52cC7kduRfojOR7RsUy51FVKppvzmIqVtWzz7R40zR9JLetSk45LxuaP5Ero4z3afE6ggnY@Du4rfuPyQTIrVEFlDYYSBhlGFhcZsi0g0SoeATLG1t8P82zLV@KfmAwUgHP0kyz1YYNlL@WV9nCiyQdNwhV8k6DTcJLmA94pttgOeaPt2gya/sLUv6fBq3p7oGpFmMf8Nklra4LTWXS6LoSX9UJpoc@xQu84mnKqvOfp9gDJSYSKfbwUtd7 "APL (Dyalog Unicode) – Try It Online") A monadic train that accepts a numeric vector. ### How it works ``` g←⍴-0(⊥⍨=)⊢⌹∘⍉∘↑⍴⍴¨(⊢,1↓¯1↓⌽)∘⍳¨∘⍳∘⍴ Accept a vector of length n ⍳∘⍴ Make a vector 1..n (⊢,1↓¯1↓⌽)∘⍳¨ For each k of the above, generate one unit of wave of power k (1..k..2) ⍴⍴¨ Repeat or truncate each row to length n (result is nested vector) ⍉∘↑ Convert nested vector to matrix, and transpose it ⊢⌹ Solve the linear equation 0(⊥⍨=) Count trailing zeros ⍴- Subtract from n ``` Basically, this solution uses the same W matrix as [Arnauld's submission](https://codegolf.stackexchange.com/a/194504/78410), solves the linear equation, and then finds the index of the last nonzero entry using the good old "count trailing ones" `⊥⍨`. [Answer] # MATLAB, 111 bytes ``` function w=f(A) n=length(A) W=ones(n,1) for k=2:n W(1:n,k)=k-abs(mod(0:n-1,2*k-2)-k+1) end w=max(find(W\A)) end ``` I'm new to this, do MATLAB answers have to be in a `function`, or can we assume `A` is set implicitly? The code is straight-forward. The sum in the OP can be replaced with a simple matrix multiplication, `A = W*B`. The code computes `B = inv(W)*A` and finds the index of the last non-zero entry in `B`. `mod(x,0)` isn't well-defined, so the first row has to be set manually. ]
[Question] [ *Related: Rather similar (but much easier) challenge horizontally: [There I fixed it (with tape)](https://codegolf.stackexchange.com/questions/157240/there-i-fixed-it-with-tape)* ## Challenge: Given a string only containing upper- and/or lowercase letters (whichever you prefer) and new-lines, put `rope` vertically to fix it. We do this by checking the difference of two adjacent letters in the alphabet (ignoring wrap-around and only going downward), and filling the space with as much `ROPE`/`rope` as we would need. NOTE: One other key difference between this challenge and the [There I fixed it (with tape)](https://codegolf.stackexchange.com/questions/157240/there-i-fixed-it-with-tape) challenge is that we're not wasting `rope` this time like we did with the `tape` (suggested by *@JonathanAllan* in part one of the challenge). ### Example: Input: ``` abc bcd ddd eex gfz hka imh ``` Output: ``` abc bcd Rdd deE efR OPO gEP hRE iOR kO PP mE R O P E R O P E R O x P z a E R O P E R h ``` ***Why?*** * Between `b` and `d` in column 1 should be `c` (length 1), so we fill this with `R`; * Between `e` and `g` in column 1 should be `f` (length 1), so we fill this with `O`; * Between `f` and `k` in column 2 should be `ghij` (length 4), so we fill this with `PERO`; * Between `k` and `m` in column 2 should be `l` (length 1), so we fill this with `P`; * Between `d` and `c` in column 3 should be `efghijklmnopqrstuvw` (length 19), so we fill this with `EROPEROPEROPEROPERO`; * Between `x` and `z` in column 3 should be `y` (length 1), so we fill this with `P`; * Between `a` and `h` in column 3 should be `bcdefg` (length 6), so we fill this with `EROPER`. ## Challenge rules: * The difference only applies downwards, so no rope between `za` (column 3 in the example above). * It is possible to have multiple of the same adjacent letters like `dd` (column 3 in the example above). * You will continue using the `ROPE` one column at a time to not waste parts (suggested by *@JonathanAllan* in part 1 of the challenge). * You are allowed to take the input in any reasonable format. Can be a single string, string-array/list, character-matrix, etc. Output has the same flexibility. * You are allowed to use lowercase and/or uppercase any way you'd like. This applies both to the input, output, and `ROPE`. * Trailing spaces are optional (note that the correct amount of leading spaces are mandatory so the columns are correct). Any amount of trailing and/or leading new-lines are also optional. * You can assume that all test cases will have the same length across all rows, so `a\naa`/`[[a][a,a]]` wouldn't be a valid input. * It is possible no `ROPE` is necessary, in which case the input remains unchanged. ## 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 and return-type, full programs. Your call. * [Default Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. * If possible, please add a link with a test for your code. * Also, please add an explanation if necessary. ## Test cases: ``` As string: Input: "abc\nbcd\nddd\neex\ngfz\nhka\nimh" Output: "abc\nbcd\nRdd\ndeE\nefR\nOPO\ngEP\nhRE\niOR\n kO\n PP\n mE\n R\n O\n P\n E\n R\n O\n P\n E\n R\n O\n x\n P\n z\n a\n E\n R\n O\n P\n E\n R\n h" As array-matrix: Input: [[a,b,c],[b,c,d],[d,d,d],[e,e,x],[g,f,z],[h,k,a],[i,m,h]] Output: [[a,b,c],[b,c,d],[R,d,d],[d,e,E],[e,f,R],[O,P,O],[g,E,P],[h,R,E],[i,O,R],[ ,k,O],[ ,P,P],[ ,m,E],[ , ,R],[ , ,O],[ , ,P],[ , ,E],[ , ,R],[ , ,O],[ , ,P],[ , ,E],[ , ,R],[ , ,O],[ , ,x],[ , ,P],[ , ,z],[ , ,a],[ , ,E],[ , ,R],[ , ,O],[ , ,P],[ , ,E],[ , ,R],[ , ,h]] As string: Input: "a\nz\na" Output: "a\nR\nO\nP\nE\nR\nO\nP\nE\nR\nO\nP\nE\nR\nO\nP\nE\nR\nO\nP\nE\nR\nO\nP\nE\nz\na" As array-matrix: Input: [[a],[z],[a]] Output: [[a],[R],[O],[P],[E],[R],[O],[P],[E],[R],[O],[P],[E],[R],[O],[P],[E],[R],[O],[P],[E],[R],[O],[P],[E],[z],[a]] As string: Input: "zz\nyy\nxx\nxx\ncc\ncc\nbb\nad" Output: "zz\nyy\nxx\nxx\ncc\ncc\nbb\naR\n d" As array-matrix: Input: [[z,z],[y,y],[x,x],[x,x],[c,c],[c,c],[b,b],[a,d]] Output: [[z,z],[y,y],[x,x],[x,x],[c,c],[c,c],[b,b],[a,R],[ ,d]] As string: Input: "a\nb\nc\nc\nx\nx\ny\nz" Output: "a\nb\nc\nc\nR\nO\nP\nE\nR\nO\nP\nE\nR\nO\nP\nE\nR\nO\nP\nE\nR\nO\nP\nE\nx\nx\ny\nz" As array-matrix: Input: [[a],[b],[c],[c],[x],[x],[y],[z]] Output: [[a],[b],[c],[c],[R],[O],[P],[E],[R],[O],[P],[E],[R],[O],[P],[E],[R],[O],[P],[E],[R],[O],[P],[E],[x],[x],[y],[z]] As string: Input: "zai\nybj\nxcq\nxcu\ncxw\ncxw\nbyr\nazw" Output: "zai\nybj\nxcR\nxcO\ncRP\ncOE\nbPR\naEO\n Rq\n OP\n PE\n ER\n Ru\n OO\n Pw\n Ew\n Rr\n OP\n PE\n ER\n RO\n Ow\n P \n E \n x \n x \n y \n z " As array-matrix: Input: [[z,a,i],[y,b,j],[x,c,q],[x,c,u],[c,x,w],[c,x,w],[b,y,r],[a,z,w]] Output: [[z,a,i],[y,b,j],[x,c,R],[x,c,O],[c,R,P],[c,O,E],[b,P,R],[a,E,O],[ ,R,q],[ ,O,P],[ ,P,E],[ ,E,R],[ ,R,u],[ ,O,O],[ ,P,w],[ ,E,w],[ ,R,r],[ ,O,P],[ ,P,E],[ ,E,R],[ ,R,O],[ ,O,w],[ ,P, ],[ ,E, ],[ ,x, ],[ ,x, ],[ ,y, ],[ ,z, ]] As string: Input: "asdljasdjk" Output: "asdljasdjk" As array-matrix: Input: [[a,s,d,l,j,a,s,d,j,k]] Output: [[a,s,d,l,j,a,s,d,j,k]] As string: Input: "asdljasdjk\nlkawdasuhq\nasjdhajksd" Output: "asdljasdjk\nRkaOdasPhR\nOPOPEajEPO\nPEPER REP\nERERO ORE\nROROh POR\nOPOP EPq\nPEPE ROd\nERER OR \nRsRO PO \nO jP EP \nl w RE \na d Os \n P \n E \n R \n O \n u \n k " As array-matrix: Input: [[a,s,d,l,j,a,s,d,j,k],[l,k,a,w,d,a,s,u,h,q],[a,s,j,d,h,a,j,k,s,d]] Output: [[a,s,d,l,j,a,s,d,j,k],[R,k,a,O,d,a,s,P,h,R],[O,P,O,P,E,a,j,E,P,O],[P,E,P,E,R, , ,R,E,P],[E,R,E,R,O, , ,O,R,E],[R,O,R,O,h, , ,P,O,R],[O,P,O,P, , , ,E,P,q],[P,E,P,E, , , ,R,O,d],[E,R,E,R, , , ,O,R, ],[R,s,R,O, , , ,P,O, ],[O, ,j,P, , , ,E,P, ],[l, , ,w, , , ,R,E, ],[a, , ,d, , , ,O,s, ],[ , , , , , , ,P, , ],[ , , , , , , ,E, , ],[ , , , , , , ,R, , ],[ , , , , , , ,O, , ],[ , , , , , , ,u, , ],[ , , , , , , ,k, , ]] As string: Input: "re\nop\npo\ner" Output: "re\noR\npO\neP\n E\n R\n O\n P\n E\n R\n O\n p\n o\n P\n E\n r" As array-matrix: Input: [[r,e],[o,p],[p,o],[e,r]] Output: [[r,e],[o,R],[p,O],[e,P],[ ,E],[ ,R],[ ,O],[ ,P],[ ,E],[ ,R],[ ,O],[ ,p],[ ,o],[ ,P],[ ,E],[ ,r]] ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~38~~ ~~37~~ 25 bytes Saved 10 bytes with suggestions from *Magic Octopus Urn* and another byte changing output format. Outputs a list of strings. Footer pretty prints. ``` 'ÙºUζεDÇ¥<)ζε`FX¬sÀU}J]Jζ ``` [Try it online!](https://tio.run/##MzBNTDJM/f9f/fDMQ7tCz207t9XlcPuhpTaaIGaCW8ShNcWHG0JrvWK9zm37f2j3/@ho9UR1HQX1JBCRrB6roxANYwOJFIhACoSNEEgFscFEBUQgHcROAxFVEIEMEDsbRCRCBDJB7FwQkaEeGwsA "05AB1E – Try It Online") **Explanation** ``` 'ÙºU # store the string "rope" in variable X ζ # transpose input ε ] # for each transposed row D )ζ # zip the row with Ç¥< # the decremented deltas of its character codes ε # for each pair of [letter, delta-1] `F } # delta-1 times do: X¬ # get the first letter of X (originally "rope") sÀU # rotate the letters left by 1 and store in X J # join the rope-letter to the current row-letter J # join to list of strings (the new columns) ζ # transpose ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 21 bytes ``` ZµOI’R“¡nⱮ»ṁż@"µF€z⁶Y ``` [Try it online!](https://tio.run/##y0rNyan8/z/q0FZ/z0cNM4MeNcw5tDDv0cZ1h3Y/3Nl4dI@D0qGtbo@a1lQ9atwW@f9w@9FJD3fO@P8/WikxKVlJh0spKTkFRKWkgKnU1AoQlZ5WBaIyshNBVGZuhlIsAA "Jelly – Try It Online") # Explanation ``` ZµOI’R“¡nⱮ»ṁż@"µF€z⁶Y Main Link Z Transpose the input so the columns are now rows µ New monadic chain O [Vectorizing] Convert each letter to its character code I [Vectorizing] Get the differences (gap size) ’ [Vectorizing] Add one R [Vectorizing] Range from 1 .. x ṁ Mold the string into the ranges “¡nⱮ» "rope" ż@" Vectorizing zip the rope strings with the original string (place ropes in gaps) µ New monadic chain F€ Flatten Each z⁶ Zip and fill with spaces Y Join on newlines for output ``` -1 byte thanks to Mr. Xcoder -2 bytes thanks to Erik the Outgolfer [Answer] # [Python 2](https://docs.python.org/2/), ~~197~~ 194 bytes ``` def f(s): r='ROPE'*len(`s`)*9;x=[] for i in zip(*s): x+='', for c,C in zip(i,i[1:]+(' ',)):l=(C>c)*(ord(C)+~ord(c));x[-1]+=c+r[:l];r=r[l:] print zip(*['%*s'%(-max(map(len,x)),s)for s in x]) ``` [Try it online!](https://tio.run/##NY49b8MgEIbn@FewRHeHyZBuxaKL1blVV4QUB0yN6i/hDDRD/7oLqbo8J73vnZ5bv2/DMj/tu@s987iRrFhU8PH2/gp87Ge8bBfiz01S2lTML5EFFmZ2DyvysnxItQIQ1aFUVrT/ZRBBn6WpERgIIjkqbF8scVyiw5bqnzItUZP06WxqZeuo5WiaqKIeZVatMcy3P4@GI9/giKepSzh1K@a/RCISGxXrVpzJ0O5RQ3e1IOBqXaZzhX2fMj/9PXP46jLDNICh6mGoHkc5LHWX4/0X "Python 2 – Try It Online") --- * -3 bytes thanks to ovs [Answer] # [Ruby](https://www.ruby-lang.org/), 119 bytes ``` ->a{l=0;a.map!{|r|r.reduce{|x,y|x+("ROPE"*7)[l%4,-l+l+=[0,y.ord+~x[-1].ord].max]+y}}.map{|s|s.ljust a.map(&:size).max}} ``` [Try it online!](https://tio.run/##XY5RC4IwFIX/SgmFNh0FQVBYTz0XvTofppuprSm7CjO3/rplPQS9HA7cc757VJt0QxYOwZ72IlzuKL7TetobZRRWnLUp7432O6OR61xO56Oz2HiRmK39QCCBwmjpd7hSDD11FKzi0cZvgo5RZ@2I6g0YwKJsoZl82O58C8WDe2PK2qFuG5hkkUOTlMgkZUQy9hbONZHX7EFkfqNEFvfcwVCLonEPRHpf8DgxzakCixtFJdQV8Pj38//0K5VVIe3wAg "Ruby – Try It Online") Yes, this is much more difficult than the "TAPE" challenge. I tried to build up on my solution to that task, but this has a few extra twists. Takes input as a columnwise array of characters, returns an array of strings, also in columnwise format. The code in the footer of the TIO link performs pre- and post-processing of I/O data so that we could supply a more manageable string and then print the result nicely. ## Explanation The code makes two passes through the input array. In the first pass we apply the `reduce` operation that fills up the space between the characters with the required amount of ROPE (`y.ord-x[-1].ord-1` characters, if positive). We also need to keep track of the used ROPE length (`l`). Unlike in the TAPE case we cannot simply use `rjust` for filling, as it would always start from the R character. Instead, taking a proper slice of a long "ROPEROPE..." string seems lighter on byte count, especially since we also need to update `l` on the fly. In the second pass we left-justify the resulting strings with spaces to match the length of the longest of them. Since we need the full results of the previous iteration here, the first pass modifies the array in place (hence `map!`, not `map`). [Answer] *-1 bytes thanks to Kevin Cruijssen* *-70 bytes thanks to [Jonathan Frech](https://codegolf.stackexchange.com/users/73111/jonathan-frech), wow.......* # [Python 3](https://docs.python.org/3/), 203 bytes ``` def f(s,c=0,x=()): for i in range(len(s[0])): p,o=" ","" for j in s:t=j[i];y=p>' 'and~ord(p)+ord(t);o+=('ROPE'*y)[c:y+c]+t;c,p=c%4+y*(y>=0)%4,t x+=o, for i in x:yield i.ljust(len(max(x,key=len))) ``` [Try it online!](https://tio.run/##bZLBbhshEIbP4SlGjiIgiyJLzckWueXcqj3aqwqzbMx6DRRm5SWHvrrLrt00ljoH0MA3M/@PCBn33n05nxvTQsuS0HIpRsk4X5G71kewYB1E5d4M641jabOs57u7ILxcwEIsFiWZyG4i0wplt7H1OsvwQoEq1/z2sWGBV9OGfO0ryej3r99e6WPmG73Kla4rXGsRpH54rvIjyy9yyR@eBZbGYyW9@KRkXGVr@gbsU98NCWdNRzWyURxMliXjnM9eQrQOf/oBw4AsFcVQ4pKChN6W2mKX8/n8Q/4/oxf06hau8Z8HuXCfoSnm6X972HrT1QKMaySlnNwynBCiJH1Xduvyrtu6Uf@almHr9Hi6Lrsct069n@hTCr1FRreOcrjXe6MP4Dwa2Jnenwi5ca04EHIPuDegbgptAvQQTbFzVDgDCUvlmwCLCfYmmtlqssdSpS1m8C1oHzIElbCAYEZV7kyCNvoj/HiF66B2cBqtd0BbCqgOhShfAFSMKoOakvJ8RRw5/wE "Python 3 – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 182 bytes ``` from itertools import* def f(l):r=cycle('ROPE');return zip_longest(*(''.join(c+''.join(islice(r,max(ord(n)+~ord(c),0)))for c,n in zip(z,z[1:]+(' ',)))for z in zip(*l)),fillvalue=' ') ``` [Try it online!](https://tio.run/##NY/BTsMwDIbve4rcbLcRAnEb6pEziCsg1CXO6pEmUZqirQdevWQbu3y29P2y/KdTGWJ4XCWkuahOIfQ7Axp2xlZaeybzsXLvlsrhu6@UcQBaXY6jksK5xOgnJWOKuTQby0459LTNnTkZzwhvL6/PQE@Zy5yDWiR9@Rj2PBVsEODuECWgaW@bTF4MY9Zjf8SYLQZqf8/TkL4nIhezMjoouZzCRS/vD9vPFkGB/tfLTTaeSDvx/qf3M3c1Qmucy7Wrw0tr2qQsof5yFVpNnDr4CDX6Bw "Python 3 – Try It Online") The function takes its input as a list (or an iterable) of strings and also returns a generator for a sequences of strings, which is almost as good as a list. ## Ungolfed …for better readability of the nested generators. ``` def f(l): r = cycle('ROPE') return zip_longest( *( ''.join( c + ''.join(islice(r, max(ord(n) - ord(c) - 1, 0))) for c, n in zip(z, z[1:] + (' ',))) for z in zip(*l)), fillvalue=' ') ``` ## Explanation 1. The function uses `zip` to transpose the incoming list of lines into a generator of columns. 2. The innermost generator looks at pairs of adjacent characters and… 3. …slices the required amount of *continuous* ROPE out of an (infinite) [`cycle`](https://docs.python.org/3/library/itertools.html#itertools.cycle) generator. 4. After copious amounts of string joining from generators the function re-transposes the list of columns back to a generator or lines and fills missing entries with [`zip_longest`](https://docs.python.org/3/library/itertools.html#itertools.zip_longest). [Answer] # [Stax](https://github.com/tomtheisen/stax), 25 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ÅiV╘ε╢+gA┘♦W[≈{`Co?-φvM«' ``` [Run and debug online!](https://staxlang.xyz/#p=8f6956d4eeb62b6741d904575bf77b60436f3f2ded764dae27&i=%5B%22abc%22+%22bcd%22+%22ddd%22+%22eex%22+%22gfz%22+%22hka%22+%22imh%22%5D%0A&a=1) Input and output are given as space separated lists. Input is the list of rows as required, output is the list of columns as permitted. ## Explanation Uses the unpacked version to explain. ``` M"ROPE"s{2B{Ev|r%b:m~|(,m_s\mJ M Transpose "ROPE" The string "ROPE" s{ mJ Map each column (in the original input) with block, and output with space as the separator 2B All contiguous pairs of current column { m Map each pair with block Ev|r% Pair [j,k] to length of range [j..k-2] b:m Repeat current repeating string to given length ~ Last line gives the result the pair should map to, now store it on the input stack |( Rotate current repeating string `p` times, where `p` is the length of the range [j..k-1] , Fetch back the result _s\ Zip with current column, filling missing element with empty string ``` ]
[Question] [ Standardized testing usually comes with a scan-tron or some type of answer document that records your answer. A computer or human(s) would then check your answers and determine your grade. So here, given a scan-tron and the answer key, determine the score and questions missed if any. A scan-tron is just a document with multiple lines with answers in which the user fills in (in this case, circled). Example: ``` --- 1. |a| b c d --- ``` As you can see, this is question 1 with answer choice `a` selected since it has a box around it. For the challenge, you will be given a scan-tron with `n` questions ( `1 <= n <= 10`) with only four answers denoted as `a`, `b`, `c`, or `d`. The answer key will be given as a string with no spaces and with all lowercase. Example scan-tron with answer key: ``` Scan-tron --- 1. |a| b c d --- --- 2. a |b| c d --- --- 3. a b |c| d --- Answer Key abb ``` You can take in the answer key and scan-tron as separate inputs or in a chosen order as long they can be identified (i.e the answer key is separated from the scan-tron). Scores will be rounded to the nearest tenth of a point. Example output for the above: ``` Score: 66.7 Missed #: 3 ``` Other acceptable answer would be: ``` 66.7 3 ``` or if multiple questions are missed ``` 66.7 3 4 5 ``` as long the question numbers for those missed are separated from the by spaces and not on the same line as the score. **Rules and Specs** * The scan-tron can be inputted as a multi-line string or one question at a time (as a string with newlines is acceptable) * Given a scan-tron and answer key, you must output the score on one line and the question(s) missed on another, with the numbers separated by spaces. If no questions are missed, no question numbers should be outputted * Scores are rounded to the nearest tenth * Selected answers are surrounded by this box: ``` --- | | --- ``` * On the scan-tron, every question takes three spaces (the top and bottom of the box takes two extra lines) * Must work for the above example * Assume that there will always be only one answer boxed **Winning Criteria** Shortest code wins! [Answer] # [Stacked](https://github.com/ConorOBrien-Foxx/stacked), 68 + 1 = 69 bytes ``` '|'split[#'1-]NO neq::size:@z~>*[]YES' '#`out is0 sum z/100*1 nround ``` [Try it online!](https://tio.run/nexus/stacked#VY9BC4JQEITv/ooBD6vCM61OHqJL1zp0ChHyqZBUaj09JEt//aWpkQsLszMfA2tRTCD5WxvjWA7qS4Zr9oJjGwZ1lhDC8F1wzJBIkBqj9@V7sXQRgyVP4V88yFUPSHDCEzBDxms9UF0LpzzPSBOTqm55HZrki2h/QJE9gkDlbRZs2/fGCaPT7ti9Yp7LpkauPKjmjnbhe57jo3iWTZFqrUX1AQ "Stacked – TIO Nexus") +1 for `-p` flag (this script can be executed as `stacked -pe "..."`) Takes two inputs from the top of the stack. Some interesting features: ``` [#'1-]NO [ ]NO do not keep members where #' its length 1- -1 is truthy (in this case, not equal to zero). ``` This yields all letters surrounded by pipes. ``` :size:@z~>*[]YES : duplicate indices of incorrect answers size length of incorrect answers :@z (stored into z) ~> range from 1 to this length * and multiply by this range []YES keep truthy elements ``` This gives us all incorrect question numbers. [Answer] # [Python 2](https://docs.python.org/2/), ~~94~~ 93 bytes -1 byte thanks to L3viathan ``` s,a=input() l=len(s) w=[i+1for i in range(l)if"|%s|"%a[i]not in s[i]] print(l-len(w))*1e2/l,w ``` [Try it online!](https://tio.run/nexus/python2#VcvBCoMwEATQu1@xBISkTSzas18Sc0isloWwirF42X@3DYrQ2zDzZk/at0jzZ5WqiG0cSCZVbK3Fez1OCyAgweLpPciocBRcJhalt@hoWvOWftEV84K0ymjyf1PqVg/NI@pt360VAGCM6aiugD1DgB5eHR2t0Hk@QVOBBw58gT9yomdGAbjnCx3MaeFDEO4L "Python 2 – TIO Nexus") [Answer] # [Pip](https://github.com/dloscutoff/pip), ~~49~~ ~~46~~ ~~44~~ ~~48~~ 45 bytes Ugh, that rounding takes so many bytes... 44 bytes of code, +1 for `-s` flag. ``` (/2+m-m/#b*#P_FI{++nbNa?un}MZa@`\|..`b)//1/t ``` Takes input as command-line arguments (the scan-tron page will need quoting and escaping of newlines if you run it from an actual command line). Outputs the missed questions first, then the score. [Try it online!](https://tio.run/nexus/pip#jYy7CsJAEEX7fMWFNOoyuyQ@Wq0EC8VaBDOz2yaNWjl@@4hsAkkh2J2Zc7g2C7VrqQ2lLMrzbX94OdfJibfP7n288K65qveNzEOowsPM6G4AiKioPJQVgohU9D@gh9qDoaKDHOmMy28g0KhDMEnyscpRhCadmhGu/1na/FoyFuGYPg "Pip – TIO Nexus") ### Explanation I'm gonna do this in two parts: the incorrect questions list and the score. ``` P_FI{++nbNa?un}MZa@`\|..`b a,b are cmdline args, u is nil, n is newline (implicit) Note that a string like n, in math contexts, is equivalent to 0 a@`\|..` Find all occurrences in a of | followed by 2 chars Because regex matches don't overlap, this does what we need { }MZ b Zip with b and map this function to each pair of items: ++n Increment n (so the first time through, it's 1) bNa Is 2nd arg a substring of 1st? ?un If so, return nil; if not, return n Now we have a list containing nil for correct questions and the question number for incorrect questions _FI Filter on identity function (keep only truthy values) P Print, joining on spaces (-s flag) (/2+m-m/#b*#...)//1/t a,b are cmdline args, m is 1000 (implicit) ... The code from the first part # Length of that list (i.e. number of incorrect questions) m/#b* Times 1000/(number of questions) m- Subtracted from 1000 /2+ Plus 1/2 (= 0.5) We now have a number like 667.1666666666667 ( )//1 Int-divide by 1 to truncate /t and divide that by 10 Print (implicit) ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 43 bytes ``` U|3ôø`\vyy'|k>èXNèQˆ}¯OXg/3°*2z+ïT/XgL¯_Ï‚» ``` [Try it online!](https://tio.run/nexus/05ab1e#@x9aY3x4y@EdCTFllZXqNdl2h1dE@B1eEXi6rfbQev@IdH3jQxu0jKq0D68P0Y9I9zm0Pv5w/6OGWYd2//@fmJScAsZcCgoKurq6XIZ6CjWJNQpJCskKKTAxBQUow0hPIVGhJqkGJokkDWEagxQkKdQk18AUoCiBcEwwTMFikimaO7CaZEaMSebEuMmCGJMssbsJAA "05AB1E – TIO Nexus") **Explanation** ``` U # store the answer key in X |3ô # split the question-rows in chunks of 3 ø` # zip and flatten \ # discard top of stack, leaving the list of # answer rows on top v # for each answer row y'|k # get the index of the first "|" y >è # get the character after that from the row XNèQ # compare it to the corresponding entry in # the answer key ˆ # add it to the global list } # end loop ¯O # calculate the number of correct answers Xg/ # divide by the length of the answer key 3°* # multiply by 1000 2z+ # add 0.5 ï # convert to integer T/ # divide by 10 XgL # push range [1 ... len(answer key)] ¯_Ï # keep only numbers corresponding to # wrong answers ‚» # format output ``` [Answer] ## Batch, 242 bytes ``` @echo off set/as=c=0 set m= set/pk= :l set/ac+=1 set/pt= set/pl= set/pt= set "l=%l:*|=% if %l:~,1%==%k:~,1% (set/as+=1)else set m=%m% %c% set k=%k:~1% if not "%k%"=="" goto l set/as=(s*2000/c+1)/2 echo(%s:~,-1%.%s:~-1% echo(%m% ``` Reads in the answer key on STDIN first, then `n*3` question rows. Note: Score is printed without a leading zero if it is less than `1.0`. Missed answers are printed with a leading space. [Answer] ## JavaScript (ES6), 88 bytes ``` x=>y=>x.replace(/\w(?=\|)/g,c=>c==y[i++]?t++:a+=i+" ",a=i=t="")&&(t/i*1e3+.5|0)/10+` `+a ``` I could save 5 bytes by using commas and returning everything one one line: ``` x=>y=>x.replace(/\w(?=\|)/g,c=>c==y[i++]?t++:a+=[,i],a=i=t="")&&(t/i*1e3+.5|0)/10+a ``` [Answer] # [CJam](https://sourceforge.net/p/cjam), ~~47~~ 45 bytes ``` lqN/(;3%_'|f#:).=.=__:+\,d/e2XmOn:!_,,:).*0-p ``` [Try it online!](https://tio.run/nexus/cjam#@59T6KevYW2sGq9ek6Zspalnq2cbH2@lHaOTop9qFJHrn2elGK@jA5TQMtAt@P8/MSmJS0FBQVdXl8tQT6EmsUYhSSFZIQUmpqAAZRjpKSQq1CTVwCSRpCFMY5CCJIWa5BqYArA4AA "CJam – TIO Nexus") **Explanation** The program is in three main parts: ``` Right/wrong list l e# Read the first line of input (answer key) qN/ e# Read the rest of the input and split it on newlines (;3% e# Delete the first line, then select every 3rd line _ e# Duplicate the array '|f# e# Find the index of the first | in each answer :) e# Increment each, gives the index of the selected letter for each answer .= e# Vectorized get-element-at with the answer strings .= e# Vectorized equality check with the answer key ``` After this section, we have an array of `0`s and `1`s, where `0` indicates a wrong answer and `1` a right answer. ``` Score __ e# Duplicate the right/wrong list twice :+ e# Take the sum of it (number of right answers) \, e# Swap top elements and take the length (total number of questions) d/ e# Divide (casting to double so it's not integer division) e2 e# Multiply by 10^2 XmO e# Round to 1 decimal place n e# Pop and print with a newline ``` After this section, the stack contains only the right/wrong list, and the percentage score has been output. ``` Wrong answers :! e# Logically negate each element of the right/wrong list _,,:) e# Generate the inclusive range 1...length(list) .* e# Vectorized multiplication of the two lists 0- e# Remove any 0s from the result p e# Print it ``` [Answer] # Jolf, 46 bytes I can't seem to break 46 bytes. I have two solutions of this length. [Try one here!](http://conorobrien-foxx.github.io/Jolf/#code=zoZSzrPPiH5tzpYgbWnCq1x8Li7Cu2Q_PeKCrEgueFNFaFNkSM6uU21YKn4xLy1szrZszrNszrZfMQ&input=ICAgLS0tCjEuIHxhfCBiIGMgZAogICAtLS0KICAgICAtLS0KMi4gYSB8YnwgYyBkCiAgICAgLS0tCiAgICAgICAtLS0KMy4gYSBiIHxjfCBkCiAgICAgICAtLS0KCiJhYmIi) ``` ΆRγψ~mΖ mi«\|..»d?=€H.xSEhSdHήSmX*~1/-lζlγlζ_1 ``` (Replace `□` with `0x7f` in the next one) ``` ΆRγψΜΖψGi'|d=1lHd?□=H.xShSEdHήSmX*~1/-lζlγlζ_1 ``` In either case, 15 bytes for rounding: `mX*~1/-lζlγlζ_1`. They are, for the most part, the same, except one uses a regex match to get the results, and the other splits on pipes. ]
[Question] [ **This question already has answers here**: [Smallest palindrome divisible by the input](/questions/91023/smallest-palindrome-divisible-by-the-input) (41 answers) Closed 7 years ago. # Goal: Given any non-zero natural number `a`, find the smallest non-zero natural number `b` such that `a•b` is palindromic, e.g. it reads the same forwards and backwards. Input `a` through any reasonable means (STDIN, function argument, etc.), And output `b` through any reasonable means (STDOUT, function return value.) # Notes: * Input will not always have a solution (multiples of 10), so you must create an error, or display -1/0 * Input validation is not necessary, assume `a` is a natural number. * Standard loopholes apply (Hardcoding, using a language created after this challenge) # Examples: ``` a=34, b=8 (272) a=628, b=78 (48984) a=15, b=35 (525) a=33, b=1 (33) a=20, (Error, -1, or 0) ``` [Answer] # Pyth, ~~10~~ 9 bytes ``` &eQf_I`*Q ``` [Try it online.](http://pyth.herokuapp.com/?code=%26eQf_I%60%2aQ&input=628&debug=0) ### Explanation ``` &eQf_I`*QT Implicitly append T, and take input in Q. eQ Calculate input mod 10. & Logical and, only evaluate the following if result ≠ 0. f Starting from 1, find the first integer T for which... ` ...the string representation of... *QT ...input multiplied by T... _I ...is equal to its reverse. ``` [Answer] ## Ruby, 51 bytes ``` ->a{(1..a%10/0.0).find{|b|(c="#{a*b}")==c.reverse}} ``` ### Explanation ``` a%10/0.0 # -> NaN for multiples of 10, Infinity otherwise ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 11 bytes ``` T% # input mod 10 0› # is greater than 0 µ # repeat the following until counter reaches that number (0 or 1) ¹N* # input * iteration ÂQ # is equal to its reverse ½ # if true, increase counter # implicitly output last iteration (or 0) ``` [Try it online!](https://tio.run/nexus/05ab1e#@x@iavCoYdehrYd2@mkdbgo8tPf/fzMjCwA "05AB1E – TIO Nexus") [Answer] # C, ~~108~~ 101 bytes *Thanks to @nmjcman101 for 7 bytes!* ``` m,o;f(n){for(o=0;n;)o=o*10+n%10,n/=10;return o;}g(n){m=-1;if(n%10)for(m=1;n*m!=f(n*m);m++);return m;} ``` Is C the only language here with no built-in reversing/checking palindrome function? [Try it online!](https://tio.run/nexus/c-gcc#NcsxCsMwDIXhq7SBgGS71KLdhA5TSBw8SComnULOnjhD1/f@79DkXMBwK97AJbMxunigHG2knOwplLnN66/ZzXlfrlblQVw76wVeUIXYgt6lb0GRNUb8I@X90E81wO3bqq0FhnEa0gKvN2L/Tg "C (gcc) – TIO Nexus") [Answer] ## [QBIC](https://drive.google.com/drive/folders/0B0R1Jgqp8Gg4cVJCZkRkdEthZDQ), 29 bytes ``` :{c=a*q~!c$=_f!c$||_Xq\q=q+1 ``` Explanation: ``` : Get cmd line param as number 'a' { DO c=a*q multiply 'a' by 'q' and assign to 'c', which is 1 at the start of a QBIC program ~ IF !c$ 'c' cast to string = equals _f!c$| 'c' cast to string, the reversed | THEN _Xq Quit, printing 'q' \q=q+1 ELSE increment q and rerun DO Loop is auto-closed by QBIC, as is the IF ``` Eventually, 'q' will overflow and throw an error on an unsolvable 'a'. [Answer] # Python 2, ~~78~~ ~~66~~ 60 bytes ``` def f(a): b=a%10!=0 while `a*b`!=`a*b`[::-1]:b+=1 print b ``` [Try it online](https://tio.run/nexus/python2#@5@SmqaQppGoacWlkGSbqGpooGhrwKVQnpGZk6qQkKiVlKBoC6airax0DWOtkrRtDbkUCooy80oUkv6naRibaHKlaZgZWYAoQ1MQaWwMIo0MNP9zcQEA) [Answer] ## Java, 113 bytes ``` i->{int j=1;for(String a;!new StringBuilder(a=String.valueOf(i*j)).reverse().toString().equals(a);)j++;return j;} ``` [Answer] ## Mathematica, 43 bytes ``` If[10∣#,0,#//.x_/;!PalindromeQ@x:>x+#]/#& ``` ### Explanation ``` If[10∣#,0,...]/#& ``` If the input is a multiple of 10, return 0 (divided by the input). ``` #//.... ``` Otherwise, repeatedly apply the following substitution to the input. ``` x_/;!PalindromeQ@x ``` Match a value which is not a palindrome. ``` ...:>x+# ``` And replace that value with itself plus the input. This repeated substitution therefore searches through consecutive multiples of the input until it finds a palindrome. ``` .../# ``` Finally, to figure out `b` we simply divide the result by the input again. [Answer] ## Python 2, 68 bytes ``` x,y=input(),1 if not x%10:x+'' while `x*y`!=`y*x`[::-1]:y+=1 print y ``` Outputs an error if input is a multiple of 10. [Answer] # Haskell, ~~67~~ 66 bytes ``` f a|a`mod`10==0=0|1>0=[b|b<-[1..],show(a*b)==reverse(show$a*b)]!!0 ``` Returns 0 if `a` is a multiple of 10. Will check from 1 to infinity for `b` if the textual reverse of `a*b` is the same as `a*b`. ]
[Question] [ The goal is simple: Output a nonzero real solution `x` to the equation `sin(x) = -mx`, given input `m`, in the fewest number of bytes. Specifications: * Your answer must be correct to 3 significant figures. * You may output any real solution other than the trivial solution `x=0`. You can assume `m` is such that at least one solution exists. You may also assume `m!=0`. An obviously suboptimal python solution using *gradient descent*: ``` from math import * from random import * a=x=0.001 m = 5. def dE(x):return 2*(sin(x)+m*x+1)*(cos(x)+m) for i in xrange(1000): x-=dE(x)*a print x ``` Test cases ``` -0.25 -> ±2.4746 -0.1 -> ±2.8523 or ±7.0682 or ±8.4232 0.2 -> ±4.1046 or ±4.9063 ``` [Answer] ## Haskell, 34 bytes ``` f m=until(\x->sin x< -m*x)(+1e-3)0 ``` Counts `x` up from 0 by 0.001 until `sin(x)< -m*x`. Ouput examples ``` f -0.2 -> 2.595999999999825 f -0.1 -> 2.852999999999797 f 0.0 -> 3.141999999999765 f 0.1 -> 3.4999999999997256 f 0.2 -> 4.1049999999997056 ``` [Answer] # Mathematica, 28 bytes ``` x/.FindRoot[Sinc@x+#,{x,1}]& ``` Searches for a numerical root from the initial guess `x=1`. Test cases: ``` % /@ {-0.25, -0.1, 0.2} (* {2.47458, 2.85234, 4.10462} *) ``` [Answer] # [ised](http://ised.sourceforge.net/): ~~32~~ 28 bytes Using Newton's iteration starting from π: ``` {:x-{sinx+$1*x}/{cosx+$1}:}:::pi ``` The argument is passed in `$1`, which can be taken from a file, like this: ``` ised --l inputfile.txt 'code' ``` A bit less stable, but shorter version: ``` {:{x-tanx}/{1+$1/cosx}:}:::pi ``` Sometimes it throws iteration limit warnings but the accuracy seems fine considering the conditions. Unicode version (same bytecount): ``` {λ{x-tanx}/{1+$1/cosx}}∙π ``` Starting from 4 cuts another byte and seems to converge to the same values ``` {λ{x-tanx}/{1+$1/cosx}}∙4 ``` [Answer] # C, 99 bytes ``` #include<math.h> float f(float m){float x=1,y;do{x=(y=sin(x)+m*x)+x;}while(fabs(y)>1e-4);return x;} ``` ungolfed: ``` #include<math.h> float f(float m){ float x=1,y; do{x=(y=sin(x)+m*x)+x;}while(fabs(y)>1e-4); return x; } ``` [Answer] # [MATL](http://github.com/lmendo/MATL), 17 bytes ``` `@2e3/tY,wG_*>}4M ``` This uses linear search on the positive real axis, so it is slow. All test cases end within 1 minute in the online compiler. [Try it online!](http://matl.tryitonline.net/#code=YEAyZTMvdFksd0dfKj59NE0&input=LTAuMjU) ### Explanation ``` ` % Do...while @ % Push iteration index, starting at 1 2e3/ % Divide by 2000 t % Duplicate Y, % Sine w % Swap G_* % Multiply by minus the input > % Does the sine exceed that? If so, next iteration } % Finally (execute after last iteration, before exiting loop) 4M % Push input of sine function again % Implicit end % Implicit display ``` [Answer] # C++ 11, ~~92~~ 91 bytes -1 byte for using `#import` ``` #import<cmath> using F=float;F f(F m,F x=1){F y=sin(x)+m*x;return fabs(y)>1e-4?f(m,x+y):x;} ``` [Answer] # Python 2, ~~81~~ 78 bytes ### Fixpoint iteration As recursive lambda ``` from math import* f=lambda m,x=1:abs(sin(x)+m*x)>1e-4and f(m,sin(x)+m*x+x)or x ``` As loop (81 bytes): ``` from math import* m=input() x=1 while abs(sin(x)+m*x)>1e-4:x=sin(x)+m*x+x print x ``` [Answer] # Mathematica, 52 bytes ``` NSolve[Sin@x==-x#,x,Reals][[;;,1,2]]~DeleteCases~0.& ``` Anonymous function. Takes a number as input, and returns a list of numbers as output. Just uses `NSolve` to solve the approximate equation. [Answer] # Axiom, 364 bytes ``` bisezione(f,a,b)==(fa:=f(a);fb:=f(b);a>b or fa*fb>0=>"fail";e:=1/(10**(digits()-3));x1:=a;v:=x2:=b;i:=1;y:=f(v);if(abs(y)>e)then repeat(t:=(x2-x1)/2.0;v:=x1+t;y:=f(v);i:=i+1;if i>999 or t<=e or abs(y)<e then break;if fb*y<0 then(x1:=v;fa:=y)else if fa*y<0 then(x2:=v;fb:=y)else break);i>999 or abs(y)>e=>"fail";v) macro g(m) == bisezione(x+->(sin(x)+m*x), 0.1, 4.3) ``` ungolf ``` bisezione(f,a,b)== fa:=f(a);fb:=f(b) a>b or fa*fb>0=>"fail" e:=1/(10**(digits()-3)) x1:=a;v:=x2:=b;i:=1;y:=f(v) if(abs(y)>e) then repeat t:=(x2-x1)/2.0;v:=x1+t;y:=f(v);i:=i+1 if i>999 or t<=e or abs(y)<e then break if fb*y<0 then(x1:=v;fa:=y) else if fa*y<0 then(x2:=v;fb:=y) else break i>999 or abs(y)>e=>"fail" v macro g(m) == bisezione(x+->(sin(x)+m*x), 0.1, 4.3) ``` results ``` (3) -> g(0.2) AXIOM will attempt to step through and interpret the code. (3) 4.1046198505 579058527 Type: Float (4) -> g(-0.1) (4) 2.8523418944 500916556 Type: Float (5) -> g(-0.25) (5) 2.4745767873 698290098 Type: Float ``` [Answer] ## Haskell, 50 bytes I just learned about newton's method in my calc class, so here goes in `haskell` using newton's method. `f m=foldl(\x _->x-(sin x+m*x)/(cos x+m))0[1..10]` [Answer] # [Scala](https://www.scala-lang.org/), 68 bytes Modified from [@xnor's Haskell answer](https://codegolf.stackexchange.com/a/97654/110802). --- Golfed version. [Try it online!](https://tio.run/##bY9BC4JAFITv/op33C1ctG7CCkHXThEdIuKpz9zYXWXdwgh/u4ke9TTMxzDMtDlqHOrsRbmHEyoLvwCgoBLMaBi6Z5vAwTn83s7eKfu88wQuVnmQUxKgGanXlpUsjMSO8yWMFzAS0Qpby82FfRB8UEOZwLF@Z5pkOivIwch0HEZohPLk0NNUzh7bmMI9F4Wrm2ulNLFOpgZ9JdrxVsdTCWG3MVxUhMXQD38) ``` m=>Stream.iterate(0.0)(_+1e-3).dropWhile(x=>math.sin(x)>= -x*m).head ``` Ungolfed version. [Try it online!](https://tio.run/##dZBLC8IwEITv/RVzTLQtrd6KCopXT@JJRGJNayRNpI0Qkf72al8KPk7ZzH6Z2U0RM8mqSh/OPDZYMaFwd4AjT5A9L4TlaRFhnufstl2bXKh0RyNslDCYNiRweapGKpIQL/BHlH6L4ZcY@MEP7RfXGpZON1RCsghLfT1ITvviNUkNXJURksRaHYURWr2ZGRZaS86UCxZ/ttrKhf1vDogEb2NiKYXtOlwW/DO5j@nP@kGDN7ugw22dvmLm5BeiRjCBl2EA62KPIULujV0E7ReUTlU9AA) ``` object Main { def main(args: Array[String]): Unit = { println(f(-0.2)) println(f(-0.1)) println(f(0.0)) println(f(0.1)) println(f(0.2)) } def f(m: Double): Double = { def until(condition: Double => Boolean, action: Double => Double, x: Double): Double = { if (condition(x)) x else until(condition, action, action(x)) } until(x => Math.sin(x) < -m * x, _ + 1e-3, 0) } } ``` ]
[Question] [ Your task is to create a program that adds random numbers to previous sums in the ultimate number racing showdown. Each racer (column) starts at 0 and adds either 1 or 0 to the previous sum at each step of the race until all of the racers reach the score required to win. The 1 or 0 should be chosen at random (the standard definition of random can be found [here](http://meta.codegolf.stackexchange.com/questions/1324/standard-definitions-of-terms-within-specifications/1325#1325)). The output will show the result of the race, with each column representing one racer, in this format: ``` >> racers:5,score needed:2 0 0 0 0 0 # all racers start at 0 + + + + + # add 1 0 0 0 1 # random 1 or 0 = = = = = # equals 1 0 0 0 1 # sum + + + + + 0 0 0 0 1 = = = = = 1 0 0 0 2 # winner! + + + + 1 1 1 1 = = = = 2 1 1 1 + + + 1 1 1 = = = 2 2 2 # losers ``` *Note: only the numbers, +, and = need to be included in the output.* ## Input Your program will accept the following two parameters as input: 1. the number of racers (columns), which must be greater than two 2. the score required to win, which must be greater than one This is code-golf--the program with the least bytes wins. *Edit: there's a non-enforceable max score of 9--this is to preserve the integrity of the column. Also, spaces between columns can be omitted in the output.* [Answer] ## Jelly, ~~37~~ ~~36~~ 33 bytes ``` ,‘X 0Ç<³$пµżIFµ“+=”ṁṖ⁸żF ÇСḊz⁶G ``` 3 bytes thanks to Dennis. [Try it online](http://jelly.tryitonline.net/#code=LOKAmFgKMMOHPMKzJMOQwr_CtcW8SUbCteKAnCs94oCd4bmB4bmW4oG4xbxGCsOHw5DCoeG4inrigbZH&input=&args=Mg+NQ) ## Explanation ``` ,‘X Helper link. Argument: n. Radomly return n or n+1. ‘ Increment n , Pair. Yield [n, n+1] X Return a random item from the pair. 0Ç<³$пµżIFµ“+=”ṁṖ⁸żF Monadic link. Argument: s. Generate one racer. 0 Start with value 0. <³$пµ While value is less than s: Ç Use helper link to increment current value. Collect intermediate results in a list. I Compute consecutive differences. ż Zip intermediate results with their next increment value 0 or 1. Fµ Flatten. Let's call the current list A. Odd items of A are racer state and even items are random 0 or 1. “+=” Yield "+=". Ṗ Yield A without its last element. ṁ Mold i.e Repeat the characters of the string until it contains length(A)-1 characters. ⁸ż Zipwith. Pair the elements of A with the correponding characters F Flatten. ÇСṫ2z” G Main link. Arguments: s (score needed), r (#racers) ÇС Call the link above r times. Generate a list of r racers. Ḋ Remove first element of the list (its a garbage s value) z⁶ Transpose with space as fill value. G Grid. Format the result. ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), ~~38~~ 34 bytes ``` ~~j.tm+j\=jL\+C,.u+NYJ.WnsHQ+ZO2Y0J+\=QE~~ j.tmj\=jL\+.T,.u+NYJ.WnsHQ+ZO2Y0JE ``` [Try it online!](http://pyth.herokuapp.com/?code=j.tmj%5C%3DjL%5C%2B.T%2C.u%2BNYJ.WnsHQ%2BZO2Y0JE&input=2%0A5&debug=0) [Answer] ## TSQL, ~~367~~ ~~345~~ 341 bytes Golfed ``` DECLARE @r int=20, -- racers @g char=2 -- goal DECLARE @ varchar(99)=REPLICATE('0',@r)a:PRINT @ DECLARE @A varchar(99)='',@s varchar(99)='',@i int=0WHILE @i<@r SELECT @i+=1,@A+=char(43-x*11),@s+=IIF(x=1,' ',LEFT(y,1)),@=RIGHT(@,@r-1)+IIF(x=1,' ',REPLACE(LEFT(@,1)+y,@g+1,' '))FROM(SELECT IIF(LEFT(@,1)IN('',@g),1,0)x,ROUND(RAND(),0)y)z PRINT @A+' '+@s+' '+REPLACE(@A,'+','=')IF @>''goto a ``` [Try it online](https://data.stackexchange.com/stackoverflow/query/503194/downward-number-race) Ungolfed: ``` DECLARE @r int=10, -- racers @g char=2 -- goal DECLARE @ varchar(99)=REPLICATE('0',@r) a: PRINT @ DECLARE @A varchar(99)='',@s varchar(99)='',@i int=0 WHILE @i<@r SELECT @i+=1, @A+=char(43-x*11), @s+=IIF(x=1,' ',LEFT(y,1)), @=RIGHT(@,@r-1)+IIF(x=1,' ',REPLACE(LEFT(@,1)+y,@g+1,' ')) FROM(SELECT IIF(LEFT(@,1)IN('',@g),1,0)x,ROUND(RAND(),0)y)z PRINT @A+' '+@s+' '+REPLACE(@A,'+','=') IF @>''GOTO a ``` Note that the random seed on the test site will always be the same, giving the same result each time, in studio management it will give different results. Can use different values for racers and goal to get a different picture [Answer] # Python 3, 237 bytes ``` from random import* def f(n,t): x='0'*n,;i=j=0;y='' while' '*n!=x[i]: if j==n:j=0;x+=y,;y='';print(x[i]);i+=1 y+=' 'if x[i][j]in(' ',str(t))else eval(["'+'","str(randint(0,1))","'='","str(int(x[i-3][j])+int(x[i-1][j]))"][i%4]);j+=1 ``` A function that takes input via argument and prints to STDOUT. This approach makes use of the fact that the output follows a cycle of period four, of the form '+ value = value', for all racers. By using a counter modulo four, a list containing the desired value for each step as a string can be indexed into, and the result evaluated using Python's eval function. **How it works** ``` from random import* Import Python's random module to access the randint function def f(n,t): Function with input number of racers n and target number t x='0'*n,;i=j=0;y='' Initialise return tuple storage x, state number i, racer number j and append string y for x while' '*n!=x[i]: Loop through all j for some i. If the current state consists only of spaces, all racers have finished, so stop y+=...eval([...][i%4])... Index into list, using i mod 4, to find the desired process for the cycle step, and append to y (If first step of cycle) ...+... Plus sign (If second step of cycle) ...str(randint(0,1))... Random number from (0,1) (If third step of cycle) ...=... Equals sign (If fourth step of cycle) ...str(int(x[i-3][j])+int(x[i-1][j]))... Addition of random number to previous racer 'score' ...' 'if x[i][j]in(' ',str(t))... But append space if the racer has previously finished, or has reached the target ...j+=1 Increment j if j==n:j=0;x+=y,;y='';print(x[i]);i+=1 If j=n, all j must have been looped through. Reset j, append new state y to x, reset y, print current state to STDOUT and increment i. When this first executes, x contains only the initial state, meaning that this is printed and the cycle starts with the second state. ``` [Try it on Ideone](https://ideone.com/2L4pAw) [Answer] # [Python 2](https://docs.python.org/2/), 191 bytes ``` from random import* def c(p,w,r=[],l=0): while p: p-=1;s='0' while`w`>s[-1]:s+="+%s="%randint(0,1);s+=`eval(s[-4:-1])`;l+=2 r+=[s] for z in map("".join,zip(*(t+l*' 'for t in r))):print z ``` [Try it online!](https://tio.run/##HczfCoMgHIbh47yKH0GkaaNiOzHcjURQ9Ic5TEVlsW6@2Y4@eHn47De8jG7Oc3VmAzfqOY7crHGhQPOywoQt25kTXc@UqAhHsL@kWsBylNhS1K0XeZWj5F@HfXj6rqx77qlIaeZFml2fUgdcsZq0MQ/LZ1Q4qjuPkAytoqJBiaOi8z2C1Tg4QGrYRovT9PY2UrNDWlzgQFWRQ36JcAlHCOHWxXM4zgk/WEPOHw "Python 2 – Try It Online") --- # [Python 3](https://docs.python.org/3/), 200 bytes ``` from random import* def c(p,w,r=[],l=0): while p: p-=1;s='0' while str(w)>s[-1]:s+="+%s"%randint(0,1);s+="=%s"%eval(s[-3:]);l+=2 r+=[s] for z in map("".join,zip(*(t+l*' 'for t in r))):print(z) ``` [Try it online!](https://tio.run/##JYzNCoMwEAbvPsUiFLMmLVrpRUlfRDyIPzQlJmETKvXlbUJP@@0wjPuGlzXNea5kN6DRzPGozVkKZTYvK0zMiV2Q7AehZYVtBvtL6QVcXOCusu68LKoiPn/uA7Edn76/1kPrucz5xeeXFFYmsErU2CUqE10@o2bRbNoBO83lPVaIy94PGayW4ABlYBsdy/Pb2yojDuVYyQLXZQFFMkIyCBFbR6l/4Dmxh7jj@QM "Python 3 – Try It Online") [Answer] **Python 2, 278 bytes** ``` import random r=5 w=2 s=(0,)*r while s.count(w)<len(s): print ''.join(map(lambda a:str(a),s))+"\n"+'+'*len(s) s = tuple(map(lambda x: x<w and x+random.randrange(2) or x,s)) print ''.join(map(lambda a:str(a), s))+"\n"+'='*len(s) s = tuple([x for x in s if x!= w]) ``` where r is the no. of racers and w is the score to win [Try it here!](http://www.tutorialspoint.com/execute_python_online.php) [Answer] # [Perl 5](https://www.perl.org/), 150 bytes ``` $,=$";say@n=(0)x(@e=('=')x(@p=('+')x<>));$t=<>;while(grep$_<$t,@n){@r=map{$_+=($g=0|rand 2);$g}@n;for$l(p,r,e,n){say map{$n[$_]>$t?$":$$l[$_]}0..$#n}} ``` [Try it online!](https://tio.run/##HY3RCoIwGEbvewqpH9xwyUq8af62F@gJIkRombDmmEKF7dVbs7vzwTl8VjldhgAMYS3G9i0NEk5fRCokKaYL2UhZpKqmVMCEVS2e914r0jlloalgYtLQWTp8tHaGJkMCHfKPa8012cek89KI2@BAE8scUyza8Sr56@YMzaWG6QjrA4Belud5DhvjfQjFqvgOduoHM4btqcz5jv8A "Perl 5 – Try It Online") First input is number of racers, second is score needed. ]
[Question] [ The Knödel numbers are a set of sequences. Specifically, the Knödel numbers for a positive integer \$n\$ are the set of composite numbers \$m\$, such that all \$i < m\$, [coprime](https://en.wikipedia.org/wiki/Coprime_integers) to \$m\$, satisfy \$i^{(m-n)} \equiv 1 \mod m\$. The set of Knödel numbers for a specific \$n\$ is denoted \$K\_n\$. ([Wikipedia](https://en.wikipedia.org/wiki/Kn%C3%B6del_number)). For example, \$K\_1\$ are the [Carmichael numbers](https://en.wikipedia.org/wiki/Carmichael_number), and [OEIS A002997](https://oeis.org/A002997). They go like: \$\{561, 1105, 1729, 2465, 2821, 6601, ... \}\$. \$K\_2\$ is [OEIS A050990](https://oeis.org/A050990) and goes like, \$\{4, 6, 8, 10, 12, 14, 22, 24, 26, ... \}\$. ## Your task Your task is to write a program/function/etc. that takes two numbers, \$n\$ and \$p\$. It should return the first \$p\$ numbers of the Knödel Sequence, \$K\_n\$. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins! ## Examples ``` 1, 6 -> [561, 1105, 1729, 2465, 2821, 6601] 2, 3 -> [4, 6, 8] 4, 9 -> [6, 8, 12, 16, 20, 24, 28, 40, 44] 3, 1 -> [9] 3, 0 -> [] 21, 21 -> [45, 57, 63, 85, 105, 117, 147, 231, 273, 357, 399, 441, 483, 585, 609, 651, 741, 777, 861, 903, 987] ``` [Answer] # Pyth, ~~29~~ 28 bytes ``` .f&tPZ!f&q1iTZt%^T-ZQZSZvzhQ ``` *1 byte saved thanks to Jakube and orlp.* [Demonstration.](https://pyth.herokuapp.com/?code=.f%26tPZ!f%26q1iTZt%25%5ET-ZQZSZvzhQ&input=5%0A21&debug=0) Input in the form ``` p n ``` A fairly straightforward calculation. Relative primeness is checked via Pyth's gcd function. This code showcases `.f`, Pyth's "first n satisfying" function. I have incorporated the implicit condition that `m > n` by starting the search for `m` values at `n + 1`. [Answer] # Haskell, 89 bytes Very straightforward implementation. Defines a binary operator `n!p`. ``` n!p=take p[m|m<-[n+1..],any((<1).mod m)[2..m-1],and[i^(m-n)`mod`m<2|i<-[1..m],gcd i m<2]] ``` Example: ``` Prelude> 4!9 [6,8,12,16,20,24,28,40,44] ``` [Answer] # Haskell, 90 ``` a#b=gcd a b>1 n!p=take p[m|m<-[n+1..],any(m#)[2..m-1],all(\i->m#i||mod(i^(m-n))m<2)[1..m]] ``` much the same as @Marius 's answer, though developed independently. ]
[Question] [ You should write a program or function which receives a list of digits as input and outputs or returns the largest sum achievable by putting these digits in a square. Input will always contain a square number of digits. An example square arrangement for the input `9 1 2 3 4 5 6 7 7` could be ``` 677 943 125 ``` The sum is calculated as the sum of all rows and columns. For the above arrangement the sum would be `677 + 943 + 125 + 691 + 742 + 735 = 3913`. Note that this is not the maximal sum so this isn't the expected output. ## Input * A list with length `n^2` (`n>=1`) containing non-zero digits (`1-9`). ## Output * An integer, the largest sum achievable with the input digits put in a square. ## Examples Example format is `input => output`. ``` 5 => 10 1 2 3 4 => 137 5 8 6 8 => 324 9 1 2 3 4 5 6 7 7 => 4588 2 4 9 7 3 4 2 1 3 => 3823 8 2 9 4 8 1 9 3 4 6 3 8 1 5 7 1 => 68423 5 4 3 6 9 2 6 8 8 1 6 8 5 2 8 4 2 4 5 7 3 7 6 6 7 => 836445 ``` This is code golf so the shortest entry wins. [Answer] # Pyth, 15 bytes ``` s*VSsM^^LTUQ2SQ ``` [Demonstration.](https://pyth.herokuapp.com/?code=s*VSsM%5E%5ELTUQ2SQ&input=9%2C1%2C2%2C3%2C4%2C5%2C6%2C7%2C7&debug=0) [Test harness.](https://pyth.herokuapp.com/?code=FQ%2B%5DQ.Q%0As*VSsM%5E%5ELTUQ2SQ&input=5%2C%0A1%2C2%2C3%2C4%0A5%2C8%2C6%2C8%0A9%2C1%2C2%2C3%2C4%2C5%2C6%2C7%2C7%0A2%2C4%2C9%2C7%2C3%2C4%2C2%2C1%2C3%0A8%2C2%2C9%2C4%2C8%2C1%2C9%2C3%2C4%2C6%2C3%2C8%2C1%2C5%2C7%2C1%0A5%2C4%2C3%2C6%2C9%2C2%2C6%2C8%2C8%2C1%2C6%2C8%2C5%2C2%2C8%2C4%2C2%2C4%2C5%2C7%2C3%2C7%2C6%2C6%2C7&debug=0) Note: Input in any python sequence format, such as `a,b,c,` or `[a, b, c]`. Fails on `a`. This will be an explanation for the example input `5,8,6,8`. `^LTUQ`: This is a list of powers of 10, out to the length of `Q`. `[1, 10, 100, 1000]`. `^ ... 2`: Then, we take pairs of powers of 10. `[[1, 1], [1, 10], ...`. `sM`: Then, we sum those pairs. `[2, 11, 101, ...` Each number repesents the value of a grid location. The value of the bottom right corner is 2, because the digit placed there is in the ones place of the two numbers it is in. Note that 16 values were generated, even though we only need 4. This will be handled shortly. `S`: Sort the value in increasing order. `[2, 11, 11, 20, 101, ...`. Note that the only values which are relevant for this input are the first 4, because this square will not have hundreds or thousands places. `SQ`: Sort the input in ascending order. `[5, 6, 8, 8]` `*V`: Vectorized multiplication over the two lists. Pyth's vectorized multiplication truncates the longer input, so this performs `[5*2, 6*11, 8*11, 8*20]`, equivalent to filling in the grid, smallest to largest, bottom right to top left. `s`: Sum the results, `324`. Printing is implicit. [Answer] # CJam, 23 bytes ``` q~$_,mQ,A\f#2m*::+$.*:+ ``` [Try it online](http://cjam.aditsu.net/#code=q%7E%24_%2CmQ%2CA%5Cf%232m*%3A%3A%2B%24.*%3A%2B&input=%5B2%204%209%207%203%204%202%201%203%5D). Generates the weights for each cell and assigns the highest digits to the highest weights. An alternative 23: ``` q~$_,mQ_,A\f#*_$.+$.*:+ ``` [Answer] # CJam, 25 bytes ``` q~_e!\,mqf/{_z+Afb:+}%$W= ``` Pretty straight forward approach. Generate all combinations, get the sum, print largest. [Try it online here](http://cjam.aditsu.net/#code=q%7E_e!%5C%2Cmqf%2F%7B_z%2BAfb%3A%2B%7D%25%24W%3D&input=%5B2%204%209%207%203%204%202%201%203%5D) [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `G`, 8 bytes ``` Ṗƛ²:∩J⌊∑ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJQRyIsIiIsIuG5lsabwrI64oipSuKMiuKIkSIsIiIsIlwiNTg2OFwiIl0=) Brute force, so pretty slow. ``` Ṗƛ²:∩J⌊∑ Ṗ # get all permutations ƛ # map over them: ² # format as a square (returns a list of strings) :∩J # append the transpose to itself ⌊ # convert each string to an integer ∑ # sum # G flag gets the maximum ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 16 bytes ``` ▲moS(ṁd+)TSCo√LP ``` [Try it online!](https://tio.run/##yygtzv7//9G0Tbn5wRoPdzamaGuGBDvnP@qY5RPw////aFMdCx0zHYtYAA "Husk – Try It Online") # [Husk](https://github.com/barbuz/Husk), 16 bytes ``` Σz*O¹OmΣπ2↑:1İ⁰L ``` [Try it online!](https://tio.run/##ASsA1P9odXNr///Oo3oqT8K5T23Oo8@AMuKGkToxxLDigbBM////WzEsMiwzLDRd "Husk – Try It Online") same idea as isaacg's answer. Somehow both of these are still 1 byte more than Pyth. [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-x`](https://codegolf.meta.stackexchange.com/a/14339/), 13 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Tried a few different approaches with permutations and partitions but, in the end, an adaptation of [isaacg's solution](https://codegolf.stackexchange.com/a/53481/58974) ended up being the shortest. ``` ñ í*¡ApYÃï+ ñ ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LXg&code=8SDtKqFBcFnD7ysg8Q&input=WzUgNCAzIDYgOSAyIDYgOCA4IDEgNiA4IDUgMiA4IDQgMiA0IDUgNyAzIDcgNiA2IDdd) or [run all test cases](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=8SDtKqFBcFnD7ysg8Q&footer=eA&input=WwpbNV0KWzEgMiAzIDRdCls1IDggNiA4XQpbOSAxIDIgMyA0IDUgNiA3IDddClsyIDQgOSA3IDMgNCAyIDEgM10KWzggMiA5IDQgOCAxIDkgMyA0IDYgMyA4IDEgNSA3IDFdCls1IDQgMyA2IDkgMiA2IDggOCAxIDYgOCA1IDIgOCA0IDIgNCA1IDcgMyA3IDYgNiA3XQpdLW1S) ``` ñ í*¡ApYÃï+ ñ :Implicit input of array U ñ :Sort í :Interleave with * :And reduce each pair my multiplication ¡ : Map each 0-based index Y in U A : 10 pY : Raised to the power of Y Ã : End map ï : Cartesian product with itself + : Reduce each pair by addition ñ : Sort :Implicit output of sum of resulting array ``` ]
[Question] [ > > Alak was invented by the mathematician A. K. Dewdney, and described in his 1984 book Planiverse. The rules of Alak are simple: > > > Alak is a two-player game played on a one-dimensional board with eleven slots on it. Each slot can hold at most one piece at a > time. There's two kinds of pieces, "x" and "o". x's belong to one player, o's to the other. > The initial configuration of the board is: > > > ``` xxxx___oooo ``` > > The players take turns moving. At each turn, each player can move only one piece, once. A player cannot pass up on his turn. A player > can move any one of his pieces to the next unoccupied slot to its right or left, which may involve jumping over occupied slots. A > player cannot move a piece off the side of the board. > > > If a move creates a pattern where the opponent's pieces are surrounded, on both sides, by two pieces of the mover's color (with no > intervening unoccupied blank slot), then those surrounded pieces are removed from the board. > > > The goal of the game is to remove all of your opponent's pieces, at which point the game ends. Removing all-but-one ends the game > as well, since the opponent can't surround you with one piece, and so will always lose within a few moves anyway. > > > I found this game online and was wondering: can it be golfed? ### Rules of the golf * Your code must follow all the rules in the game, handling captures, proper moving, etc. (only exception is you don't have to add a bot, but you must have both players controlled somehow, and one player must be human). * Input must be move piece at tile X to tile Y, or quit. For example, you can use `1 4` to say 'move this piece at tile 1 to tile 4'. `quit` would end the program, although using `Control`-`C` would be acceptable. You also have to check if a move is invalid (by going outside the board or moving somewhere that you would have to cross over unoccupied spaces to get to or sending a message that is not a pair of tiles or `quit`). * Outputs for players winning and invalid must be `P1 WINS`, `P2 WINS`, and `INVALID`, respectively. (All of these are 7 characters.) * Output must show the board. That's all that's required. * It doesn't matter if you use any aids like numbered tiles or other pieces. * The challenge ends if: + One answer gets 50 votes + One answer remains the top-voted for 3 weeks, and no other answers were posted in that time and the challenge has at least 3 answers (so there's some real competition). ### Rules of the game * The player on the left must start first. * Only one piece occupies a square at a time. You move the piece left or right until it hits an unoccupied space. The board does not wrap, and you can't move through unoccupied areas. For example: + `xoo__o`. Here, the `x` moving right would change the board to `_oox_o`. + `xxooo_`. Here, the farthest-left `x` could move to yield `_xooox`, which captures the `o`s, leaving `_x___x`. + `x__oox`. Here, the `o`s are not captured (there is still a gap). Capture is not possible because you can't move through unoccupied spaces. The `x` on the left could only move one space, because there are no other pieces in between (leaving `_x_oox`). * Multiple adjacent pieces can be captured at once if the group is surrounded by the opponent's pieces. E.g. from `x_oox` to `_xoox` will capture both `o`s and result in `_x__x`. * If after a move, you first capture the *opponent's* pieces, before checking if your own piece should be remove. Take two examples: + `o_oxx` to `oxox_`. First, the second `o` is captured, `ox_x_`, so the first `x` remains on the board. + `o_oox` to `oxoo_`. This time, none of the `o`s are captured, so the `x` is captured instead. + If you have only one piece, the game ends, because you can't capture with just one piece. Let the games begin! I look forward to seeing what you come up with. [Answer] # C, ~~617~~ 592 bytes ``` #define O(x)(x-'x'?'x':'o') q,f,t,k,i,x=4,o=4,*d;main(){char*A,Q[9],c='x',b[]="xxxx___oooo";printf(b);while(!q){scanf(" %8[^\n]%*[^\n]",Q);if(!strcmp(Q,"quit"))break;f=*Q>47&&*Q<58?atoi(Q):-1;A=f>9?Q+2:Q+1;t=*A==32&&A[1]>47&&A[1]<58?atoi(A+1):-1;i=t==f&&t<0&&f<0?1:0;for(k=f;k!=t;k+=(t-f)/abs(t-f))if(b[k]==95||b[t]-95||b[f]-c)i=1;if(i){printf("INVALID");continue;}b[t]=c;b[f]=95;for(t=0;t<2;t++){d=c-'x'?&o:&x;for(k=1;k<11;k++)if(b[k]==O(c)){for(i=k+1;b[i]==O(c)&&b[i];i++);if(b[i]==c&&b[k-1]==c)while(k<i)b[k++]=95,(*d)--;}c=t?c:O(c);}printf(b);if(o<2||x<2)printf("P%d WINS",(x>1)+1),q=1;}} ``` Unraveled: ``` #define O(x)(x-'x'?'x':'o') q,f,t,k,i,x=4,o=4,*d; main(){ char*A,Q[9],c='x',b[]="xxxx___oooo"; printf(b); while(!q){ scanf(" %8[^\n]%*[^\n]",Q); if(!strcmp(Q,"quit"))break; f=*Q>47&&*Q<58?atoi(Q):-1; A=f>9?Q+2:Q+1; t=*A==32&&A[1]>47&&A[1]<58?atoi(A+1):-1; i=t==f&&t<0&&f<0?1:0; for(k=f;k!=t;k+=(t-f)/abs(t-f)) if(b[k]==95||b[t]-95||b[f]-c) i=1; if(i){ printf("INVALID"); continue; } b[t]=c; b[f]=95; for(t=0;t<2;t++){ d=c-'x'?&o:&x; for(k=1;k<11;k++) if(b[k]==O(c)){ for(i=k+1;b[i]==O(c)&&b[i];i++); if(b[i]==c&&b[k-1]==c) while(k<i)b[k++]=95,(*d)--; } c=t?c:O(c); } printf(b); if(o<2||x<2)printf("P%d WINS",(x>1)+1),q=1; } } ``` I really wanted to get this one in ~400 bytes, but there are a lot of little rules here and the input processing ended up pretty obnoxious. I'm definitely not done with this. Here's a set of sample runs that covers just about everything: ``` xxxx___oooo0 4 _xxxx__oooo7 6 _xxxx_o_ooo4 5 _xxx_xo_ooo8 6 INVALID8 7 _xxx_xoo_oo3 4 _xx_xxoo_oo7 3 _xxo__o__oo1 4 __x_x_o__oo10 9 INVALID10 8 __x_x_o_oo_2 3 ___xx_o_oo_6 5 ___xxo__oo_6 6 INVALID5 5 INVALID3 6 ____x_x_oo_8 7 ____x_xo_o_6 8 ____x__o_o_P2 WINS xxxx___oooo0 4 _xxxx__oooo10 6 _xxxx_oooo_1 5 __xxxxoooo_9 1 _o____ooo__P2 WINS xxxx___oooo0 4 _xxxx__oooo7 6 _xxxx_o_ooo1 5 __xxxxo_ooo10 7 __xxxxoooo_2 10 ___xxx____xP1 WINS xxxx___oooo3 4 xxx_x__ooooquits INVALIDtestme INVALID3*4 INVALID3 four INVALIDthree four INVALIDthisstringislongerthanmybuffer INVALID10 0 INVALID4 5 INVALID7 6 xxx_x_o_oooquit ``` If I've misinterpreted something, please let me know! [Answer] # PHP - 505 ``` <?php $s="xxxx___ooo".$y=o;$x=x;$c=function($m)use(&$x){return$x.str_repeat('_',strlen($m[1])).$x;};$e='$s=preg_replace_callback("~$x($y+)$x~",$c,$s);';$_=substr_count;while(true){echo$s;if($_($s,x)<2)die("P2 WINS");if($_($s,o)<2)die("P1 WINS");$i=trim(fgets(STDIN));if($i=='quit')die;if(!preg_match('!^(\d+) (\d+)$!',$i,$m)||$s[$f=$m[1]]!=$x||$s[$t=$m[2]]!="_"||(0&($a=min($f,$t))&$b=max($f,$t))||$_($s,"_",$a,($b-$a)+1)>1)echo"INVALID\n";else{$s[$f]='_';$s[$t]=$x;eval($e);$z=$x;$x=$y;$y=$z;eval($e);}} ``` Notices must be suppressed by redirecting `STDERR` to `/dev/null`. With sane whitespace: ``` <?php @$s = "xxxx___ooo".($y = o); @$x = x; $c = function($m)usea(&$x){ return$x.str_repeat('_',strlen($m[1])).$x; }; $e = '$s=preg_replace_callback("~$x($y+)$x~",$c,$s);'; @$_ = substr_count; while (true){ echo $s; if (@$_($s,x) < 2) die("P2 WINS"); if (@$_($s,o) < 2) die("P1 WINS"); $i = trim(fgets(STDIN)); if($i == 'quit') die; if( !preg_match('!^(\d+) (\d+)$!',$i,$m) || $s[$f = $m[1]] != $x || @$s[$t = $m[2]] != "_" || (0 & ($a = min($f, $t)) & $b = max($f, $t)) || $_($s, "_", $a, ($b - $a) + 1) > 1 ) echo "INVALID\n"; else { $s[$f] = '_'; $s[$t] = $x; eval($e); $z = $x; $x = $y; $y = $z; eval($e); } } ``` With the test cases of BrainSteel: ``` xxxx___oooo0 4 _xxxx__oooo7 6 _xxxx_o_ooo4 5 _xxx_xo_ooo8 6 INVALID _xxx_xo_ooo8 7 _xxx_xoo_oo3 4 _xx_xxoo_oo7 3 _xxo__o__oo1 4 __x_x_o__oo10 9 INVALID __x_x_o__oo10 8 __x_x_o_oo_2 3 ___xx_o_oo_6 5 ___xxo__oo_6 6 INVALID ___xxo__oo_5 5 INVALID ___xxo__oo_3 6 ____x_x_oo_8 7 ____x_xo_o_6 8 ____x__o_o_P2 WINS xxxx___oooo0 4 _xxxx__oooo10 6 _xxxx_oooo_1 5 __xxxxoooo_9 1 _o____ooo__P2 WINS xxxx___oooo0 4 _xxxx__oooo7 6 _xxxx_o_ooo1 5 __xxxxo_ooo10 7 __xxxxoooo_2 10 ___xxx____xP1 WINS xxxx___oooo3 4 xxx_x__ooooquits INVALID xxx_x__ooootestme INVALID xxx_x__oooo3*4 INVALID xxx_x__oooo3 four INVALID xxx_x__oooothree four INVALID xxx_x__oooothisstringislongerthanmybuffer INVALID xxx_x__oooo10 0 INVALID xxx_x__oooo4 5 INVALID xxx_x__oooo7 6 xxx_x_o_oooquit ``` [Answer] # Python 2, ~~536~~ ~~509~~ ~~448~~ 441 bytes Call via `a()`; moves are to be entered in the form `piece,destination` (i.e., `1,4`); quit with Ctrl-C. If anyone can see more golfing potential, I'm all ears. ``` b,r,x='_',lambda p:''.join([p[i]for i in x]),range(11) def a(m='xo'): t=w=0;p=dict(zip(x,'xxxx___oooo')) while w<1: print r(p);y=m[t%2] try: s,v=input();1/all([y==p[s],{v}<{r(p).rfind(b,0,s),r(p).find(b,s)},v-s]);p[s],p[v],h,c=b,y,0,{} for _ in y,m[-~t%2]: for i in p:exec{_:"h=1;p.update(c)",b:"h,c=0,{}"}.get(p[i],h*"c[i]=b") w=min(map(r(p).count,m))<2;t+=1 except:print"INVALID" print"P%d WINS"%-~(r(p).count('o')<2) ``` [Answer] # SpecBAS - 718 bytes [SpecBAS](https://sites.google.com/site/pauldunn/) is an updated version of Sinclair/ZX BASIC that can run outside of an emulator. (Still interpreted). Have used some of the new features to get the size down as much as I could. Line 12 sets up a regex to search for "sandwiched" pieces using inline IF and line 18 uses the wrap around nature of INC (rather than saying `INC p: IF p=3 THEN LET p=1`) ``` 1 LET b$="xxxx---oooo": LET p=1: LET c$="xo": DIM s=4,4 2 LET v=0: PRINT b$'"[";p;"] "; 3 INPUT m$: IF m$(1)="Q" THEN PRINT "QUIT": STOP 4 LET f=VAL(ITEM$(m$,1," ")): LET t=VAL(ITEM$(m$,2," ")): PRINT f;" ";t 5 IF (f<1 OR f>11) OR (t<1 OR t>11) THEN LET v=1: GO TO 10 6 IF (b$(f)<>c$(p)) OR b$(t)<>"-" THEN LET v=1: GO TO 10 7 FOR i=f TO t STEP SGN(t-f) 8 IF b$(i)="-" THEN IF i<>t THEN LET v=1 9 NEXT i 10 IF v=1 THEN PRINT "INVALID": GO TO 2 11 LET b$(t)=b$(f): LET b$(f)="-" 12 LET r$=IIF$(p=1,"xo+x","ox+o") 13 LET m=MATCH(r$,b$): IF m=0 THEN GO TO 18 14 FOR i=m+1 TO POS(c$(p),b$,m+2) 15 IF b$(i)=c$(3-p) THEN LET b$(i)="-": DEC s(3-p): END IF 16 NEXT i 17 IF s(3-p)<2 THEN PRINT b$'"P";p;" WINS": STOP 18 INC p,1 TO 2 19 GO TO 2 ``` Output (can't copy from the output widow, so screen shot) ![enter image description here](https://i.stack.imgur.com/wq8Dv.png) ![enter image description here](https://i.stack.imgur.com/lsdZV.png) [Answer] # C#, 730 bytes ``` using System;using System.Linq;class P{static void Main(string[]z){int p=1,d,e,g,x,y;var b=new[]{3,1,1,1,1,0,0,0,2,2,2,2};var o=new[]{"_","x","o"};Action<string>h=s=>{Console.Write(s,p);Environment.Exit(0);};Action i=()=>h("INVALID");Func<int,int,bool>j=(q,r)=>b.Select((v,w)=>w<=q||w>=r||v>0?0:w).Any(w=>w>0);Action<int>k=m=>{e=0;for(d=1;d<12;d++){if(b[d]==m){if(e>0&&!j(e,d))for(g=e+1;g<d;g++)b[g]=0;e=d;}}if(b.Count(w=>w>0&&w!=m)<3)h("P{0} WINS");};try{for(;;){for(g=1;g<12;g++)Console.Write(o[b[g]]);var n=Console.ReadLine();if(n=="quit")h("");var c=n.Split(' ');x=int.Parse(c[0]);y=int.Parse(c[1]);if(c.Length>2||b[x]!=p||b[y]!=0||(p>1?y:x)>=(p>1?x:y)||j(x<y?x:y,x<y?y:x))i();b[x]=0;b[y]=p;k(p);p=p>1?1:2;k(p);}}catch{i();}}} ``` I imagine that further improvements are possible. On the other hand, I interpreted the `INVALID` output as ending execution, so I may need to fix that issue to be in parity with other answers. ]
[Question] [ Let's try this again. The object of this contest is to make two pieces of code that are anagrams of each other (the two must contain the same bytes in a different order), and they will do the following tasks: * One must test if an inputted number is [happy](http://en.wikipedia.org/wiki/Happy_number) or [prime](http://en.wikipedia.org/wiki/Prime_number), and output if the number is either (for example, `7` must output `happy prime` and `4` must output `sad non-prime`). * The other must output its code size in bytes as a word (a 60-byte program would output `sixty`, a 39-byte program would output `thirty-nine`). If any clarification is needed on the rules, don't hesitate to tell me. This is a code golf competition, so shortest program wins! [Answer] ## CJam, ~~80~~ ~~49~~ 48 characters **UPDATE** : Inspired by Dennis' implementation to calculate sum of squares of digits, here is a shorter version Happy/Sad Prime/Non-prime: ``` ri:T{Ab2f#:+}G*X="happy""sad"?STmp4*"non-prime"> ``` How it works: ``` ri:T "Read input as integer and store it in T" { }G* "Run this code block 16 times" Ab "Convert the number into base 10" 2f# "Calculate square of each digit" :+ "Sum all the squared digits and put the sum on stack" X= "Compare the sum after 16th iteration to 1" "happy""sad"? "If sum is 1, put `happy` to stack, otherwise `sad`" ST "Put space on stack then put the value of T on stack" mp4* "Put 4 to stack if input is prime, otherwise 0" "non-prime"> "Put `non-prime` to stack and slice out first four characters if the input number is prime" ``` *forTy-eiGhT* ``` ""A"forTy-eiGhT""ri:{b2#:+}*X=appsadSmp4*nnpm>"? ``` How this works: ``` "" "Push empty string to stack" A "Push 10 to stack" "forTy-eiGhT" "Push `forTy-eiGhT` to stack" "ri:....pm>" "Push this string to stack too" ? "Keep `forTy-eiGhT` on stack and pop the other string" ``` [Try it online](http://cjam.aditsu.net/) The first program reads the number from STDIN --- My original 80 character solution Happy/Sad Prime/Non-prime: ``` r:N{1/~]{i_*T+:T;}/T_s\1=:H!X):XK<&0:T;}g;H"happy""sad"?SNimp"prime"_"non-"\+?:Y ``` *eigHTY* ``` "eigHTY""r:N{1/~]{i_*T+:T}/_s\1=:H!X):XK<&0:T}happysad?SNmp";"prim_";"non-\?:+"; ``` [Answer] # CJam, ~~50~~ 49 bytes **Happiness and primality test** ``` li_{Ab2f#:+}30*(T="happy""sad"?S@mp4*"non-prime"> ``` Reads a number from STDIN. Both tests work only for 64-bit integers. [Try it online.](http://cjam.aditsu.net/ "CJam interpreter") **Own length** ``` A"forTy-nine""l_{b2#:+}30*(=happsadS@mp4*pim>"?"" ``` Prints *forTy-nine*. [Answer] ## Golfscript - 81 This program tests if a number is happy and/or prime. ``` ~.:a;0.{).a\%!@+\}a*;2="""non-"if"prime"@ {`0\{48-.*+}/}9*("sad ""happy "if@@#get ``` This program, an anagram of the last, outputs "eighty-one" (its bytesize as a word). ``` ;"eighty-one"# !""""""""%()***++-..../002489:;=@@@@\\\`aaaaadffiimnppprs{{{}}}~ ``` This should serve as an example. [Answer] # J - 87 char A naive attempt at this in J. No use of the standard library, though I doubt it would get any shorter by using that. ``` ((sad`happy{~1 e.(,[:+/@:*:,.&.":@{:)^:(1-{:e.}:)^:_);@,' ';'gtv]non-prime'}.~4+4*1&p:) '((ad`app{~1 .(,[:+/@:*:,.&.":@{:)^:(1-{:.}:)^:_);@, ;onprm}.~4+4*1&p:)']'eighty-seven' ('(ad`app{~1 .(,[:+/@:*:,.&.:@{:)^:(1-{:.}:)^:);@, ;onprm}.~4+4*1&p:']'eighty-seven'"_) ``` The line on the top is a verb taking an integer and diagnosing its happiness and primality as an output string. The second line is an expression returning the string `eighty-seven`, while the third is a constant function doing the same. I included both because they were both possible and because I don't know what the ruling will be on function answers as opposed to program ones, and J doesn't have such a thing as no-argument functions—you just give a function a dummy argument. We lose most of the chars checking for happiness. `(,[:+/@:*:,.&.":@{:)` is the main body that sums the squares of the digits of a number, and `(1-{:e.}:)` is the test of whether that number has occurred yet. `sad`happy{~1 e.` turns this into a word result, and we attach that to the front of the string `non-prime`, potentially snipping off four characters if the number was actually prime. In the anagram we just hide all the bits that aren't `'eighty-seven'` in a string that we ignore. I could do better if J had more letters to reuse, but it doesn't, so oh well. ]
[Question] [ Farmer Jack is very poor. He wants to light his whole farm but with minimum of cost. A lamp can illuminate its own cell as well as its eight neighbors . He has arranged the lamps in his field but he needs your help in finding out whether or not he has kept any extra lamps. Extra lamps : Lamps which on removing from the farm will make no difference to the number of cells lit. Also, the lamps you will point will not be removed one by one, but they will be removed simultaneously. Note: The only action you can perform is to remove some lamps. You can neither rearrange nor insert lamps. Your final target is to remove maximum number of lamps such that every cell which was lit before is still lit. Help Farmer Jack in spotting the maximum number of useless lamps so that he can use them elsewhere. **Input** You will be given in the first line dimensions of the field **M** and **N**.Next **M** lines follow containing **N** characters each representing the field. '1' represents cell where lamp is kept. '0' represents an empty cell. **Output** You have to output an integer containing number of useless lamps. **Sample Input:** ``` 3 3 100 010 001 ``` **Sample Output:** ``` 2 ``` **Winner:** Since it is code golf, winner will be the one who will successfully complete the task in least number of characters [Answer] # Mathematica 186 (greedy) and 224 (all combinations) ## Greedy Solution ``` t=MorphologicalTransform;n@w_:=Flatten@w~Count~1 p_~w~q_:=n[p~t~Max]==n[q~t~Max] g@m_:=Module[{l=m~Position~1,r,d=m},While[l!={},If[w[m,r=ReplacePart[d,#-> 0]& [l[[1]]]],d=r];l=Rest@l];n@m-n@d] ``` This turns off superfluous lights one by one. If the light coverage is not diminished when the light goes off, that light can be eliminated. The greedy approach is very fast and can easily handle matrices of 15x15 and much larger (see below). It returns a single solutions, but it is unknown whether that is optimal or not. Both approaches, in the golfed versions, return the number of unused lights. Un-golfed approaches also display the grids, as below. Before: ![before](https://i.stack.imgur.com/kQ9A5.png) After: ![after](https://i.stack.imgur.com/X2fjP.png) ## Optimal Solutions using all combinations of lights (224 chars) With thanks to @Clément. ### Ungolfed version using all combinations of lights fThe morphological transform function used in `sameCoverageQ` treats as lit (value = 1 instead of zero) the 3 x3 square in which each light resides.When a light is near the edge of the farm, only the squares (less than 9) within the borders of the farm are counted.There is no overcounting; a square lit by more than one lamp is simply lit.The program turns off each light and checks to see if the overall lighting coverage on the farm is reduced.If it is not, that light is eliminated. ``` nOnes[w_]:=Count[Flatten@w,1] sameCoverageQ[m1_,m2_]:=nOnes[MorphologicalTransform[m1,Max]]== nOnes[MorphologicalTransform[m2,Max]] (*draws a grid with light bulbs *) h[m_]:=Grid[m/.{1-> Style[\[LightBulb],24],0-> ""},Frame-> All,ItemSize->{1,1.5}] c[m1_]:=GatherBy[Cases[{nOnes[MorphologicalTransform[ReplacePart[Array[0&,Dimensions[m1]], #/.{{j_Integer,k_}:> {j,k}-> 1}],Max]],#,Length@#}&/@(Rest@Subsets[Position[m1,1]]), {nOnes[MorphologicalTransform[m1,Max]],_,_}],Last][[1,All,2]] ``` `nOnes[matrix]` counts the number of flagged cells. It is used to count the lights and also to count the lit cells `sameCoverageQ[mat1, mat2]` tests whether the lit cells in mat1 equals the number of lit cells in mat2.MorphologicalTransform[[mat] takes a matrix of lights and returns a matrix` of the cells they light up. `c[m1]` takes all combinations of lights from m1 and tests them for coverage. Among those that have the maximum coverage, it selects those that have the fewest light bulbs. Each of these is an optimal solution. --- **Example 1:** A 6x6 setup ``` (*all the lights *) m=Array[RandomInteger[4]&,{6,6}]/.{2-> 0,3->0,4->0} h[m] ``` ![original](https://i.stack.imgur.com/bjNRF.png) All optimal solutions. ``` (*subsets of lights that provide full coverage *) h/@(ReplacePart[Array[0&,Dimensions[m]],#/.{{j_Integer,k_}:> {j,k}-> 1}]&/@(c[m])) ``` ![answers](https://i.stack.imgur.com/4eYi7.png) --- ## Golfed version using all combinations of lights. This version calculates the number of unused lights. It does not display the grids. `c` returns the number of unused lights. ``` n@w_:=Flatten@w~Count~1;t=MorphologicalTransform; c@r_:=n@m-GatherBy[Cases[{n@t[ReplacePart[Array[0 &,Dimensions[r]],# /.{{j_Integer,k_}:> {j,k}-> 1}],Max],#,Length@#}&/@(Rest@Subsets[r~Position~1]), {n[r~t~Max],_,_}],Last][[1,1,3]] ``` `n[matrix]` counts the number of flagged cells. It is used to count the lights and also to count the lit cells `s[mat1, mat2]` tests whether the lit cells in mat1 equals the number of lit cells in mat2.t[[mat] takes a matrix of lights and returns a matrix` of the cells they light up. `c[j]` takes all combinations of lights from j and tests them for coverage. Among those that have the maximum coverage, it selects those that have the fewest light bulbs. Each of these is an optimal solution. **Example 2** ``` m=Array[RandomInteger[4]&,{6,6}]/.{2-> 0,3->0,4->0}; m//Grid ``` ![grid](https://i.stack.imgur.com/TG8ex.png) Two lights can be saved while having the same lighting coverage. c[m] > > 2 > > > [Answer] ## Python, 309 chars ``` import sys I=sys.stdin.readlines()[1:] X=len(I[0]) L=[] m=p=1 for c in''.join(I):m|=('\n'!=c)*p;L+=('1'==c)*[p<<X+1|p<<X|p<<X-1|p*2|p|p/2|p>>X-1|p>>X|p>>X+1];p*=2 O=lambda a:m&reduce(lambda x,y:x|y,a,0) print len(L)-min(bin(i).count('1')for i in range(1<<len(L))if O(L)==O(x for j,x in enumerate(L)if i>>j&1)) ``` Works using bitmasks. `L` is a list of the lights, where each light is represented by an integer with (up to) 9 bits set for its light pattern. Then we exhaustively search for subsets of this list whose bitwise-or is the same as the bitwise-or of the whole list. The shortest subset is the winner. `m` is a mask that prevents wraparound of the bits when shifting. [Answer] # Java 6 - 509 bytes I made some assumptions about the limits and solved the problem as stated at this time. ``` import java.util.*;enum F{X;{Scanner s=new Scanner(System.in);int m=s.nextInt(),n=s.nextInt(),i=m,j,k=0,l=0,r=0,o,c,x[]=new int[30],y[]=x.clone();int[][]a=new int[99][99],b;while(i-->0){String t=s.next();for(j=n;j-->0;)if(t.charAt(j)>48){x[l]=i;y[l++]=j;}}for(;k<l;++k)for(i=9;i-->0;)a[x[k]+i/3][y[k]+i%3]=1;for(k=1<<l;k-->0;){b=new int[99][99];for(j=c=l;j-->0;)if((k&1<<j)>0)for(c--,i=9;i-->0;)b[x[j]+i/3][y[j]+i%3]=1;for(o=i=0;i++<m;)for(j=0;j++<n;)o|=a[i][j]^b[i][j];r=c-o*c>r?c:r;}System.out.println(r);}} ``` Run like this: `java F <inputfile 2>/dev/null` [Answer] c++ - 477 bytes ``` #include <iostream> using namespace std;int main(){ int c,i,j,m,n,p,q=0;cin>>m>>n; int f[m*n],g[m*n],h[9]={0,-1,1,-m-1,-m,-m+1,m-1,m,m+1}; for(i=0;i<m*n;i++){f[i]=0;g[i]=0;do{c=getchar();f[i]=c-48;}while(c!='0'&&c!='1');} for(i=0;i<m*n;i++)if(f[i])for(j=0;j<9;j++)if(i+h[j]>=0&&i+h[j]<m*n)g[i+h[j]]++; for(i=0;i<m*n;i++)if(f[i]){p=0;for(j=0;j<9;j++)if(i+h[j]>=0&&i+h[j]<m*n)if(g[i+h[j]]<2)p++;if(p==0){for(j=0;j<9;j++)if(i+h[j]>=0&&i+h[j]<m*n)g[i+h[j]]--;q++;}}cout<<q<<endl;} ``` [Answer] ## Ruby, 303 **[this was coded to answer a previous version of the question; read note below]** ``` def b(f,m,n,r)b=[!1]*1e6;(n..n+m*n+m).each{|i|b[i-n-2,3]=b[i-1,3]=b[i+n,3]=[1]*3if f[i]};b[r*n+r+n+1,n];end m,n=gets.split.map(&:to_i) f=[!1]*n m.times{(?0+gets).chars{|c|f<<(c==?1)if c>?*}} f+=[!u=0]*n*n f.size.times{|i|g=f.dup;g[i]?(g[i]=!1;u+=1if m.times{|r|break !1if b(f,m,n,r)!=b(g,m,n,r)}):0} p u ``` Converting to arrays of Booleans and then comparing neighbourhoods for changes. Limitation(?): Maximum farm field size is 1,000 x 1,000. Problem states "Farmer Jack is very poor" so I'm assuming his farm isn't larger. ;-) Limitation can be removed by adding 2 chars. **NOTE:** Since I began coding this, it appears the question requirements changed. The following clarification was added *"the lamps you will point will not be removed one by one, but they will be removed simultaneously"*. The ambiguity of the original question allowed me to save some code by testing *individual* lamp removals. Thus, my solution will not work for many test cases under the new requirements. If I have time, I will fix this. I may not. **Please do not upvote this answer** since other answers here may be fully compliant. [Answer] # APL, 97 chars/bytes\* Assumes a `⎕IO←1` and `⎕ML←3` APL environment. ``` m←{s↑⊃∨/,v∘.⊖(v←⍳3)⌽¨⊂0⍪0⍪0,0,s⍴⍵}⋄n-⌊/+/¨t/⍨(⊂m f)≡¨m¨(⊂,f)\¨t←⊂[1](n⍴2)⊤⍳2*n←+/,f←⍎¨⊃{⍞}¨⍳↑s←⍎⍞ ``` **Ungolfed version:** ``` s ← ⍎⍞ ⍝ read shape of field f ← ⍎¨ ⊃ {⍞}¨ ⍳↑s ⍝ read original field (lamp layout) n ← +/,f ⍝ original number of lamps c ← ⊂[1] (n⍴2) ⊤ ⍳2*n ⍝ all possible shutdown combinations m ← {s↑ ⊃ ∨/ ,v ∘.⊖ (v←⍳3) ⌽¨ ⊂ 0⍪0⍪0,0, s⍴⍵} ⍝ get lighted cells given a ravelled field l ← m¨ (⊂,f) \¨ c ⍝ map of lighted cells for every combination k ← c /⍨ (⊂ m f) ≡¨ l ⍝ list of successful combinations u ← ⌊/ +/¨ k ⍝ min lamps used by a successful comb. ⎕ ← n-u ⍝ output number of useless lamps ⎕ ← s⍴ ⊃ (⊂,f) \¨ (u= +/¨ k) / k ⍝ additional: print the layout with min lamps ``` I agree that more test cases would be better. Here's a random one: Input: ``` 5 5 10001 01100 00001 11001 00010 ``` Output (useless lamps): ``` 5 ``` Layout with min lamps (not included in golfed version): ``` 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 0 1 0 0 1 0 0 0 0 0 ``` ⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯ \*: APL can be written in its own (legacy) single-byte charset that maps APL symbols to the upper 128 byte values. Therefore, for the purpose of scoring, a program of N chars *that only uses ASCII characters and APL symbols* can be considered to be N bytes long. [Answer] ## C++ 5.806 Bytes This is not optimized for size yet. But since there are few contestants i will leave it at that for now. FarmersField Header: ``` #pragma once namespace FarmersLand { class FarmersField { private: unsigned _m_size, _n_size; int * _lamp, * _lumination; char * _buffer; void _illuminate(unsigned m, unsigned n); void _deluminate(unsigned m, unsigned n); void _removeLamp(unsigned m, unsigned n); void _setLamp(unsigned m, unsigned n); int _canRemoveLamp(unsigned m, unsigned n); int _coordsAreValid(unsigned m, unsigned n); int _getLuminationLevel(unsigned m, unsigned n); int * _allocIntArray(unsigned m, unsigned n); int _coordHelper(unsigned m, unsigned n); public: FarmersField(char * input[]); FarmersField(const FarmersField & field); ~FarmersField(void); int RemoveLamps(void); char * Cstr(void); }; } ``` FarmersField CPP: ``` #include "FarmersField.h" #include <stdio.h> namespace FarmersLand { void FarmersField::_illuminate(unsigned m, unsigned n) { if(this -> _coordsAreValid(m,n)) { ++this -> _lumination[this -> _coordHelper(m,n)]; } } void FarmersField::_deluminate(unsigned m, unsigned n) { if(this -> _coordsAreValid(m,n)) { --this -> _lumination[this -> _coordHelper(m,n)]; } } void FarmersField::_removeLamp(unsigned m, unsigned n) { if(this -> _coordsAreValid(m,n)) { unsigned mi_start = (m == 0) ? 0 : m - 1; unsigned mi_end = m + 1; unsigned ni_start = (n == 0) ? 0 : n - 1; unsigned ni_end = n + 1; for(unsigned mi = mi_start; mi <= mi_end; ++mi) { for(unsigned ni = ni_start; ni <= ni_end; ++ni) { this -> _deluminate(mi, ni); } } --this -> _lamp[this -> _coordHelper(m,n)]; } } void FarmersField::_setLamp(unsigned m, unsigned n) { if(this -> _coordsAreValid(m,n)) { unsigned mi_start = (m == 0) ? 0 : m - 1; unsigned mi_end = m + 1; unsigned ni_start = (n == 0) ? 0 : n - 1; unsigned ni_end = n + 1; for(unsigned mi = mi_start; mi <= mi_end; ++mi) { for(unsigned ni = ni_start; ni <= ni_end; ++ni) { this -> _illuminate(mi, ni); } } ++this -> _lamp[this -> _coordHelper(m,n)]; } } int FarmersField::_canRemoveLamp(unsigned m, unsigned n) { unsigned can = 1; unsigned mi_start = (m == 0) ? 0 : m - 1; unsigned mi_end = (m == (this->_m_size - 1)) ? m : m + 1; unsigned ni_start = (n == 0) ? 0 : n - 1; unsigned ni_end = (n == (this->_n_size - 1)) ? n : n + 1; for(unsigned mi = mi_start; mi <= mi_end; ++mi) { for(unsigned ni = ni_start; ni <= ni_end; ++ni) { if( 1 >= this -> _getLuminationLevel(mi, ni) ) { can = 0; } } } return can; } int FarmersField::_coordsAreValid(unsigned m, unsigned n) { return m < this -> _m_size && n < this -> _n_size; } int FarmersField::_getLuminationLevel(unsigned m, unsigned n) { if(this -> _coordsAreValid(m,n)) { return this -> _lumination[this -> _coordHelper(m,n)]; } else { return 0; } } int * FarmersField::_allocIntArray(unsigned m, unsigned n) { int * a = new int[m * n]; for(unsigned i = 0; i < m*n; ++i) { a[i] = 0; } return a; } int FarmersField::_coordHelper(unsigned m, unsigned n) { return m * this -> _n_size + n; } int FarmersField::RemoveLamps(void) { int r = 0; for(unsigned m = 0 ; m < this -> _m_size; ++m) { for(unsigned n = 0 ; n < this -> _n_size; ++n) { if(this -> _canRemoveLamp(m,n)) { ++r; this -> _removeLamp(m,n); } } } return r; } char * FarmersField::Cstr(void) { unsigned size = this -> _m_size * this -> _n_size + _m_size ; unsigned target = 0; delete(this -> _buffer); this -> _buffer = new char[ size ]; for(unsigned m = 0 ; m < this -> _m_size; ++m) { for(unsigned n = 0 ; n < this -> _n_size; ++n) { this -> _buffer[target++] = (0 == this -> _lamp[this -> _coordHelper(m,n)])? '0' : '1'; } this -> _buffer[target++] = '-'; } this -> _buffer[size - 1 ] = 0; return this -> _buffer; } FarmersField::FarmersField(char * input[]) { sscanf_s(input[0], "%u %u", &this -> _m_size, &this -> _n_size); this -> _lamp = this -> _allocIntArray(this -> _m_size, this -> _n_size); this -> _lumination = this -> _allocIntArray(this -> _m_size, this -> _n_size); this -> _buffer = new char[1]; for(unsigned m = 0 ; m < this -> _m_size; ++m) { for(unsigned n = 0 ; n < this -> _n_size; ++n) { if('0' != input[m+1][n]) { this -> _setLamp(m,n); } } } } FarmersField::FarmersField(const FarmersField & field) { this -> _m_size = field._m_size; this -> _n_size = field._n_size; this -> _lamp = this -> _allocIntArray(this -> _m_size, this -> _n_size); this -> _lumination = this -> _allocIntArray(this -> _m_size, this -> _n_size); this -> _buffer = new char[1]; for(unsigned m = 0 ; m < this -> _m_size; ++m) { for(unsigned n = 0 ; n < this -> _n_size; ++n) { if(0 != field._lamp[this -> _coordHelper(m,n)]) { this -> _setLamp(m,n); } } } } FarmersField::~FarmersField(void) { delete(this -> _lamp); delete(this -> _lumination); delete(this -> _buffer); } } ``` And a set of tests to show that the code does what it was built to do: ``` #include "../../Utility/GTest/gtest.h" #include "FarmersField.h" TEST(FarmersField, Example1) { using namespace FarmersLand; char * input[] = {"3 3", "100", "010", "001"}; FarmersField f(input); EXPECT_STREQ("100-010-001", f.Cstr()); EXPECT_EQ(2, f.RemoveLamps()); EXPECT_STREQ("000-010-000", f.Cstr()); } TEST(FarmersField, Example2) { using namespace FarmersLand; char * input[] = {"3 6", "100000", "010000", "001000"}; FarmersField f(input); EXPECT_STREQ("100000-010000-001000", f.Cstr()); EXPECT_EQ(1, f.RemoveLamps()); EXPECT_STREQ("000000-010000-001000", f.Cstr()); } TEST(FarmersField, Example3) { using namespace FarmersLand; char * input[] = {"6 3", "100", "010", "001", "000", "000", "000",}; FarmersField f(input); EXPECT_STREQ("100-010-001-000-000-000", f.Cstr()); EXPECT_EQ(1, f.RemoveLamps()); EXPECT_STREQ("000-010-001-000-000-000", f.Cstr()); } TEST(FarmersField, Example4) { using namespace FarmersLand; char * input[] = {"3 3", "000", "000", "000",}; FarmersField f(input); EXPECT_STREQ("000-000-000", f.Cstr()); EXPECT_EQ(0, f.RemoveLamps()); EXPECT_STREQ("000-000-000", f.Cstr()); } TEST(FarmersField, Example5) { using namespace FarmersLand; char * input[] = {"3 3", "111", "111", "111",}; FarmersField f(input); EXPECT_STREQ("111-111-111", f.Cstr()); EXPECT_EQ(8, f.RemoveLamps()); EXPECT_STREQ("000-010-000", f.Cstr()); } TEST(FarmersField, Example6) { using namespace FarmersLand; char * input[] = {"6 6", "100001", "001010", "001001", "001010", "110000", "100001",}; FarmersField f(input); EXPECT_STREQ("100001-001010-001001-001010-110000-100001", f.Cstr()); EXPECT_EQ(6, f.RemoveLamps()); EXPECT_STREQ("100011-001010-000000-000010-010000-000001", f.Cstr()); } ``` [Answer] **Perl 3420 bytes** Not a golf solution, but I found this problem interesting: ``` #!/usr/bin/perl use strict; use warnings; { package Farm; use Data::Dumper; # models 8 nearest neighbors to position i,j forall i,j my $neighbors = [ [-1, -1], [-1, 0], [-1, +1], [ 0, -1], # current pos [ 0, 1], [+1, -1], [+1, 0], [+1, +1] ]; sub new { my ($class, %attrs) = @_; bless \%attrs, $class; } sub field { my $self = shift; return $self->{field}; } sub rows { my $self = shift; return $self->{rows}; } sub cols { my $self = shift; return $self->{cols}; } sub adjacents { my ($self, $i, $j) = @_; my @adjs; NEIGHBORS: for my $neighbor ( @$neighbors ) { my ($imod, $jmod) = ($neighbor->[0] + $i, $neighbor->[1] + $j); next NEIGHBORS if $imod >= $self->rows || $jmod >= $self->cols; # push neighbors push @adjs, $self->field->[$imod]->[$jmod]; } return @adjs; } sub islit { my ($lamp) = @_; return defined $lamp && $lamp == 1; } sub can_remove_lamp { my ($self, $i, $j) = @_; return scalar grep { islit($_) } $self->adjacents($i, $j); } sub remove_lamp { my ($self, $i, $j) = @_; $self->field->[$i]->[$j] = 0; } sub remove_lamps { my ($self) = @_; my $removed = 0; for my $i ( 0 .. @{ $self->field } - 1) { for my $j ( 0 .. @{ $self->field->[$i] } - 1 ) { next unless islit( $self->field->[$i]->[$j] ); if( $self->can_remove_lamp($i, $j) ) { $removed++; $self->remove_lamp($i, $j); } } } return $removed; } 1; } { # Tests use Data::Dumper; use Test::Deep; use Test::More; { # 3x3 field my $farm = Farm->new( rows => 3, cols => 3, field => [ [1,0,0], [0,1,0], [0,0,1] ] ); is( 2, $farm->remove_lamps, 'Removed 2 overlapping correctly' ); is_deeply( $farm->field, [ [0,0,0], [0,0,0], [0,0,1], ], 'Field after removing lamps matches expected' ); } { # 5x5 field my $farm = Farm->new( rows => 5, cols => 5, field => [ [0,0,0,0,0], [0,1,0,0,0], [0,0,1,0,0], [0,0,0,0,0], [0,0,0,0,0] ] ); is( 1, $farm->remove_lamps, 'Removed 1 overlapping lamp correctly' ); is_deeply( $farm->field, [ [0,0,0,0,0], [0,0,0,0,0], [0,0,1,0,0], [0,0,0,0,0], [0,0,0,0,0], ], 'Field after removing lamps matches expected' ); } } ``` (I/O was taken out so I could show concrete tests) [Answer] ## Python - 305 bytes ``` import sys,itertools w,h=map(int,input().split());w+=1 l=[i for i,c in enumerate(sys.stdin.read())if c=="1"] f=lambda l:{i+j for i in l for j in(0,1,-1,w-1,w,w+1,1-w,-w,-w-1)if(i+j+1)%w}&set(range(w*h)) for n in range(1,len(l)): for c in itertools.combinations(l,n): if f(c)^f(l):print(len(l)-n);exit() ``` ]
[Question] [ **This question already has answers here**: [Code the Huffman!](/questions/61903/code-the-huffman) (7 answers) Closed 8 years ago. Write a filter that converts text from standard input to a representation of its [Huffman tree](http://en.wikipedia.org/wiki/Huffman_coding) on standard output. In as few characters as possible. * you're free to consider newlines or not * output format is free, as long as it's some *human-readable* encoding of a tree. s-exps, ascii-art and .png, all good. RPN, .dot, I'll smile or frown, but that ought to be ok. Program cores and/or raw pointers , no way. * no canonicalization needed; if the characters are at the right depth, that's good enough. Sample possible output for "this is an example of a huffman tree" (from wikipedia): ``` (((e . (n . (o . u))) . (a . (t . m))) . (((i . (x . p)) . (h . s)) . (((r . l) . f) . #\space))) ``` I can't reproduce all possible valid outputs with human-readable representation combinations in here (the margin is a bit too thin), but what should check is which characters end up at which number of bits: * 3 bits: a e [space] * 4 bits: f h i m n s t * 5 bits: l o p r u x If [newline] is kept in, it appears appears in the "5 bits" level, but (any) two characters have to drop from there to 6 bits. [Answer] # Ruby 1.9 - ~~160~~ ~~138~~ 113 ``` f=Hash.new(0);$<.chars{|c|f[c]+=1} f.all?{a,b,*f=f.sort_by(&:last);*a,i=a;*b,j=b;f<<[a,b,i+j];f[1]} p f[0][0..-2] ``` Ungolfed: ``` f=STDIN.chars.inject(Hash.new(0)){ |f,c| f[c]+=1 f } f=f.to_a.map &:reverse while f.size > 1 a, b, *f = f.sort_by &:first f = [[a[0]+b[0], a, b], *f] end p=->a{ a[1].is_a?(String) ? a[1] : [p[a[1]],p[a[2]]] } p p[f[0]] ``` Output for `this is an example of a huffman tree`: ``` [[[[["l", "p"], ["r", "u"]], ["s", ["o", "x"]]], [["i", "n"], "e"]], [["a", ["h", "t"]], [["m", "f"], " "]]] ``` [Answer] ## Perl, 148 With the `p` command-line option (counted in): ``` $b{$&}++while/./g;for(@_=map[$b{$_},$_],keys%b;$# _;@_=([$_[0][0]+$_[1][0],"($_[0][1]$_[1][1])"],@_ [2..$#_])){@_=sort{$$a[0]<=>$$b[0]}@_}$_=$_[0][1] ``` Sample use: ``` $ <<< 'this is an example of a huffman tree' perl -pe '$b{$&}++while/./g;for(@_=map[$b{$_},$_],keys%b;$#_;@_=([$_[0][0]+$_[1][0],"($_[0][1]$_[1][1])"],@_[2..$#_])){@_=sort{$$a[0]<=>$$b[0]}@_}$_=$_[0][1]' (((ae)(((rx)h)((po)(ul))))(((nm)(ti))((sf) ))) ``` Ungolfed: ``` # count characters $b{$&}++ while /./g; for( # init: convert hash to array of [freq,tree] pairs @_ = map [$b{$_},$_], keys %b; # as long as there are more than one elements left $#_; # merge the two leftmost nodes @_ = ( [ $_[0][0]+$_[1][0], "($_[0][1]$_[1][1])" ], @_[2..$#_] ) ) { # keep array in ascending order at all times @_=sort{$$a[0]<=>$$b[0]}@_ } # set up for print $_=$_[0][1] ``` [Answer] ### GolfScript, 54 34 characters ``` :)1/.&.,({{),)@-,-}$(\(@[[\]]+}*~` ``` The script takes input from STDIN and prints the tree in the following form: ``` [[["a" "e"] [["t" "h"] ["i" "s"]]] [[["n" "m"] [["x" "p"] ["l" "o"]]] [[["u" "r"] "f"] " "]]] ``` You may [try the code online](http://golfscript.apphb.com/?c=OyJ0aGlzIGlzIGFuIGV4YW1wbGUgb2YgYSBodWZmbWFuIHRyZWUiCgo6KTEvLiYuLCh7eyksKUAtLC19JChcKEBbW1xdXSt9Kn5g). *Edit:* In contrast to the longer version the character counts are not saved inside the tree but recalculated each time we need them. *Previous version with comments:* ``` 1/ # split text into chars ..& # create string with unique chars \`{ # for each char {1$=}, # filter the original string for this char , # count number of occurences ] # build data entry [char count] }+% # end of for-each loop ., # count number of distinct chars ({ # decrement and loop that many times {1=}$ # sort list by count field (\(@ # take first two elements of sorted list +~ # flatten to stack [[ # start new entry @+ # add count values @@[\] # join nodes into a new tree \ # swap count and tree ]]+ # close entry and add back to list }* # end of for-loop ~~ # flatten array ; # discard count ` # transform to readable ``` [Answer] ## Haskell (~~233~~ ~~228~~ 223) Not completely shure whether it is valid. ``` import List data T=Char:=Int|N T T Int s(x:=_)=show x s(N a b _)='(':s a++s b++")" g(_:=a)=a g(N _ _ a)=a i[a]=a i(a:b:x)=t$N a b(g a+g b):x t=i.sortBy((.g).(compare.g)) main=interact$s.t.map(\x->x!!0:=length x).group.sort ``` Outputs: * The quick, brown fox jumps over the lazy dog. ``` ((((('k''l')('i''j'))(('p''q')('m''n')))((('a''b')('.''T'))(('f''g')('c''d'))))(((('z'('x''y'))'e')((('v''w')('s''t'))'o'))((('r''u')(('\n'',')'h'))' '))) ``` * this is an example of a huffman tree ``` ((('a''e')(('h''i')(('o''p')('\n''l'))))((('s''t')('m''n'))((('x'('r''u'))'f')' '))) ``` Output format is like in the question, but whithout whitespace and whithout `,` between the two arms. I assume it's human readable. [Answer] Python 3.1.2, 132 chars ``` i=input();n=[(i.count(c),c)for c in set(i)] while n[1:]:n.sort(key=lambda x:x[0]);(a,b),(c,d),*e=n;n=e+[(a+c,(b,d))] print(n[0][1]) ``` It can't handle the empty string. ]
[Question] [ Write a program that accesses [Project Gutenberg's KJV Bible](https://gutenberg.org/cache/epub/10/pg10.txt), either from a file called `pg10.txt` in the working directory or in any other way that is typical for the language, takes a Bible verse reference as input, and prints the corresponding verse, with no newlines except optionally one at the end, as output. The standard format for a reference is `[book] [chapter]:[verse]`, e.g. `John 3:13`. However, some books have only one chapter. For these books, the format is `[book] [verse]`, e.g. `Jude 2`. Your program must accept this format for single-chapter books. Behavior when using the standard format with single-chapter books, or when using the single-chapter format with multi-chapter books, is undefined. Note that the "title" for the book of Psalms, for the purposes of this question, is `Psalm`, not `Psalms`, because references are usually written like `Psalm 119:11`, not `Psalms 119:11`. Use the following titles for books of the Bible. Single-chapter books are in *italics*. * Genesis * Exodus * Leviticus * Numbers * Deuteronomy * Joshua * Judges * Ruth * 1 Samuel * 2 Samuel * 1 Kings * 2 Kings * 1 Chronicles * 2 Chronicles * Ezra * Nehemiah * Esther * Job * Psalm * Proverbs * Ecclesiastes * Song of Solomon * Isaiah * Jeremiah * Lamentations * Ezekiel * Daniel * Hosea * Joel * Amos * *Obadiah* * Jonah * Micah * Nahum * Habakkuk * Zephaniah * Haggai * Zechariah * Malachi * Matthew * Mark * Luke * John * Acts * Romans * 1 Corinthians * 2 Corinthians * Galatians * Ephesians * Philippians * Colossians * 1 Thessalonians * 2 Thessalonians * 1 Timothy * 2 Timothy * Titus * *Philemon* * Hebrews * James * 1 Peter * 2 Peter * 1 John * *2 John* * *3 John* * *Jude* * Revelation | Reference | Text | | --- | --- | | Genesis 1:1 | In the beginning God created the heaven and the earth. | | 1 Samuel 1:1 | Now there was a certain man of Ramathaimzophim, of mount Ephraim, and his name was Elkanah, the son of Jeroham, the son of Elihu, the son of Tohu, the son of Zuph, an Ephrathite: | | 1 Kings 1:1 | Now king David was old and stricken in years; and they covered him with clothes, but he gat no heat. | | Psalm 119:11 | Thy word have I hid in mine heart, that I might not sin against thee. | | John 3:16 | For God so loved the world, that he gave his only begotten Son, that whosoever believeth in him should not perish, but have everlasting life. | | 1 John 1:9 | If we confess our sins, he is faithful and just to forgive us our sins, and to cleanse us from all unrighteousness. | | 3 John 1 | The elder unto the wellbeloved Gaius, whom I love in the truth. | | Jude 21 | Keep yourselves in the love of God, looking for the mercy of our Lord Jesus Christ unto eternal life. | | Revelation 21:11 | Having the glory of God: and her light was like unto a stone most precious, even like a jasper stone, clear as crystal; | | Revelation 21:16 | And the city lieth foursquare, and the length is as large as the breadth: and he measured the city with the reed, twelve thousand furlongs. The length and the breadth and the height of it are equal. | | Revelation 22:20 | He which testifieth these things saith, Surely I come quickly. Amen. Even so, come, Lord Jesus. | | Revelation 22:21 | The grace of our Lord Jesus Christ be with you all. Amen. | [Answer] # GNU sed `-En`: ~~ 330 321 303 298 ~~ 283 bytes The reference is given in the first line. In real life you can do this like `sed 'the script' <<(echo Luke 19:10;cat pg10.txt)` ``` 1{s/^([123]) /\1/;s/.* S/S/;/:/!s/ / 1:/;h} /\n/!N;N;/^.{5}$/!D;n;n;s/\r//;/Bi/D /Ac|La|Re/s/ of.*// s/The Fi/1/;s/The Se/2/;s/The Th/3/;s/^[123].*M// s/[^0-9]* //;s/ms$/m/;G;/^(..*)\n\1/!d :1 n;G;/(.*:.*) .*\n.* \1$/!b1 s/\n.*//;s/.*[0-9]:\S* // :2 N;/ *[0-9]*[:*]\S.*/!b2 s///;s/\r\n/ /gp ``` **Explanation:** The first line forms the given verse to remove the whitespace after a number, rename the Song of Salomon and add `1:` for one-chapter books; this gets saved in the hold space. The second line finds book titles, the following three convert them to a canonical form and check for a match with the given verse. The rest of the script search for the exact verse inside the book and strip it to only that verse. This was the original POSIX `sed -n` version with 298 bytes: ``` 1{s/^\([123]\) /\1/;s/.* S/S/;/:/!s/ / 1:/;h;} /\n/!N;N;/^.....$/!D;n;n;s/^M//;/Bi/D /[ALR][cae]/s/ of.*// s/The F/1/;s/The Se/2/;s/The T/3/;s/^[123].*M// s/[^0-9]* //;s/ms$/m/;G;/^\(..*\)\n\1/!d :1 n;G;/\(.*:.*\) .*\n.* \1$/!b1 s/\n.*//;s/.*[0-9]:[^ ]* // :2 N;/ *[0-9]*[:*][^ ].*/!b2 s///;s/^M\n/ /g;p ``` [Answer] # JavaScript (ES6), 216 bytes Expects `(text)(reference)`. ``` t=>s=>([,s,v]=s[M='match'](/(.+) (.+)/),t.split(/\*+|[\r\n]{10}/)[(n=t.split` `.findIndex(r=>r[M](s.replace(/\d/,n=>` ${"_FST"[n]}.* .*`))))?n-21:64]+0)[M]((v[1]?v:"1:"+v)+"([^]*?)\\d")[1].trim().replace(/\r\n/g," ") ``` [Try it online!](https://tio.run/##hZTZkqPIFYbv5ykqFI4YqWkX@9YT1RMCxCIhsSOguuxmX8QOAsR4nr1dNbbDc2XnRUbk@f5zzp8RJ7PwJ38I@7wd/1o3UfwjefkxvnwdXr5uXz8Pn6e3l@H1/PJz5Y9h9vPbFtw@A7unjw3cfR6fh7bMxy347RPwj9dv/bf67TcY@h3cvW7rl3/D7z99f07yOpLqKF62/cvX/vX8th2e@7gt/TB@z43Az/XL1@9Pf/lt83feMDev9dvvz5@enj99372vX@u/IvAXAnsDoN1H5nZ6hd9@nb5s4C8bYNoBm@3r394@/br79i3a7N7R89jn1Xb3p/rvtsD08@Zps/sRNvUwPiXD08tTH3f3vI@3m2TY7H756V9kLfPgz@zj/F9qHhzznX4En/M6Kf0x1v3ZeNThlrknSdw/J31TbZOPy/kRn5fxHwzaPY@N8W6rTre7z0@bwB9iAtvs/hz@5ac/ejRl/Fw26TbZfvTabTdCXMdDPjzBX@DN7gl42nyr/@Pnf2iR/6s9LE10/5Ci7z5@@dHaySXIBvQgYzLEDRrBwloWZW1qufgj8YSyOspZpx18qYm7C7rcMsFxVE68Ao4d39OC1i1iphH7aF0VPDJYyUDxJFS8AAtCLKBBkDxbs0IMgHZqPUJNNR/c4@l8L/jbGlJ0AzSqpXjTvM9Wkrl4xwapBYx68A77PpJZAUTmKEs6wvG6uCwkshx0KTwc@76I@L2DW3sWWjtFHXVjprwrWtwhs3euQWQKSuzNVi0bFUH7dNwVvOVhON7OsMxKx9aG0kmwYzO97526t2b6fs@J2mpncp6pVEFWFIJTJqLSgZ5nwhmGcgYbxu7akNHpMdmvd7cptGukAQDJ8FVehzETlFf8xratpJRWllJuBBIphxS2b7iQ38QX206ctRxnFDiDAo08uLrmLZ2Z1PJwwwmHP9c2gWo0czoN1kEHQprI96ljxQ022tcu0g5kjAiw1aF0NgVoiJ3OXGwJh7YnjaW80@Do7onSXveYHE9Q5Z7ZIm1vvtjvs/ygVlK@isVIAvQY0Lco0k0gmhJi7VsxmuDxVGmWBZ2GC/uwvcfeG/b@Vdyndo4jNEGqKwzoo483Qa@q@7CEMqjvNJOO@2jtRqens1zx5gmJZ/oKYzUpYED1MBxjDYj74VHxVEktx5OMxAtXq8NcN6TriXkgX/LakzF3JdyRQI5U6J3nyyXwjxpfXQVcltnc0tQBoavIlmKP9E0Bi9Ixa5W9QB6lPgtvYaq5taPBoSZ0c95QxY2kz3zWpGSOkryCCWJnOL420gEm86fiodRaYIw35wQ8YsbGWN5vIGTxXWEk2WNoyHNKChoec8gCBEyOXDpZTHWNgS4JGnU1rXUJ/EBSupw6L2QlXGjTLsHvOHfrVkgK9w3LDjUPVkVOHDWiFGJYRbmaErMOHiyT2QMFbyA6VJ4MhQThx5XJblomVKHcJIZ6oezziRLWAeDimDzjang5g0DdmB2eiIdVJMY1IosjTWWBPUD0nu37XHHpyD2eisty4biDBEZBFSNYeYMUTvCnCi@Nkjbl24lhZDInUNuN1nvS6HqTxf499vDVsJQW41wFdWTeeojBZMY80Y9kgMRr4c69FvBZlXXB8u7PZe1je4EfBWl2sZdFKhbjbDzWJT68T7g@VhwBjI1birUZPG7jybCA5Sxm2n1OH7pErxbK0jbV1DeWuOh6fEC5U3CYKJ1Iq/BwDeQJy3VXQHB@Fe8ZbzxkHjzcQ/OCof5VsW8gw01hJ6YHUGJZnUprOXhYTOLiFR4OIxTh/H3i/Oikw/Kejg6EBDDtle96QZFRXeZjcpKzY/GodXe4IYAazIEggW6VivTJyBYURhuF100VqkCDvF0PnIuOVzME5to2F5WAo@sdVAq5TB6S6ZEgCVwQ2Z6tYmRqUmUEfXLqbk5LuDdPuWIOkc6S7Njq6R4p1hZZQU1C3p0kAwR4lBpZtrfw8Ogf1hWmIGsaMuK8XkjeWaq4lnMqpxjNSt@/AY@oIck3955J91HJn3zkLLWMwwTYZaCyglnNAY34hFg6EL1pnH7mUYcOuGIIzUd5cs1zGQKHQ8BhhH5GhXl6gIURwtcToFq2oClXeOrq8EaLgWqPY/7@GCX5fB0Lb60asQ@Cc2YNup2jKWxn1@NxMiZAgTT7luKxeq3VboR5jaGOqauzxFTY51hor8i6niV/2dN0xvIVA8mgh41J6@b2kqYYkheqaDV61BQoItg2w9BAE8B7p5HJh1aVLAid7qR3w/GTuTi@kBwGtG0Inl28kU8aKm/0dNUqfx@Cw7E3QEM3Ovbo6LVHM/Lt3I1SiEWM34C1ddcu2B1SFcim8DCCMBGq8kasBv20rhZfmffljtAPCHa0tYKBLFoOV0PlpJ69rEeb5lSjvQ3xGSjzQuTLYrUFROaVIR9xTnQilBPGKZ1ycVl7Pk19uj/PUUuigT@dk5JiZK@p2aBQFP4CBCHMxVTpX2nhCE5SglWxDCcnCYsRgj2ld2NqrPxRANzVipeGV42mVTVEvC3ZjcKEyKWdyXFAdX55@Sc "JavaScript (Node.js) – Try It Online") (The TIO code works on a small extract of the original file.) ### Method 1. We compute the book number by looking for the line containing the book name in the summary. There's a special case for *James* which appears on the very first line of the file. We also have to be careful about the misalignment between *Malachi* and *Matthew*. 2. We split the text and extract the relevant book. 3. We look for the requested verse in this book and format it. ### Commented ``` t => // t = input text s => // s = reference ( // [, s, v] = s.match( // split s into: /(.+) (.+)/ // s = book name ), // v = "chapter:verse" or just "verse" t.split( // turn t into an array of books /\*+|[\r\n]{10}/ // by splitting on "***" or "\r\n" * 5 )[( // n = t.split`\n` // split t on new lines .findIndex(r => // and find the first string r r.match( // which contains: s.replace( // the book name /\d/, n => // with the leading digit (if any) " " + // replaced with a space "_FST"[n] + // followed by "F", "S" or "T" // (for "First", "Second", "Third") ".* .*" // followed by ".* .*" ) // end of replace() ) // end of match() ) // end of findIndex() ) ? // if n is not 0: n - 21 // use n - 21 : // else: 64 // use 64 for "James" ] + 0 // get the n-th book and append a "0" ).match( // then find: (v[1] ? v : "1:" + v) // the verse header, + "([^]*?)" // followed by the verse content, + "\\d" // followed by a trailing digit )[1] // end of match(); keep the content .trim() // trim it .replace(/\r\n/g, " ") // and turn line breaks into spaces ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~80~~ # [Jelly](https://github.com/DennisMitchell/jelly), 66 bytes ``` ḢfØDV+2ị=”JƲo1 Ḳ-ị⁹œṣ⁷x5¤¤ỴḢwɗƇị@Ç{ỴKḲ<”AȦ$€œṗ$Ḣ⁼¥ƇḲṪ¹⁾1:;$f?”:ʋḢK ``` [Try it online!](https://tio.run/##pVg9jxzHEc3nV3SgzGOBe5REcmlDvjMJ6o4iafAoE1DWs9O709yZ6XX3zA33nIhOFCh0IDtwYssODEeEAZOQ4YCCBdv/4u6PnF9Vdc/uHk@QAW80/VVd9arqVfU@M3W9vrg4e/X7@Te/ufPzH@ydff3Fj88/@93Rty/dJDt79fKHmDh/8fqfvz57/YfzF397/v6br958dfb1X3Fi@PeX336O5Z988/kvMXMfu3@Eo/v/@tM757/6C5348h1sO3/x9zd/xMZXL89e//nN6/MX/5hMb78z/xBbp//5AhvuX1xcPNBdV5lB7U0nNy@eVEY9xOCJCZ1uTNspN1dYVvdtu1BHmArqwBa1yehHu@@5sDK12p/NnC9pU@fUsbY4GQVj32Q6UbS3cG6ZBC5Ma7zurGtp5siEPqifVt6GLuf1IAt39IkteSaLM/uF15Vu3iWxe2mkCrPQnToMWs9uK92W8hmnj/TMFTLNn2m6L3XIaLayQRXedJU37W01mV5X@7SX1uPen1Xaw3ba/Kn2mhR5gnu1Z7FZXJa9d4N3jVzHn3F63@uGhL/HwmmUFhrb6lIXt1mXNIqLD7UOsFzExUFcOtZ141jf91mkjDNZPHDulLR8rGeVjsbznCw/KkzJy31XySLP8GIGbwRDcj8QHGgYz7E/2EFLOFtO7s5FGceudo14rDIeqzhcabrBtLx3sHNDq594qwNddkOMiOdEymNXOB2xlO@EWWG1TNNXmgyaBN0UgINO5rigV7g/RkAcpSBwPl3Anwmf06jVLRKW8XA8oWHNeIYHSQFgfRrVos8UEKdmSeIoEa6xcnEmrj/QLfxqgpxMozE6kvf3N96FEVG/yUR8xBNJQzOrXEvjy8GdK124vsvIAZ1tDHlirQbjjZpp7y1CQA96TUl8oIt17dop3bHHd@h5x56MJ7LCu35RdVub862rxxgFQNbUYsI4jK751HlX6IKWcY2k3Ti3cXVfjr7uywRqbfXSNpI0cZBOnDrPAmOqYTiqU7pZUgWfUQ04yzaj30Y5kEo3Q5AkGI/HNaNPU/rHwehOEJ9ukzd5sMtEkBhTa0NHFKZmVXFuVH0o6DDS44H265w@hgpMMhCwzrdCmDlNKrh3puvalJnwJzPj5AYySWH6EtkGNSdGSrQJ10n2gr7U3PW@Q3pmW9vFCD4jG/u2syKUAmZNCc8RA8Yfw4CkZUmaulra90jANS7as6PbtjQx9KZ66AYWV1jfVZerCUPmiHKA02CDmaqnFeRgFjNZ4zqiJ0KZd5qwcn1AGkAXcUgO98ydj6ky05Q0bmHoWK4CERmKCNSDYYPF/YifukxV7iNXr9W9yiWv3KI62EbJTIzR1XQLI6Ge9VC60ZSqENk6WGDrWipr1uil4WNarfqitrOlMs91s6pNzuqjdpSi/KrvZCNBu/L2xNZrqZnX1AHWBqhJoqCmZDFjZAJN4LJAClWultoLVRbIRzEq@/jR4ztKr1YGjuGAcIpyxgJUVXqjG@Ciya/5CCFdslvSszmOs3k43pFZLAjyjXijq9ZcI6bwfawf0HlWcby7dmbsCUIel5KVmLsa8T2hR/JTqCgdCk9QQiRcpUklwVkUxI6Ok4lJs4Wvs6O7x58ciw6jjKBPDO9YGQfox4C2XgUb43Jvj@NSMpBCD94pXWtyMcXCx5ZgL3C8r@eWEjgaSAGFMFyaNhn1MXorVaz5e@XdqjLdBmPcdV0dRGdpdWL9AqiwpqgWW0Epln4PDIhx2ZFgyAgGdbdBSPamzqOOEq1IWeNXqC3Q3SJk7rmYBH0E4b2deJdDXltKMAYt1MasVEkEFN4KNDY746bBliXEIMqimtRIjoEnmU2RghuFqZctmlgKDA4wgJtRBLCoWLTEdNoytz50TKqByh2XTBMpdYwDxXEAo9Ams2MHtouJZiRlwH4AYqhNZRrmITSQRtM0WVPqNUVp9pHxbtMu7eQZl@HGME8ptN8bqjQ6UKagNfN90LUBEHtof49jDDzls9CVE5riK6rEfXuE88gM4UMyPBsIC8RwMIxqUOj2fdKTrhKYiXhnjglPDc6Hyq4IcEbhutDorjGMcIXELi9xidCk6gA@Hg8SiRkF2GiPxE2SLoWbMY5@Q4UkG8uxpiGkzZyYDU8VaXTCzNvCJCbIYnJuyJp8YBDGpUn83NAVMDKWigASqKnAM3asiISTpIW2G7bL1eGVzk5shbCw5IVs8LbrYMbl7N2LzTUTzygoT06oY/knqXmmfSeRTCscChq94CJKtCDDkDaLAujxoomRszL2o0aGnhjfOh9pSFLd98CpWSc6Owxem5rNvyH5y17Od/wRS0rKE@noJWpzZdpf9NYzzBnDXNraonJ3ODDQvan3lMBLtYSvlO6dluj5yaepL9ggxK7W9Cq852SAw6CkzR2Z@MCoNcryQshPWg@2YB2jX4o2O1PokDKPmFYv8IDNM0boELV4LVnAAjZpgEgMjlW@JbnAUbKTATHDeaE0K7jRiCK5ql0@ApBnQqoxzIbdTBwIh00PAm2J0Ci8mCsYARBimZFrY0BfMp6ST7jr2paqdNOogkx588zZmYksbp7PjOFH/QJlvVPP3FqkTDbpufWAIIxsLOKqojYq371oS6OML@BCT/wjbZj4dm5gXemGWJIi4ism42a6cSOJ5urgVugJy1iAO2gaejzG492oThRI243Kws47tKILF0tiNve6XVIWtUHwbNbeV2KqPH2kcg3at8IdVOg2/Y7kUqydTCGUrCiLPRgYpB3TZycMRqSgM2wFetAPaOhWOlK0baLA9auwTlK@u0uT4hkzC1CP/eyVfdo@@M/E2kq92OitTOInvSN3/ITaLVbcXaxXsWQU0lDGYiaPhcNM0ovZiBJMOEpKBzW3VIeWb8UsBJfgdu/WY1nAg@5p5CDtHWlM9Y6agcuHdxUm9m2p3cr5tbjrA9Z@Sv9/CdkP0oqM6nPtRvjz04KVnmb/Sw@nvrOHy97q4R4JX7MqQk6HiVnBy@hLxPwPrqRjSS/6f0WqbONmy7HEbbEy9ZWblB48oIlsSgzDDVEc12bYrrM1oqWNLTg9/Lf7HDlBMZX2O00FmRF08zy2MIMD7WqPMiXOyUC9HEjb/xuO/0oIhrHSbNWOrbrCOCbbBJ1YrAiCjTu2Hg5bPoEf0HmYZrcoZ8kd9F8oFfjHutFb8YDmmthR@B0Uzv@Q8ltUeGRAM8vnCRKhzAbv1pbn6I84ZGfcEx8UfoQ3ShjZo2BCJadIls90H@IblNoybBGjb8XX3NiL8UPD6C1q0O3bzKBGZsi2eWybJGJW79GL8fj/4ImF21SF1NZIi5GaJbEpI62jq0L8Z2k3q88/@21QNTr9d/nvZxV//wU "Jelly – Try It Online") A pair of links that is called as a dyad and that takes the pg10.txt file as its right argument and the required biblical reference as its left argument. TIO fails with the full document (presumably because the POST exceeds the maximum size), and the links to TIO on CGCC are even more limited because of length. However, it should work with the full text if run locally. Pleasingly now code length in bytes == number of books in bible. ## Explanation (outdated) ``` ḢfØDV+2ị=”JƲo1 # Helper link: Takes a bible reference and returns which number book should be used that matches the textual part of the reference; half the code is to handle the John letters Ḣ # Head fØD # Keep only digits V # Evaluate (will be 0 if no digits) + Ʋ # Add the result of the following, applied to the helper link's original argument 2ị=”J # - 1 if the second remaining character is a J, otherwise 0 o1 # Or 1 (replaces 0s with ones) Ḳ-ị⁹œṣ”¶x5¤¤Ỵ€¤Ḣw¥Ƈị@Ç{KœṣḲṪ¹⁾1:;$f?”:ʋ2ịwⱮØD;€”:¤œPƊḢḊ # Main link: takes a bible reference as its argument and returns the verse Ḳ # Split at spaces -ị # Penultimate part (will be the last word of the book title) ⁹ ¤ # Using the following applied to the right argument: œṣ”¶x5¤¤ # - Split at five consecutive newlines Ỵ€ # - Split each at newlines Ḣw¥Ƈ # Keep those where the first line includes the book title word from earlier ị@Ç{ # Index into this using the result of calling the helper link on the original reference (so returning a single book) K # Join with spaces œṣ Ʋ # Split at the substring determined by calling following on the original reference: Ḳ # - Split at spaces Ṫ # - Tail (i.e. the verse or chapter:verse) f?”: # - If contains a colon: ¹ # - Leave as is ⁾1:;$ # - Else: prepend "1:" 2ị # Take the second part (i.e. the bit immediately after the chapter:verse reference) Ɗ # Following as a monad: wⱮØD;€”:¤ # - Find the position of every sublist that comprises of a digit followed by a colon œP # - And split at these ḢḊ # Take the first remaining part, and then remove the first character (which will be the space left just after the original chapter:verse marker) 💎 ``` Created with the help of [Luminespire](https://vyxal.github.io/Luminespire). ]
[Question] [ We already have a [challenge](https://codegolf.stackexchange.com/q/151436/9288) for polynomial interpolation: given a list of points, output the coefficients of the polynomial that passes through them. [Hermite interpolation](https://en.wikipedia.org/wiki/Hermite_interpolation) is a generalization of polynomial interpolation. Instead of just specifying the points that the polynomial passes through, we also specify the higher-order derivatives at those points. If we have \$n\$ points, and we specify the value and the first \$m-1\$ derivatives at each point, then we can uniquely determine a polynomial of degree less than \$mn\$. For example, the following data uniquely determines the polynomial \$x^8+1\$: | \$x\$ | \$y=x^8+1\$ | \$y'=8x^7\$ | \$y''=56x^6\$ | | --- | --- | --- | --- | | 0 | 1 | 0 | 0 | | 1 | 2 | 8 | 56 | | 2 | 257 | 1024 | 3584 | ## Task Given an \$m \times n\$ matrix \$\mathbf{A}=(a\_{ij})\_{1\leq i\leq m, \; 1\leq j\leq n}\$, find a polynomial \$p\$ of degree less than \$mn\$ such that \$p^{(i)}(j) = a\_{i+1,j+1}\$ for all \$0 \leq i < m\$ and \$0 \leq j < n\$. Here \$p^{(i)}(j)\$ denotes the \$i\$th derivative of \$p\$ evaluated at \$j\$. For example, if \$\mathbf{A}=\begin{bmatrix}1&0&0\\2&8&56\\257&1024&3584\end{bmatrix}\$, then \$p(x)=x^8+1\$. You may take input and output in any convenient format. You may transpose the input matrix if you wish. You may flatten it into a list. You may take \$m\$ or \$n\$ or both as additional inputs. Here are some example formats for the output polynomial: * a list of coefficients, in descending order, e.g. \$24 x^4 + 96 x^3 + 72 x^2 + 16 x + 1\$ is represented as `[24,96,72,16,1]`; * a list of coefficients, in ascending order, e.g. \$24 x^4 + 96 x^3 + 72 x^2 + 16 x + 1\$ is represented as `[1,16,72,96,24]`; * taking an additional input \$k\$ and outputting the coefficient of \$x^k\$; * a built-in polynomial object. When the degree of the polynomial is less than \$mn-1\$, you may pad the coefficient list with zeros. When the coefficients are not integers, you may output them as rational numbers, floating-point numbers, or any other convenient format. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes in each language wins. ## Test Cases Here I output lists of coefficients in descending order. ``` [[1,0,0],[1,0,0]] -> [1] [[1,2],[0,0]] -> [4,-7,2,1] [[1,2],[3,4]] -> [2,-2,2,1] [[0,0,1],[3,11,33]] -> [1,1/2,1,1/2,0,0] [[1,2],[3,4],[5,6]] -> [3,-14,21,-10,2,1] [[1,2,3],[4,5,6]] -> [-3/2,9/2,-7/2,3/2,2,1] [[1,16],[209,544],[1473,2224]] -> [24,96,72,16,1] [[0,0,0],[0,1,0],[0,0,0]] -> [-1,7,-18,20,-8,0,0,0] [[1,0,0],[2,8,56],[257,1024,3584]] -> [1,0,0,0,0,0,0,0,1] [[1,0,0],[0,0,0],[0,0,0]] -> [3/2,-207/16,713/16,-1233/16,1083/16,-99/4,0,0,1] ``` [Answer] # [Mathematica](https://www.wolfram.com/wolframscript/), 76 bytes Mathematica has built-in [`InterpolatingPolynomial`](https://reference.wolfram.com/language/ref/InterpolatingPolynomial.html) to construct an interpolating polynomial that reproduces function values and derivatives. [Try it online!](https://tio.run/##JYxBC8IgGEDv/YrBoNMXTttqFIMuHRYEu4uENFfC/JThwRB/uy26PR6PZ6R/KyO9fsqcp4t5nLoevVqcnVeJr8HOH7RGy5nfpetxVEGN/GY18lgyzqkQO5qgpGILRkAQhFyDkzjmdbroUHRFjBQqqBJEBi00hx80R6AVq2HftHVK583E/7koCBkWjT5/AQ) ``` f@m_:=InterpolatingPolynomial[MapIndexed[Join[{#2[[1]]-1},#1]&,m],x]//Expand ``` [Answer] # Python3, 604 bytes: ``` import math E=enumerate def M(p,*P): for i in P: D={} for a,b in i.items(): for A,B in p.items():D[a+A]=D.get(a+A,0)+b*B p=D return p def O(p,*P): for i in P: for j,k in i.items():p[j]=p.get(j,0)+k return p def f(A): z,l,d=zip(*[(i,a[0],a[1:])for i,a in E(A)for _ in a]) L=[[(a,[i])for i,a in E(l)]] c=1 while len(U:=L[-1])>1:L+=[[(d[min(U[i][1])][c-1]/math.factorial(c)if 0==(D:=z[max(U[i+1][1]+U[i][1])]-z[min(U[i+1][1]+U[i][1])])else(U[i+1][0]-U[i][0])/D,U[i][1]+U[i+1][1])for i in range(len(U)-1)]];c+=1 return O(*[M({0:a[0][0]},*[{1:1,0:-z[j]}for j in range(i)])for i,a in E(L)]) ``` [Try it online!](https://tio.run/##fVFNb@IwEL3nV/hok4HaCWnZrLwSVXqjai97sqzKBaeYJiFKU@0uiN9Oxyll2yysZMX2vI8Zv9R/2uW6iid1s9@7sl43LSlNuwxupK1eS9uY1gYLm5NbWsPgnqUBydcNccRV5B4vJJPbHW6@aODRl93ItbZ8oZ77Dkzh2gP1EciUCadaZqMn21I8Amfh4@Aa@bXMAtLY9rVBftf47kxjf1vB89eOtVppWXe2K2/63DPL6dQ7baCAhdy4mg4UdWAU1/gRqWZdDzDe9Qa5/vrgL0azgMykUtSAcj1ewbQOyFyKgPxausKSwlb0Zypnaig0@yHSWeiVC1U6rKNcYVmrOaIXPuxRbubtunGmoHPmcsKlpFkqN6o0vz0/FF4RHpXDzYdTH2G2eLEfANfDDuCaXWRw4IRHFTvm2ZjqydJuaDYU@Jjv89A/5hDdHaZ0S7c89Tnh2sFAbUUqgKc4yUrvul/x18ixXj4zLOzrxlUtzalSAgjHpYGoCMgESHLZnZMrIIJHYyBxMhlrzVjwWcQBJYe9j0WInKvH0PdCJogOEQLi@KwKVAKX/6IQIzKGU5jAl6iIf4Nk7OVifBVDFEWnBuDdyOKwnxr@nRPBBJLOFvPp4vlPOvzLjpz9Gw) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~99~~ 94 bytes ``` FLθF⌊θ⊞υι≔Eυ¬κη≔×⁰ηζFLυ«≔Eυ⎇⁼κ§υ⁺λι∕§§θκι∨Π…·¹ι¹∕⁻§ε⊕λ§ελ⁻§υ⁺λικεUMζ⁺κ×§ε⁰§ηλUMη⁺§η⊖λ×±§υικ»Iζ ``` [Try it online!](https://tio.run/##XZDLbsIwEEXX5Cu8HEuuRPrasELQBVKhUcUuysJKpomVxGn8QG2qfntqByiGjS3fmXvmjvOKq7zjzTh@dIrAK8rSVNBTSqb3VkjR2nYSEqsrsIwIuoiWWotSwpZ/emXXGagpZaS6lPaiRQ1zrzEyOD3kW4f7iWbXlD0qydU3vPSWNxpqRpZmIwv88sWksRoaP9zPWYuDKBDO9fPdM1JT38PIm4JEdYXNDWxk7szigO9clgjxBGEkDkBuTYc/Y5AR51HYojRYQOMbg9r0vnZcB/Qpppjo1p657VZd23JZwHBqc6sdvyegzoMh1TSE3rirkzvoWuNNzCN2hyU3GKb7T7WIfqNECWlgxbWBwSnjmKZpzO4zlj6wR3c@secsy8a7Q/MH "Charcoal – Try It Online") Link is to verbose version of code. Outputs the polynomial coefficients in ascending order of degree. Explanation: ``` FLθF⌊θ⊞υι ``` Create a list of x-coordinates `xᵢ` where each coordinate is repeated by the number of times equal to the number of differentials provided. ``` ≔Eυ¬κη ``` Create a unit polynomial. ``` ≔×⁰ηζ ``` Create a zero polynomial, which will be the running total. ``` FLυ« ``` Loop over each row of the divided difference table. ``` ≔Eυ⎇⁼κ§υ⁺λι∕§§θκι∨Π…·¹ι¹∕⁻§ε⊕λ§ελ⁻§υ⁺λικε ``` Calculate the row. For each cell, if the x-coordinates of the triangle that generates this cell are all equal then divide the appropriate derivative of that coordinate by the factorial of the row number, otherwise divide the difference of the two cells from the previous row by the difference of the x-coordinates. (Some additional bogus entries are also calculated but none of them affect the final result.) ``` UMζ⁺κ×§ε⁰§ηλ ``` Multiply the (originally unit) polynomial by the first entry in the row and add it to the running total. ``` UMη⁺§η⊖λ×±§υικ ``` Multiply the (originally unit) polynomial by `x-xᵢ`. (This generates a bogus result on the last pass but since it won't be used this is irrelevant.) ``` »Iζ ``` Output the final total polynomial. 97 bytes for a version that accepts a list of x-coordinates as an additional argument, rather than assuming that they're 0-indexed: ``` FηF⌊θ⊞υι≔Eυ¬κη≔×⁰ηζFLυ«≔Eυ⎇⁼κ§υ⁺λι∕§§θ÷λL⌊θι∨Π…·¹ι¹∕⁻§ε⊕λ§ελ⁻§υ⁺λικεUMζ⁺κ×§ε⁰§ηλUMη⁺§η⊖λ×±§υικ»Iζ ``` [Try it online!](https://tio.run/##XZDBbsIwDIbP9ClydKQgtUibJnFCsAPSYNXEreIQtV4b0aYjSdHGtGfvnFK2wMnJb/v/bOeVNHkr675/bw2DirMhbpRWTdfAkXOWdraCTjDF59HCWlVq2MgPr2xbBwfOBav@UzvVoIXYa4KdSR/8XlCXjlzI7jua3Lrs0GhpvuD52MnawkGwhVvrAj99Mq07C7WHe85KnVSBcM1f41GwtXZjkopHWrAE9w6CvRpITVt0uYO1zslanfBN6hIhGRCCJQGG@gl@haCH5AYb1A4LqH1hkBv@tx234wtGp/IB6SgT2n3ZNo3UBZzHMlr8crzANQ4g1QDhd93V2B1UrfBuzIvtFkvpMJzub6p59BOlRmkHS2kdnEnp@yzLZmL6JB4e9yJLRCxiijMxCPSaeinZ7/vpqf4F "Charcoal – Try It Online") Link is to verbose version of code. [Answer] # [PARI/GP](https://pari.math.u-bordeaux.fr), 52 bytes ``` f(a,m)=a/matrix(#a,,k,i,derivn(x^k--,i--%m)%(x-i\m)) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=XZBRasMwDIbZW48RUgo2_GaxbDfZQ3cRzy2GrcN0KSakJTtLX_oydqbtNHOapjRDIPRJ_y-ETt_RN2HzHs_nr0O7FdWP3jKPmq_8Y-3bJnRs7oEdAl7fmnDcs269EwJBiEXNF6wT4aXmfPD-Psx8jB-fzGfiOYtN2LepzHvIs7TWSgdvyXGOzForUaS4ZAfl-p4EDUg3VNAjDnIFmZK6tyQNDJb_bENrVMklqHiC0RpSlwpENFl8u2V6T4-ECibZTQlZkIYylZ4q7qIfuOtDxqf-AQ) Takes input as a flatten list and \$m\$. Outputs a list of coefficients in ascending order. Using the fact that Hermite interpolation is a linear map. We can construct a \$mn\times mn\$ matrix, whose entries are the \$i\$th derivative of \$x^k\$ evaluated at \$x=j\$, where \$0\leq i< m\$, \$0\leq j< n\$, and \$0\leq k< mn\$. Then we can multiply the flattened input by the inverse of this matrix. [Answer] # [R](https://www.r-project.org), 149 bytes ``` \(y,n,m,o=m*n-1,z=y,v={},`^`=c){for(i in 0:o){v=v^0+(z=ifelse(x<-i:o%/%n-(j=0:(o-i)%/%n),diff(z)/x,y[i+1,j+1]/factorial(i)))[1]*T;T=0^T-T^0*i%/%n};v} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=ZVJdjpswEJb62FMg1JXsZFxsQwJky_YGfcobP9psFiqvCETApvlpjtGnvqSVeogepT1Nx8CGZCtkz3i-H88If_9RnX5mwa_nJmPen28R2UEBKyiD1ahgAvbBDjbB4Qj3yX2wpIesrIgyVGHwWUkPm2CT8DHZBypL8zol2w9Mzcob66Zg5CngM1IyRfWRwqPKMrKn1hZ2oRoLeBqL2MoWy6as1CInilIaing0v50HPJmzecJHSiuPt5tj19zfN7_NMBTAgcfQx9hgdwbq3mpAYnkoOsBckHCB2eD0mAQmXzBUYKJRIcC2XyxBWEhod-15ZQLhBKY90QYmHJACA7-4DmxkOTDwmI1OPi7m4qYPZ7KYIldyHyaO9haOa4OU8tysA_4UXKRPh455O6vo4zA1_jIXW_FAcmAe8KH5TiPBg0l738QFwdHbnnjOeWh-9YlLJb-K_fB6HsldC1tzha0DE9JuE8G9ruD7ltPbmcbXO4NEZEs_188PxDTCJCrikQmGiWtLKaGaUTdVvc5VQ8yoMNtKmndIq63T5tNildZke6HpEG2aRFFI3o9oFMXvtPPyQRWPJIoENV_zuy46_kctaPn_cfPFep3vWkW6wce6XlT42JsACa_xTDdVVOUXzDFZljnRrO4Fn05d_Ac) A function taking the matrix, n and m as arguments and returning a vector of coefficients, starting from the zeroth. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~71~~ 63 bytes ``` I÷ḢṛṪḢ?@"Z} FJḶṚ1ị+",Ʋ:L_/żṪ©ị"¥ɗ÷"J’!Ɗ$Żç\Ḣ€Ḋ×"®Ḣ1;$Ż_×ɗ\Ṗ¤F€S ``` [Try it online!](https://tio.run/##VVFLS8NAEL73V9TQm7NkZ3fzsqCeCoo3QbAPevIi/QMehOKlUG8ejPVxEUUU8VDEJlQ8JLTQn7H5I3HSpk1L2JnZ@R47Q87POp2LND2IRzp41uGDDj@o2Ns36pel2qEOfnR4j3p8vW3AdLhz1DYnv0SJ3qllRK8zPx4Zh0l3sDXtVybj@K1J4uTqUwf92DeiL7phlYB27M/8pg5vo5cawcepDv@qSfexzHbLSfepGvcmNzq8q5R0OMB63Cvp8bcOhiQ/mfZJEPconKapYRiNBgIH3oI8tzKPBrZKGSCoXTQVMAcErGESVI4JYGKJkYKKDEUEKZeWgCYR5jHz3DCBhgV2TpTAUIFASnztOZDEUlDwmCQnjw5zKGSXFRlt4grugaUyb1SOBCHEalgFng0O0e1iYj7fFfNcbM0QHBrFBcGBucCL4RcaAS5Y8/csB5CTt7RctVqab3y4ruQbOV8@20dwx6TRHJRZYijkvEDuLhqeZ6rcjv7gPw "Jelly – Try It Online") A pair of monadic links that takes a list of lists and returns a list of polynomial coefficients. The argument holding the input is transposed and then rotated both vertically by 1 such that the 0th column appears at the end. This is done to best fit with Jelly’s 1-indexing and the fact that zero refers to the last column. The output starts with the zeroth coefficient and works upwards. Updated to a more efficient algorithm, but still based on the one on the Wikipedia page. ## Explanation ``` I÷ḢṛṪḢ?@"Z} # ‎⁡Helper link: takes the current list of values for the divided difference algorithm on the left, and a list of the x differences and potential relevant derivatives on the right and returns the next column for the divided difference algorithm I # ‎⁢Increments ÷ # ‎⁣Divided by the right argument Ḣ # ‎⁤Head (effectively gives the differences divided by the x differences) @"Z} # ‎⁢⁡Take each pair of x differences and possible relevant derivatives as the left argument and the relevant divided difference as the right and do the following for each: Ḣ? # ‎⁢⁢- If the x-difference was non-zero: ṛ # ‎⁢⁣- Then the divided difference Ṫ # ‎⁢⁤- Else the relevant derivative FJḶṚ1ị+",Ʋ:L_/żṪ©ị"¥ɗ÷"J’!Ɗ$Żç\Ḣ€Ḋ×"®Ḣ1;$Ż_×ɗ\Ṗ¤F€S # ‎⁣⁡Main link: takes a matrix as described above and returns a list of coefficients F # ‎⁣⁢Flatten J # ‎⁣⁣Sequence along flattened matrix from 1 to length Ḷ # ‎⁣⁤For each of these, sequence from 0 to value minus 1 Ṛ # ‎⁤⁡Reverse Ʋ # ‎⁤⁢Following as a monad (argument z): 1ị # ‎⁤⁣- First list within z +" # ‎⁤⁤- Add zipped to z (so each member of first list in z increases by zero, each member of second list of z increases by 1, etc.) , # ‎⁢⁡⁡- Pair with z :L # ‎⁢⁡⁢Integer divide by length of matrix (m) ɗ # ‎⁢⁡⁣Following as a dyad (see below for right argument details, referred to as y) _/ # ‎⁢⁡⁤- Reduce by subtraction (gives x differences) ż # ‎⁢⁢⁡- Zip with ¥ # ‎⁢⁢⁢- Following as a dyad: Ṫ© # ‎⁢⁢⁣ - Tail (effectively z from above but after the integer divide bit), also copying this for later ị" # ‎⁢⁢⁤ - Index zipped into right argument $ # ‎⁢⁣⁡y, which will be the result of the following applied as a monad to the original argument (the matrix) ÷" Ɗ # ‎⁢⁣⁢- Divide zipped by the result of the following applied as a monad to the original matrix: J # ‎⁢⁣⁣ - Sequence along original matrix rows ’ # ‎⁢⁣⁤ - Decrease by 1 ! # ‎⁢⁤⁡ - Factorial Ż # ‎⁢⁤⁢Prepend zero ç\ # ‎⁢⁤⁣Reduce using the helper link, collecting all intermediate values Ḣ€ # ‎⁢⁤⁤Head of each Ḋ # ‎⁣⁡⁡Remove the original zero ×"® ¤ # ‎⁣⁡⁢Multiply zipped by the result of applying the following to the register value stored earlier Ḣ # ‎⁣⁡⁣- Head 1;$ # ‎⁣⁡⁤- Prepend 1 ($ used to prevent the ¤ only tracking back to the 1) ɗ\ # ‎⁣⁢⁡- Reduce using the following, collecting up intermediate values Ż # ‎⁣⁢⁢ - Prepend zero _× # ‎⁣⁢⁣ - Subtract the result of multiplying the previous list by the incoming x value Ṗ # ‎⁣⁢⁤- Remove the last list member F€ # ‎⁣⁣⁡Flatten each (deals with the 1 introduced above that is not a list) S # ‎⁣⁣⁢Sum 💎 ``` Created with the help of [Luminespire](https://vyxal.github.io/Luminespire). ]
[Question] [ I am trying to write a solution to the following problem using as few characters as possible (to meme my friend and introduce him to golfing). Can any improvements be done to my code? So the problem requires us to write a function called `navigate` in Python 3.6 (language of the judge, sorry, no walruses) that takes two arguments: * the first is a list of strings called "commands", which can be chosen from the following: `Drive`, `TurnL`, `TurnR` * the second is a tuple of three element, the first two are integers describing, respectively, the `x` and `y` coordinates of a "car", and the third element of the tuple is a single-character string chosen out of `N`, `E`, `S` and `W`, describing the direction which the car is facing initially and returns a tuple with the same format as the second argument, which denotes the final coordinates and orientation of the car. The commands are defined as follows (I tried to make them rigorous): * `TurnL`: change the orientation of the car with the following map: `f:{N->W->S->E->N}` * `TurnR`: change the orientation of the car with the inverse of `f` * `Drive`: increment or decrement the value of `x` or `y` by 1, depending on the current orientation (see below table) | orientation | change in `x` | change in `y` | | --- | --- | --- | | N | 0 | 1 | | E | 1 | 0 | | S | 0 | -1 | | W | -1 | 0 | --- My current progress is 189 Bytes: ``` N,E,S,W='NESW' def navigate(c,s): x,y,d=s for i in c: if i[4]=='L':d={N:W,W:S,S:E,E:N}[d] elif i[4]=='R':d={N:E,E:S,S:W,W:N}[d] else:x+=(d==E)-(d==W);y+=(d==N)-(d==S) return x,y,d ``` I do not think typing out the long word "navigation" is avoidable. However, although the question asks for an implementation of a function, I do believe any callable, including anonymous functions, methods, etc., would be accepted. --- Below is a test case ``` >>> navigate(['Drive', 'TurnR', 'Drive'], (0, 0, 'E')) (1, -1, 'S') ``` [Answer] # Flip comparisons You can remove the space after `if` if you swap the order of the string comparisons, so `if i[4]=='L'` becomes `if'L'==i[4]`. # String ordering Because strings in Python can be compared, and are ordered alphabetically (with lowercase coming after uppercase, according to their ASCII codes), and we know the 5th character of each input string will always be `L`, `R`, or `e`, we can change `==` to `>` and compare with the next letter in the alphabet in each case. `if'L'==i[4]` becomes `if'M'>i[4]`. # Unpacking `i` *Thanks to @ovs for this suggestion* Because `i[4]` is always the last character in the string `i`, we can unpack it with Python's `*` syntax in the for loop (`for*_,i in c:`), and remove both instances of `[4]`. The first 4 characters are stored in `_` - which we just ignore - and the last becomes `i`. # Complex numbers Complex numbers are often useful in [grid](/questions/tagged/grid "show questions tagged 'grid'") problems like this, because you can do arithmetic with them like you can with vectors. This avoids the need for two separate variables, and eliminate the costly direction maps you used (`d={N:W,W:S,S:E,E:N}`). `1j**'ENW'.find(D)` converts a direction character into a complex number which points in that direction. `'ENW'.find(d)` returns the index of `D` in that string, so `0` for `E`, `1` for `N`, `2` for `W`, and, because `S` is not present, it returns `-1`. When we use `1j**`, this gets the complex number with the right direction using the fact that \$ i \$ (`1j`), when exponentiated, returns different rotations of the complex numbers. \$ i^{-1} \$ is the same as \$ i^3 \$, so that handles the `S` case. `d*=1j` and `d/=1j` turn `d` by 90° anticlockwise and clockwise respectively, again using \$ i \$'s rotation-like properties. # [Python](https://www.python.org), 167 bytes ``` def navigate(c,s): x,y,D=s;p=0;d=1j**'ENW'.find(D) for*_,i in c: if'M'>i:d*=1j elif'S'>i:d/=1j else:p+=d return p.real+x,p.imag+y,'WESN'['-1-1j'.find(str(d))] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=PY9NbsIwEIX3OcXsxk4mKdm1QekqWcKiVGKBUBVhmw4CYzkGkbN0w6btmXqbuuVHmsXMp6c37318uSG87-35_HkIJn_8-VbagO2OvO6CFivqZZXAiQZq6n7s6tFY1eUmTbGdzrEwbJVoZAJm79M3YmALq6gHNjjBZ65UGtXx1ttIZv_k4UZ6XbmsVgl4HQ7egiu87rbZiVzBu26dDYTzdjbFBeZlXm6u3_rghZJyeY375DzbIO6BF9h4PmokwNdo-vK3XMiSQIwI4mCLUsqLwa33Lw) This is a start. I feel like I'm missing a trick in converting `p` back to a coordinate pair, because `.real` `.imag` is quite verbose. Thanks to @ovs for the slightly better way of converting the complex numbers back to compass directions, by storing overlapping string representations of the possible values, and searching within it. --- Also, I don't know if it's possible to switch to Python 2, but if you can, you can save some bytes: * 2 bytes by extracting the `s` tuple inside the function argument list * 3 bytes using the `expression` for converting values to strings # [Python 2](https://docs.python.org/2/), 162 bytes ``` def navigate(c,(x,y,D)): p=0;d=1j**'ENW'.find(D) for*_,i in c: if'M'>i:d*=1j elif'S'>i:d/=1j else:p+=d return p.real+x,p.imag+y,'WESN'['-1-1j'.find(`d`)] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=RY-xbsJADIb3PIU35xInJZ1QUDolYxkKEgNCJeLuqBE9TtcDkWfpgpAQz8TbcC0gJA_2p9_-f_-ebee_Nub1cDhtvc76l6NUGky742XrVbygeE8d1UKUEdiqN5BVsUoSbIYTzDUbGdciAr1xyScxsIFF0AFrfMc3LmUS1GFW60BG_-TlQX5UadNKRuCU3zoDNneqXad7sjl_t8u0I5w0oyFOMSuyYnV3m8u5mN2T9q1j459Zp1g73ikkwHG4-PHX3MiMIO4RhMIGhbjtPz6-Ag) [Answer] [pxeger's answers](https://codegolf.stackexchange.com/a/240792/64121) covers how this problem would best apporached on our site, where input and output formats are often flexible. However, with your fixed format we can do a bit better by mostly working within the format. Our starting point is your function with a few improvements taken from the other answer (182): ``` N,E,S,W='NESW' def navigate(c,s): x,y,d=s for*_,i in c: if'L'==i:d={N:W,W:S,S:E,E:N}[d] elif'R'==i:d={N:E,E:S,S:W,W:N}[d] else:x+=(d==E)-(d==W);y+=(d==N)-(d==S) return x,y,d ``` [Try it online!](https://tio.run/##Rc6xCsIwEAbgvU9x2zV6guAWyWY2ydAIGUREmlQDEiWtxSI@e00oWDi4479v@J9Dd3uEzTgqkqTJCFRSGyysayBcen@9dK6sqWW8gDcNZEVbQPOIizN58AHqlINvcI9CeG7FR3FDhmvSXJLk6nu0pyTcPZlqNvmXTbazaR1/L0VphZBslZdh22EK1BRoVkB03SuGqc34jD505b/pEXfR9w4J8JBQlY8pORGUa4I0KJExNv4A "Python 3 – Try It Online") --- First, lets focus on the rotations. Dictionaries are convenient data structures to implement lookup tables, but are a bit lengthy. Using strings instead can help here: ``` if'L'==i:d='WSEN'['NWSE'.find(d)] elif'R'==i:d='ESWN'['NESW'.find(d)] ``` With a bit of reordering, we can use the same value for the `'...'.find` expression: ``` j='NWSE'.find(d) if'L'==i:d='WSEN'[j] elif'R'==i:d='ENWS'[j] ``` And `str.find` returns `-1` if the value is not in the string, which means `E` can be removed. The two cases are now quite similar and can be combined into one by shifting the index based on `i`: ``` j='NWS'.find(d) if'e'>i:d='WSEN'[j-(2 if i>'L' else 0)] # shorter with j-2*(i>'L') ``` Plugging this into our starting point, we get to 155 bytes: ``` def navigate(c,s): x,y,d=s for*_,i in c: j='NWS'.find(d) if'e'>i:d='WSEN'[j-2*(i>'L')] else:x+=(d=='E')-(d=='W');y+=(d=='N')-(d=='S') return x,y,d ``` [Try it online!](https://tio.run/##PY5BC4JAEIXv/oq5za6tEXUztlPewkMGHkRC3LUmYpXVRH@9rVnBHB7fe7x5zdjda7ObJqUrMEVPt6LTrBQtDz0YxCiUbD2oautfBQEZKB2Hh8Q4TXBdkVFMcUeoQo0HCpXENIlizB7B1md0wBPy3Pn62epwWEmmpMQIefARKfL9@IXxDyboCq3uXtYsC6bGkunYf12GR0u9RgF4caHzLBaSC2AbAe7mH5xPbw "Python 3 – Try It Online") --- Now we can look at the moving part. The value of `j` can be used here as well, to get expressions to update the position: | `d` | `j='NWS'.find(d)` | `j%2*j` | `~j%2*~-j` | | --- | --- | --- | --- | | N | 0 | 0 | -1 | | W | 1 | 1 | 0 | | S | 2 | 0 | 1 | | E | -1 | -1 | 0 | # [Python 3](https://docs.python.org/3/), 134 bytes ``` def navigate(c,s): x,y,d=s for*_,i in c: j='NWS'.find(d) if'e'>i:d='WSEN'[j-2*(i>'L')] else:x-=j%2*j;y-=~j%2*~-j return x,y,d ``` [Try it online!](https://tio.run/##jZJBa8IwFMfv@RQPx0gj6Zju5qin9SY9rIMeREZqkpriWkmjU0S/epdY7WTKKJSQ95L/@/1autqZRVm81DUXEgq2URkzwpvTiowQbOmO8qBCIEvd/6QKVAFz24c8wFES4yepCu5xYjtKYoHHasQDnMRhhKe5P@x7aownmMzsuVhWYrT1g/xx2M9fd35wdLujnyPQwqx10cDqBzCiMrAU0oBrI4sGRiF1bAvFFCzArXHoVotyQtYONAS/bzDFHzY9wTMK3jMF@zDiPFlVCW3c3QBSCrLnrqkia4hSl1@wZweoFuV6ySEVsE8PFLLSwF4fegid/bTKFncFT1JJdBI8yYbxf4Lv3QUbZGdDrtXGxazeN9Mcnede8d/sDXHFxxEmxGFdPWjqLrHkEvMHbaNLLr7CuahrdMmFl9ygrRFCK60K493k7Hnzne3m7iRym2z@nDbQjvibrH8A "Python 3 – Try It Online") Finally, a few more bytes can be saved by using `ord(d)` instead of `'NWS'.find(d)` and using short position and direction update formulas found by a brute force search: [131 bytes](https://tio.run/##jZLRasIwFIbv8xQHh6R1Ka7KxnDUq/VOerEOeiEyWpPWiGsljU4Rn707sdrJHKNQQnJyvvN/hK73elHkw6riIoU83sos1sKas9IeEdixPeNeSSAtVO@DSZA5zLEOS69Q3OI2bmVKBR3LEfdoEIU@nS67z91HZ9Cz5JhOqD3DHrEqxWh37y3xYviyd3Dz1O8PHJeAEnqj8jqpugMtSg0rkWowZYK5EDNITDCOpwxoFJoVg3D1A2psUA0UeD/6U/qO9ITOGFgPDPCLbeMal6VQ2vR6kDBIO6ZN5lmdmKriEw7xEcpFsVlxSAQckiODrNBwUMcOIWc/JbPFn4InqSg4CZ5k/fA/wbf2gnVka0Ou5NZgqPcVK07Oc6/yX7FDXOXTgNq2iTVntz63waIL5rhNoQ0XXsUZ1BTacP6Fc5szIWStZK6tGw7v63fGzZ@T7Fuy/nMaoBnxm6y@AQ) ]
[Question] [ ## Background The [4-8-8 tiling](https://en.wikipedia.org/wiki/Euclidean_tilings_by_convex_regular_polygons#Archimedean,_uniform_or_semiregular_tilings) looks like this: ![](https://i.stack.imgur.com/4SJPd.png) For the purpose of this challenge, we take the orientation of the tiling as exactly shown above. In plain English words, we take the tiling so that it can be seen as a rectangular grid of alternating octagons and squares, the upper left corner being an octagon. In order to define a Game of Life on this tiling, we use a simplified definition of neighborhood: cell B is a neighbor of cell A if the two cells share an edge. An octagon has at most 8 neighbors and a square has at most 4. We assume the cells outside the given grid are simply non-existent (or alternatively, hardwired as all dead). Other than the grid differences, we use the rules of Game of Life as-is: * An off-cell is turned on if it has exactly three on-neighbors, and is kept off otherwise. * An on-cell is kept on if it has exactly two or three on-neighbors, and is turned off otherwise. ## Challenge Given a rectangular grid of on- and off-cells on the 4-8-8 tiling as defined above, calculate the next generation in Game of Life. The on- and off-cells can be represented by any two distinct, consistent values respectively. The rectangular grid may be represented in any suitable format supported by your language. The output format doesn't need to be the same as the input format. The grid can be assumed to have at least two rows and two columns. Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins. ## Test cases Generated using [this Python program](https://tio.run/##rZLBioMwEIbvfYopy4LBLCT1Vuqpb@A1hMVNUxspSTdaln16dxLTWmoLPSyCGWe@/88f9fTbH5wthmGn99C5Y9Z4syPrBYDXPZQgBIO98/AJxoJ3PzI@YRGeAysRregW0aO2o5peKsEkwXFURH1tG51V0X5sq6m9TW0As4fM54q8r6Asga3hDZzq68bZBABYbZrDl/Md7suu3eBoJkf/wanPV1ffC9JOiEJE3SG37jnab0qzqaC2u1C2m20sM7MsPQSzZalIbMUTGylamcz0sdMhfPd9rr1@JTuN0URMrgjFt5BWikHHNedE3qZ9IessGH5a4aVQEhMY22eTR9hdFJKKFS2kFFEZyfghUXf2NiyLkw/C8MMIwSlHRbhLQh5M2NMJp2w2YRSv0S@p2TMqkYxGNtWX/iMFvyoe1fOM4yydbuRman7HzE/7D25kGP4A). For simplicity, the grid is represented as a list of lists of zeros (off) and ones (on). Some test cases have multiple steps, which means if your program is given the first state, it should produce the second, and if given the second, it should produce the third, etc. ``` [[1, 1], [1, 1]] -> unchanged [[1, 1], [0, 1]] -> unchanged [[1, 1], [1, 0]] -> [[1, 0], [0, 1]] -> [[0, 0], [0, 0]] [[0, 0, 0], [1, 1, 1], [0, 0, 0]], -> [[0, 0, 0], [0, 1, 0], [0, 0, 0]] [[0, 0, 0, 0, 0], [0, 1, 1, 1, 0], [0, 0, 0, 0, 0]] -> [[0, 0, 1, 0, 0], [0, 0, 1, 0, 0], [0, 0, 1, 0, 0]] -> back to first [[1, 0, 0, 1, 1], [1, 1, 0, 1, 0], [0, 0, 1, 0, 0], [0, 1, 0, 1, 1], [1, 1, 0, 0, 1]] -> [[1, 0, 1, 1, 1], [1, 1, 1, 1, 0], [1, 1, 0, 1, 1], [0, 1, 1, 1, 1], [1, 1, 1, 0, 1]] -> [[1, 1, 0, 1, 1], [1, 0, 1, 0, 1], [0, 1, 0, 1, 0], [1, 0, 1, 0, 1], [1, 1, 0, 1, 1]] -> [[1, 0, 1, 0, 1], [0, 0, 0, 0, 0], [1, 0, 0, 0, 1], [0, 0, 0, 0, 0], [1, 0, 1, 0, 1]] -> [[0, 0, 0, 0, 0], [0, 1, 0, 1, 0], [0, 0, 0, 0, 0], [0, 1, 0, 1, 0], [0, 0, 0, 0, 0]] -> all zeros ``` [Answer] # JavaScript, 99 bytes ``` a=>a.map((r,y)=>r.map((c,x)=>((g=i=>i--&&((i%2|x+~y&i!=4)&a[~-(y+i/3)]?.[x+i%3-1])+g(i))(9)|c)==3)) ``` ``` f= a=>a.map((r,y)=>r.map((c,x)=>((g=i=>i--&&((i%2|x+~y&i!=4)&a[~-(y+i/3)]?.[x+i%3-1])+g(i))(9)|c)==3)) print = (a, contain) => { let t = contain.appendChild(document.createElement('div')); t.className = 'grid'; a.map(r => { let tr = t.appendChild(document.createElement('div')); tr.className = 'row'; r.map(c => { tr.appendChild(document.createElement('div')).className = c ? 'on cell' : 'off cell'; }); }); } test = (a, n, contain) => { contain ??= document.body.appendChild(document.createElement('div')); contain.className = 'testcase'; print(a, contain); if (n) test(f(a), n - 1, contain); }; test([[true, true], [true, true]], 1); test([[true, true], [false, true]], 1); test([[true, true], [true, false]], 2); test([[false, false, false], [true, true, true], [false, false, false]], 1); test([[false, false, false, false, false], [false, true, true, true, false], [false, false, false, false, false]], 2); test([[true, false, false, true, true], [true, true, false, true, false], [false, false, true, false, false], [false, true, false, true, true], [true, true, false, false, true]], 5); ``` ``` body { background: #ccc; } .grid { display: flex; flex-direction: column; padding: 10px; } .grid + .grid { margin-top: 10px; } .row { display: flex; } .cell { width: 23px; height: 23px; position: relative; padding: 0; } .on { --cell-color: white; } .off { --cell-color: black; } .cell::before { content: " "; display: block; position: absolute; } .cell::before { width: 16px; height: 16px; top: 4px; left: 4px; background-image: linear-gradient(to bottom, var(--cell-color), var(--cell-color)), linear-gradient(to right, gray, gray); background-position: 1px 1px, top left; background-repeat: no-repeat; background-size: 14px 14px, 16px 16px; } .row:nth-child(2n) .cell:nth-child(2n)::before, .row:nth-child(2n+1) .cell:nth-child(2n+1)::before { width: 34px; height: 34px; top: -5px; left: -5px; background-image: linear-gradient(to bottom, gray 0, gray 1px, transparent 1px, transparent 33px, gray 33px, gray 34px), linear-gradient(to right, gray 0, gray 1px, transparent 1px, transparent 33px, gray 33px, gray 34px), linear-gradient( 135deg, transparent 0, transparent 7px, gray 7px, gray 8px, var(--cell-color) 8px, var(--cell-color) 20px), linear-gradient(-135deg, transparent 0, transparent 7px, gray 7px, gray 8px, var(--cell-color) 8px, var(--cell-color) 20px), linear-gradient( 45deg, transparent 0, transparent 7px, gray 7px, gray 8px, var(--cell-color) 8px, var(--cell-color) 20px), linear-gradient( -45deg, transparent 0, transparent 7px, gray 7px, gray 8px, var(--cell-color) 8px, var(--cell-color) 20px); background-position: top center, left center, top left, top right, bottom left, bottom right; background-repeat: no-repeat; background-size: 16px 34px, 34px 16px, 20px 20px, 20px 20px, 20px 20px, 20px 20px; } .testcase { padding: 10px; } .testcase + .testcase { border-top: 1px solid gray; } ``` [Answer] # JavaScript (ES6), 109 bytes ``` a=>a.map((r,y)=>r.map((n,x)=>[...'0124689',10].map(i=>n+=x-~y&1|i&5&&(a[y+~-(i/4)]||0)[x+i%4-1]<<1)|n>4&n<8)) ``` [Try it online!](https://tio.run/##dVHRboMgFH33K@7LFCIyaOzSRfFtX8F4IK5uNB02dlk0s/11h9gu07RAwrmHc86FsNPf@lg25vCV2PptO1Ri0KLQ9FMfEGpIh0XRTIUlrSskpTRifJU@bZ4jwpnyh0YUNhZtcu5C3ptwHYZIyy4@J8g8plj1PcOyjc1DmnCV5xz3tkhDm28wHjIZAEjJCXBFHIQJOrzk2R3eQfbHO9G4/kXNAtgN7czBJodfbO5buPmVWlz9ys3d/EaXO97pnYEKaFU3L7r8QEgTMBhEAT9O6lhkQQDLwEIuRicnKz/XShrl6DjGXgpQ1vZY77d0X7@j6VebMaehu9pYFEGE8QW@2ghDDH7PvFe7JhXSvjoF86wouYxJfsLDLw "JavaScript (Node.js) – Try It Online") [Answer] # JavaScript (ES2020), 139 bytes ``` x=>x.map((y,i)=>y.map((v,j)=>(v+=(g=(a,b)=>x[i+a]?.[j+b]*2|0)(0,1)+g(1,0)+g(n=-1,0)+g(0,n)+(i+j+1)%2*(g(1,1)+g(1,n)+g(n,1)+g(n,n)))>4&v<8)) ``` [Try it online!](https://tio.run/##TYzLCoMwEEX3@QoRWmZMlKR04aLxR6yLKEUSbCK1BAX/3cZqH3Bh7rkcxiivhuah@2fq86VxdnDdLetcC7CMshizu@oBJqZRFtMGnpkA4KmEVoJi9Upjqamq5pljaWhdJafQgDOBtAXB@HqsTPfGmUUKmhoq8HBKYFV2077NjWwgxOJ89JcccUEgpCw5i36pGInWRXzyXf6cihDMjNMW4quNw6MX "JavaScript (V8) – Try It Online") (Link uses a 142 byte version, as TIO doesn't support the ES2020 `?.` operator) ## Explanation ``` x=>x.map((y,i)=>y.map((v,j)=> // Map over each element of the grid: (v+= // Add to the value of the cell (0 or 1): (g=(a,b)=>x[i+a]?.[j+b]*2|0) // Define a function g to get neighbor // values; 2 for alive, 0 for dead. (0,1)+g(1,0) // Sum the neighbor values for the cells +g(n=-1,0)+g(0,n) // above, below, left, and right. + // Add the product of: (i+j+1)%2 // 1 for octagons, 0 for squares. *(g(1,1)+g(1,n) // The sum of the values for the +g(n,1)+g(n,n)) // diagonal neighbors. )>4&v<8 // 1 if the sum is >4 and <8, 0 otherwise. )) // This is true for: // - 5 (1 (alive cell) + 4 (2 alive neighbors)) // - 6 (0 (dead cell) + 6 (3 alive neighbors)) // - 7 (1 (alive cell) + 6 (3 alive neighbors)) ``` [Answer] # [MATL](https://github.com/lmendo/MATL), ~~35~~ ~~33~~ ~~32~~ 31 bytes ``` t1Y6Z+G5B&*Z+G&n:w:!+o~*+E+5:7m ``` [Try it online!](https://tio.run/##y00syfn/v8Qw0ixK293USU0LSKnlWZVbKWrn12lpu2qbWpnn/v8fbaAAhNYKhiBorQDmxQIA) Or [verify all test cases](https://tio.run/##bZA9DsIwDIV3ThGWDg3D81CQ0g2BuAADFFUCsVJYKsHE1UNiY5efylH8/PTJcdyd@ks8xp7288ZvqmVRplRcwz1M/e1Z@rWvwqKLOO9WzWMbD@SodulqJyIxSHJgCXWRMpgWEgzAvYMxDtTO3Nxi5sAnidyXhZSZNK0ljcHZkXF0ABpe46Rj0TdgP1JCBBSGtjDXWHsP9mFdgch/lz53NWwFP1sZd9sX). ### How it works ``` t % Implicit input: binary matrix. Duplicate 1Y6 % Push [0 1 0; 1 0 1; 0 1 0]. This mask defines cells that are neighbours % of the central cell, whether the central cell is a square or an octagon Z+ % 2D convolution, maintaining size. This counts neighbours according to % the above mask. (*) G % Push input again 5B % Push 5, convert to binary: gives [1 0 1] &* % All pair-wise products: gives [1 0 1; 0 0 0; 1 0 1]. This mask defines % cells that are neighbours of octagons squares and not of squares Z+ % 2D convolution, maintaining size. (**) G % Push input again &n % Push number of rows R, then number of columns C : % Range: gives row vector [1 2 ... C] w % SWap: moves R to top :! % Range, transpose: gives column vector [1; 2; ... ; R] + % Add, element-wise with broadcast o~ % Modulo 2, negate. This gives a matrix the same size as the input with a % checkered pattern, where 1 indicates octagon and 0 indicates square * % Multiply, element-wise. This keeps the results (**) for cells that are % octagons, and sets the rest to 0 + % Add (*) and (**). This gives the number of neighbours of each cell E % Multiply by 2 + % Add to copy of the input that is at the bottom the stack. (***) 5:7 % Push range [5 6 7] m % Ismember. This gives 1 for cells at which (***) equals 5 (meaning the % cell was active and had 2 active neighbours), 6 (it was inactive and had % 3 active neighbours) or 7 (it was active and had 3 active neighbours) % Implicit display ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 37 bytes ``` ŒJ§ị3ṗ2$’’A§ĠịƲḊ;\¤+"Ʋf€$œị⁸§ṁ,+¥=3o/ ``` [Try it online!](https://tio.run/##y0rNyan8///oJK9Dyx/u7jZ@uHO6kcqjhplA5Hho@ZEFQLFjmx7u6LKOObREW@nYprRHTWtUjk4GCj9q3AHUsrNRR/vQUlvjfP3///9HRxvqKBiAEZBhGKvDpQASMYSJGIBF4AoMkEQMcegCCcbGAgA "Jelly – Try It Online") A monadic link taking and returning a 2D list of 0 and 1. [Answer] # [Python 3](https://docs.python.org/3/), 136 bytes Returns a 2d-list of booleans. ``` lambda c,E=enumerate:[[sum(sum([([0]+l)[x-y:x-y+3]for l in c[y+y%~y:y+2]],[])[x%2::1+x%2])-~x*v%2|v==3for x,v in E(r,y)]for y,r in E(c)] ``` [Try it online!](https://tio.run/##bY/NboQgFIX3PgUbMzAyBnVH4nKeAllQf1ITRQOMkaSZV7cgmYZ2mnDDud895wZWaz4XWR1D3RyTmD86AVp8r3v5mHslTE8Z048Z@mKQEZ5NiO03S11lFR8WBSYwStAym9n0aanNSs4x486VlpQWmbs4uj3365aWX1tdVz6z482n7lBhi84tFqtAWsSPcV4XZYC2OvEz02vjh67PtelGmatedBDlep1GAy@NbOQF0QQEZw36TUzQa@SY33DuHgLyPgBWNUoDr7NYoRMYKOS9gaKDsQKDguMEBMGTJELkHTlBAnJDf36yUYj8NUVWEqznIXEgjhWv/tfrXiSOFW@r/02Fn3wD "Python 3 – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 65 bytes ``` WS⊞υιυUMυ⪪ι¹FLυ«J⁰ιFL§υι«§≔§υικ¬÷⁻⁷⁺IKK⊗№⎇﹪⁺ικ²KVKM1³→»»J⁰¦⁰Eυ⪫ιω ``` [Try it online!](https://tio.run/##VVBNb4MwDD2TXxH1ZCQmJdth0naq6KXVqNBa7Z6VDCJCjCChm6b@dua03dchiWO/Z7/nQ6OGAyo7z8fGWM1h7frgd34wroY05WUYGwgZN@kjKynpIVBUqD7HrlOuirVdb40Hk3GZUu0NBw5P2tWeiNThkyWb0PV7BHFpk/xFLP3aVfr9MuKCTpbjaGr3XfmHyHib8S16kulXZjKVhsK4MMJ9xktLb65GD6XWLYnP@ArDq9UV5BhI@V4PTg0fUGAVLMIZT6pbAt7SiawXdFsdyJiDa6ZAHPS52UIuSCEFd2n0mSQFThoenk3d@Pg/sRP7dSp@FkbLiuI3aFwcd4zseZZCSMmkFFIwCgXd8poRks03k/0C "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a newline-terminated list of strings of `0`s and `1`s. Explanation: ``` WS⊞υιυ ``` Input the strings and print them to the canvas. ``` UMυ⪪ι¹ ``` Split the strings into character lists so that they can be replaced. ``` FLυ« ``` Loop over each of the lists. ``` J⁰ι ``` Jump to the start of its line. ``` FL§υι« ``` Loop over the cells of the list. ``` §≔§υικ¬÷⁻⁷⁺IKK⊗№⎇﹪⁺ικ²KVKM1³ ``` Look at the Von Neumann or Moore neighbourhood depending on the parity of the square, count the number of `1`s, double that, add on the current square, subtract from 7, integer divide by 3, and complement the result. This gives the new live state of the cell. ``` → ``` Move to the next cell. ``` »»J⁰¦⁰Eυ⪫ιω ``` Overwrite the canvas with the new states. ]
[Question] [ Given a positive integer \$n\$, output \$n\$ 2D bool images with the same width and height such that: 1. Each image should be 4-connected, i.e. for each two pixels that are true, you can start from one and go up, down, left and right for some times to the other pixel, only passing through true pixels. 2. Each image should have no holes, i.e. the complement should be 4-connected. 3. If we choose itself or its complement for each image, their intersection should be non-empty and 4-connected. ## Examples (only a finite amount of solutions shown, but there are infinitely many more) Input: 1 Possible output: ``` ..... .***. .**.. ..*.. ``` Input: 1 Possible output: ``` ..... ...*. ..... ..... ``` Input: 2 Possible output: ``` ..... ..... .***. ..**. ..... ..**. ..... ..... ``` Input: 2 Possible output: ``` ..... ..... .**.. ..**. ..**. ..**. ..... ..... ``` Input: 3 Possible output: ``` ..... ..... ..... .**.. ..**. ..... .**.. ..**. .***. ..... ..... .***. ``` Input: 4 Possible output: ``` ....... ....... ....... ....... .***... ..***.. ....... ....... .***... ..***.. .*****. ....... .***... ..***.. .*****. .*****. .***... ..***.. ....... .*****. ....... ....... ....... ....... ``` The shortest code in each language wins. [Reference](https://en.wikipedia.org/wiki/Venn_diagram#Extensions_to_higher_numbers_of_sets) [Sandbox](https://codegolf.meta.stackexchange.com/a/17453/) [Answer] # Python, 62 bytes ``` lambda n:[[[0,j>>i&1,1]for j in range(1<<n)]for i in range(n)] ``` [Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSHPKjo62kAny84uU81QxzA2Lb9IIUshM0@hKDEvPVXD0MYmTxMsmIkQBIr8TyvKz1UoKCjKzCtRyMwtyC8qgfK4IJRGmoaJpuZ/AA "Python 3 – Try It Online") Generates \$3 × 2^n\$ images like these: ``` ..* ..* ..* ..* .** ..* ..* ..* ..* .** ..* ..* .** .** ..* ..* ..* ..* .** ..* .** ..* .** ..* ..* .** .** ..* .** .** .** ..* ..* ..* ..* .** .** ..* ..* .** ..* .** ..* .** .** .** ..* .** ..* ..* .** .** .** ..* .** .** ..* .** .** .** .** .** .** .** ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~12~~ ~~10~~ ~~9~~ ~~8~~ ~~7~~ 6 bytes ``` 4,6Bṗz ``` [Try it online!](https://tio.run/##y0rNyan8/99Ex8zp4c7pVf8Pt0c9alrzcHf3o8Z9ynqRQHYWkHVo26Ft//@bAQA "Jelly – Try It Online") Returns a list of binary matrices (that is, a 3D list). Output for \$n=6\$, transposed and ASCII-artified: ``` ################################################################ ................................################################ ................................................................ ################################################################ ................################................################ ................................................................ ################################################################ ........########........########........########........######## ................................................................ ################################################################ ....####....####....####....####....####....####....####....#### ................................................................ ################################################################ ..##..##..##..##..##..##..##..##..##..##..##..##..##..##..##..## ................................................................ ################################################################ .#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.#.# ................................................................ ``` ## Explanation ``` 4,6Bṗz Main monadic link, taking n as the argument 4,6 [4,6] B Convert to binary: [[1,0,0],[1,1,0]] ṗ Cartesian power to n z Zip with filler n (since it's already a rectangle, the filler will be ignored) ``` [Answer] # [R](https://www.r-project.org/), 64 bytes ``` function(n)Map(function(i)rbind(1,(1:(2^n)-1)%/%2^i%%2,0),1:n-1) ``` [Try it online!](https://tio.run/##K/pflpqXl2f7P600L7kkMz9PI0/TN7FAA87N1CxKysxL0TDU0TC00jCKy9PUNdRU1Vc1istUVTXSMdDUMbTKAwpBzNEw1OSCMIxgDGPN/wA "R – Try It Online") Port of [Anders Kaseorg's approach](https://codegolf.stackexchange.com/a/230107/95126) - upvote that one! [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 8 bytes ``` 46SbIãIζ ``` [Try it online!](https://tio.run/##yy9OTMpM/f/fxCw4yfPwYs9z2/7/NwMA "05AB1E – Try It Online") ]
[Question] [ # Objective Given a matrix of **connected** box drawing characters, count its [genus](https://en.wikipedia.org/wiki/Genus_(mathematics)), the number of plane sections it encloses. # Valid input The box drawing characters are `─│┌┐└┘├┤┬┴┼╴╵╶╷` (U+2500 U+2502 U+250C U+2510 U+2514 U+2518 U+251C U+2524 U+252C U+2534 U+253C U+2574 U+2575 U+2576 U+2577). The matrix shall contain these characters only, along with unique "nothing" value that represents a blank. The input may also be a string with box drawing characters, whitespaces, and line feeds. You cannot mix different types of whitespaces, or different types of line feeds. Trailing whitespaces and line feeds are permitted. # Rule Invalid input falls in *don't care* situation. In particular, you don't need to handle any input having multiple connected components, e.g. ``` # this ┌─┐┌─┐ └─┘└─┘ # or this ┌───┐ │┌─┐│ │└─┘│ └───┘ ``` # Examples For font issues, every example is presented using normal spaces (U+0020) once and ideographic spaces (U+3000) once. ## Genus 0 ``` # Using U+0020 space ┤ ╷ └─┘ ┌┼┐ ─┴ # Using U+3000 space ┤ ╷ └─┘ ┌┼┐  ─┴ ``` ## Genus 1 ``` # Using U+0020 space ┌─┬ │ │ └─┘ ┼┬─┬ ╵│ │ └┴─┘ # Using U+3000 space ┌─┬ │ │ └─┘ ┼┬─┬ ╵│ │ └┴─┘ ``` ## Genus 2 ``` # Using U+0020 space ┼┼┼┼ ┼┼┼ # Using U+3000 space ┼┼┼┼  ┼┼┼ ``` [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 73 bytes ``` 1-1⊥∘(∊∨/¨⍮2(-⊃⍤∧∘⌽/⍮(3⊃∧∘⌽)⌿)⊢)(⊂4⍴2)⊤¨(9467+⎕AV⍳'ð{dòlxõ _0h8p∆')⍳⎕UCS ``` [Try it online!](https://tio.run/##bY7NSsNAFIV3LvIU2TVBQm1S/FlKN7o16lYKSbUQasAKlSJIhBBCprQwga5cSMQsiopNcVMRkjc5LxLvVFsoFIaZO@c7957bdB3Nums615ea3evaHcu2Sqt948IfIvJEVda0GsIXBGMFQYggreYp2JuuaAgfwRIEr8QQfVdJVQwhLhUV0Y@K8FlVEHp1sEynX5KnykF9d28bg/jwHGxaKT76VvHpbPWKmXyxc7XvIvArKhFynDXMsiWWYQOanL8b8EckmycNuk@Pjs2y3XFvu8Lhj/pgT/e0HYWzqdSSF0jWJfBERvxFLwd/AB@vsQh8Dj6U5AXLVsz4Y6RNqPIIexsmCBe1T5bGeLbmzTYEzldHZP6Xvw "APL (Dyalog Extended) – Try It Online") Over half of the bytes were used in converting the char matrix into an easier-to-use format. Basically, converts each box-drawing char into `[right, up, down, left]`, counts non-blanks and joints, and computes `1 - non-blanks + joints`. This works because of [Euler characteristic](https://en.wikipedia.org/wiki/Euler_characteristic) `V - E + F = 1` (not counting the surrounding area as a face), thanks to the assumption that the entire figure is connected. If we count any segment starting from the center to some boundary as an edge (and the respective endpoints as vertices), every non-blank char has `V - E = 1`, but the `V` in the entire shape is reduced by the number of joints. Plugging into the rearranged equation `F = 1 - V + E` gives the above formula `1 - non-blanks + joints`. [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 131 [bytes](https://mothereff.in/byte-counter#T%60%E2%94%80%E2%94%90%E2%94%AC%E2%95%B4%E2%94%BC%E2%94%A4%E2%94%B4%E2%94%98%E2%94%82%E2%95%B5%E2%94%94%E2%94%9C%E2%94%8C%E2%95%B6%E2%95%B7%60L%0A%28%3F%3D%28.%29%2a%5BBCEFILMO%5D.%2a%C2%B6%28%3F%3E%28%3F%3C-1%3E.%29%2a%29%5BE-L%5D%29%0A-%0A%28%3F%3D%5BACEGK-N%5D-%3F%5BA-H%5D%29%7C%5E%0A-%0A%2B%60-%5Cs%2a%5Cw%0A%0AC%60-) ``` T`─┐┬╴┼┤┴┘│╵└├┌╶╷`L (?=(.)*[BCEFILMO].*¶(?>(?<-1>.)*)[E-L]) - (?=[ACEGK-N]-?[A-H])|^ - +`-\s*\w C`- ``` [Try it online!](https://tio.run/##K0otycxLNPz/PyTh0ZSGR1MmPJqy5tHULY@m7Hk0ZcmjKUDGjEdTmh5N3fpoypRHU@Y8mtLzaOq2R1O3J/hwadjbauhpakU7Obu6efr4@sfqaR3apmFvp2Fvo2toB5TRjHbV9YnV5NIFKY12dHZ199b1i9W1j3bU9YjVrIkDSmgn6MYUa8WUc3E5J@j@/w@2Foq4FOBMAA "Retina – Try It Online") TIO counts the box drawing characters as only one byte even though they are not ASCII (the Retina code page). ## How? This uses a rearranged Euler characterstic `F=1+E-V` to find the number of faces under the assumption that there is only one connected component. The number of vertices, `V`, is the same as the number of box characters. There is +1 edge for every horizontally adjacent pair of box characters where the first has a right edge and the second has a left edge. There is +1 edge for every vertically adjacent pair of box characters where the first has a down edge and the second has a up edge. This is harder to express in regex, so I borrowed the method of [standard vertical matching](https://codegolf.stackexchange.com/a/75120/68261) to deal with vertical edges. ``` # Translate each of the box characters into letters to avoid repeating them # We do this smartly: # ─┐┬╴┼┤┴┘ correspond to A-H and all have a left edge # ┼┤┴┘│╵└├ correspond to E-L and all have an up edge # └├┌╶ correspond to K-N and all have a right edge T`─┐┬╴┼┤┴┘│╵└├┌╶╷`L # Prepend a '-' to the first character of a vertically adjacent pair with (down edge, up edge) # Each '-' will represent one edge (?=(.)*[BCEFILMO].*¶(?>(?<-1>.)*)[E-L]) - # Prepend a '-' to the first character of a horizontally adjacent pair with (left edge, right edge) # Simply pass over '-' from the previous step using -? # |^: also prepend an extra '-', which counts as an extra edge, to the beginning of the whole string for the +1 (?=[ACEGK-N]-?[A-H])|^ - # Now there is a - for each edge and a capital letter for each vertex, with some whitespace # Compute #(edges) - #(capital letters) # Until the output is constant: # Replace an edge and a capital letter with the empty string (`\s*` to pass over whitespace) +`-\s*\w # Count the number of `-`s C`- ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 100 bytes ``` WS⊞υιB׳⊕Lθ׳⊕LυψFυ«⸿⸿⸿Fι«M³→F⁴¿&X²λ⍘§”E←T¹÷S1²m[ω→℅P”﹪℅κ⊕⊘φφP✳⊗λ²»»≔⁰ηFLθFLυ«J׳ι׳κ↘≧⁺¬℅KKη¤#»⎚I⊖η ``` [Try it online!](https://tio.run/##fVHBTuMwED03X2FlL2MpK7GFXVg4tVRou6JsBBy5mGTqWHXt4tgtaFUJ7XkPHHrg@/ojwXYJpRxQItlv3mTmvZeiYqbQTDbNohISCQzVzNkra4TiQCnJXV2By4igJ0lf38O1mGIN@xkZqsLgFJXFEs5RcVvBHaU0I591uNjx4GeNtSEekr9JJ/e7LKQ3Jjyp5zqRFJHsjPQcw7TjS8ErG9gNfUCJGBPoC7sQNfZUCbleoIFuRqTf0Wc1vrro2aEq8R7Sg@63I374E/lewfl4v@TffzDOb9OMjHTppIY/phSKSZjQXfW/mJz7Y0yj/HCQkZNWzKLygTBYWKEVDLS7lb4xCOgGqctkmfTqWnAFexmpWt/bvMh77NMJln@76exab5MW70Od0DA3hnI80Av1lsqIzTabYgVy6eqMXGj7ZipHnEA0EHR0zoSUkH4JeS@TU4nMgL9u/sUpq70t3AZQ@e9Omma9@r9ePbbv0weYrFf/2tJTvO/ADb2K@LmltzBpwWNb2oFJ83UuXwA "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a newline-terminated rectangular character array. While I could have written a version that uses the Euler characteristic, I felt that I should really write a version using all of Charcoal's power to calculate the number of regions in any shape. Explanation: ``` WS⊞υι ``` Input the shape. ``` B׳⊕Lθ׳⊕Lυψ ``` Draw an empty box large enough to completely enclose the shape at three times scale. ``` Fυ«⸿⸿⸿Fι«M³→ ``` Loop over each character of the input, positioning the cursor at the appropriate position. ``` F⁴¿&X²λ⍘§”E←T¹÷S1²m[ω→℅P”﹪℅κ⊕⊘φφP✳⊗λ² ``` Loop over each direction, looking up the box lines based on taking the ordinal of the character modulo 501 and 23 (the latter automatically via Charcoal's cyclic indexing) in a table of hex digits (and `g`s for filler), drawing a line for each matching bit in the digit, thus drawing the original shape at triple size. ``` »»≔⁰η ``` Start with no regions. ``` FLθFLυ« ``` Loop over each character. ``` J׳ι׳κ↘ ``` Jump to the upper right of the character. ``` ≧⁺¬℅KKη ``` Increment the region count if it's empty. ``` ¤# ``` And then try to fill it anyway. ``` »⎚I⊖η ``` Print one less then the resulting count (since this procedure counts the outside too). ]
[Question] [ ## Introduction I can type at a moderate pace, using the QWERTY keyboard layout. But if a word like [yellowwooddoor](https://puzzling.stackexchange.com/questions/7875/what-is-the-english-word-with-the-longest-number-of-consecutive-repeated-letters) has a ton of repeated letters, it takes a bit longer to type it. Even worse is when a word like "jump" has the same finger used for multiple different consecutive letters. Here's how long it takes me to type letters on each finger (very unscientifically measured): Columns are Finger name, keystrokes/second, seconds/keystroke, and the keys used by each finger ``` Typing same letter twice: L Pinky 5.2 0.1923076923 1qaz L Ring 5 0.2 2wsx L Mid 5.3 0.1886792453 3edc L Index 5.5 0.1818181818 4rfv5tgb R Thumb 6.5 0.1538461538 [space] R Index 6.9 0.1449275362 6yhn7ujm R Mid 6.3 0.1587301587 8ik, R Ring 6.2 0.1612903226 9ol. R Pinky 6.1 0.1639344262 0p;' Typing different letter on same finger: L Pinky 4.6 0.2173913043 L Ring 4.6 0.2173913043 L Mid 4.5 0.2222222222 L Index 5.3 0.1886792453 R Index 5.4 0.1851851852 R Mid 5.1 0.1960784314 R Ring 5.2 0.1923076923 R Pinky 5.2 0.1923076923 ``` Same data in [CSV format](https://docs.google.com/spreadsheets/d/e/2PACX-1vSNRIdt2WMMF1PV89a0BM6m4aREIUNcyHKSsMDEWzt71lXd1NnVO3s7mq4rcXWoqkX_1xQNz8tG4_kC/pub?output=csv). It takes ``` .75 * (first_finger_same_letter_time + second_finger_same_letter_time) / 2 ``` time to switch between two fingers. ## Challenge Given a string as input, how long does it take to type it? * The "timer" starts the moment the first key is pressed and ends when the last key is pressed. You are just counting the time between keypresses. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Shortest answer in bytes wins. * Submission can be either a complete program or function. * Input and output [any way you want it](https://youtu.be/atxUuldUcfI?t=37), stdin/out, function params, file, doesn't matter. * Output should be accurate to at least 3 decimal places (+/- 0.001 for rounding error is fine). Leading 0. for numbers under 1 and trailing newline optional. * Input will be a string that contains (lowercase) a-z, 0-9, space, semicolon, comma, period, and apostrophe. * I always type spaces with my right thumb. * I use the [normal touch typing fingers](https://commons.wikimedia.org/wiki/File:Touch_typing.svg) (you can also look at the above table for finger-key mappings). * [Reference code used to generate test cases](https://tio.run/##fZLvboIwFMW/8xQ3fBmdBPkjOF14kmUhOMpkIrC2Tt3Ls/YWgbpsDSHp/fWcnt62u4p920R9v6saDik4jv2Zfwe2C7EXurDyEuJaMAzHPvNLiMz/zWjxFiGLFIsNxsov8b5bxchjXGRwkCBRILkTXvfN6eOYrJFvlHBl8Orw5CKLFAsM1tbeBlmIpzFY9@w/IAs0I5ZV0BLKqiky2QqnpkJQRrYoKVsGsgjyU23ajj5VCXrhgF781wmqwag4MUTa/9yygyN/xeCMBo2uQJqCP8kHqe/5WBKtyGt5Qbd5nXMhp0opdx1jTnGQBNtZoK7lvNrVNNOLuAs8P1IXiqosKaON8rtvwCjOXNwy05LMWCrrxOgJZkuHMGZH9DkW8qUFnr9UbpOU1jexzH@f9j@b8QRzL07/kHjrGB7lSx8DwELbjAckBJYQjuqh1zqINbsctLSsjlWNcPBubXrJj11NbUL6/gc) ## Test cases (empty string or any one-character string) - 0.000 `aa` - 0.192 `fff` - 0.364 `fj` - 0.123 `the quick brown fox jumped over the lazy dog` - 5.795 `yellowwooddoor` - 1.983 `orangewooddoor` - 1.841 `jump on it, jump on it` - 2.748 `type on it, type on it` - 2.549 `abcdefghijklmnopqrstuvwxyz01234567890 ;,.'` - 5.746 `ok, this may not be the most accurate but it's in the ballpark, maybe within 30 percent or so.` - 12.138 [Answer] # [JavaScript (Node.js)](https://nodejs.org), 180 bytes ``` s=>(B=Buffer)(s).map(p=c=>(b='23841410645532207643205431765001333746443'[c*45%91%73%41]*2,t+=1/p?p-b?3/8*(g(b)+g(p)):g(b|c!=s):0,p=b,s=c),t=0,g=x=>10/B('4.2.5-75E6?3>4=4AA')[x])&&t ``` [Try it online!](https://tio.run/##XVHbbqMwEH3vV8xWSsEpIQabW1dO1Ui7P1H1wYAhJAS7tsml2n9PSQOttG@jc5mZM7PlB24K3Si76GQpLhW7GLZy12zdV5XQyDXI33PlKlYMcM6ckKQ0oAGOaRSRMMRJTEmII0qCJI4wDgghCY0pJc5rMafRLAtmCZnR4G0eevaRBUv1rBb5M1mmc7d2c/RYuwqhp6H8V/xiBj1hT7HcM6xAnmXYq9mJrQK8XLsO9UM/WiTRn/iZrCijLy8Oej29oYcHe7HCWGBggK2gkJ2RrfBbWbvVNYCVf5uTKF2C0N3dVene3yNYLgH7GOMR4XzCgiwcsaqqJpDEdAK338KQjJjdCHjvm2IHuZbHDip5gm2/V6IEeRAarnzLP85Qyvrmjvwki0b3WbStPB6lLEsp9Y0P/CydukvNu1r8zw9/GPnrJJAdNNaDn/qmC/2EptOWZyUm3U896SKaTafIi1JU9abZ7tp9J9W7NrY/HE/nDzxEplGcpBmG357vfGeh8bTrbui9aQzs@Rk6aSEXX@n3cngQL4pecysg7@0w2THQdF9szttWcT14B9vgODZDjw4IBiV0IToLUoOR/pg99AOSXj4B "JavaScript (Node.js) – Try It Online") ## How? ### Storing delays The helper function \$g\$ takes an integer \$0\le x \le17\$ and returns a delay in seconds. ``` g = x => 10 / Buffer('4.2.5-75E6?3>4=4AA')[x] ``` The input \$x\$ is expected to be either: * twice the bin number to get the delay for the same letter * twice the bin number + 1 to get the delay for different letters What is actually stored in the string `'4.2.5-75E6?3>4=4AA'` is the number of keystrokes per second multiplied by \$10\$ and converted to ASCII. Conveniently, all resulting characters are printable. For instance, \$5.2\$ is stored as `chr(52)` which is `'4'`. ### Converting a character to a key bin We use the following hash function to convert an ASCII code \$c\$ to an index into a lookup table containing the bin numbers in \$[0..8]\$: $$i = (((c\times 45) \bmod 91)\bmod 73)\bmod 41$$ ### Main loop The total time \$t\$ is updated with: ``` t += // add to t: 1 / p ? // if p is numeric: p - b ? // if p is not equal to b: 3 / 8 * (g(b) + g(p)) // 0.75 * (g(b) + g(p)) / 2 : // else: g(b | c != s) // g(b) if c == s or g(b + 1) otherwise : // else (first iteration): 0 // leave t unchanged ``` where \$p\$ is the previous bin and \$s\$ is the previous character. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 78 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` “bk¶ŀqṣṁq*E’b25+45s2 Øq;"““;“,.'”Zṙ-ØD;"s2ẎW$€3,4¦ẎœiⱮQḢ€ị¢QƑịZƊQ3.75⁵Ḋ?÷$SµƝS ``` **[Try it online!](https://tio.run/##y0rNyan8//9Rw5yk7EPbjjYUPty5@OHOxkIt10cNM5OMTLVNTIuNuA7PKLRWAqoBImsg1tFTf9QwN@rhzpm6h2e4WCsVGz3c1Reu8qhpjbGOyaFlQM7RyZmPNq4LfLhjEVDw4e7uQ4sCj00E0lHHugKN9cxNHzVufbijy/7wdpXgQ1uPzQ3@//9/fraOQklGZrFCbmKlQl5@iUJSKpCfqpCbX1yikJicXFqUWJKqkFRaopBZol6skJkHlk1KzMkpSCwC6gVqA@oozwSakadgbKBQkFqUnJpXopBfpFCcrwcA "Jelly – Try It Online")** ### How? ``` “...’b25+45s2 - Link 1, keystrokes per 10 seconds: no arguments “...’ - base 250 integer = 379310849477441257135820 b25 - to base 25 = [16,7,7,1,5,1,8,0,10,8,24,9,18,6,17,7,20] +45 - add 45 = [61,52,52,46,50,46,53,45,55,53,69,54,63,51,62,52,65] s2 - split into twos - = [[61,52],[52,46],[50,46],[53,45],[55,53],[69,54],[63,51],[62,52],[65]] - For: 0... 1... 2... 3... 4... 6... 8... 9... space Øq;"““;“,.'”Zṙ-ØD;"s2ẎW$€3,4¦ẎœiⱮQḢ€ị¢QƑịZƊQ3.75⁵Ḋ?÷$SµƝS - Main Link: list of characters µƝ - for each neighbouring pair: Øq - qwerty = ["qwertyuiop","asdfghjkl","zxcvbnm"] ““;“,.'” - list of lists = ["",";",",.'"] " - zip with: ; - concatenate = ["qwertyuiop","asdfghjkl;","zxcvbnm,.'"] Z - transpose = ["qaz","wsx","edc","rfv","tgb","yhn","ujm","ik,","ol.","p;'"] ṙ- - rotate left -1 = ["p;'","qaz","wsx","edc","rfv","tgb","yhn","ujm","ik,","ol."] ØD - digits = "0123456789" " - zip with: ; - concatenate = ["0p;'","1qaz","2wsx","3edc","4rfv","5tgb","6yhn","7ujm","8ik,","9ol."] s2 - split into twos = [["0p;'","1qaz"],["2wsx","3edc"],["4rfv","5tgb"],["6yhn","7ujm"],["8ik,","9ol."]] ¦ - sparse application... 3,4 - ...to indices: [3,4] $€ - ...do: last two links as a monad for each: Ẏ - tighten W - wrap in a list = [["0p;'","1qaz"],["2wsx","3edc"],["4rfv5tgb"],["6yhn7ujm"],["8ik,","9ol."]] Ẏ - tighten = ["0p;'","1qaz","2wsx","3edc","4rfv5tgb","6yhn7ujm","8ik,","9ol."] Q - de-duplicate (the neighbouring letters) Ɱ - map with: œi - multi-dimensional index-into e.g. "fj" -> [[5,3],[6,7]] - (note <space> is not there so yields an empty list) Ḣ€ - head of each -> [5,6] - (...and the head of an empty list is 0) ¢ - call the last Link (1) as a nilad ị - index-into -> [[55,53],[69,54]] - (...and 0 indexes into the rightmost entry) Ɗ - last three links as a monad: Ƒ - invariant under?: Q - de-duplicate (1 if so, else 0) Z - transpose -> [[55,69],[53,54]] ị - index-into -> [55,69] Q - de-duplicate -> [55,69] $ - last two links as a monad: ? - if... Ḋ - ...condition: dequeue 3.75 - ...then: 3.75 ⁵ - ...else: 10 -> 3.75 ÷ - divide -> [0.06818181818181818,0.05434782608695652] S - sum -> 0.12252964426877469 S - sum ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~92~~ 86 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` Îü)v•δ'ā∍ë*8U¾Ã•₂в45+2ô9ÝÀžV€Sζ‚ø˜ð",.;'"S.;ykD4/ïD3›-D4›-‚©θ讀ËOUεXè}T/zX_iO3*8/ëθ]O ``` [Try it online](https://tio.run/##AZwAY/9vc2FiaWX//8OOw7wpduKAos60J8SB4oiNw6sqOFXCvsOD4oCi4oKC0LI0NSsyw7Q5w53DgMW@VuKCrFPOtuKAmsO4y5zDsCIsLjsnIlMuO3lrRDQvw69EM@KAui1ENOKAui3igJrCqc64w6jCruKCrMOLT1XOtVjDqH1UL3pYX2lPMyo4L8OrzrhdT///eWVsbG93d29vZGRvb3I) or [verify all test cases](https://tio.run/##TY7NSsNQEIVfZcimWGNbbastXXTTfRf@IIjITXLTpkkz8SZpTKFQK4ggblyKblxVFBVRKSJd9OpKCD5DXqTeBEQ3Z4Zz5psZdIli0HkvrEsQH5@DVJ8XQv6@0IuH19Fz5uMwPjnjt9nK5mzKj4QXj0bfT6Xy4gp/rvIrPvycbsWju/XoNR5e8MnXJX@U5FwtI63naqHZKOX5Q6MYD9@WGqVExdDsJprw8exeUPy0uRm9bPPxYCPf394zmsVsJc9vo8lg0JzL8x1JkkEiqaSq63paOol6bQr7vqGaoDAMbNDxADp@16EaYI8ySHKL9EPQsJXMh9SyMAgQNQ2RJQ4yYrfofyfhAW0wPBn@@vRa6NDf5K9PX1NUjeqtttExra6Nzj5zPb8XHIT9wvJKsVReXatUC1CTc5n0pin4tuFCl4RgowcKTT/tousBUVWfEY@C4ntie8YFw05ThViWQ5hgBSaIwBA7bCgWwKFMpbYHyMDFnLT7Aw). **Explanation:** ``` Î # Push 0 and the input-string ü) # Create all pairs of the (implicit) input-string # (which will be [] if the input-string is of length 0 or 1) # i.e. "ab d" → ["a","b"],["b"," "],[" ","d"]] v # Loop over these pairs `y`: •δ'ā∍ë*8U¾Ã• '# Push compressed integer 307264255556527588774514 ₂в # Converted to Base-26 as list: [7,1,5,1,8,0,10,8,24,9,18,6,17,7,16,7,20] 45+ # Add 45 to each: [52,46,50,46,53,45,55,53,69,54,63,51,62,52,61,52,65] 2ô # Split into parts of size 2: [[52,46],[50,46],[53,45],[55,53],[69,54],[63,51],[62,52],[61,52],[65]] 9Ý # Push list [0,1,2,3,4,5,6,7,8,9] À # Rotate it once to [1,2,3,4,5,6,7,8,9,0] žV # Push builtin ["qwertyuiop","asdfghjkl","zxcvbnm"] €S # Convert each to a list of characters ζ # Zip/transpose; swapping rows/columns, with space as default filler: # [["q","a","z"],["w","s","x"],["e","d","c"],["r","f","v"],["t","g","b"],["y","h","n"],["u","j","m"],["i","k"," "],["o","l"," "],["p"," "," "]] ‚ø # Pair it with the digit list, and zip/transpose again ˜ # Then flatten this entire list: # ["1","q","a","z","2","w","s","x","3","e","d","c","4","r","f","v","5","t","g","b","6","y","h","n","7","u","j","m","8","i","k"," ","9","o","l"," ","0","p"," "," "] ð",.;'"S.; # Replace the four spaces with [",", ".", ";", "'"] in order yk # Get the indices of the characters in the pair `y` in this list # i.e. ["b"," "] → [19,-1] 4/ # Divide both by 4 # i.e. [19,-1] → [4.75,-0.25] ï # Floor the decimals to integers # i.e. [4.75,-0.25] → [4,-1] D3›- # If an index is larger than 3: decrease it by 1 # i.e. [4,-1] → [3,-1] D4›- # If an index is now larger than 4: decrease it by 1 again D ‚ # Pair it with the original index # i.e. [[19,-1],[3,-1]] © # And save it in the register (without popping) θè # Then use the last of the two to index into the list of pairs # i.e. [3,-1] → [[55,53],[65]] ®€Ë # Check for each pair in the register if they're equal # i.e. [[19,-1],[3,-1]] → [0,0] O # Take the sum of that U # And pop and store it in variable `X` ε } # Map the pairs in the list to: Xè # The `X`'th value in the pair # i.e. [[55,53],[65]] and `X`=0 → [55,65] T/ # Divide each by 10 # i.e. [55,65] → [5.5,6.5] z # And take 1/value for each # i.e. [5.5,6.5] → [0.181...,0.153...] X_i # If variable `X` was 0: O # Take the sum of these decimal values # i.e. [0.181...,0.153...] → 0.335... 3*8/ # Multiply it by 3, and then divide it by 8 # i.e. 0.335... → 0.125... ë # Else: θ # Pop the pair of decimal values, and only leave the last one ] # Close both the if-else statement and the loop O # And take the sum of the stack # (which is output implicitly as result) ``` [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 `•δ'ā∍ë*8U¾Ã•` is `307264255556527588774514` and `•δ'ā∍ë*8U¾Ã•₂в` is `[7,1,5,1,8,0,10,8,24,9,18,6,17,7,16,7,20]`. ]
[Question] [ Given the sequence [OEIS A033581](http://oeis.org/A033581), which is the infinite sequence, the **n**'th term (0-indexing) is given by the closed form formula **6 × n2** . Your task is to write code, which outputs all the subsets of the set of N first numbers in the sequence, such that the sum of the subset is a perfect square. # Rules * The integer `N` is given as input. * You cannot reuse a number already used in the sum. (that is, each number can appear in each subset at most once) * Numbers used can be non-consecutive. * Code with the least size wins. # Example The given sequence is {0,6,24,54,96,...,15000} One of the required subsets will be {6,24,294}, because ``` 6+24+294 = 324 = 18^2 ``` You need to find all such sets of all possible lengths in the given range. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 10 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ݨn6*æʒOŲ ``` **[Try it online!](https://tio.run/##ARwA4/8wNWFiMWX//8OdwqhuNirDpsqST8OFwrL//zEw "05AB1E – Try It Online")** ## How? ``` ݨn6*æʒOŲ || Full program. I'll call the input N. Ý || 0-based inclusive range. Push [0, N] ∩ ℤ. ¨ || Remove the last element. n || Square (element-wise). 6* || Multiply by 6. æ || Powerset. ʒ || Filter-keep those which satisfy the following: O ||---| Their sum... Ų ||---| ... Is a perfect square? ``` [Answer] # [Haskell](https://www.haskell.org/), ~~114 104 103~~ 86 bytes ``` f n=[x|x<-concat<$>mapM(\x->[[],[x*x*6]])[0..n-1],sum x==[y^2|y<-[0..],y^2>=sum x]!!0] ``` Thanks to [Laikoni](https://codegolf.stackexchange.com/users/56433/laikoni) and [Ørjan Johansen](https://codegolf.stackexchange.com/users/66041/%C3%98rjan-johansen) for most of the golfing! :) [Try it online!](https://tio.run/##VcmxDoIwFEDR3a94EAYlLSkOTG2/QCfH8kwalEikDwIlKQn/XsXN8dz7svP72fcxtkDKhC1I3gzUWC8z7ex4PdaBa2OQmZCHvEI8GVEUxEtk8@IgKGXW@3lbJd87si@0@h1MEoHR2Y5AwWM4AIxTRx4yaKHatfibny4EaU3p3y1F/AA "Haskell – Try It Online") The slightly more readable version: ``` -- OEIS A033581 ns=map((*6).(^2))[0..] -- returns all subsets of a list (including the empty subset) subsets :: [a] -> [[a]] subsets[]=[[]] subsets(x:y)=subsets y++map(x:)(subsets y) -- returns True if the element is present in a sorted list t#(x:xs)|t>x=t#xs|1<2=t==x -- the function that returns the square subsets f :: Int -> [[Int]] f n = filter (\l->sum l#(map(^2)[0..])) $ subsets (take n ns) ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 12 bytes -2 bytes thanks to Mr. Xcoder ``` fsI@sT2ym*6* ``` [Try it online!](https://tio.run/##K6gsyfj/P63Y06E4xKgyV8tM6/9/QwMA "Pyth - Try it online!") 2 more bytes need to be added to remove `[]` and `[0]`, but they seem like valid output to me! --- Explanataion ``` fsI@sT2ym*6* f filter y the listified powerset of m*6*ddQ the listified sequence {0,6,24,...,$input-th result} sT where the sum of the sub-list sI@ 2 is invariant over int parsing after square rooting ``` [Answer] # [Clean](https://clean.cs.ru.nl), ~~145~~ ... 97 bytes ``` import StdEnv @n=[[]:[[6*i^2:b]\\i<-[0..n-1],b<- @i]] f=filter((\e=or[i^2==e\\i<-[0..e]])o sum)o@ ``` [Try it online!](https://tio.run/##Pc27CsIwFADQvV@RsRVT1KFDaSCDDoJbx@QKaZuUC3lIkgr@vLGT@4EzW618cWHZrCZOoS/oXiFmMubl5t8V90wI6IXoDvi89BNIiQMVp7b19AzHaaCEI0BlmEGbdaxrqVmIYseM6T/WAE0gaXNN4GXMag8YMaQr39lYtaZC749y/XjlcE4/ "Clean – Try It Online") Uses the helper function `@` to generate the power set to `n` terms by concatenating each term of `[[],[6*n^2],...]` with each term of `[[],[6*(n-1)*2],...]` recursively, and in reverse order. The partial function `f` is then composed (where `->` denotes `o` composition) as: `apply @ -> take the elements where -> the sum -> is a square` Unfortunately it isn't possible to skip the `f=` and provide a partial function *literal*, because precedence rules require it have brackets when used inline. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes ``` Ḷ²6׌PSƲ$Ðf ``` [Try it online!](https://tio.run/##AScA2P9qZWxsef//4bi2wrI2w5fFklBTw4bCsiTDkGb/w4fFkuG5mP//MTA "Jelly – Try It Online") Output is a list of subsets including `0`s and the empty subset. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 49 bytes Brute force approach ``` Select[Subsets[6Range[#]^2],Sqrt@Tr@#~Mod~1==0&]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7Pzg1JzW5JDq4NKk4taQ42iwoMS89NVo5Ns4oVie4sKjEIaTIQbnONz@lztDW1kAtVu1/QFFmXkl0moOhQex/AA "Wolfram Language (Mathematica) – Try It Online") [Answer] # JavaScript (ES7), 107 bytes ``` n=>[...Array(n)].reduce((a,_,x)=>[...a,...a.map(y=>[6*x*x,...y])],[[]]).filter(a=>eval(a.join`+`)**.5%1==0) ``` ### Demo ``` let f = n=>[...Array(n)].reduce((a,_,x)=>[...a,...a.map(y=>[6*x*x,...y])],[[]]).filter(a=>eval(a.join`+`)**.5%1==0) console.log(f(6).map(a => JSON.stringify(a)).join('\n')) console.log(f(10).map(a => JSON.stringify(a)).join('\n')) ``` ### Commented ``` n => // n = input [...Array(n)] // generate a n-entry array .reduce((a, _, x) => // for each entry at index x: [ // update the main array a[] by: ...a, // concatenating the previous values with ...a.map( // new values built from the original ones y => // where in each subarray y: [ 6 * x * x, // we insert a new element 6x² before ...y ] // the original elements ) // end of map() ], // end of array update [[]] // start with an array containing an empty array ) // end of reduce() .filter(a => // filter the results by keeping only elements for which: eval(a.join`+`) ** .5 // the square root of the sum % 1 == 0 // gives an integer ) // end of filter() ``` [Answer] # [Japt](https://github.com/ETHproductions/japt/), 15 bytes ``` ò_²*6Ãà k_x ¬u1 ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=8l+yKjbD4CBrX3ggrHUx&input=OAotUg==) --- ## Explanation Generate on array of integers from 0 to input (`ò`) and pass each through a function (`_ Ã`), squaring it (`²`) & mutiplying by 6 (`*6`). Get all the combinations of that array (`à`) and remove those that return truthy (`k`) when passed through a function (`_`) that adds their elements (`x`), gets the square root of the result (`¬`) and mods that by 1 (`u1`) ]
[Question] [ Imagine you have two lights. These lights blink on and off at a specific rate: ``` Light 0: Delay 0ms and then blink every 1000ms Light 1: Delay 500ms and then blink every 1000ms ``` Let's simulate these lights for the first 2000ms: ``` 0ms: Light 0 on 500ms: Light 1 on 1000ms: Light 0 off 1500ms: Light 1 off 2000ms: Light 0 on ``` # The challenge Given a list of ordered pairs representing the timing for lights, write a program or function to output the sequence for when they blink. ### Input The input should be in the following format: ``` TimeToSimulate Light0Delay,Light0Period Light1Delay,Light1Period ... ``` In this format, the example above would be: ``` 2000 0,1000 500,1000 ``` ### Output The output should be a series of ordered triples: ``` Time,LightNum,LightStatus ``` LightStatus is a truthy value if the light turns on and a falsy value if the light turns off. The output from the above example would be: ``` 0,0,True 500,1,True 1000,0,False 1500,1,False 2000,0,True ``` If two lights blink at the same time, the light with the lower number should display first in the output. ### Other stuff * The input and output formats aren't strict * Code shouldn't produce any errors * The solution shouldn't rely on race conditions * No standard loopholes * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest solution wins! ### Test cases ``` Input: 2000 0,1000 500,1000 Output: 0,0,True 500,1,True 1000,0,False 1500,1,False 2000,0,True ---- Input: 2 0,1 0,1 Output: 0,0,True 0,1,True 1,0,False 1,1,False 2,0,True 2,1,True ---- Input: 500 100,50 200,100 300,150 Output: 100,0,True 150,0,False 200,0,True 200,1,True 250,0,False 300,0,True 300,1,False 300,2,True 350,0,False 400,0,True 400,1,True 450,0,False 450,2,False 500,0,True 500,1,False ---- Input: 1000 23,345 65,98 912,12 43,365 Output: 23,0,True 43,3,True 65,1,True 163,1,False 261,1,True 359,1,False 368,0,False 408,3,False 457,1,True 555,1,False 653,1,True 713,0,True 751,1,False 773,3,True 849,1,True 912,2,True 924,2,False 936,2,True 947,1,False 948,2,False 960,2,True 972,2,False 984,2,True 996,2,False ``` # Leaderboard Snippet: ``` var QUESTION_ID=137465,OVERRIDE_USER=41505;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i; ``` ``` body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px} ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> ``` [Answer] # JavaScript, ~~98~~ 97 bytes ``` a=>b=>[...Array(a+1)].map((_,i)=>b.map((d,j)=>d[0]--||c.push([i,j,d[d[0]=d[1]-1,2]^=1])),c=[])&&c ``` [Try it online](https://tio.run/##bVDbboJAEH3fr7CJ0Z2wLBfFVM1qmv6BSZ@AlhVQIRQIoEkjfrudBaJ96CZ7mTPn7MycVF5kHVZJ2eh5EcX3g7hLsdmLjcs5f6sq@UOlZoHPv2VJ6RdLALN9ELEUg8g1fV1v25CX5/pE3YSlLHIVKiLX8nWL2f6nsHwAFgrXh8kkvF9kNWriunmXdVyPxCggtmmaxGSWuhxzeOi4iK3gbnchJgkmmWMqjeKRmbqdgd4J7RmbzR2ycNjylSwtm1k2mSO2cEiwJqp6kpfnBiu7/po8OuF1mSUN3QnD0zUDuinRjI7bTycRa8ITNbxI8xgeLW7jCABr0tFETx6UsjdKsr1ybSv7AgELHoTWhJU6UB8WeV1kMc@KI33@MoiD8fVAJZoK2EOdJWFMLYD/6@j2Vq4QfnmR2nQKKOJN8VGWcaWmpKD9@QF4WiR54OXBLejfFIPx9elJP/AObsjBNu@/) *Saved a byte thanks to [Shaggy](https://codegolf.stackexchange.com/users/58974/shaggy)* - use currying input syntax. [Answer] # [Python 2](https://docs.python.org/2/), 93 bytes ``` lambda t,l:sorted(sum([zip(range(x[0],-~t,x[1]),[i]*-~t,[1,0]*t)for i,x in enumerate(l)],[])) ``` [Try it online!](https://tio.run/##TYpBCsIwEEX3niLLpIyQVrIRPMl0FpGmGmjTkk6huvDqMbEiboY3/735wfcpNKm/tGmw47WzgmE4L1Nk18llHSU@/SyjDTcnN9QExxfDhjUpQE9V@bAGTRWrforCwyZ8EC6so4uWnRwUAZJSaY4@sOhlA4ga6ryWS@rwE1rr3WXI2ugv/jXmk@QVTEmaPcl0KmRKm1J6Aw "Python 2 – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly11), ~~26~~ 25 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` Ḣrm⁸ð€µ;€€"J;"J$€€ẎẎḂ0¦€Ṣ ``` A dyadic link taking a list of `delay, period` number-lists and a time-frame number and returning a list of `time, light, action` integers. The lights are 1-indexed and `0` represents the 'off' action, while `1` represents the 'on' action. **[Try it online!](https://tio.run/##y0rNyan8///hjkVFuY8adxze8KhpzaGt1kASiJS8rJW8VCDsh7v6QGhHk8GhZSDuzkX///@PjjY0MNAxNYjViTYCMoAcIMsYxAKKxf43NTAAAA "Jelly – Try It Online")** ### How? ``` Ḣrm⁸ð€µ;€€"J;"J$€€ẎẎḂ0¦€Ṣ - Link: [[delay, period],...], time-frame ð€ - for €ach [delay, period]: Ḣ - head (get the delay and modify the item to [period]) r - inclusive range to time-frame = [delay,delay+1,...,time-frame] ⁸ - chain's left argument = [period] m - modulo slice = [delay, delay+period, delay+2*period, ...] µ - monadic chain separation, call that v J - range(length(v)) = [1,2,...,nLights] " - zip with: ;€€ - concatenate for €ach for €ach (add light indexes to times) $€€ - last two links as a monad for €ach for €ach: J - range (length(switch-times-for-a-light)) " - zip with: ; - concatenation (i.e. append a 1-based index) ẎẎ - tighten & tighten again (flatten by 2 to a list of triples) |€ - sparse application of (for €ach): 0 - ...to indexes: 0 (=last entry) Ḃ - ...action: modulo by 2 (even appended indexes ->0s; odds -> 1s) Ṣ - sort the resulting list of triples ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~206~~ 214 bytes * Added eight bytes to comply with the rules (taking input via stdin). ``` Q=input();D,T=Q[0],[map(int,q.split(","))for q in Q[1:]];O,l=[],len(T) for j in range(l): t,b=T[j][0],9>8 while t<=int(D):O+="%0*d,%0*d,%s"%(len(D),t,len(str(l)),j,b),;b=not b;t+=T[j][1] print"\n".join(sorted(O)) ``` [Try it online!](https://tio.run/##JY1Bi4MwEEbP9VeEQCGzHUpia6m62ZN3Eby5OVTqthEbrc6y7K93k@1lePA@3ky/dB9dvK6Vtm76JgF5gbWuGmmweVwmYR3hc79MgyXBkQN8jTN7MutY1ajMmLzEQTcGh86JGqJg@2Dni7t1YoAs2hC2um56E5rpxzna/Nzt0DF69y9JFJCVO8238u2Kr7PwrQi5ApD@uwvNvgTYYwuYt9qNxNqcdq@qMtE0@xL/dHzfj9bvx5m6qygB1lVwJaXkyHh8wMMxCXRKMD0HSFWMKg509PKUcPgD "Python 2 – Try It Online") This code generates an unordered lists containing each light's switching times, pads those times and the light identifier, sorts said list and outputs it. [Answer] # [Perl 5](https://www.perl.org/), 106 + 1 (-n) = 107 bytes ``` ($a[$i],$b[$i++])=eval for<>;for$i(0..$_){for(0..$#a){$a[$_]+=$b[$_],say"$i,$_,".($s[$_]^=1)if$i==$a[$_]}} ``` [Try it online!](https://tio.run/##JYtBCsIwFET3PYXUv0hIGn6UrDTewBNIDBFa@FCa0oggpVc3JrqZNzPMzP0ympwZhBuQk/AoEMJx27/CuBvicr6cigIxVAo8X0v42X3gaz15J2x9eSdTeLdAErxsFYNUu7vVnAYga//bbcvZIDYaURpsDgXFNsdKg584PylOKXdXo1Bj7qYv "Perl 5 – Try It Online") [Answer] # Haskell, 121 bytes ``` import Data.List t!l=sort$(zip[0..]l)>>=takeWhile(\(a,_,_)->a<=t).(\(i,(d,w))->iterate(\(t,i,s)->(t+w,i,not s))(d,i,2>1)) ``` [Try it online.](https://tio.run/##Nco9C4MwEMbx3U9xgkOOXkMUujWZOnbvYEUCBjyML5gDoV/epkO35//jGX2aQoznyfO27gIPL14/OUkhZbQpU6U@vLVG6y6ic1b8FF4jx6DeylNPPV6dv1tBnYFJDXRgJpawe/mdhJhSFiWXI89lFUiI@cfUuBrxnD0vYGFYC4Bt50WggsYYAyW0CsAQ1LmQQN3MP7rzCw) This is the program I started from: ``` import Data.List type LightId = Int type Time = Int type State = Bool type LightEvent = (Time, LightId, State) lightSimulation :: Time -> Time -> [(Time, State)] lightSimulation delay interval = iterate step (delay, True) where step (time, state) = (time+interval, not state) addId :: LightId -> (Time, State) -> LightEvent addId id (t, s) = (t, id, s) simulate :: Time -> [(Time, Time)] -> [LightEvent] simulate timeLimit lights = sort $ concatMap lightSim (zip [0..] lights) where withinTimeLimit = ((<=timeLimit) . fst) lightSims (id, (delay, interval)) = map (addId id) $ takeWhile withinTimeLimit (lightSimulation delay interval) ``` And before final golfing I has shortened it to: ``` import Data.List light (id,(delay,interval)) = iterate step (delay, id, True) where step (time, id, state) = (time+interval, id, not state) simulate timeLimit lights = sort $ concatMap lightSims (zip [0..] lights) where lightSims l = takeWhile(\(a,b,c)->a<=timeLimit)$light l ``` [Answer] # [Röda](https://github.com/fergusq/roda), ~~105~~ ~~87~~ 85 bytes ``` {|t|enum|[([_+_]*(t-_1[0]+1))()|enum|(_+_)]|{[[_+_4,_3,_4//_2%2=0]]if[_4%_2=0]}|sort} ``` [Try it online!](https://tio.run/##VY/LasMwEEXX8VcMgoDcqESS7dAY/AHdd6cIYRI5McQPLKWb2N/ujuw@6EKa4Z553Bm6Szk/o00FeQGn@Tn60baPZlRUmZ3RL9S/GqG43ok4pvHKKJJYj08VSlJmEmbS/d7IrSy41nWlTLo1IZ9G1w1@mqcoasq6BdwTBsAIVTeAt86bc@ksgxYuXbTZ9EPdeiBFUcAHQggQCOKdYEBygiX@HIz@tsIeCCx63dhA@nJw9r319moH6s/oPEZ6r6837wJXqIlc0xhNKOX6e@2pYeBsXxBGgvpvAt6p9d8ANE7DJqxDMRxhPy1aXtx/218U3IuOG5ef/NIarliBQNA/3I0S6FpcWFegvpHUoMHe8aqfgqoiwf6la220/tMsOefAmQgh42sSyaCEF6EEKLGMg1wpJCFmPFpaZMKSNINDxo5vcBSSCQkpaofsCw "Röda – Try It Online") Explanation: ``` {|t| /* Declare a lambda with one parameter */ /* The input stream contains arrays */ enum| /* For each array in the input, push an ascending number after it */ /* [1] (for stream content in this point, see below) */ [ /* For each array-number pair in the stream: */ ( [_+_] /* Create a copy of the array with the number as the last element */ *(t-_1[0]+1) /* Create copies of the array for every ms simulated */ )()| /* Push all copies to the stream */ enum| /* After each copy, push an ascending number to the stream */ (_+_) /* Append the number to each array before */ ]| /* [2] (for stream content in this point, see below) */ { /* Push an on or off event to the stream: */ [[ _+_4, /* delay + time = actual time */ _3, /* light-id */ _4//_2%2=0 /* does the light go on or off? */ ]] if[_4%_2=0] /* if the light goes on or off (time%period=0) */ }| /* [3] (for stream content in this point, see below) */ sort /* Sort the events */ } ``` The stream contains at point `[1]` values in the following order: ``` [delay, period], light-id _1[0] _1[1] _2 ``` The stream contains at point `[2]` values in the following order: ``` delay, period, light-id, time _1 _2 _3 _4 ``` The stream contains at point `[3]` arrays with the following structure: ``` [time, light-id, on_or_off] ``` ]
[Question] [ Given a number n, print the nth **prime** Fermat number, where the Fermat numbers are of the form 22k+1. This code should theoretically work for any n (i.e. don't hardcode it), although it is not expected to terminate for n > 4. (It should **not** return 4294967297 for n=5, as 4294967297 is not a prime number.) Do note that while all Fermat primes are of the form 22n+1, not all numbers of the form 22n+1 are prime. The goal of this challenge is to return the n-th **prime.** # Test cases ``` 0 -> 3 1 -> 5 2 -> 17 3 -> 257 4 -> 65537 ``` # Rules * Standard loopholes are disallowed. * 0-indexing and 1-indexing are both acceptable. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), lowest byte-count wins. Related: [Constructible n-gons](https://codegolf.stackexchange.com/questions/92272/constructible-n-gons) [Answer] # [Python 2](https://docs.python.org/2/), 53 bytes ``` k=input();F=2 while k:F*=F;k-=3**(F/2)%-~F/F print-~F ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P9s2M6@gtERD09rN1oirPCMzJ1Uh28pNy9bNOlvX1lhLS8NN30hTVbfOTd@Nq6AoM68EyPz/3wQA "Python 2 – Try It Online") Uses [Pépin's test](https://en.wikipedia.org/wiki/P%C3%A9pin%27s_test). --- **[Python 2](https://docs.python.org/2/), 54 bytes** ``` f=lambda k,F=4:k and f(k-3**(F/2)%-~F/F,F*F)or F**.5+1 ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P802JzE3KSVRIVvHzdbEKlshMS9FIU0jW9dYS0vDTd9IU1W3zk3fTcdNy00zv0jBTUtLz1Tb8H8akJ2tkJmnUJSYl56qYappxcVZUJSZVwLSq/kfAA "Python 2 – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~13~~ 11 bytes ``` ÆẸ⁺‘©ÆPµ#ṛ® ``` Uses 1-based indexing. [Try it online!](https://tio.run/##ASIA3f9qZWxsef//w4bhurjigbrigJjCqcOGUMK1I@G5m8Ku//81 "Jelly – Try It Online") ### How it works ``` ÆẸ⁺‘©ÆPµ#ṛ® Main link. No argument. # Read an integer n from STDIN and call the chain to the left with arguments k = 0, 1, 2, ... until n matches were found. ÆẸ Find the integer with prime exponents [k], i.e., 2**k. ⁺ Repeat the previous link, yielding 2**2**k. ‘ Increment, yielding 2**2**k+1 and... © copy the result to the register. ÆP Test the result for primality. ® Yield the value from the register, i.e., the n-th Fermar prime. ṛ Yield the result to the right. ``` [Answer] # [Perl 6](https://perl6.org), ~~45~~ 42 bytes ``` {({1+[**] 2,2,$++}...*).grep(*.is-prime)[$_]} ``` [Try it](https://tio.run/##K0gtyjH7X1qcqlBmppdszZVbqaCWnJ@SqmD7v1qj2lA7WksrVsFIx0hHRVu7Vk9PT0tTL70otUBDSy@zWLegKDM3VTNaJT629n9xYqUCSKOGSrymQlp@kYKBnp6J9X8A "Perl 6 – Try It Online") ``` {({1+2**2**$++}...*).grep(*.is-prime)[$_]} ``` [Try it](https://tio.run/##K0gtyjH7X1qcqlBmppdszZVbqaCWnJ@SqmD7v1qj2lDbSEsLiFS0tWv19PS0NPXSi1ILNLT0Mot1C4oyc1M1o1XiY2v/FydWKoB0aajEayqk5RcpGOjpmVj/BwA "Perl 6 – Try It Online") ## Expanded: ``` { # bare block lambda with implicit parameter 「$_」 ( # generate a sequence of the Fermat numbers { 1 + 2 ** 2 ** $++ # value which increments each time this block is called } ... # keep generating until: * # never stop ).grep(*.is-prime)\ # reject all of the non-primes [$_] # index into that sequence } ``` [Answer] # Mathematica, 56 bytes ``` (t=n=0;While[t<=#,If[(PrimeQ[s=2^(2^n)+1]),t++];n++];s)& ``` [Try it online!](https://tio.run/##y00sychMLv6fZvtfo8Q2z9bAOjwjMyc1usTGVlnHMy1aI6AoMzc1MLrY1ihOwyguT1PbMFZTp0RbO9Y6D0QUa6r9ByrJK1FwSFNwMPkPAA "Mathics – Try It Online") [Answer] # Dyalog APL (29 Characters) I'm almost certain this can be improved. ``` {2=+/0=(⍳|⊢)a←1+2*2*⍵:a⋄∇⍵+1} ``` This is a recursive function which checks the number of divisors of 1+2^2^⍵, where ⍵ is the right argument of the function. If the number of divisors is 2, the number is prime, and it returns it, otherwise, it calls the function again with ⍵+1 as a right argument. ## Example ``` {2=+/0=(⍳|⊢)a←1+2*2*⍵:a ⋄ ∇ ⍵+1}¨⍳4 5 17 257 65537 ``` Here I call the function on each of ⍳4 (the numbers 1-4). It applies it to every number in turn. [Answer] # [Pyth](https://github.com/isaacg1/pyth), 14 bytes ``` e.f&P_ZsIltZQ3 ``` [Try it online!](https://tio.run/##K6gsyfj/P1UvTS0gPqrYM6ckKtD4/39TAA "Pyth – Try It Online") Uses 1-indexing. [Answer] # [Pyth](https://github.com/isaacg1/pyth), 14 bytes ``` Lh^2^2byfP_yTQ ``` [Try online.](https://pyth.herokuapp.com/?code=Lh%5E2%5E2byfP_yTQ&test_suite=1&test_suite_input=0%0A1%0A2%0A3%0A4&debug=0) Main idea "borrowed" from [xnor's answer in another question](https://codegolf.stackexchange.com/a/97036/61272) ``` Lh^2^2byfP_yTQ L define a function with name y and variable b, which: h^2^2b returns 1+2^2^b y call the recently defined function with argument: f Q the first number T >= Q (the input) for which: P_yT the same function with argument T returns a prime and implicitly print ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 8 bytes ### Code: Results are 1-indexed. ``` µN<oo>Dp ``` Uses the **05AB1E** encoding. [Try it online!](https://tio.run/##MzBNTDJM/f//0FY/m/x8O5eC//@NAQ "05AB1E – Try It Online") ### Explanation: ``` µ # Run the following n succesful times.. N # Push Nn oo # Compute 2 ** (2 ** n) > # Increment by one D # Duplicate p # Check if the number is prime # Implicit, output the duplicated number which is on the top of the stack ``` [Answer] # Javascript, ~~12~~ 46 bytes ``` k=>eval('for(i=n=2**2**k+1;n%--i;);1==i&&n') ``` Most of the code is taken up by the prime check, which is from [here](https://codegolf.stackexchange.com/questions/57617/is-this-number-a-prime/91309#91309). [Answer] # [Haskell](https://www.haskell.org/), 61 bytes ``` p n=2^2^n;f=(!!)[p x+1|x<-[0..],all((>)2.gcd(p x+1))[2..p x]] ``` [Try it online!](https://tio.run/##LYyxCoMwGIT3PsUvOCS0BpvRmkKHDp07ikKoUYPJb4ihWOi7p1a85Y674xvkPCpjorZu8gGenzkoy@741n5CqzCQXoWb72caHaDgDW/w0gmSJLRysBzP36XMqpyx@iSNIeRKOetfLdk2SivO2BrrOlqpUUA7HWCTXJFQZrDT99Z5jSHtgHglW0hh@Nt2LQp4YKAx5j8 "Haskell – Try It Online") 0-based index **Explanation** ``` p n=2^2^n; -- helper function -- that computes what it says f= -- main function (!!) -- partially evaluate -- index access operator [p x+1| -- output x-th fermat number x<-[0..], -- try all fermat number indices all [2..p x] -- consider all numbers smaller F_x -- if for all of them... ((>)2 -- 2 is larger than... .gcd(p x+1)) -- the gcd of F_x -- and the lambda input -- then it is a Fermat prime! ] ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 11 bytes ``` !fṗmȯ→‼`^2N ``` [Try it online!](https://tio.run/##yygtzv7/XzHt4c7puSfWP2qb9KhhT0Kckd////9NAA "Husk – Try It Online") [Answer] # [GolfScript](http://www.golfscript.com/golfscript/), 26 bytes ``` ~3\{{(.*).,(;{*}*)1$%}do}* ``` [Try it online!](https://tio.run/##S8/PSStOLsosKPn/v844prpaQ09LU09Hw7paq1ZL01BFtTYlv1br/38TAA "GolfScript – Try It Online") 0-indexed ``` ~ # Parse n to a number 3 # Push 3 \{ }* # Execute this block n times, this block gets the next Fermat prime { }do # While the number is composite (.*) # Go to the next Fermat number .,(; # Make an array from 1 to (F_n)-1 {*}* # Multiply the numbers to get ( (F_n)-1 )! ) # Increment it 1$% # This will be 0 iff the Fermat number is prime ``` The primality test used here is [Wilson's theorem](https://en.wikipedia.org/wiki/Wilson%27s_theorem#Primality_tests). ]
[Question] [ ## Challenge Given a list of SI base units, a list of equations and a target, you must derive the units of the target using only the base units. ## Derived Units *From Wikipedia:* > > The International System of Units (SI) specifies a set of seven base units from which all other SI units of measurement are derived. ***Each of these other units (SI derived units) is either dimensionless or can be expressed as a product of powers of one or more of the base units.*** > > > For example, the SI derived unit of area is the square metre (m2), and the SI derived unit of density is the kilogram per cubic metre (kg/m3 or kg m−3). > > > The seven SI base units are: * Ampere, *A* * Candela, *cd* * Kelvin, *K* * Kilogram, *kg* * Metre, *m* * Mole, *mol* * Second, *s* ## Example ### Input **Base units:** ``` d [m] m [kg] t [s] ``` **Equations:** ``` v = d/t a = v/t F = m*a E = F*d ``` **Target:** ``` E ``` ### Output ``` E [kg*m*m/s/s] ``` --- ### Input **Base units:** ``` G [cd] L [m] y [A] a [K] ``` **Equations:** ``` T = y*y/L A = T*G ``` **Target:** ``` A ``` ### Output ``` A [cd*A*A/m] ``` ## Rules The units will be always be given in the form ``` a [b] ``` Where `a` will be a single uppercase or lowercase alphabetical letter and `b` will be a unit (one or more characters). The equation will be in the form ``` a = c ``` Where `c` will be an expression which will only ever use previously defined units and the operators `*` and `/`. Powers must be expanded. For example, the unit of area is officially `m^2`, but you should represent this as `m*m`. The same applies to negative powers such as speed (`m*s^-1`) which should be represented as a division: `m/s`. Similarly, the units for acceleration, `m/s^2` or `m*s^-2`, should be represented as `m/s/s`. You do not have to do any cancelling out. For example, an output `C*s/kg/s` is valid even though it can be cancelled down to `C/kg`. There is no specific order for the multiplication: `kg*s/m`, `s/m*kg`, `s*kg/m` are all valid (but `/m*s*kg` is invalid). **Note: *You will never have to divide by a derived unit.*** ## Winning The shortest code in bytes wins [Answer] ## [Retina](https://github.com/m-ender/retina), ~~50~~ 48 bytes ``` = +`((.) (.+)\D*)\2(?!\w*]) $1$3 A-2` ](.). $1 ``` [Try it online!](https://tio.run/nexus/retina#DcpBCoAgEEbh/X@KCVqokVGtI4LqEjqgILQIV4Ud32b18eBVWoAuKGU1KdtpvxvtJ7U2/jOs0Y7tjK2fAlgOK11rIpcZmdx9MV5yD6PQQml4EcUinmI2EYd4mvQD "Retina – TIO Nexus") ### Explanation ``` = ``` Remove all equals signs together with the space in front of them. Who needs those anyway... ``` +`((.) (.+)\D*)\2(?!\w*]) $1$3 ``` This performs the substitutions of known quantities. It repeatedly matches a quantity definition (the quantity is any character in front of a space and the definition the string after it), as well as some place after the definition where that quantity is used, and insert the definition for the usage. We exclude units from those matches (by ensuring that there is no `]` after the match), so that we don't replace `[m]` with `[[kg]]` for example. This substitution is repeated until the regex no longer matches (which means that there are no usages of a quantity left, and all lines have been turned into expressions of units). ``` A-2` ``` Discard all but the last line. ``` ](.). $1 ``` Finally, remove extraneous square brackets. Basically, we want to keep the first `[` and the last `]` but discard all others. Those others always appear with an operator in between, so either as `]*[` or as `]/[`. But more importantly, those are the only cases where a `]` is followed by two more characters. So we match all `]` with two characters after them, and replace that with the second of those three characters to retain the operator. [Answer] # JavaScript (ES6), ~~155~~ ~~153~~ 152 bytes ``` (U,E,T)=>(u={},U.map(x=>u[x[0]]=x.slice(3,-1)),e={},E.map(x=>e[x[0]]=x.slice(4)).map(_=>s=s.replace(r=/[A-z]/g,m=>e[m]||m),s=e[T]),s.replace(r,m=>u[m])) ``` Takes base units and equations as arrays of strings. ``` f= (U,E,T)=>(u={},U.map(x=>u[x[0]]=x.slice(3,-1)),e={},E.map(x=>e[x[0]]=x.slice(4)).map(_=>s=s.replace(r=/[A-z]/g,m=>e[m]||m),s=e[T]),s.replace(r,m=>u[m])) console.log( f( ['d [m]', 'm [kg]', 't [s]'], ['v = d/t', 'a = v/t', 'F = m*a', 'E = F*d'], 'E' ) ) console.log( f( ['G [cd]', 'L [m]', 'y [A]', 'a [K]'], ['T = y*y/L', 'A = T*G'], 'A' ) ) ``` ## Explanation ``` // Base Units, Equations, Target (U,E,T)=>( // Map variable names to SI units u={}, U.map(x=>u[x[0]]=x.slice(3,-1)), // x[0] is the variable name, // x.slice(3,-1) is the unit // Map variable names to equations e={}, E.map(x=>e[x[0]]=x.slice(4)) // x[0] is the variable name, // x.slice(4) is the unit // (Initialize return string to the target variable's equation // using the (useless) second argument to .map() below) // s=e[T] // For as many times as there are equations (chained from above), .map(_=> // Substitute each variable with its equivalent expression // if there is one. s=s.replace( r=/[A-z]/g, // Save this regex for final step. m=>e[m]||m ), // The working string variable is initialized here. s=e[T] ), // Substitute remaining variables with SI units and return. s.replace(r,m=>u[m]) ) ``` ]
[Question] [ # Today, we'll be generating a map for a roguelike RPG! ## Example Map: ``` ########## #### F# #### ## ## C#C# # ## # # C #E # #### # # # # #P # ########## ``` `#` are walls, `P` is the player's starting location, `F` is the finish that must be reached, `C` are coins that can be collected, and `E` are enemies that can be fought. ## Map specifications: * Height and Width should both be between 10 and 39, inclusive. Height does not have to equal width. * The maps borders should be filled in with walls. * `P` should be placed in the bottom left corner. * `F` should be placed in the top right corner. * There should be between 1 and 3 enemies. * There should be between 2 and 4 coins. * There should be some amount of walls in the middle. There should be a path to get from `P` to Every `C`, `E`, and `F`, keeping in mind that the player cannot move diagonally. * Every possible combination should have some chance of occurring. ## Rules * Fewest byte program wins. * Your program should not take any input. * Your program may not exit with an error (non-fatal output is `STDERR` is ok, but we can't have our rogue-like crash after map generation!) * A single trailing newline is allowed and trailing space is allowed. * No other output is allowed. [Answer] ## Perl, 293 bytes *-9 bytes thanks to @Dom Hastings* ``` {$==7+rand 30;@r=$"=();@a=((C)x4,(E)x3,("#")x1369,(" ")x1369);for$i(0..7+rand 30){$r[$i][$_]=splice@a,rand@a,1for 0..$=}$r[0][$=]=F;$r[-1][0]=P;$_=$r=join$/,$v="#"x($=+=3),(map"#@$_#",@r),$v;1while$r=~s/F(.{$=})?[^#F]/F$1F/s||$r=~s/[^#F](.{$=})?F/F$1F/s;$r!~/[CEP]/&&/C.*C/s&&/E/?last:redo}say ``` Add `-E` flag to run it: ``` perl -E '{$==7+rand 30;@r=$"=();@a=((C)x4,(E)x3,("#")x1369,(" ")x1369);for$i(0..7+rand 30){$r[$i][$_]=splice@a,rand@a,1for 0..$=}$r[0][$=]=F;$r[-1][0]=P;$_=$r=join$/,$v="#"x($=+=3),(map"#@$_#",@r),$v;1while$r=~s/F(.{$=})?[^#F]/F$1F/s||$r=~s/[^#F](.{$=})?F/F$1F/s;$r!~/[CEP]/&&/C.*C/s&&/E/?last:redo}say' ``` However, it takes a long time to run, so I recommend using this version instead: ``` perl -E '{${$_}=8+rand 30for"=","%";@r=$"=();@a=((C)x4,(E)x3,("#")x($v=rand $=*$%),(" ")x($=*$%-$v));for$i(0..$%-1){$r[$i][$_]=splice@a,rand@a,1for 0..$=-1}$r[0][$=-1]=F;$r[$%-1][0]=P;$_=$r=join$/,$v="#"x($=+=2),(map"#@$_#",@r),$v;1while$r=~s/F(.{$=})?[^#F]/F$1F/s||$r=~s/[^#F](.{$=})?F/F$1F/s;$r!~/[CEP]/&&/C.*C/s&&/E/?last:redo}say' ``` [Try it online!](https://tio.run/##NY5BT4NAEIX/Ci7TdrelLFgPxs2kJATOvRMkq8UUg4Xsmoqh9K/jgHra2e@9N/NetD2NY1ua2tkmzqqHHooBHzdGn4/OLnhrDEPmsQVTkUFgyIWKNHIei@7B44nodh5nLhMdhwvOIcA1LARRZ6bTbwsXIRTtgooHvk8gFD2YDKo8gyJH29bVaxlpb1pAT0hWZzLiNhzIF5CNxhxTNaUonhPDg4ICweB7U51BelSAmkwnN3hPBT50y9wICpd5kREkq/DrVNUlJW5WptzvAQexz57dNJcphKm01@uvOLN/Q/on0u27m8zi5JDL5VLG/jqWloZE7mttP59MeWwGq79X4/gD "Bash – Try It Online") **Explanation** ``` { # enter a block (which is used as a loop) {$==7+rand 30; # randomly select the width of the map -2 # (-2 because we don't include the borders yet) @r=$"=(); # reset @r, and set $" to undef @a=( # create a list of the character that can be on the board (C)x4, # 4 coins 'C' (E)x3, # 3 enemies 'E' ("#")x1369, # 37*37 '#' (" ")x1369); # 37*37 spaces for$i(0..7+rand 30) # create the 2D map (7+rand 30 is the height, which is generated just now) for$_(0..$=-1){ $r[$i][$_]= # index [$i][$_] receives ... splice@a,rand@a,1 # .. a random character from the list previously generated # (the character is then removed from the list thanks to 'splice') } } $r[0][$=]=F; # add the finish cell $r[-1][0]=P; # add the start cell $_=$r= # here we generate a string representation of the map join$/, # join the following elements with newlines $v="#"x($=+=3), # a first line of # only (map"#@$_#",@r), # add a # to the beginning and the end of each line $v; # the last line of # 1while # the following regex will replace every accessible cell with a F $r=~s/F(.{$=})?[^#F]/F$1F/s # a cell on the right or the bottom of a F cell is replaced || # or $r=~s/[^#F](.{$=})?F/F$1F/s; # a cell on the left or the top of a F cell is replaced $r!~/[CEP]/ # if there is no C, E or P on the map (meaning they were all accessible) && /C.*C/s # and there are at least 2 coins && /E/ ? # and 1 enemy last: # the the map is valid, we exit the loop redo # else, start over } say # and print the board ``` It takes a long time to run, because the list from which we randomly pick the characters to put on the board (`@a`) contains 1369 whitespaces and `#`, and only 4 coins and 3 enemies. So if the size of the width and height are small, there are a lot of spaces and `#` compared to the coin and the enemies, so it's quite likely that a random map won't be valid. That's why the "optimized" version is faster: the list from which we pick the characters is just a little bigger than the map (the list is `@a=((C)x4,(E)x3,("#")x($v=rand $=*$%),($")x($=*$%-$v))` : a random number `$v` of `#` (inferior to the size of the map), and `size of the map - $v` whitespaces). [Answer] # PHP, ~~422~~ ~~417~~ ~~415~~ ~~309~~ ~~373~~ ~~369~~ ~~364~~ 361 bytes ``` function w($p){global$r,$h,$w;for($q=$p;$r[$q]<A;)for($r[$p=$q]=" ";($q=$p+(1-(2&$m=rand()))*($m&1?:$w))%$w%($w-1)<1|$q/$w%$h<1;);}$r=str_pad("",($w=rand(10,39))*$h=rand(10,39),"#");$r[$w*2-2]=F;w($p=$q=$w*(--$h-1)+1);$r[$p]=P;for($c=rand(2,4);$i<$c+rand(1,3);$p=rand($w,$h*$w))if($r[$p]<A&&$p%$w%($w-1)){w($p);$r[$p]=EC[$i++<$c];w($p);}echo chunk_split($r,$w); ``` operates on a string without linebreaks; digs random paths between the extras. Run with `-r`. **Note:** The paths are created by walking in random directions. The choice of direction for every step will mostly generate maps that are wide open; and the example map is very unlikely to appear; but it *is* possible. **breakdown** ``` // aux function: randomly walk away from $p placing spaces, stop when a special is reached function w($p) {global$r,$h,$w; for($q=$p; $r[$q]<A; // while $q is not special ) for($r[$p=$q]=" "; // 3. replace with space ($q=$p+(1-(2&$m=rand()))*($m&1?:$w)) // 1. pick random $q next to $p %$w%($w-1)<1|$q/$w%$h<1; // 2. that is not on the borders ); } // initialize map $r=str_pad("", ($w=rand(10,39))*$h=rand(10,39) // random width and height ,"#"); // fill with "#" $r[$w*2-2]=F; // place Finish w($p=$q=$w*(--$h-1)+1); // build path from Player position to F // $h is now height -1 ! $r[$p]=P; // place Player // place Coins ans Enemies for($c=rand(2,4);$i<$c+rand(1,3); // while $i has not reached no. of coins+no. of enemies $p=rand($w,$h*$w)) // pick a random position if($r[$p]<A&&$p%$w%($w-1)) // that is neither special nor out of bounds { w($p); // build path from there to another special $r[$p]=EC[$i++<$c]; // place this special w($p); // additional path to allow special in the middle of a dead end tunnel } // insert linebreaks and print echo chunk_split($r,$w); ``` [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 730 bytes ``` var R=new Random();for(;;){char P='P',C='C',E='E',Q='#';int w=R.Next(8,37),h=R.Next(8,37),H=h,t,g=99,W,i,j,r;string l,s,p=new string(Q,w+2);var m=new List<string>();for(;H>0;H--){l="";for(W=w;W>0;W--){r=R.Next(999);l+=r<3?C:r<6?E:r<g?Q:' ';}m.Add(l);}m[0]=m[0].Substring(0,w-1)+'F';m[h-1]=P+m[h-1].Substring(1);s=String.Join("#\n#",m);t=s.Split(E).Length-1;if(t<1||t>3)continue;t=s.Split(C).Length-1;if(t<2||t>4)continue;while(g>0){g--;for(i=0;i<h;i++)for(j=0;j<w;j++)if(m[i][j]!=Q&&m[i][j]!=P&&(i>0&&m[i-1][j]==P)||(i<h-1&&m[i+1][j]==P)||(j>0&&m[i][j-1]==P)||(j<w-1&&m[i][j+1]==P))m[i]=m[i].Substring(0,j)+P+m[i].Substring(j+1,w-j-1);}if(String.Join("",m).Split(E,C,'F').Length>1)continue;Console.Write(p+"\n#"+s+"#\n"+p);break;} ``` [Try it online!](https://tio.run/##XZHBjtowEIZfhQYJ27ITJUvVNutMUBVRoWpVBTjkQDmwkE2cJg5KvE0l2GendoAu9DKa@fx7PP5n29rbVpxOvzfNYAEy7QaLjdzVFSb8pW4w5@SwzfVZDChGLAIUITYFNEVsDmiIuJBq0MHC@ZH@UfgLG38mLL8vZ5AzxTLwfZYwwQrW8FY1QmaDkrVs3795BnjOOvpAuJml6vmTaFVwPgyvE81Cl89smxxKsKweJdDxRNPE0Ob6uu/7hJcUmmA8iR6b4NNkqmM2mT@iAeJvlfN1t8Ml0dnKXYMJzvL1@TKJyzrbIxR9Q7xa5ba3hpiekxuRR3gLyz53vtdCYmv4Uw4tVhGuoHWW@1IoPCXOUyozpe9y8YJV4B2PKhyTbS2VkK/pjTT6X/pgpB/fpV0uyhRnoUsOmW33fxfgchHkXFBKTF3ougg6Xuha96hWYr0q1h9gPhr9y@PRCIvQ7Yn@kWYAMTkesW5kez2mt7i4aDUyTlxg0F20GtMzJqYCE@6sLAg17t1RfUVbrPvpBeg571w0Dl7dYxHTS7gaE3rvZkS1bOsydZJGqBTvqWW8py01S7DonvDnJt384m@n018 "C# (Visual C# Interactive Compiler) – Try It Online") Ungolfed: ``` var R = new Random(); for (;;) { char P = 'P', C = 'C', E = 'E', poundSymbol = '#'; int width = R.Next(8, 37), height = R.Next(8, 37), HeightTemp = height, testVariable, goThroughLoop = 99, WidthTemp, i, j, rand; string line, strMap, poundSymbolPadding = new string(poundSymbol, width + 2); var map = new List<string>(); //initialize map for (; HeightTemp > 0; HeightTemp--) { line = ""; for (WidthTemp = width; WidthTemp > 0; WidthTemp--) { rand = R.Next(999); //add a character randomly. Re-use the goThroughLoop variable here, which gives approx. 1 wall per 10 spaces. line += rand < 3 ? C : rand < 6 ? E : rand < goThroughLoop ? poundSymbol : ' '; } map.Add(line); } //add finish and player map[0] = map[0].Substring(0, width - 1) + 'F'; map[height - 1] = P + map[height - 1].Substring(1); strMap = String.Join("#\n#", map); //check proper # of enemies, regenerate if invalid testVariable = strMap.Split(E).Length - 1; if (testVariable < 1 || testVariable > 3) continue; //check proper # of coins, regenerate if invalid testVariable = strMap.Split(C).Length - 1; if (testVariable < 2 || testVariable > 4) continue; //map out areas Player can access. Iterates until all accessible places have been marked as such. while (goThroughLoop > 0) { goThroughLoop--; for (i = 0; i < height; i++) for (j = 0; j < width; j++) if (map[i][j] != poundSymbol && map[i][j] != P && ((i > 0 && map[i - 1][j] == P) || (i < height - 1 && map[i + 1][j] == P) || (j > 0 && map[i][j - 1] == P) || (j < width - 1 && map[i][j + 1] == P))) //mark this space as accessible map[i] = map[i].Substring(0, j) + P + map[i].Substring(j + 1, width - j - 1); } //if player cannot access all features (defeated enmies, collected coins, arrived at finish), regenerate map. if (String.Join("", map).Split(E, C, 'F').Length > 1) continue; //output our final map Console.Write(poundSymbolPadding + "\n#" + strMap + "#\n" + poundSymbolPadding); break; } ``` Edit: saved 8 bytes, made it slightly less efficient by locking the player accessible test loop to 99 iterations. I know it'll never really compete with the other answers here, but I'm having fun! ]
[Question] [ The objective is to produce output of n squares (nxn) of random integers (`0-9`) with a moving `*` that rotates clockwise around the corners, starting from the top left. The squares should be side by side and separated by a single space. If `n = 0`, the output should be empty. Output for `n=1`: `*` Output for `n=2`: ``` *3 4* 14 07 ``` Output for `n=3`: ``` *34 82* 291 453 224 924 145 158 57* ``` Output for `n=4`: ``` *153 135* 0154 0235 2352 5604 3602 2065 2245 6895 3561 7105 7225 5785 479* *662 ``` Notice how, for each square, the `*` rotates around the corners of the square, from left to right, beginning in the top left corner of the first, then moving to the top right of the second, and so on. [![enter image description here](https://i.stack.imgur.com/R7V3o.png)](https://i.stack.imgur.com/R7V3o.png) The shortest answer (measured in bytes) wins. [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), ~~50~~ 49 bytes ``` 3mF9Ý.R}J¹ô¹ävy`¦'*ìN4%©>ir}®iRr}®<iR})ˆ}¯øvyðý}» ``` **Explanation** Examples for input = 4. First we create a string of input^3 random numbers between 0 and 9. ``` 3mF9Ý.R}J ``` producing ``` 6799762549425893341317984133999075245812305412010122884262903656 ``` Then we split that into pieces each the size of the input. That is further split into input pieces. ``` ¹ô¹ä ``` This gives us a matrix of numbers. ``` [['6799', '7625', '4942', '5893'], ['3413', '1798', '4133', '9990'], ['7524', '5812', '3054', '1201'], ['0122', '8842', '6290', '3656']] ``` We then loop over the rows of the matrix, inserting asterisks in the right places. ``` v } # for each row in matrix y` # flatten list to stack ¦'*ì # replace the first digit of the last number with "*" N4%©>ir} # if row-nr % 4 == 0, move the number with "*" to the front ®iRr} # if row-nr % 4 == 1, move the number with "*" to the front # and reverse the number, moving "*" to the numbers right side ®<iR} # if row-nr % 4 == 2, reverse the number, moving "*" # to the numbers right side )ˆ # wrap row in a list and add to global array ``` Now we have the matrix with a "\*" on each row, but we want an asterisk per column. ``` [['*893', '4942', '7625', '6799'], ['099*', '4133', '1798', '3413'], ['7524', '5812', '3054', '102*'], ['0122', '8842', '6290', '*656']] ``` So we zip this list turning rows into columns and vice versa. ``` [['*893', '099*', '7524', '0122'], ['4942', '4133', '5812', '8842'], ['7625', '1798', '3054', '6290'], ['6799', '3413', '102*', '*656']] ``` All that's left now is to format the output. ``` vyðý}» ``` Joining the rows on spaces and the columns on newlines gives us the final result. ``` *893 099* 7524 0122 4942 4133 5812 8842 7625 1798 3054 6290 6799 3413 102* *656 ``` [Try it online!](http://05ab1e.tryitonline.net/#code=M21GOcOdLlJ9SsK5w7TCucOkdnlgwqYnKsOsTjQlwqk-aXJ9wq5pUnJ9wq48aVJ9KcuGfcKvw7h2ecOww719wrs&input=Ng) **Old 50 byte solution** ``` F¹Fõ¹F9Ý.R«}}¦'*ì})¹ävyN4%©>iR}®iíÁ}®<ií}})øvyðý}» ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 47 bytes ``` {⍉⎕FMT'*'@((⍳⍵),¨⍵⍴2⍴¨1(⍵1)⍵(1⍵))⊢⎕D[?10⍴⍨3⍴⍵]} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///v/pRb@ejvqluviHqWuoOGhqPejc/6t2qqXNoBZB61LvFCIgPrTAEim811AQSGoYgac1HXYuAulyi7Q0NgAoe9a4wBlNbY2v/pz1qm/Cot@9RV/Oj3jUg3euNH7VNBKoODnIGkiEensH/0xQMudIUjIDYGIhNgNgUAA "APL (Dyalog Unicode) – Try It Online") Anonymous prefix lambda. `{`…`}` "dfn"; n is called `⍵`  `⎕D[`…`]` index the list of digits with the indices:   `3⍴⍵` cyclically **r**eshape n into a list of length 3   `10⍴⍨` cyclically **r**eshape the number 10 into an array of those dimensions (3×n×n)   `?` random index (1…10) for each  `⊢` yield that as argument to the upcoming function (separates indices from data)  `'*'@(`…`)` place asterisks **at** the following locations:   `1(⍵1)⍵(1⍵)` the list `[1,[n,1],n,[1,n]]`   `2⍴¨` cyclically reshape each into a list of length 2: `[[1,1],[n,1],[n,n],[1,n]]`   `⍵⍴` cyclically reshape that list into length n   `(`…`),¨` prepend an element to each, taking elements from this list:    `⍳⍵` indices 1…n  `⎕FMT` ForMaT as character matrix (joins layers with a line of spaces)  `⍉` transpose [Answer] # Java 10, ~~370~~ ... ~~243~~ 242 bytes ``` n->{int j=n*n,k,m=1;var a=new String[j];var r="";for(m*=Math.pow(10,n-1);j-->0;a[j]=(k*=Math.random())+m+r)k=9*m;for(;++j<n;m=k<2?0:n*n-n,a[m+j]=a[m+j].replaceAll(k%3<1?"^.":".$","*"))k=j%4;for(j=0;j<n*n;r+=j%n<1?"\n":" ")r+=a[j++];return r;} ``` Returns the result-String with trailing newline. -51 bytes thanks to *@ceilingcat*. [Try it online.](https://tio.run/##fZFNT8MwDIbv/AorYlLTtFUHCIml2cSRw8aB4xhS6Drol1ul6SY09bcX9@MKl1ixn7yOX2f6rP3smPdxoZsGtjrF6w1AijYxJx0nsBuuAG/WpPgFsUMVQC4p2d3Q0Vht0xh2gKB69NfXoZ4pdNHLvVINON9q@x3U1cVZhh76Sy7P2oBWmFxm2X12GHNGMSZPlXFk5vvrUGoqKCd31ahgNB6r0uFclMLwXD255QQLkUUoS5VHd5twRa199PS@FPR4CoFJ6oKGeS4KJ1/cR8sN@wjYigW3zGMu4ySWLR5GsUyFktRclEZQEgf2HYkFxilDPxLiIE1iW4NgZNfLwYW6/SzIhdmMc5UeoSQnnXm8A2g@2UgtYLQwBQWhpBApeKQoBIcJIa9/GpuUQdXaoKb3tkCHvWDd2hUwkY7e/4W9tnbi/qMwoDXymejGTXb9Lw) **Explanation:** ``` n->{ // Method with integer parameter & String return-type int j=n*n,k, // Index-integers m=1; // Temp-integer var a=new String[j]; // Create a String-matrix of size n by n var r=""; // Result-String, starting empty for(m*=Math.pow(10,n-1); // Start the temp-integer `m` at 10 to the power the // input minus 1 j-->0 // Loop `j` in the range [0,n²): ; // After every iteration: a[j]= // Set the j'th cell to: (k*=Math.random()) // A random integer in the range [0,k) +m // Add `m` +r; // And then convert it to a String k=9*m; // Set `k` to 9 multiplied by `m`, so the random // integer will be in the range [0,9*m) for(;++j<n; // Loop `j` in the range (-1,n): ; // After every iteration: m=k<2? // If `k` is 0 or 1: 0 // Set `m` to 0 (first row) : // Else: n*n-n, // Set `m` to n²-n instead (last row) a[m+j]=a[m+j].replaceAll( // Then replace a digit in the (m*j)'th cell: k%3<1? // If `k` is 0 or 3 (first column): "^." // Replace its first digit : // Else (last column instead): ".$", // Replace its last digit "*")) // And replace this digit with a "*" k=j%4; // Set `k` to `j` modulo-4 for(j=0;j<n*n; // Loop `j` in the range [0,n²) again: ; // After every iteration: r+=j%n<1? // If `j` is divisible by `n`: "\n" // Append a newline to the result : // Else: " "; // Append a space to the result instead r+=a[j++]; // Append the j'th value to the result return r;} // Return the result-String ``` [Answer] # PHP ,181 Bytes ``` for($i=-1;++$i<$c=($n=$argv[1])**3;){echo!($i%$q=$n*$n)?"\n":((!$m=$i%$n)?" ":"");echo(!$m&!($b=$i%$q/$n&3)|$m==$n-1&$b==1)&$i<$q|($m==$n-1&$b==2|!$m&$b==3)&$i>$c-$q?"*":rand(0,9);} ``` [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-R`](https://codegolf.meta.stackexchange.com/a/14339/), ~~20~~ 19 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) I could save a byte by either filling each square with the same random digit but ``` ƲÆAöìh* òU zXÃÕm¸ ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVI&code=xrLGQfbDrGgqIPJVIHpYw9VtuA&input=OA) ## 18 bytes By using the same random digit to fill each square. Dunno if that'd fit the definition of "pseudo-random" for this challenge, though. ``` ƲçAö)h* òU zXÃÕm¸ ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVI&code=xrLnQfYpaCog8lUgeljD1W24&input=OA) ``` ƲÆAöìh* òU zXÃÕm¸ :Implicit input of integer U Æ :Map each X in the range [0,U) ² : U squared Æ : Map the range [0,U²) A : 10 ö : Random number in the range [0,A) à : End map ¬ : Join h* : Replace 1st char with "*" (Handles the edge case of U=1 by instead inserting the "*" into the empty string) òU : Partitions of length U zX : Rotate 90 degrees clockwise X times à :End map Õ :Transpose m :Map ¸ : Join with spaces :Implicit output, joined with newlines ``` ``` ƲçAö)h* òU zXÃÕm¸ :Implicit input of integer U Ʋ :As above ç : Repeat to length U² Aö : As above ) : End repeat h* òU zXÃÕm¸ :As above :Implicit output, joined with newlines ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 27 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` иLdć'*0ǝšIGDøí})øJ»εDižhΩ]J ``` [Try it online](https://tio.run/##ATEAzv9vc2FiaWX//9C4TGTEhycqMMedxaFJR0TDuMOtfSnDuErCu861RGnFvmjOqV1K//81) or [verify multiple dimensions](https://tio.run/##yy9OTMpM/W92bJKSZ15BaYmVgpK9nw6Xkn9pCYSn4@ei9P/CDp@UI@3qWgbH5x5d6OfucnjH4bW1mod3eB3afW6rS@bRfRnnVsZ6/VfSC9M5tM3@PwA). **Explanation:** Step 1: Create a matrix of the input by input amount of `1`s, with the top-left value replaced with a `"*"`: ``` и # Repeat the (implicit) input the (implicit) input amount of times as list # (e.g. 5 → [5,5,5,5,5]) L # Convert each inner integer to a list in the range [1,input] d # Convert each inner integer to a 1 (with a >=0 check) ć # Extract head; pop and push remainder-list and first item separated '*0ǝ '# Replace the first item in this list with a "*" š # Prepend this list back to the matrix ``` [Try just step 1 online.](https://tio.run/##yy9OTMpM/f//wg6flCPt6loGx@ceXfj/vykA) Step 2: Rotate it the input-1 amount of times clockwise and keep each intermediate matrix in a list: ``` IG # Loop the input-1 amount of times: D # Duplicate the current matrix øí # Rotate it once clockwise: ø # Zip/transpose; swapping rows/columns í # Reverse each inner row }) # After the loop: wrap all matrices on the stack into a list ``` [Try just the first 2 steps online.](https://tio.run/##ASEA3v9vc2FiaWX//9C4TGTEhycqMMedxaFJR0TDuMOtfSn//zU) Step 3: Format these lists of loose matrices to the output-format by putting them next to each other with space delimiter: ``` ø # Zip/transpose; swapping rows/columns J # Join each inner-most list together to a string » # Join each inner lists by spaces, and then these lines by newlines ``` [Try just the first 3 steps online.](https://tio.run/##ASYA2f9vc2FiaWX//9C4TGTEhycqMMedxaFJR0TDuMOtfSnDuErCu///NQ) Step 4: Replace every 1 with a random digit, and output the final result: ``` ε # Map over each character in the multi-line string: D # Duplicate the current character i # Pop, and if it's a 1: žh # Push constant "0123456789" Ω # Pop and push a random digit from this ] # Close both the if-statement and map J # Join this list of characters back to a string again ``` ]
[Question] [ It's weekend and what are the cool guys doing on weekends? Drinking of course! But you know what's not so cool? Drinking **and** driving. So you decide to write a program that tells you how loaded you are and when you are gonna be able to drive again without getting pulled over by the cops and loosing your license. # The Challenge Given a list of beverages you enjoyed this evening, calculate your blood alcohol level and the time you have to wait till you can hop into your car and get home. # Input Input will be a list of drinks you had this night. This will look like this: ``` 4 shots booze 1 glasses wine 2 bottles beer 3 glasses water ``` *Containers will always be plural.* As you can see each entry consists of: * The type of drink (booze, wine, beer, water) * The container for the drink (shots, glasses, bottles) * The amount x of the drinks you had of that type as integer with x > 0, Each drink type adds a certain amount of alcohol to your blood: ``` booze -> 0.5 ‰ / 100 ml beer -> 0.1 ‰ / 100 ml wine -> 0.2 ‰ / 100 ml water -> -0.1 ‰ / 100 ml ``` Water is the exception here, since it thins your blood out and lowers your alcohol level (would be so nice if that actually worked...). Each container has a certain volume: ``` shots -> 20 ml glasses -> 200 ml bottles -> 500 ml ``` # Output You have to output two numbers: * The alcohol level in ‰ * The time in hours you have to wait until you reached 0.5 ‰ or less, so you can drive again. You loose 0.1 ‰ per hour. **Notes** * The alcohol level can never fall below zero. * Same goes for the waiting time. If you have 0.5 ‰ or less, output zero. * The order of drinks does not matter, so drinking water may lower the alcohol level below zero in the process of the calculation. If it remains there, you need to replace it with zero. The alcohol level for the the example above would be calculated like this: ``` 4 shots booze -> 0.4 ‰ 1 glasses wine -> 0.4 ‰ 2 bottles beer -> 1.0 ‰ 3 glasses water -> -0.6 ‰ => 0.4 + 0.4 + 1 - 0.6 = 1.2 ‰ ``` To reach 0.5 ‰ you need to loose 0.7 ‰. You loose 0.1 ‰ per hour, so you need to wait 7 hours to drive again. # Rules * You can take the input in any format you want, but you have to use the exact strings as given above. You may take the numbers as integers. * You can output the two numbers in any order, just make in clear which one you use in your answer. * You may assume that the input will always have at least one entry. * Function or full program allowed. * [Default rules](http://meta.codegolf.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) for input/output. * [Standard loopholes](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so lowest byte-count wins. Tiebreaker is earlier submission. # Test cases Input as list of strings. Outputs alcohol level first, values seperated by a comma. ``` ["4 shots booze","1 glasses wine","2 bottles beer","3 glasses water"] -> 1.2, 7 ["10 shots booze", "1 bottle water"] -> 0.5, 0 ["3 glasses wine", "2 bottles booze"] -> 6.2, 57 ["6 shots beer", "3 glasses water"] -> 0, 0 ["10 glasses beer"] -> 2.0, 15 ``` **Happy Coding!** [Answer] ## TSQL, ~~301~~, ~~299~~, ~~219~~, 206 Bytes Input goes into temp table `#I` (you said any format :) ``` SELECT * INTO #I FROM ( VALUES (4,'shots','booze') ,(1,'glasses','wine') ,(2,'bottles','beer') ,(3, 'glasses','water') ) A (Q, V, N) ``` Code: ``` SELECT IIF(L<0,0,L),IIF(10*L-.5<0,0,10*L-.5)FROM(SELECT SUM(Q*S*P)L FROM(VALUES('bo%',.5),('be%',.1),('wi%',.2),('wa%',-.1))A(W,S),(VALUES('s%',.2),('g%',2),('b%',5))B(X,P),#I WHERE N LIKE W AND V LIKE X)A; ``` Thanks for the ideas to improve it, Micky T :) [Answer] # JavaScript (ES6), 131 ``` a=>a.map(s=>([a,b,c]=s.split` `,t+=a*[50,20,2]['bgs'.search(b[0])]*~-'0236'['aeio'.search(c[1])]),t=0)&&[t>0?t/100:0,t>50?t/10-5:0] ``` **Less golfed** ``` a=>( t=0, a.map(s=>( [a,b,c] = s.split` `, t += a * [50,20,2]['bgs'.search(b[0])] // char 0 is unique * [-1,1,2,5]['aeio'.search(c[1])] // char 1 is unique // golfed: add 1 to get a string of dingle digits, the sub 1 using ~- ) ), [ t>0 ? t/100 : 0, t>50 ? t/10-5 : 0] ) ``` [Answer] # Javascript (ES6), 111 Takes input as arrays of arrays of strings/integers e.g. ``` [[4, "shots", "booze"], [1, "glasses", "wine"], [2, "bottles", "beer"], [3, "glasses", "water"]] ``` **Outputs to simple array** e.g. `[1.2, 7]` ``` a=>(b=0,c={s:2,g:20,b:50,o:2,e:10,i:5,a:-10},a.map(([d,e,f])=>b+=d*c[e[0]]/c[f[1]]),g=b>0?b:0,[g/10,g>5?g-5:0]) ``` #Explained ``` a => ( b = 0, // Counter For Alcohol Level c = {s:2, g:20, b:50, o:2, e:10, i:5, a:-10}, // Look up for values a.map( // Loops over array ([d, e, f]) => // Sets d,e,f to respective array indexes b += d * c[e[0]] / c[f[1]] // Increases Level by values from lookup ), g = b > 0 ? b : 0, // If Level is lower than 0 make it = 0 [g / 10, g > 5 ? g - 5 : 0]) // Output: Level / 10 and Level - 5 bound to 0 ``` [Answer] # Perl, ~~133~~ 119 + 3 = ~~136~~ 122 bytes ``` %u=(o,.5,e,.1,i,.2,a,-.1,g,2,b,5,s=>.2);/(\d+) (.).* .(.)/;$x+=$1*$u{$2}*$u{$3}}{$_=($x>0?$x:0).$".($x-.5>0?$x-.5:0)*10 ``` To be run with `perl -p`. Takes line-oriented input on STDIN, produces output on STDOUT. Less-golfed version: ``` # char->number conversion table # declared using barewords except for 's', which can't be a bareword # because it's a keyword %u=(o,.5, e,.1, i,.2, a,-.1, g,2, b,5, s=>.2); # extract the number, first letter of first word, second letter of # second word /(\d+) (.).* .(.)/; # do unit conversion and multiply up all factors $x += $1 * $u{$2} * $u{$3} # hack for -p to produce an END { ... print } block }{ # format output $_ = ($x > 0 ? $x : 0) . $" . ($x-.5 > 0 ? $x-.5 : 0)*10 ``` Thanks to [dev-null](https://codegolf.stackexchange.com/users/48657/dev-null) for suggestions saving 11 bytes. [Answer] # [C (GCC)](https://gcc.gnu.org), ~~176~~ 166 bytes *-10 bytes thanks to [@ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)* ``` float x;main(a){for(char b[9],c[9];~scanf("%d%s%s\n",&a,b,c);)x+=a*(*b-98?*b-103?.02:.2:.5)*(*c-98?c[1]-97?2:-1:c[1]-111?1:5);printf("%f %f",x>0?x:0,fmax(0,x*10-5));} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=RY7RSsMwGIXv9xShUElqMpJuZWuC5sLHqEWS2GyFtpEmYlD0RbzZzfSZ9jZmThB-DvzfORzO59E87Iz5bjIyjFl7OD4HS7anLzs4FUAUo-onqNCbdTM0ezUD3dQtNknEhzdqsjDLH3Of-_spw1cKa2yQQPH6RhWw0KTeyqSMruSSlnyZrkLJMGfDNKwl9UaWnDD--zDGJOMVEk9zP4VztQW5zXC8pTJyiu2oIqQ4FoySCiHxfln7N_pwulsDv3fBA-3cawcAWDCwG5T3nQcv_ZTIokxeCEMCuuvmBFb_CRUSuXT9AA) ]