text
stringlengths
180
608k
[Question] [ [Gematria](https://en.wikipedia.org/wiki/Gematria) is an ancient Jewish method to determine a numeric value of a letter sequence, using a fixed value for each letter. Gematria is originally applied to Hebrew letters, but for the context of this challenge, we'll use Latin script instead. There are many ways to implement Gematria in Latin script, but let's define it as a close as it can be to the original standard encoding. The numbering goes as such: A = 1, B = 2, C = 3, D = 4, E = 5, F = 6, G = 7, H = 8, I = 9, J = 10, K = 20, L = 30, M = 40, N = 50, O = 60, P = 70, Q = 80, R = 90, S = 100, T = 200, U = 300, V = 400, W = 500, X = 600, Y = 700, Z = 800. **Your job is to calculate the Gematria value for each character of a string, sum the result and print it or return it.** **Rules** * Lowercase and uppercase letters yield the same value. Anything else equals 0. You can assume the input encoding will always be ASCII. * You can input the file in whatever method you see fit, be it loading it from a file, piping it in the terminal or baking it into the source code. * You can use any method you see fit in order to make this go fast, except const evaluation of the input's value and baking *that* into the binary or a similar method. That would be way too easy. The calculation must happen locally on runtime. And here's a naïve implementation in Rust to provide an example implementation: ``` #![feature(exclusive_range_pattern)] fn char_to_number(mut letter: char) -> u32 { // map to lowercase as casing doesn't matter in Gematria letter = letter.to_ascii_lowercase(); // get numerical value relative to 'a', mod 9 and plus 1 because a = 1, not 0. // overflow doesn't matter here because all valid ranges ahead have valid values let num_value = ((letter as u32).overflowing_sub('a' as u32).0) % 9 + 1; // map according to the Gematria skip rule match letter.to_ascii_lowercase() { 'a'..'j' => num_value, // simply its value: 1, 2, 3... 'j'..'s' => num_value * 10, // in jumps of 10: 10, 20, 30... 's'..='z' => num_value * 100, // in jumps of 100: 100, 200, 300... _ => 0 // anything else has no value } } fn gematria(word: &str) -> u64 { word .chars() .map(char_to_number) .map(|it| it as u64) // convert to a bigger type before summing .sum() } ``` In order to measure speed, each implementation will be fed the exact same file: a random 100MB text file from Github: <https://github.com/awhipp/100mb-daily-random-text/releases/tag/v20221005> The speed of my implementation, measured with Measure-Command, completes in ~573ms and yields the number `9140634224`. I compiled using -O 3 and baked the input text into the source code, and then ran the code on an Intel i5-10400 CPU. [Answer] # Rust, ≈ 10 ms Compile with `cargo build --release`, run with `target/release/gematria random-20221005.txt`. **`Cargo.toml`** ``` [package] name = "gematria" version = "0.1.0" edition = "2021" [dependencies] memmap = "0.7.0" rayon = "1.5.3" ``` **`src/main.rs`** ``` use core::arch::x86_64::*; use memmap::MmapOptions; use rayon::prelude::*; use std::env::args; use std::fs::File; use std::io; fn gematria(bytes: &[u8]) -> u64 { let (prefix, vecs, suffix) = unsafe { bytes.align_to::<__m256i>() }; let (mut sum0, mut sum10, mut sum19) = vecs .par_chunks(2048) .map(|chunk| unsafe { let splat32 = _mm256_set1_epi8(32); let splat123 = _mm256_set1_epi8(123); let splat229 = _mm256_set1_epi8(-27); let splat0 = _mm256_set1_epi8(0); let splat10 = _mm256_set1_epi8(10); let splat19 = _mm256_set1_epi8(19); let mut sum0 = splat0; let mut sum10 = splat0; let mut sum19 = splat0; for &vec in chunk { let x = _mm256_subs_epu8( _mm256_sub_epi8(_mm256_or_si256(vec, splat32), splat123), splat229, ); sum0 = _mm256_add_epi64(sum0, _mm256_sad_epu8(x, splat0)); sum10 = _mm256_add_epi64(sum10, _mm256_sad_epu8(x, splat10)); sum19 = _mm256_add_epi64(sum19, _mm256_sad_epu8(x, splat19)); } ( (_mm256_extract_epi64(sum0, 0) + _mm256_extract_epi64(sum0, 1) + _mm256_extract_epi64(sum0, 2) + _mm256_extract_epi64(sum0, 3)) as u64, (_mm256_extract_epi64(sum10, 0) + _mm256_extract_epi64(sum10, 1) + _mm256_extract_epi64(sum10, 2) + _mm256_extract_epi64(sum10, 3)) as u64, (_mm256_extract_epi64(sum19, 0) + _mm256_extract_epi64(sum19, 1) + _mm256_extract_epi64(sum19, 2) + _mm256_extract_epi64(sum19, 3)) as u64, ) }) .reduce( || (0, 0, 0), |(a0, a10, a19), (b0, b10, b19)| (a0 + b0, a10 + b10, a19 + b19), ); for affix in [prefix, suffix] { for &byte in affix { let x = (byte | 32).wrapping_sub(123).saturating_sub(229); sum0 += x as u64; sum10 += x.abs_diff(10) as u64; sum19 += x.abs_diff(19) as u64; } } (101 * sum0 + 9 * sum10) / 2 + 45 * sum19 - 900 * bytes.len() as u64 } fn main() -> io::Result<()> { let [_, filename]: [String; 2] = Vec::from_iter(args()).try_into().expect("missing filename"); let file = File::open(filename)?; let mmap = unsafe { MmapOptions::new().map(&file)? }; println!("{}", gematria(&mmap[..])); Ok(()) } ``` [Answer] # [C++ (clang)](https://clang.llvm.org/), ~21 ms on my Linux machine ``` #include <array> #include <chrono> #include <fcntl.h> #include <iostream> #include <numeric> #include <thread> #include <vector> #include <unistd.h> constexpr std::array<unsigned long, 128> numbering { // ASCII NUL to @ 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // A to Z 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 200, 300, 400, 500, 600, 700, 800, // [ \ ] ^ _ ` 0, 0, 0, 0, 0, 0, // a to z 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 200, 300, 400, 500, 600, 700, 800, // all the rest up to 127 0, 0, 0, 0, 0 }; struct accumulate_block { void operator()(const char* first, const char* last, std::vector<unsigned long>::reference result) { result = 0; for (const char* str = first; str < last; ++str) result += numbering[*str]; } }; int main() { const auto start = std::chrono::high_resolution_clock::now(); auto fd = open("random-20221005.txt", O_RDONLY); posix_fadvise(fd, 0, 0, 1); constexpr std::size_t buffer_size = 4 * 1024 * 1024; constexpr unsigned long num_threads = 8; constexpr unsigned long min_per_thread = buffer_size / num_threads; std::vector<unsigned long> results(num_threads); std::vector<std::thread> threads(num_threads - 1); char buffer[buffer_size]; unsigned long count = 0; while (const std::size_t bytes_read = read(fd, buffer, buffer_size)) { const char* block_start = buffer; unsigned long const block_size = bytes_read / num_threads; for(unsigned long i = 0; i < num_threads - 1; ++i) { const char* block_end = block_start + block_size; threads[i] = std::thread(accumulate_block(), block_start, block_end, std::ref(results[i])); block_start = block_end; } accumulate_block()(block_start, buffer + bytes_read, results[num_threads - 1]); for(auto& entry: threads) { entry.join(); } count = std::accumulate(results.begin() , results.end(), count); } const auto finish = std::chrono::high_resolution_clock::now(); constexpr unsigned long expected = 9140634224L; const char* checker[] = {"\xE2\x9C\x95", "\xE2\x9C\x93"}; std::cout << "count = " << count << " " << checker[count == expected] << "\n"; const auto ms_interval = std::chrono::duration_cast<std::chrono::milliseconds>(finish - start); const std::chrono::duration<double, std::milli> ms_double = finish - start; std::cout << ms_interval.count() << " ms\n"; std::cout << ms_double.count() << " ms\n"; return 0; } ``` Outputs: ``` count = 9140634224 ✓ 21 ms 21.8556 ms ``` Compiled with clang++ \$14.0.0\$ using `-O3 -march=native -std=gnu++20` [Answer] # [C# (.NET Core 6)](https://www.microsoft.com/net/core/platform), ~60 ms on my Windows machine ``` var sw = new System.Diagnostics.Stopwatch(); sw.Start(); var data = File.ReadAllBytes("random-20221005.txt"); sw.Stop(); var readTime = sw.ElapsedMilliseconds; sw.Restart(); var list = new List<long>(); long taskCount = 16; long taskSize = data.Length / taskCount; for (long i = 0; i < taskCount; i++) list.Add(i * taskSize); long grandTotal = 0; Parallel.ForEach(list, start => { var lookup = new long[] { 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 200, 300, 400, 500, 600, 700, 800, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 200, 300, 400, 500, 600, 700, 800, 0, 0, 0, 0, 0 }; long total = 0; long end = start + taskSize; for (long i = start; i < end; i++) total += lookup[data[i]]; grandTotal += total; }); sw.Stop(); var calcTime = sw.ElapsedMilliseconds; Console.WriteLine($"read time: {readTime} ms"); Console.WriteLine($"calc time: {calcTime} ms"); Console.WriteLine($"total time: {readTime + calcTime} ms"); Console.WriteLine($"result: {grandTotal}"); ``` **Output:** ``` read time: 48 ms calc time: 12 ms total time: 60 ms result: 9140634224 ``` **Ouput without parallelization:** ``` read time: 48 ms calc time: 64 ms total time: 112 ms result: 9140634224 ``` [Answer] # [Julia 1.0](http://julialang.org/), 140 bytes ``` !x=sum(getindex.((Dict(Char.([1:255...]).=>[zeros(Int,64)...,1:9...,10:10:90...,100:100:800...,zeros(Int,165)...]),),collect(uppercase(x)))) ``` [Try it online!](https://tio.run/##RU1BCsIwELz3FW1OuxBCqlZsoF4UxKvX4iG0oUbatCQpFD8fY0VcBnZml5l5zr2W@RJCtlRuHqBTXptWLQzgrBsPp4e0DOpcbIqCMXZHVh3rl7Kjg6vxdL/DeKW5KNfFRUTJv/wjuDjwVf4t@b7ANYkibca@V7FlniZlG@kULBgnTFYb3xvIyEUN0lstCSaz06ZLb9K045C4ykbi4st0sOWY/CyOpkSkhKaZw/AG "Julia 1.0 – Try It Online") [Answer] # Python (multithreaded + numpy + numba) <30ms total windows i7-8750H windows laptop, imdisk ramdisk ``` import numpy as np from numba import jit import os from concurrent.futures import ThreadPoolExecutor @jit(nogil=True, fastmath=True) def counter(full_dict, bytearr): total = 0 for i in bytearr: total += full_dict[i] return total _ = counter(np.zeros((128,), dtype=np.int32), b'abc') #to compile def final_fast_gematria(filename, chunksize=600000, max_threads=4): maindict = {65: 1, 66: 2, 67: 3, 68: 4, 69: 5, 70: 6, 71: 7, 72: 8, 73: 9, 74: 10, \ 75: 20, 76: 30, 77: 40, 78: 50, 79: 60, 80: 70, 81: 80, 82: 90, 83: 100, \ 84: 200, 85: 300, 86: 400, 87: 500, 88: 600, 89: 700, 90: 800} full_dict = {**{i:0 for i in range(128)}, **maindict, **{key+32:val for key,val in maindict.items()}} full_dict = np.array(tuple(full_dict.values()), dtype=np.int32) threads = [] with ThreadPoolExecutor(max_workers=max_threads) as executor: with open(filename, 'rb', 0) as f: filesize = os.fstat(f.fileno()).st_size for _ in range(filesize//chunksize - 1): threads.append(executor.submit(counter, full_dict, f.read(chunksize))) return counter(full_dict, f.read()) + sum(thread.result() for thread in threads) ``` --- ``` print(final_fast_gematria("E:/random-20221005.txt")) ``` --- ``` 9140634224 ``` --- ``` %%timeit -n 2 -r 10 final_fast_gematria("E:/random-20221005.txt") ``` --- ``` 27.9 ms ± 1.11 ms per loop (mean ± std. dev. of 10 runs, 2 loops each) ``` --- ## Read time ``` def only_read(filename, chunksize=600000): with open(filename, 'rb', chunksize) as f: filesize = os.fstat(f.fileno()).st_size for _ in range(1 + filesize//chunksize): f.read(600000) ``` --- ``` %%timeit -n 1 -r 10 only_read("E:/random-20221005.txt") ``` --- ``` 22.6 ms ± 985 µs per loop (mean ± std. dev. of 10 runs, 1 loop each) ``` notebook with other variants [link](https://github.com/arrmansa/Fast-Gematria-calculator/blob/main/Fastest%20Gematria%20calculator.ipynb) ]
[Question] [ We can model a rail network as a directed graph, where each node is a train station and each edge is a train connecting two train stations. We'll assume that each train travels between its corresponding stations at a regular schedule and takes a fixed amount of time Your code should take a list of trains, where each train is a tuple `(from, to, base, interval, duration)`, where 1. `from` is an integer denoting the station the train departs from. 2. `to` is an integer denoting the station the train arrives at. 3. `base` is the integer timestamp of an arbitrary departure of the given train. 4. `interval` is a positive integer denoting how often the train departs. 5. `duration` a positive integer denoting how long the train takes. In other words, the departures are given by `base + n * interval`, and the corresponding arrivals by `base + n * interval + duration`, for integer `n`. For example, `0 2 -3 4 5` would describe a train going from station `0` to station `2`, which is at station `0` at times `..., -11, -7, -3, 1, 5, 9, 13, ...` and is at station `2` at times `..., -6, -2, 2, 6, 10, 14, 18, ...`. If you are at some station `x` want to take a train from `x` to `y`, you must wait until the train from `x` to `y` is at station `x`. Then, after another `duration` units of time, you are at station `y`. For example, if at time `0` you're at station `0` and want to use the train described above, you'd need to wait until time `1`, then at time `6` you would be at station `2`. Given these trains, your code should calculate the earliest arrival time at station `1`, given that you start at station `0` at time `0`. If no route is possible, you should return a distinguished value. ## Worked Example Suppose we are given input: ``` 0 2 -3 4 5 2 1 9 3 2 0 1 -1 7 9 ``` From this, we can see the pairs of arrival and departure times of each train are: ``` ..., (1, 6), (5, 10), (9, 14), (13, 18), (17, 22), (21, 26), (25, 30), ... ..., (0, 2), (3, 5), (6, 8), (9, 11), (12, 14), (15, 17), (18, 20), ... ..., (6, 15), (13, 22), (20, 29), (27, 36), (34, 43), (41, 50), (48, 57), ... ``` There are 2 routes from stations `0` to `1`: `0 -> 1` and `0 -> 2 -> 1`. * For the route `0 -> 1`, we can board the train at time `6` and get off at time `15`. * For the route `0 -> 2 -> 1`, we can get on train `0 -> 2` at time `1`, arrive at station `2` at time `6`, then immediately board train `2 -> 1`, arriving at station `1` at time `8`. Out of these, `0 -> 2 -> 1` is the fastest, so we output `8`. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 44 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` æʒø2£ø˜Á2ôćRJs€ËP*}ε0svy¦¦`U©%∞<®*+Dr@ÏнX+]ß ``` Outputs an empty string if no valid route can be found. What a mess.. Those arbitrary `base`-times are pretty annoying to deal with. Ah well, it works.. Will try to golf it some more later on. [Try it online](https://tio.run/##AXMAjP9vc2FiaWX//8OmypLDuDLCo8O4y5zDgTLDtMSHUkpz4oKsw4tQKn3OtTBzdnnCpsKmYFXCqSXiiJ48wq4qK0RyQMOP0L1YK13Dn///W1swLDIsLTMsNCw1XSxbMiwxLDksMywyXSxbMCwxLC0xLDcsOV1d) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaXS/8PLTk06vMPo0OLDO07POdxodHjLkfYgr@JHTWsOdwdo1Z7balBcVnlo2aFlCaGHVqo@6phnc2idlrZLkcPh/gt7I7RjD8//r6QXpvM/OjraQMdIR9dYx0THNFYn2kjHUMdSx1jHCMg2ALJ1DXXMdSxjY3UUorHwjXQMdEx1jKH6THQMDXRM0OViYwE). **Explanation:** Step 1: Get all valid routes: ``` æ # Get the powerset of the (implicit) input-list of quintuplets ʒ # Filter it by: ø # Zip/transpose; swapping rows/columns 2£ # Keep the first two inner lists ø # Zip/transpose back # (we now have a list of all [from,to]-pairs for the current potential # route) ˜ # Flatten it Á # Rotate it once towards the left 2ô # Split it back into pairs ć # Extract the head R # Reverse it J # Join it together to a string # (note: only 1 is truthy in 05AB1E, including "01") s # Swap so the remainder-list is at the top €Ë # Check for each pair whether they're equal P # Check if this is truthy for all of them * # Check if both are truthy } # Close the filter ``` [Try just the first step online.](https://tio.run/##yy9OTMpM/f//8LJTkw7vMDq0@PCO03MONxod3nKkPcir@FHTmsPdAVq1//9HRxvoGOnoGuuY6JjG6kQb6RjqWOoY6xgB2QZAtq6hjrmOZWwsAA) Step 2: Calculate the time each route takes, and leave the smallest as result: ``` ε # Map over each valid route: 0 # Start at time 0 (let's call this the `current_time`) s # Swap so the route-list is at the top of the stack vy # For-each over its quintuplets: ¦¦ # Remove the `from` and `to` from the quintuplet ` # Pop and push the remaining three values to the stack U # Pop the top one (`duration`), and store it in variable `X` © # Store the next top (`interval`) in variable `®` (without popping) % # Pop both values, and calculate base modulo interval ∞< # Push an infinite non-negative list: [0,1,2,...] ®* # Multiply each by interval `®`: [0,interval,2*interval,...] + # Add the (base modulo interval) to each D # Duplicate the infinite list r # Reverse the values on the stack @ # Check for each value in the infinite list if it's >= `current_time` Ï # Only keep the values in the infinite list at the truthy indices н # Pop and push the first/lowest X+ # Add duration `X` to it, # which is the next iteration's `current_time` ] # Close both the loop and map ß # Pop and push the minimum # (which is output implicitly as result) ``` [Answer] # JavaScript (ES6), 102 bytes Expects an array of tuples `[ from, to, base, interval, duration ]`. Returns \$+\infty\$ if there's no solution. ``` f=(a,p,t=0,m)=>p^1?Math.min(...a.map(([A,B,b,i,d])=>p^A|m>>B&1?1/0:f(a,B,t+((b-t)%i+i)%i+d,m|1<<B))):t ``` [Try it online!](https://tio.run/##NczNDoIwEATgu0@xF00bhkpRYyACgbtPQDApf1pjgUjjiXdHJPGwc/hmsk/1UWP11oN1u75u5rmNmMIAG3kwPIqHm0yuyj6E0R0TQihh1MBYniJDCY26WEfpZOI428lE7r2wXT5ksA5jpWv5Vjv6FzXMJC@XjHMe2rnqu7F/NeLV31nL8g1RTh7IB7kH0BF0ogKrLiRBFICWwv@rt6q73BkUULEpOJ@/ "JavaScript (Node.js) – Try It Online") Or [86 bytes](https://tio.run/##NctBDoIwEAXQPaeYjck0TGtBjYEECew9AalJEdAaoI00Xr8iiYv5i/f/vPRHL/e3cZ7PtutDGArU5MgXkhUXd0vKq/ZPMZkZhRBaTNohNhXV1JKhTm2jqkz2Mh/Wx5p8jNhyz3YmNr/oGGO5D3c7L3bsxWgfOGATATQgCVICfiA4EpxA0aYrJQSQEaxF@le5KV/vTJCBihRj4Qs) if the graph is guaranteed to be acyclic. ### Commented ``` f = ( // f is a recursive function taking: a, // a[] = list of routes p, // p = current position t = 0, // t = current time m // m = mask of visited stations ) => // p ^ 1 ? // if the current position is not 1: Math.min(... // take the minimum of ... a.map( // for each route in a[] going from ([A, B, b, i, d]) => // A to B with parameters (b, i, d): p ^ A | // if the current position is not A m >> B & 1 ? // or B was already visited: 1 / 0 // return +Infinity : // else: f( // do a recursive call: a, // pass a[] unchanged B, // set p = B t + // compute the updated time ((b - t) % i + i) // by adding the delay before % i // departure + d, // and the duration m | 1 << B // mark B as visited ) // end of recursive call ) // end of map() ) // end of Math.min() : // else: t // destination reached: return t ``` [Answer] # Python3, 111 bytes: ``` f=lambda t,s=0,D=0:min(m)if(m:=[D]*(s==1)+[K for a,b,c,d,e in t if a==s and(K:=f(t,b,max(c%d-D,0)+D+e))])else[] ``` [Try it online!](https://tio.run/##fY7BCsIwDEDvfkUuQusy6DZFHeS2m59QeqhuxcJax9aDfv2MXlQUDwnkJXnJcEvnS6x2wzjPjnobjq2FhBMpbEjVwUcRpHci1KQbsxITUSEzfQB3GcHiEU/YYgc@QgLvwBJNYGMrDjU5kbgf7FWclm3eoJJZk3VSGtn1U6fNPIw@JuGE1gqhRMgrhDXCxiBoLguEPQKz8gHUE@QcW@bGSLn42P/bZBvnDdtebr5UMFz/nH5/5Vs@3wE) [Answer] # [Python 3](https://docs.python.org/3/), 119 bytes ``` f=lambda a,n=0,t=0:t*(n==1)or min([f(a-{(x,y,s,i,d)},y,s-(s-t)//i*i+d)for x,y,s,i,d in a if x==n]or[max(sum(a,()))**2]) ``` [Try it online!](https://tio.run/##ZctBCoMwEIXhvaeY5YydYKItpYWcRFykSGigiaIpKOLZbSylXXT35uOffo73LlTbZvXD@FtrwHDQkqOW15hj0FpRN4B3AWuLRiw48cwjO25p3ZfAUUQqCpe7Q0s2td8AXAADzsKkdWi6ofZmwvHp0TASUZ6XDW394EJEi0uGkqFkEBXDkeFEnGE6Ewol5c/SrP4qxXB5e/lJ1P7GcE6eZCXaXg "Python 3 – Try It Online") ]
[Question] [ Implement a function or program that can run simplified [BitCycle](https://github.com/dloscutoff/Esolangs/tree/master/BitCycle) code. The functions you must implement are: `<^>v`: Change the direction of a bit to the direction this is pointing. `+`: Turn all 0s left and all 1s right. `\` and `/`: Reflect one bit 90 degrees, then become inactive. In regular BitCycle, this is displayed as `-` or `|`, but that isn't required here. There are no collectors in this implementation, so these will never reset. `?`: Take one bit at a time from input and send it east until all input is gone. You only need to worry about one input here. Bits only input from `?`. `!`: Output and delete the bit present here. Only one output is required. `~`: Send the inputted bit right and a negated version of it left. `@`: When a bit hits this device, terminate the program. The `=`, `0`, and `1` operations, multiple inputs/outputs, and collectors are not included in this specification. Other than that, everything should behave the same as in regular BitCycle. ## Basic BitCycle Rules The program itself forms a rectangular grid. A list of bits, either 0 or 1, will be taken as input, and a potentially-empty list of bits will be given as output. Bits travel rightwards at a rate of 1 character per cycle (which is the term I will try to use for each "tick" of the program) until they hit some sort of operation character. In those cases, they will behave as specified by the operator. Code will stop running upon hitting a `@` character, or, depending on your output specification, also after some amount of time. Left-right turns (from `+`) are relative to the direction of input. For example, if the character entered from the right, 0s will head downwards and 1s upward. In standard BitCycle, values output as soon as they reach a `!` character. However you may instead save all the bits and output them at the end, as long as your interpreter will stop evaluation after some amount of time. Any bit which leaves the grid is destroyed. For the purpose of this challenge, if it doesn't otherwise interfere with your code (ignoring integer overflow of their position), you may choose to not destroy the bits and just have them continue moving in the direction they were. All undefined characters are no-ops. ## Example Programs (mostly taken from the BitCycle github) ``` ?! ``` Cat program ``` v ~ !+~ ?^< ``` Truth Machine ``` ? v ~ / >! < ``` Negate the first bit, output the rest ``` ?~ @+! ``` Output all 0s before the first 1 ## Rules This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so lowest byte count wins. Standard I/O rules apply for both the bits and the program. You may choose whether to output as bits, a signed integer, or an unsigned integer, however, you must always be able to handle a case with only 1 or 0 bits as output AND if you don't output as bits, your program must meet the output-at-end rules. This is because any integer-output version wouldn't output anything on an infinite loop unless there was some form of max round number. If you are outputting all bits at the end, your code must stop after some number of rounds. You may handle this in any "reasonable" way, as long as most simple programs will fully evaluate before your code automatically halts them. A few examples of a valid method for halting the code: * A button that shows the round number, and when pressed, outputs all bits and halts the program. * A program which halts in n cycles, where n based on the number of flags it is given (as long as the max size of n isn't unreasonably small) * A third input which specifies the number of cycles it should do. * A program that always halts after 1000 cycles. * A function which halts after going 100 cycles with no new I/O. [Answer] # [Python 3](https://docs.python.org/3/), 442 bytes ``` def f(s,I): if[0]>I:return[] N='\n';l=s.split(N);W=max(map(len,l))+1;s=[*N.join(i.ljust(W-1)for i in l)+N*W];Q=s.index('?');B=[(Q,I.pop(0),1)];O=[];R=999;L=[-1,-W,1,W] while B*R: C=[];R-=1 for p,v,d in B:p+=d;c=s[p];z=L[L.index(d)-3];d=dict(zip('<^>v+~\/',L+[z*2*v-z,z,W//d,-W//d])).get(c,d);O+=[v]*(c=='!');R*=c!='@';s[p]=[c,' '][c in'\/'];C+=[(p,1-v,-d)]*(c=='~')+[(p,v,d)]*(c not in'!?\n') if I:C+=[(Q,I.pop(0),1)] B=C return O ``` [Try it online!](https://tio.run/##fVJNb6MwEL37Vwy92AaTQLuXxHXSTU6RokTtJQfqSghI6y4lCBy2mwN/PWso@eoqKwxYM@/Ne@Nx/ke/bbK7/T5O1rAmJZvRIQK1Djw5mg2LRG@LLJAIFgI/Z5inouyVeao0WVC@Eh/hJ/kIc5ImGUspdXxeisBe9N43KiOql75vS01Wrk/XmwIUqAxS6izsleSPppDK4uST4DGmfCIC8shmvXyTE48yn0q@FIHkT2IwGPC5CFyfuSvms5Xx8vtNpQlM7CfjFKYtzBW@2TcqOatY3ChNhrkjYh6JMsgl34l5MO8UY@reSR6LWEWa7FRO8P3LqHLq5z5mcyfY2bd25e7Yjq36/djImq@ktPeaaBKxmPKlI4JK2iQSAlvG/JMtIkvgB8wbKRFEDAOWQWRcYFNT8qkhkJz5bsXcmHbMGlOniRq7bQiyjW4Y1tgcNDXdqDXMhi318mRMaiKmCL6GA8t9FGoQcHNzg9DYQqjZ6GKr3w7BCmpkOTUav9x/ZbPkNdTJWhXliQhQIaihjyoLOpgOfyXbTKv0CKrRg9MpZNv0GAcYWaaCYzZ1l0ZhWSaFNlfKuGMQ@GZ2nnnav6QgRBMDs7x2dXt54rUtNMwDWtq3Pwb/5g/VzrlnDV7R9i5i15hd/us9uj6Pnfk5nNaZ5yvpUzHvKqKVPpr9H@4b8rIdM6VvfXiX4NMjEcoLlWmCf5rR6sRcjigskxLyplxsbvr@Lw "Python 3 – Try It Online") Test cases adapted from those in [@Ajax1234's answer](https://codegolf.stackexchange.com/a/247411/95116) Ungolfed: ``` def f(s, I): if I == []: return [] l = s.split('\n') width = max(map(len, l))+1 # including newline s = list('\n'.join(i.ljust(width-1) for i in l) + '\n'*width) Q = s.index('?') # location input bits start at # directions are 1, -1, width, -width corresponding to right, left, down, up bits = [(Q, I.pop(0), 1)] O = [] # output R = 999 # rounds remaining directions = [-1, -width, 1, width] while bits and R: C = [] R -= 1 for pos, val, dir in bits: pos += dir char = s[pos] z = directions[directions.index(dir) - 3] # dir turned right dir = {'<':-1, '^':-width, '>':1, 'v':width, '+':z*(2*val - 1), '~':z, '\\':width//dir, '/':-width//dir}.get(char, dir) if char == '!': O.append(val) if char == '@': R = 0 if char in '\/': s[pos] = ' ' if char == '~': C.append((pos, 1-val, -dir)) if char not in '!?\n': C.append((pos, val, dir)) if I: C.append((Q, I.pop(0), 1)) bits = C return O ``` [Answer] # Python3, 789 bytes: ``` E=enumerate def f(p,s): b=[*map(list,p.split('\n'))] x,y=[(x,y)for x,a in E(b)for y,c in E(a)if'?'==c][0] q,C,s,D=[(x,y,0,1,a,[(x,y)],i)for i,a in E(s)],[],[],{(0,1):[(-1,0),(1,0)],(0,-1):[(1,0),(-1,0)],(-1,0):[(0,-1),(0,1)],(1,0):[(0,1),(0,-1)]} while q: x,y,X,Y,B,p,I=q.pop(0) if(p,I)not in s and 0<=(x:=x+X)<len(b)and 0<=(y:=y+Y)<len(b[0]): s+=[(p,I)] if(O:=b[x][y])in(L:={'>':(0,1),'<':(0,-1),'v':(1,0),'^':(-1,0)}):q+=[(x,y,*L[O],B,p+[(x,y)],I)] if'+'==O:q+=[(x,y,*D[(X,Y)][B],B,p+[(x,y)],I)] if O in['\\','/']:q+=[(x,y,*((Y,X)if X==0 else(0,[1,-1][X==1])),B,p+[(x,y)],I)];b[x][y]=' ' if'~'==O:q+=[(x,y,*D[(X,Y)][0],not B,[(x,y)],I)];q+=[(x,y,*D[(X,Y)][1],B,[(x,y)],I)] if'!'==O:C+=[int(B)] if'@'==O:q=[] if' '==O:q+=[(x,y,X,Y,B,p+[(x,y)],I)] return C ``` [Try it online!](https://tio.run/##nVJNT@MwFLznV7z2Ypu8QqK9rLI1RS0ckJB6beUaKYVERAppmoRuI0T@enl2ElTYZSutFPljPPM885y8rp422Y@feXE43Mgoe3mOirCKnMcohpjnWIrAgbVUZ89hztOkrDA/L/M0qThbZUwI7cAea6k4jSLeFLQLIcnghq/ttsaHdhuKJGYTJuWDVh6ptjjDEq9bJXroY4htFY2JlSZ9pZIgZb9XTkQRKD7y0RPIzaiRwJFFW3DUoXYm1J6iVepWYsEWoyP95sDvpySNYEtZTRxc4BKnmOOt3J7nm5x7gg4S049bkW0qY6uEMHsEbyz5PpB7dyHGaZRR6B6tA1m7yw6lxKaPAKVLgU0VbXZUcR7ItdprVWuRZPwukK/skgWtPTa2K@Oe7Whp47F7WtlobyLYul3/zu7UXBvLbt/DjyuYS02fH1GvFad8QqvpNwqYU0DFViuG7ILpIynnS1zQQ8JCSg@itIzIn/LJolYE@VqIryV/dfEkA9YZar4z5Gk03Z3isf4vPN8Y/zPowNadET/JKj79wK/a@6TqAfhsoHvtz40oouqlyGB2yAtTLebD4XAyoMHkpfbbX5ZmiuwcUXbQOAO3cSb345PcCcDOgQYunMsB/BfdEr/SGnCu3M7pP85OaTsbJxg95/AO) ]
[Question] [ ## Input A positive integer N representing the size of the problem and four positive integers v, x, y, z. ## Output This is what your code should compute. Consider a set of N distinct integers and consider all ways of choosing 3 subsets (which can overlap) from the set. There are \$2^{3N}\$ different possible ways of choosing the three subsets. Call the three subsets A, B and C. Your code must count the number of possible choices of subsets A, B, C such that |A∩B∩C| = v, |A∩B| = x, |B∩C| = y, |C∩A| = z for non-negative integers v, x,y, z. ## Scoring I will generate a set of 5 valid inputs for each N and the time for your code will be the longest running time for a given problem size for any of the 5 inputs. Each answer will be tested on the same set of inputs, and your score is the highest N your code reaches on my PC in 60 seconds (spec details below). This means you need to give me simple and complete instructions on how to compile and run your code in Linux. ## Examples Answers for different values of N, v, x, y, z. * 2, 0, 1, 1, 1 gives 0 * 2, 1, 1, 1, 1 gives 8 * 2, 2, 1, 1, 1 gives 0 * 8, 0, 2, 3, 3 gives 560 * 8, 1, 2, 3, 3 gives 80640 * 8, 2, 2, 3, 3 gives 215040 * 8, 3, 2, 3, 3 gives 0 ## My PC I have an AMD Ryzen 5 3400G running Ubuntu 20.04. ## Notes This challenge is run *per* language so the fastest in Python is not competing with the fastest in C directly. I will maintain a league table per language once the first answer is given. [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/) ``` from math import comb C=lambda n,k:comb(n,k) if n>=0 and k>=0 else 0 f=lambda n,v,x,y,z:C(n,v)*C(n-v,x-v)*C(n-x,y-v)*C(n-x-y+v,z-v)*4**(n-x-y-z+2*v) ``` [Try it online!](https://tio.run/##bY7LCoMwEEX3@YpZ@hghiQ9EsBu/JFaDoomiItWft5GWVKFkkZtz7gwZt6UZdJiO03HIaVCgxNJAq8ZhWuA5qJIUeS9UWQnQ2GUncUxwoZWgHzkFoSvozlD3cw2UyF99xRduuGeFmVhdz1yBQcE3GmdjsPkr7ucz8rwPCHafe6tLiJjn2vxFOhwpsvO4eU6vmFmcXjH/107NEo4hhgbHyU0wK1KaRDfFreIspncXWkeP4w0 "Python 3.8 (pre-release) – Try It Online") [![Venn diagram](https://i.stack.imgur.com/09ur5.png)](https://i.stack.imgur.com/09ur5.png) We fill the Venn diagram's compartments one by one, and we multiply the numbers of options we have at each step: `C(v,n)` - to fill the common intersection `A∩B∩C`, we need to choose `v` elements out of a total of `n`. After making that choice, we are left with `n-v` elements. `C(n-v,x-v)` - we fill the `x-v` compartment from those `n-v`, and we're left with `n-v-(x-v) = n-x` elements `C(n-x,y-v)` - we fill `y-v`, with `n-x-y+v` left `C(n-x-y+v,z-v)` - we fill `z-v` For each of the remaining `n-x-y-z+2*v` elements, there are four possibilities - either belong to exactly one of `A`, `B`, or `C`, or to none of them. Those choices are independent, so we multiply by `4**(n-x-y-z+2*v)`. [Answer] # Mathematica [Try it online!](https://tio.run/##dY7BCoJAEIbvPsV/CjWDdSuRwA7eunXptGwhkbSYG9Qi6svbrBK1QTDD7Mz3zbB1Ya6XujDqXAxDLvQpQnWS2GTYlUJjm4FhNkM1viLkSt9rVdyEJk9GYNIrx6WGsqXsKPvpQG6lRoZUsUBD3JZ335Lr9JQd5tbrp/nq6H/AgqZz8LAJPM8PcdDKwFye5okw8PYPpY0oBY/sH@MpJLLM/u8Lxi5MHcj/bqbjWeJLihGuExfHLk5ZsnIF7go8XrMfY@kaTA7DCw) ``` B[n_, k_] := If[n >= 0 && k >= 0, Binomial[n, k], 0] f[n_, v_, x_, y_, z_] := B[n, v]*B[n - v, x - v]*B[n - x, y - v]*B[n - x - y + v, z - v]*4^(n - x - y - z + 2*v) (* Unit tests *) Print[f[2, 0, 1, 1, 1] == 0] Print[f[2, 1, 1, 1, 1] == 8] Print[f[2, 2, 1, 1, 1] == 0] Print[f[8, 0, 2, 3, 3] == 560] Print[f[8, 1, 2, 3, 3] == 80640] Print[f[8, 2, 2, 3, 3] == 215040] Print[f[8, 3, 2, 3, 3] == 0] ``` ]
[Question] [ You are given an array \$A\$, **which may contain duplicate elements**. In each swap, you may swap the value of any two indices \$i, j\$ (i.e. switch the values of \$A\_i\$ and \$A\_j\$). What is the **least** amount of swaps needed to sort the array, and what are the corresponding swapped indices? ## Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code wins. **However, your program must terminate in reasonable time (less than 10 seconds) for any array \$A\$ with less than 1000 elements.** ## Input The array \$A\$, in any necessary form. ## Output A list of swaps, with each swap being a pair of numbers, in sequential order - first pair in list is swapped first, in any necessary form. In the output, the numbers should all represent indices. You may output the answer either one-indexed or zero-indexed, but my samples will use one-indexing. **The answer might not be unique. However, your answer should still have the same length as the optimal sequence of swaps.** ## Test cases ``` [4,3,2,1] => [(1,4),(2,3)] [1,3,2,3] => [(2,3)] [1,2,1,3,2,3]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dBSsWsg6yueTDQc0uqBCEyFMjCY4r@fiDo0JqgzxHKJIUREYB2ejNZnByzpGDPRJGa1PPnjWMCrkewp9gLETyRWeSF31RDl5MstArmI0Cp7PMERM7jO0qBLXI9XoulvrYmxQ9xrXzF4v0ZPRRl0VlTObv0Qb7eRpWHGJd7dgGejRYgy1vDFuVivPCtmWxjVpGT1aRzpPQENodPWtozOsokLcG9WwBARrS3bbNU/dQiaIVqOTOWbFShLUN5kbDLj8Q4O5o0UD8ehk0WjRbuwIvNN1KQYJQHS2QlMrwwwZwjrlM37vguZzXklsCo1r6zaqkEajIxNrNGkula8IGn17DOa7zxVnDJZhooOlX0pOZmuKMtFWPRls042aYsZ1Csad/2kIwAwIEVK1flLWzfMkWrYiN7pbAaeNFwZCp754UllSTADrCOiZx@1mDKGpa3IYs1q0gpaeAIGbrccwWalE4qFLCGe@ggwxYLiLxyhb4stGj/GmW/2m0DsdAF6u6a4AgcgU6@HekAcaYwxqzmCu8Z1hSqsYutBrtDmaFhXrfmBxL/kPoUBL9KgjHphc6Iu/Bgg@j65rKN3NgRjG9TvQECVC2c7mzKp1lgYpC9mGYs1M9xu5geY5DQCv@BV@jSy54ywmQgukakx0zYFCNPk@r228h29On2c4ityoQpy5xjzgybjYNilde4AIQoTINP@TaUXhGa37fnOe7z1oUKFnOnFIWg8SWbTXrqyDHhpQFNoFWoB78zrgFCerrV@rBMviwbuefPs/ "J – Try It Online") Here is the same code in a more procedural form, if you're looking for an explanation of algorithm. ``` f=. 3 :0 sorting=.y NB. copy of input we'll mutate sorted=./:~y swaps=.0 2$'' for_j. i.#y do. correct=.j{sorted cur=.j{sorting if. cur = correct do. continue. end. NB. correctly fill the current idx j valid_idxs=.(j<i.#sorting) good_j=. valid_idxs * correct = sorting NB. will any of these be the correct desitnation for the current elm? good_dest=. valid_idxs * cur = sorted both=.good_j * good_dest use=.(1 e.both) { good_j ,: both swap_with=. {.I.use swaps=.swaps,(j, swap_with) sorting=.(sorting {~ swap_with, j) (j, sw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Y0RHfskhKaTDZo1hArjPXh9IGMHBhd4stQlDZSDJrNAyJGMQkHzGQXRJ/UZtqjo6lmqWdfVWquwYXVPrmbUevSezNoIVZ45o/hLb72dnIYVpXhRC4aA4i1GUMMa4aZqpVkhSFLfghZYj9pIpwmo8xqdpLVXhJFULO6Z2VAdgtaS1XbFU7WQgURL3snkM3xlENA3OTcIcNjHGkwd2RuIRicVjeztRoaQd1BnPkgQREXLa2riMMMIUTrTp3/uguJzaCQWhfrWuoUqSYPRkROrN2kqha0saOzbvTNffS4qYmQZRRRiqU2Uk1E1BZHIrZ50kqlGzWSm6UwYdf7TEEAxRIguJdVPpnXWPMla1pDr1a0Ip4RHDoQKfdSkUs0ngDYCauZRu@m90KQWHI5Z2VtBthMg5GYuPkwmZiL9YZcAzvwK0vmAoS7uo2z0LxvFx5ui6jd4vcMFwks1RRkAEDnFargX5I5G74OaIhiSf2cYrBVDJXryNsemxYxVP1Bxj@GpULCW4BFXNDAp0au@BgA@ja7NlaLmQB/69h2o8xRh2o7iTKt1Kg2oLIw2KZbFdO3ADNY8hYHAw3@4nzxK6jhVRMiOVPKJLstREg22j62NF7dN4dMMxyQXqiTOmHwe0GQcJZshbT0ABKGHLNP8ZKThhWa0Iv3iPL/3sAZF9kwFjiWtOIlUtFtXxkUNDawobBesBTRvbANOVLBy@1oFWKoG7zT7/C8 "J – Try It Online") --- # original answer, doesn't work for repeats # [J](http://jsoftware.com/), 18 bytes ``` [:;(2]\])&.>@C.@/: ``` [Try it online!](https://tio.run/##VZdfbxU3EMXf8yksKhWoSlh7vfY6QBUVqU9VH/pKkaDhUmhREpGLWql/vjo9vzMOtDRp9nrt8cyZM2fm/vrxzund1@nJWbqbvk5LOtPvg9P09Mfvv/v47OzRvfL8p@f3vzz95vzp6fnDs4/3T3749jR9uHx7TMfDzTG9Oby7Pry/OTm5@f3l9ZPT9Nfp@dmfL569eP63V26u3h@1@uwsPeJ/LMnWw/T4Tj7X1te68nHSP4y@vL5@9/Zwk26u3n04v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GdX1kEPDSgK7QItwL19DjjFyWrza5VgGR6868nHfwE "J – Try It Online") *NOTE: Thanks to Neil for pointing out this currently fails on the test case `4 5 2 1 3 3`.* * `/:` Grade up, ie, return the permutation that puts the list into order * `C.@` Convert that to [cyclic permutation form](https://code.jsoftware.com/wiki/Vocabulary/ccapdot), which uses boxes * `&.>` For each of those boxed lists, ie, permutation cycles... * `(2]\])` Return all consecutive pairs of two elements. This gives us the swaps, and it works because J gives the cycle list in descending order. * `[:;` raze the list of boxes. This gives us all the swap pairs as a single list of pairs, ie, an N x 2 matrix. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~51~~ 43 bytes ``` ṪµṢ,$Ḣ©€E¬a="ʋṚƊ×\ẸÞṪTḢ,®ṛ¦Ẹ}¡@¥ WÇẸпFĖẠƇÄ ``` [Try it online!](https://tio.run/##XZfPil5FEMX38xRBslBo4Xbf/nOboLjRlUtBJGbhIigSXLlxIQQRAnHjSkGNaEBBEXdCJguFGcnCt5i8yHh@p3oSlJlh7ne7u7rq1KlT9X14@86dTy4vL05/Pfvj4vRhun7x6OHZL08/@@31s9/ee@WFf764OP3myf3zr9@9ePzo/Htte0sb0tnvF6ffnv2sd5@e/fja2U8nb5/fY8OXZ3@98fdXF49/eHLv/HMZ/fPG07vfXXv51WtP7z64oS3rxYt3bn/0/scf8PbJ/RtvPrl/Xa8fvHRyfk8Xv3N5efPkZk17KinfSic3sx/3eNS7/37cU@WxprbW9v99THlLM43U05EO1vaR8pFKTXWm2lLVVRsPZWC5sl@/e/GWnoqec8ojlZZyl6GavVhS5YaqZZ8tmZWs@yYf9Vxi1eZK52PngE7huJZyJYAdd@RUS/sh87qp2sPmU5WfzBK7MKAN2S9K@G/fvEzUux3l4Eb0VXfqBtnSAYLUsd3nJ/Frtx4Un55zMaZDfmm99TT1q6My3XSlTGV97FoeRVh2X629I43BHbIytZe/JmtTf3iNa/I0D/bKfzmRiVmPW8Pro6aph3rE2mh4q@sF4tSZA3yUvO4gM5Z4o/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IzWKx88axgV8t1CH2BsI7nCE6mrHgebx7EM5CpGo@ChDEPE5D5DiypxPVKNrru1TmODute45vD7Ej0ZbdRVUTmH@Uu00U6uhhWX@HALloERLcZQyxvjZrXyrJBtaV9Jy@jRmuM8AW2h0dW37s6wigpx71TDDAhWS3bbNU/dQhpEq9HJHLNiJQnqm8wNBlz@ocHc0aOBeHSyaPRoN3YE3um6FIMEIDpboamVYYYMYZ3y2Z93QfM5LxKbQvtq3UYV0mh0ZEyNJs2l8hVBo2/vwXz3ueKMwTJMDLD0YmdmR1OUib70ZLNNN2qKGdcpGHf@qyEAMyBESNX6SVl3z5No2UJud7cCThsvDIROffGkMlNMAGsE9MzjdrOH0NSVHMasHq2gpytA4GYfMUxWKpF46BLCme8dWwwY7uIxypb4hjFivBlWvxZ6pwPAyzXDFSAQmWI90RvyQGOPQc0ZzDW@KLS0xNCFXqPN0bSoWPcDi3vJz4QCLdGjjnhgcqFPfw0QfB5dVyjDzYEY9vXFZ4sSoWwPc2ZpnaVBykK2oVg3070iN9A8pwHgFb/Cr5Eld5xpIvRAqsZE1x0oRJPvx2rjI3xz@jzDUeRGFeIcNeYBT8bFtknp6gEiCBEi0/wn04rCM9rw/eY833vQoELPdOKQtBEksmivrqyDHhpQFNoFWoB7xxpwipPV19cqwTI9eNdbJ7f@BQ "Jelly – Try It Online") A pair of links which when called as a monad returns a list of pairs of 1-indexed indices to swap. Based on the [clever J algorithm developed by @Jonah](https://codegolf.stackexchange.com/a/197540/42248), so be sure to upvote that one too! ## Explanation ### Helper link Takes a list containing a list of the remaining items to be sorted, optionally preceded by the most recent swap. Takes full advantage of the way that `Ḣ` (Head) and `Ṫ` (tail) pop items from a list, which for someone from an R background was something I found took some getting used to when I started using Jelly! ``` Ṫ | Tail (yields the list of remaining items, and also removes this from the list that п is collecting up) µ | Start a new monadic chain Ṣ,$ | Pair the sorted list with the unsorted remaining items Ḣ©€ | Take the head of each, removing from the list and storing each in turn in the register (so the register is left holding the head of the unsorted list) Ɗ | Following as a monad ʋṚ | - Following as a dyad, using a list of the remaining sorted and unsorted lists (in that order) as right argument E | - Equal (i.e. the head of the unsorted and sorted lists matches) ¬ | - Not a | - And: =" | - Equal to zipped right argument (effectively a logical list indicating which of the remainder of the sorted list matched the head of the unsorted and vice-versa) ×\ | Cumulative product ẸÞ | Sort by whether any true Ṫ | Tail T | Convert to list of truthy indices Ḣ | Head (will be 0 if the head of the unsorted and sorted lists matches) ¥ | Following as a dyad, using the remaining unsorted list as right argument , | Pair the index to swap with: @ | - Following with arguments reversed: Ẹ}¡ | - Run following once if index to swap is nonzero: ®ṛ¦ | - Replace item at index to swap with the original head of the unsorted list that was stored in the register ``` ### Main link, takes a list to be sorted ``` W | Wrap in a further list Ẹп | While any non-zero, do the following collecting up intermediate results Ç | - Call helper link F | Flatten (will remove the now empty initial list) Ė | Enumerate (pair the index of each with the item) ẠƇ | Keep only those without zeros Ä | Cumulative sum of each pair ``` ## Original algorithm that fails with repeated values, 16 bytes ``` ỤịƬ€`Ṣ€ŒQTịƲṡ€2Ẏ ``` [Try it online!](https://tio.run/##VZc7jl5VEITzWQULOEjn/UjYAxIJsiyRkCA2QGaROEAiIIYAROiIzFgiQbCP8UaG@qrP2EIzo7n/vff0o7q6uv9vvv722@@enh7f/f747od/37z//s1Xj29/079/fvr8C2798fj2V32sj3/@@JT@fv349i99@ub9q58/@fSzT96/@uXh79e68eXT04uHFz21VFN5mR5eFF@2uNS9/39sqXPZVio71Z76SX2krvOZi7p4vaeS@W3Vr8xUdV1SWamOVGZaqRc/rKnjoeuxz9bCk9JSOXzUdY2nNlcnHycHdIpo9Kh0omqEo6BGalvm5ak7wuFTnZ/CI97CgF4ovlEjfsfmxx0bDpSDcp1al095kC0dIEkdaz5/yF9v60L56bpUA7UUl56PmY5@dVSmh1zKVNHHqcerpp2mXevdldbCh6wcvcvfkLWjP6ImNEVaFu8qfgVRyFmXeRD17unoou94tgbRyr1APDqzwWcm/WKpYIk7@p/11G8Q3QGlRcGOK0iVh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cjWjUfBShiFy8pxhRNVwj1Sj6x6tx9ig7j3cbN@vMZPRRrmKztnmL9nGOHleVtziyyNYBlaMGEOtaIyb1cq7QrGldotW0KO7x3kDyqHR3V6bK6ymQtwn3XACgjuSPXbNU4@QAdF6TDLnrFwpguYme4MBV3xoMD5mDBCvThaNGePGgcA7uUuxSACiqxWa2llmqBDWaZ/2cQqaz@WS2BRqd3QbVUij1ZE1NYY0ThUrgsbcbsF8z7nqisEyTCyw9EPJybamqBLz6km2TQ9qmpnQaRhP/uclADMgRErd@klbT@@TaNlFrnlaAaeNVxZCl756UzkpNoC7Anrn8bhpITT9Foc1a8YomOkZELg5VyyTnU4kH6aEcOZ7R44Fw1M8Vtka3zBWrDfL6jdC73QAeHGz3AECkS3WG70hDzRaLGquYOnxRWGkK4Zu9B5jjqFFx3oeWNxr@SAUaIkudcQLkxv9@GuA4PPqelNZHg7k0O4XnxwtQttuc@ZqnaVBykK1odg00/1EYaB5LgPAK3@l36NKnjjHRJiBVI@NbjpRiKbY9x3jK2Jz@bzD0eRGFeLsHvuAN@Nq25T0zgARhAyRaf5TaWXhHW3ZvznP9x40qDIzXTgkbQWJLNp3KuuglwYUhXGBFhDevgtOdbHm/VolWI4X7/7y4eV/ "Jelly – Try It Online") A monadic link taking a list of integers and returning a list of lists of integers representing the 1-indexed swaps. ### Explanation ``` Ụ | Grade the list z up, i.e., sort its indices by their corresponding values. Ƭ€` | For each member of the resulting list, do the following until no new values, using the list of indices itself as the right argument. Keep all intermediate values. ị | - Index into list Ʋ | Following as a monad: Ṣ€ | - Sort each list ŒQ | - Logical list, true for original copy of each unique value T | - Indices of truthy values ị | - Index into list ṡ€2 | Split each into overlapping sets of 2 Ẏ | Join outer together ``` ## Inefficient algorithm that is too slow for long lists with lots of repeats, 27 bytes ``` ĠŒ!€ŒpµFịƬ€`Ṣ€ŒQTịƲṡ€2Ẏ)LÞḢ ``` [Try it online!](https://tio.run/##TZc9q95FEMX7fIpYCivs@/63sbSyEWwkBGxsQg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ALziV/g9suSOs02EGUj1mOimA4Vo8v06bXyFb06fZziK3KhCnKvHPODJuNo2KT09QAQhQmSa/2RaUXhGWz7fnOd3DxpU6ZlOHJK2gkQW7dOVtdFDA4pCu0ALcO86A051sub5WSVYtgfv/vDew/8A "Jelly – Try It Online") [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~219~~ ~~188~~ 184 bytes ``` F@A_:=MinimalBy[##&@@@f/@#[[1]]&@*(FindPermutation@A~PermutationProduct~#&)/@GroupElements@PermutationGroup[Cycles@*List/@Join@@((f=Partition[#,2,1]&)/@Values@PositionIndex@A)],Length] ``` [Try it online!](https://tio.run/##XY7RSsMwFIbv9xRCoHTjSK3tdAqTU8WKY0KvvAlBQpu5QJNIm4KjdK9e09CL4d33n/87h6O4PQrFrSz5OOaYfT1uP6SWitfPJ0pIgIiHCAmlMWMBrsJc6qoQjeqs2zEas/NFKhpTdaU9k2AZ4Vtjup/XWiihbYsXli/oy6msRYurvWxthDsjNWIYHrYFb6ycNErgFmI2nfrkdefcwrS@edeV@MVsyWAv9Lc9srFopLaUXD/llLg/I1z0fQrJdGCAxVUfe05mdtN/OYHUc@p47dtkzuvZTiC@gQe4hzvYwGYYxj8 "Wolfram Language (Mathematica) – Try It Online") -31 bytes thanks to [@Chris](https://mathematica.stackexchange.com/a/212104) -4 bytes by making the code much faster (no more GroupSetwiseStabilizer slowness) Thanks to @NickKennedy for pointing out that the first version failed on non-unique list entries. The present version is a tour-de-force that calculates the permutation group that leaves the list unchanged, then tries each element of this group to see if it can be used to shorten the result. This code still goes very slowly on massively duplicated lists. Explicit code: ``` A = {4,5,2,1,3,3,10,9,7,6,8,8} (* compute the indices of equal elements *) Q = Values[PositionIndex[A]] (* compute the permutation group that leaves A invariant *) G = PermutationGroup[Cycles@*List /@ Join @@ (Partition[#, 2, 1] & /@ Q)] (* find the permutation that sorts A and combine it with every element of G *) F = PermutationProduct[FindPermutation[A], #] & /@ GroupElements[G] (* convert every resulting permutation to the desired form *) J = Join @@ (Partition[#, 2, 1] & /@ #[[1]]) & /@ F (* pick the shortest solutions *) MinimalBy[J, Length] ``` ]
[Question] [ ## Challenge: ### Input: * An integer `n` (`> 0`) * An integer-array `a` of size `> 0` (which contains positive and negative values, but no zeroes) ### Output: 1. First output the first `n` items 2. Then take the last item you've outputted (let's call it `e`), and go `e` steps forward if `e` is positive, or `abs(e)` steps backwards if `e` is negative. And from that position, output `abs(e)` items (again either going forward / backwards depending on positive / negative). 3. Continue the process until you've either: * Outputted every distinct value of the array * Output one of the items at least `n` times ### Example 1: ``` n = 3 a = [2, 6, 9, 2, -4, -1, 3, 5, -7, 3, -2, 2, 2, 3] ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ A B C D E F G H I J K L M N ← Added as clarification ``` **Step 1:** - Starting position `A`, `n=3` - Output line 1: `2, 6, 9` (`A-C`) - `e = 9` (`C`) - Distinct values already visited: `2, 6, 9` - Distinct values left to visit: `-7, -4, -1, -2, 3, 5` - Amount of times we've visited the items: `A=1, B=1, C=1` **Step 2:** - Starting position `L` (9 steps forward from position `C`), `e=9` - Output line 2: `2, 2, 3, 2, 6, 9, 2, -4, -1` (`L-N` + `A-F`) - `e = -1` (`F`) - Distinct values already visited: `-4, -1, 2, 3, 6, 9` - Distinct values left to visit: `-7, -2, 5` - Amount of times we've visited the items: `A=2, B=2, C=2, D=1, E=1, F=1, L=1, M=1, N=1` **Step 3:** - Starting position `E` (1 step backwards from position `F`), `e=-1` - Output line 3: `-4` (`E`) - `e = -4` (`E`) - Distinct values already visited: `-4, -1, 2, 3, 6, 9` - Distinct values left to visit: `-7, -2, 5` - Amount of times we've visited the items: `A=2, B=2, C=2, D=1, E=2, F=1, L=1, M=1, N=1` **Step 4:** - Starting position `A` (4 steps backwards from position `E`), `e=-4` - Output line 4: `2, 3, 2, 2` (`A` + `N-L`) - `e = 2` (`L`) - Distinct values already visited: `-4, -1, 2, 3, 6, 9` - Distinct values left to visit: `-7, -2, 5` - Amount of times we've visited the items: `A=3, B=2, C=2, D=1, E=2, F=1, L=2, M=2, N=2` We've now visited `A` `n (3)` amount of times, so we stop. ### Example 2: ``` n = 2 a = [2, 3, 2] ^ ^ ^ A B C ← Added as clarification ``` **Step 1:** - Starting position `A`, `n=2` - Output line 1: `2, 3` (`A-B`) - `e = 3` (`B`) - Distinct values already visited: `2, 3` - Distinct values left to visit: none - Amount of times we've visited the items: `A=1, B=1` We've already outputted all distinct values, so we stop. ## Challenge rules: * Input and output are flexible. Input can be an array/list of integers, string with delimiter, etc. Output can be to STDOUT, can be a 2D integer array/list, a string, etc. * As you may have noticed from the test cases, you wrap around the array if you're out of bounds. * The input `n` can also be larger than the size of `a` (i.e. `n = 5, a = [2, 3, 4]` will have an output of `2, 3, 4, 2, 3`, and will stop there since we've outputted all distinct values already). * Input array can contain any reasonable integer (including those larger than the array-size) excluding `0`. * If the input for `n` is 1, it means the output will always be just the first item. ## 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: ``` Input: 3, [2, 6, 9, 2, -4, -1, 3, 5, -7, 3, -2, 2, 2, 3] Output: [[2, 6, 9], [2, 2, 3, 2, 6, 9, 2, -4, -1], [-4], [2, 3, 2, 2]] Input: 2, [2, 3, 2] Output: [[2, 3]] Input: 5, [2, 3, 4] Output: [[2, 3, 4, 2, 3]] Input: 1, [2, 1, -3] Output: [[2]] Input: 2, [1, 1, 2, -3] Output: [[1, 1], [2], [1, 1]] Input: 17, [1, 4, 9] Output: [[1, 4, 9, 1, 4, 9, 1, 4, 9, 1, 4, 9, 1, 4, 9, 1, 4]] Input: 2, [1, -2, 3, -4, 5, -6, 6, -5, 4, -3, 2, -1, 1, 1, 1] Output: [[1, -2], [1, 1], [1]] Input: 4, [1, -2, 3, -4, 5, -6, 6, -5, 4, -3, 2, -1, 1, 1, 1] Output: [[1, -2, 3, -4], [1, 1, 1, -1], [2], [1, 1], [1], [1], [-2], [1, 1], [1]] Input: 3, [-1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] Output: [[-1, 1, 2], [4, 5], [10, 11, 12, 13, -1], [13], [12, 13, -1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]] Input: 5, [5, 2, -3, 7, -3, 2, -4, 4, 4, 4] Output: [[5, 2, -3, 7, -3], [2, 5, 4], [7, -3, 2, -4]] Input: 2, [7, 24, 11] Output: [[7, 24], [24, 11, 7, 24, 11, 7, 24, 11, 7, 24, 11, 7, 24, 11, 7, 24, 11, 7, 24, 11, 7, 24, 11, 7]] ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~149~~ 140 bytes ``` n,a=input() l=len(a) s=set(a) i=0 v=[n]*l while min(v)and s: for x in range(i,i+n,n>0 or-1):v[x%l]-=1;n=a[x%l];s-={n};print n, i=x+n;print ``` [Try it online!](https://tio.run/##nU/RboMwDHzPV1hIU6GNJRKgXYuyx/5Emwe0sTUScytgHdO0b2eJ0/UDJiVwtu/iu8vXeDqTnvcmSZKZZGMcXT7GNBOd6VpKm0wMZmjHAJzJxdUcyC478XlyXQvvjtJr1tALDDsBr@ceJnAEfUNvbeqkW5GkpxzOPapsdz1MD51Fo2oyDeN6QPNNP/WldzQCSQHOTCuK9ewNiXZqn9P9KuHO4ngkRPTfRZ1kS6XmQsJBS1hL2ErwAEt/lQTfrzzaMELNM38KK3RU@La2oroXpRUqFv6HN57iSseG2sSO37C9jzGqw9qwb81WsGIWFlEbXwnHivJ/shAT724K5lUs8qYeObzK/Q2UEKGI0aqbeab9vVuyuuTIIYUf6TJo7S8 "Python 2 – Try It Online") --- * -9 bytes, thanks to Bubbler [Answer] # [R](https://www.r-project.org/), ~~167~~ 163 bytes ``` function(n,a,l=sum(a^0),u=rep(n,l),v=0)while(!(all(a%in%v))&min(u)){for(i in F+0:(n-sign(n))){x=i%%l+1 v=c(v,a[x]);u[x]=u[x]-1} print(tail(v,abs(n)));n=a[x];F=i+n} ``` [Try it online!](https://tio.run/##VU5dT8MwDHzvrzAPZbaaSE02QFDy2j9BQQrVBpEyb@oXk6b@9uJ2fQApti93vpOb6dAzvGqYZ92FEyMrr6Jr@yP6j5xU75r9WchIanA5/XyHuMc79DGiTwOnA9H9MTD2RNfDqcEAgaHM8hdk3YYvySNRLi6kacxMMrgaB@XfLu9U9NLd3LQZk3MTuMPOhzjrn@3iK9jNq0XpQsbjVN5u/XMqeIKr/G@wgNp3uKlY64or3tCYiAW3Cmq0Ch4VPCsQoHdSRoEID4KeFqTtosnbEi0@u/pEtCtlVkqm/rcmGVZSjSGapl8 "R – Try It Online") I started with a slightly longer solution but then got inspired by [TFeld](https://codegolf.stackexchange.com/users/38592/tfeld)'s [Python 2 answer](https://codegolf.stackexchange.com/questions/156948/visit-and-exit-an-array/156960#156960) which saved me 3 bytes. *−4 bytes thanks to [Giuseppe](https://codegolf.stackexchange.com/users/67312/giuseppe).* [Answer] ## Pyth, ~~112~~ 109 bytes ``` =HQJ@H0K@H1=H.{K=bJ=Y*]0lKW&>[[email protected]](/cdn-cgi/l/email-protection)._bVrZ+Zb XYNh@YN=b@KN=-Hbp+bd).?Vr+ZbZ XYNh@YN=b@KN=-Hbp+bd))=Z+Nbp"\n ``` [Try it online!](https://pyth.herokuapp.com/?code=%3DHQJ%40H0K%40H1%3DH.%7BK%3DbJ%3DY%2a%5D0lKW%26>J%40.MZY0HI._bVrZ%2BZb+XYNh%40YN%3Db%40KN%3D-Hbp%2Bbd%29.%3FVr%2BZbZ+XYNh%40YN%3Db%40KN%3D-Hbp%2Bbd%29%29%3DZ%2BNbp"%5Cn&input=2%2C+%5B1%2C+-2%2C+3%2C+-4%2C+5%2C+-6%2C+6%2C+-5%2C+4%2C+-3%2C+2%2C+-1%2C+1%2C+1%2C+1%5D&test_suite=1&test_suite_input=3%2C+%5B2%2C+6%2C+9%2C+2%2C+-4%2C+-1%2C+3%2C+5%2C+-7%2C+3%2C+-2%2C+2%2C+2%2C+3%5D%0A2%2C+%5B2%2C+3%2C+2%5D%0A5%2C+%5B2%2C+3%2C+4%5D%0A1%2C+%5B2%2C+1%2C+-3%5D%0A2%2C+%5B1%2C+1%2C+2%2C+-3%5D%0A17%2C+%5B1%2C+4%2C+9%5D%0A2%2C+%5B1%2C+-2%2C+3%2C+-4%2C+5%2C+-6%2C+6%2C+-5%2C+4%2C+-3%2C+2%2C+-1%2C+1%2C+1%2C+1%5D%0A4%2C+%5B1%2C+-2%2C+3%2C+-4%2C+5%2C+-6%2C+6%2C+-5%2C+4%2C+-3%2C+2%2C+-1%2C+1%2C+1%2C+1%5D%0A3%2C+%5B-1%2C+1%2C+2%2C+3%2C+4%2C+5%2C+6%2C+7%2C+8%2C+9%2C+10%2C+11%2C+12%2C+13%5D%0A5%2C+%5B5%2C+2%2C+-3%2C+7%2C+-3%2C+2%2C+-4%2C+4%2C+4%2C+4%5D%0A2%2C+%5B7%2C+24%2C+11%5D&debug=0) This is just a translation of [TFeld](https://codegolf.stackexchange.com/users/38592/tfeld)['s Python 2 answer](https://codegolf.stackexchange.com/questions/156948/visit-and-exit-an-array/156960#156960). Could probably be golfed far better by someone with a better understanding of Pyth, but I figured I might as well share this anyway. [Answer] # JavaScript (ES6), 188 bytes ``` (n,l)=>{for(N=l.length,b=l.map(_=>0),o=[],u=l,e=n,p=0,O=[];!o[n]*u[0];p+=j-s,e=j,O.push(g))for(s=e<0?-1:1,g=[],i=0;i<e*s;p+=s)g[i++]=j=l[p=(p%N+N)%N],o[++b[p]]=u=u.filter(k=>k-j);return O} ``` [Try it online!](https://tio.run/##rVJbb5swFH7Pr3AjVcLFRkCg3ZY60173QB76iKwpTQwldTHCMK2q8tszXzBZaKtNWqUQjv1dzsex95ufG7ltq6bDtdixY0GOXo04JKuXQrReRnjAWV12D@helU@bxvtBViFEguQU9YQjRmrUkBCt1cbyQuQ1verzkC4bn@yxVPAerYOmlw9eCaG2lITdhl9x9CVCpTapSLisbtmV1BIJy7zyfUr2hOcN8ZrLzM/gZUaRyH3/Pm8oJT3pg6LiHWu9R7J6xHu4bFnXtzVYH44dkx0gQH0D4AiwXw0EZAVeZgAItf2tbTfPQdGKJ68wFAgVUhXA@363zgLZtVVdVsWzJ@AFIZM9bQa1EwBbUUvBWcBF6c1Ny2JTcbaboxpNVLbFRCL6ruk7AOboVd832Kox23ba/a1Ein8AjEsG3ssm@@2Wsd2HxTvMDjNt7C0QyGMErhH4jIAqcKKeCAG1n6rqxlQ4Npj6LajiOwG12thwXptoGCcDyTJiSqHtG5@2neViBNMRTEZQ1UMCx4osS73wEOvMPTJQPKJ6bcLQATwZ3didZPgmVxuDfyqmjbFNrOegp3htZoNTI8F2FNjmc6msaoym36Np8n@mg4qOM4nc6Uz6ub/3cui7gsex2hNJTQo1wE92GKF6NEUfjJ27U@iFFhjPM5qLYwWnvb90Orsu6XDUhuGmkRhh4q7RhDPczHSA/9SdnacC4kTnNSZmZaSJ/YYR/pBSdT7@Bg "JavaScript (Node.js) – Try It Online") Comes with a header/footer that run the test cases. Works somewhat like TFeld's Python answer, but ended up slightly longer. [Answer] # [Perl 5](https://www.perl.org/), `-a` ~~123~~ ~~120~~ ~~116~~ ~~115~~ 114 bytes This has the slight blemish that it prints an extra space at the start of each line ``` #!/usr/bin/perl -a @;{@F}=$,=$";say$e!~/-?/,map$U{$z}=$S[++$s[$%]]=$e=$F[$%=($&.1+$%)%@F],($%+=$&.~-$')x($' or$@.=<>)until@S>$@|%U~~% ``` [Try it online!](https://tio.run/##FYm9DoIwFEZ3n@JqbgVSWvkRjcFiJzYnwkQYGBhIEAhgoqJ9dGvNN5yT8w312EZay3iR6UegK3ATT9UT67XascvOvVUD5gu@zJcVlOJUIClLgbXA1Kiwcct9isQhMi1dGwkVpiiGlvOw0YJ@RMnFOXHu3dy0MktQvkmuFNE6gAOcIAC2B@ZDCBGwowEL4L9wFX77YW76btKs0uwacd/j3g8 "Perl 5 – Try It Online") ]
[Question] [ # World Time Conversion ### Challenge: Given an initial clock time in UTC and a list of countries: for each country in the list, output the local time it is in that country based on the initial time. In cases where a country is big enough to have multiple local time zones (like the United States), you may output *any* valid local time for that country, provided you state which time zone you are using (i.e. for United States, EST for Eastern Standard Time). You do not have to worry about daylight savings time. ### Input: The current time, in UTC, followed by a list of countries. The format of the *input* time can be given in any way (12 or 24 hour, with or without seconds, etc), and the countries can all be on the same line or on new lines after the time, your choice. You may also use any characters to delimit the countries (space, comma, etc.). You may choose to take a list of country -> timezone in as input, in which case I would prefer a common list be used across all answers, found [here](https://en.wikipedia.org/wiki/List_of_time_zones_by_country). This part can be excluded from your byte count. ### Output: The local time in each country from the input list. Once again, you may use any characters or newline to delimit the times for each country so long as it is easy to tell one time from another. However, unlike the input, the times must be output in a 12 hour format (so there must be an AM/PM indication). Other than that, you may express the digits in the time in any format (i.e. leading 0's for hours that are single digits, with or without seconds/milliseconds) as long as the character that is used to separate hours and minutes is **different** than the character that is used to separate the different times. I would prefer if a date was not included in the answer since this is a challenge dealing specifically with different times. ### Examples: Input 1: ``` 12:00 AM [United States] ``` Output 1: ``` 7:00 PM EST (or any other time zone with the appropriate time) ``` Input 2: ``` 12:00 PM [United States, Italy, Russia] ``` Output 2: ``` 4:00 AM PST, 2:00 PM, 3:00 PM MSK ``` ### Rules: This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins. [Standard loopholes](https://codegolf.meta.stackexchange.com/q/1061/42963) are forbidden. ### Common list of country -> timezone: ``` // Format: <country>,<UTC offset>,<time-zone abbreviation> // You may use any alternate format or any other UTC/abbreviation for a country for those that have more than one zone France,1,CET United States,-5,EST Russia,3,MSK United Kingdom,0,UTC Australia,10,AEST Canada,-5,EST Kingdom of Denmark,1,CET New Zealand,12,NZST Brazil,-3,BRT Mexico,-6,MDT Indonesia,7,WIST Kiribati,12,LINT Chile,-3,CLT Democratic Republic of the Congo,1,WAT Ecuador,-5,ECT Federated States of Micronesia,11,KOST Kazakhstan,6,ALMT Kingdom of the Netherlands,1,CET Mongolia,8,ULAT Papua New Guinea,10,AEST Portugal,0,WET South Africa,2,SAST Spain,1,CET Afghanistan,4.5,AFT Albania,1,CET Algeria,1,CET Andorra,1,CET Angola,1,WAT Antigua and Barbuda,-4,AST Argentina,-3,ART Armenia,4 Austria,1,CET Azerbaijan,4 Bahamas,-5,EST Bahrain,3 Bangladesh,6,BDT Barbados,-4 Belarus,3,FET Belgium,1,CET Belize,-6 Benin,1,WAT Bhutan,6,BTT Bolivia,-4 Bosnia and Herzegovina,1,CET Botswana,2,CAT Brunei,8 Bulgaria,2,EET Burkina Faso,0,UTC Burundi,2,CAT Cambodia,7 Cameroon,1,WAT Cape Verde,-1,CVT Central African Republic,1,WAT Chad,1,WAT China,8,CST Colombia,-5 Comoros,3,EAT Republic of the Congo,1,WAT Costa Rica,-6 Croatia,1,CET Cuba,-5 Cyprus,2,EET Czech Republic,1,CRT Djibouti,3,EAT Dominica,-4 Dominican Republic,-4 East Timor,9 Egypt,2,EET El Salvador,-6 Equatorial Guinea,1,WAT Eritrea,3,EAT Estonia,2,EET Ethiopia,3,EAT Fiji,12 Finland,2,EET Gabon,1,WAT Gambia,0,GMT Georgia,4 Germany,1,CET Ghana,0,GMT Greece,2,EET Grenada,-4 Guatemala,-6 Guinea,0,GMT Guinea-Bissau,0,GMT Guyana,-4 Haiti,-5 Honduras,-6 Hong Kong,8,HKT Hungary,1,CET Iceland,0,GMT India,5.5,IST Iran,3.5,IRST Iraq,3 Ireland,0,WET Israel,2,IST Italy,1,CET Ivory Coast,0,GMT Jamaica,-5 Japan,9,JST Jordan,2 Kenya,3,EAT North Korea,8.5,PYT South Korea,9,KST Kuwait,3,AST Kosovo,1 Kyrgyzstan,6 Laos,7 Latvia,2,EET Lebanon,2,EET Lesotho,2 Liberia,0,GMT Libya,2,EET Liechtenstein,1,CET Lithuania,2,EET Luxembourg,1,CET Macau China,8,CST Macedonia,1,CET Madagascar,3,EAT Malawi,2,CAT Malaysia,8,MYT Maldives,5 Mali,0,GMT Malta,1,CET Marshall Islands,12 Mauritania,0,GMT Mauritius,4,MUT Moldova,2,EET Monaco,1,CET Montenegro,1,CET Morocco,0,WET Mozambique,2,CAT Myanmar,6.5,MST Namibia,1,WAT Nauru,12 Nepal,5.75,NPT Nicaragua,-6 Niger,1,WAT Nigeria,1,WAT Norway,1,CET Oman,4 Pakistan,5,PKT Palau,9 Panama,-5 Paraguay,-4 Peru,-5,PET Philippines,8,PHT Poland,1,CET Qatar,3,AST Romania,2,EET Rwanda,2,CAT Saint Kitts and Nevis,-4 Saint Lucia,-4 Saint Vincent and the Grenadines,-4 Samoa,13 San Marino,1,CET São Tomé and Príncipe,0,GMT Saudi Arabia,3,AST Senegal,0,GMT Serbia,1,CET Seychelles,4,SCT Sierra Leone,0,GMT Singapore,8,SST Slovakia,1,CET Slovenia,1,CET Solomon Islands,11 Somalia,3,EAT South Sudan,3,EAT Sri Lanka,5.5,SLST Sudan,3,EAT Suriname,-3 Swaziland,2 Sweden,1,CET Switzerland,1,CET Syria,2,EET Taiwan,8 Tajikistan,5, Tanzania,3,EAT Thailand,7,THA Togo,0,GMT Tonga,13 Trinidad and Tobago,-4 Tunisia,1,CET Turkey,2,EET Turkmenistan,5 Tuvalu,12 Uganda,3,EAT Ukraine,2,EET United Arab Emirates,4 Uruguay,-3 Uzbekistan,5,UZT Vanuatu,11, Vatican City,1,CET Venezuela,-4 Vietnam,7,ICT Yemen,3 Zambia,2,CAT Zimbabwe,2,CAT ``` [Answer] ## PowerShell v3+, 71 bytes ``` param($a,$b,$x)$b|%{$y=$x[$_];"{0:t} $($y[1])"-f(date $a).AddHours($y[0])} ``` (74 bytes, -3 bytes for input `,$x`, the dictionary of country->timezone conversions, equals 71 bytes) Uses the below dictionary/hashtable for the timezone conversion, which I manually created (with some creative Excel, PowerShell, and Ctrl-H help) based on the Wikipedia link. ``` $x=@{'France'=(1,'CET');'United States'=(-5,'EST');'Russia'=(3,'Moscow');'United Kingdom'=(0,'UTC');'Australia'=(10,'AEST');'Canada'=(-5,'EST');'Kingdom of Denmark'=(1,'CET');'New Zealand'=(12,'NZST');'Brazil'=(-3,'BRT');'Mexico'=(-6,'Zona Centro');'Indonesia'=(7,'WIST');'Kiribati'=(12,'Gilbert');'Chile'=(-3,'CLT');'Democratic Republic of the Congo'=(1,'WAT');'Ecuador'=(-5,'Ecuador Time');'Federated States of Micronesia'=(11,'Kosrae');'Kazakhstan'=(6,'Almaty');'Kingdom of the Netherlands'=(1,'CET');'Mongolia'=(8,'Ulaanbaatar');'Papua New Guinea'=(10,'AEST');'Portugal'=(0,'WET');'South Africa'=(2,'SAST');'Spain'=(1,'CET');'Afghanistan'=(4.5,'Afghanistan');'Albania'=(1,'CET');'Algeria'=(1,'CET');'Andorra'=(1,'CET');'Angola'=(1,'WAT');'Antigua and Barbuda'=(-4,'AST');'Argentina'=(-3,'ART');'Armenia'=(4,'');'Austria'=(1,'CET');'Azerbaijan'=(4,'');'Bahamas'=(-5,'EST');'Bahrain'=(3,'');'Bangladesh'=(6,'BDT');'Barbados'=(-4,'');'Belarus'=(3,'FET');'Belgium'=(1,'CET');'Belize'=(-6,'');'Benin'=(1,'WAT');'Bhutan'=(6,'BTT');'Bolivia'=(-4,'');'Bosnia and Herzegovina'=(1,'CET');'Botswana'=(2,'CAT');'Brunei'=(8,'');'Bulgaria'=(2,'EET');'Burkina Faso'=(0,'UTC');'Burundi'=(2,'CAT');'Cambodia'=(7,'');'Cameroon'=(1,'WAT');'Cape Verde'=(-1,'CVT');'Central African Republic'=(1,'WAT');'Chad'=(1,'WAT');'China'=(8,'Chinese Standard Time');'Colombia'=(-5,'');'Comoros'=(3,'EAT');'Republic of the Congo'=(1,'WAT');'Costa Rica'=(-6,'');'Croatia'=(1,'CET');'Cuba'=(-5,'');'Cyprus'=(2,'EET');'Czech Republic'=(1,'CRT');'Djibouti'=(3,'EAT');'Dominica'=(-4,'');'Dominican Republic'=(-4,'');'East Timor'=(9,'');'Egypt'=(2,'EET');'El Salvador'=(-6,'');'Equatorial Guinea'=(1,'WAT');'Eritrea'=(3,'EAT');'Estonia'=(2,'EET');'Ethiopia'=(3,'EAT');'Fiji'=(12,'');'Finland'=(2,'EET');'Gabon'=(1,'WAT');'Gambia'=(0,'GMT');'Georgia'=(4,'');'Germany'=(1,'CET');'Ghana'=(0,'GMT');'Greece'=(2,'EET');'Grenada'=(-4,'');'Guatemala'=(-6,'');'Guinea'=(0,'GMT');'Guinea-Bissau'=(0,'GMT');'Guyana'=(-4,'');'Haiti'=(-5,'');'Honduras'=(-6,'');'Hong Kong'=(8,'HKT');'Hungary'=(1,'CET');'Iceland'=(0,'GMT');'India'=(5.5,'IST');'Iran'=(3.5,'IRST');'Iraq'=(3,'');'Ireland'=(0,'WET');'Israel'=(2,'IST');'Italy'=(1,'CET');'Ivory Coast'=(0,'GMT');'Jamaica'=(-5,'');'Japan'=(9,'JST');'Jordan'=(2,'');'Kenya'=(3,'EAT');'North Korea'=(8.5,'Pyongyang');'South Korea'=(9,'KST');'Kuwait'=(3,'AST');'Kosovo'=(1,'');'Kyrgyzstan'=(6,'');'Laos'=(7,'');'Latvia'=(2,'EET');'Lebanon'=(2,'EET');'Lesotho'=(2,'');'Liberia'=(0,'GMT');'Libya'=(2,'EET');'Liechtenstein'=(1,'CET');'Lithuania'=(2,'EET');'Luxembourg'=(1,'CET');'Macau (China)'=(8,'Macau');'Macedonia'=(1,'CET');'Madagascar'=(3,'EAT');'Malawi'=(2,'CAT');'Malaysia'=(8,'Malaysia');'Maldives'=(5,'');'Mali'=(0,'GMT');'Malta'=(1,'CET');'Marshall Islands'=(12,'');'Mauritania'=(0,'GMT');'Mauritius'=(4,'Mauritius');'Moldova'=(2,'EET');'Monaco'=(1,'CET');'Montenegro'=(1,'CET');'Morocco'=(0,'WET');'Mozambique'=(2,'CAT');'Myanmar'=(6.5,'MST');'Namibia'=(1,'WAT');'Nauru'=(12,'');'Nepal'=(5.75,'Nepal');'Nicaragua'=(-6,'');'Niger'=(1,'WAT');'Nigeria'=(1,'WAT');'Norway'=(1,'CET');'Oman'=(4,'');'Pakistan'=(5,'PKT');'Palau'=(9,'');'Panama'=(-5,'');'Paraguay'=(-4,'');'Peru'=(-5,'PET');'Philippines'=(8,'PHT');'Poland'=(1,'CET');'Qatar'=(3,'AST');'Romania'=(2,'EET');'Rwanda'=(2,'CAT');'Saint Kitts and Nevis'=(-4,'');'Saint Lucia'=(-4,'');'Saint Vincent and the Grenadines'=(-4,'');'Samoa'=(13,'');'San Marino'=(1,'CET');'São Tomé and Príncipe'=(0,'GMT');'Saudi Arabia'=(3,'AST');'Senegal'=(0,'GMT');'Serbia'=(1,'CET');'Seychelles'=(4,'Seychelles');'Sierra Leone'=(0,'GMT');'Singapore'=(8,'SST');'Slovakia'=(1,'CET');'Slovenia'=(1,'CET');'Solomon Islands'=(11,'');'Somalia'=(3,'EAT');'South Sudan'=(3,'EAT');'Sri Lanka'=(5.5,'SLST');'Sudan'=(3,'EAT');'Suriname'=(-3,'');'Swaziland'=(2,'');'Sweden'=(1,'CET');'Switzerland'=(1,'CET');'Syria'=(2,'EET');'Taiwan'=(8,'');'Tajikistan'=(5,'');'Tanzania'=(3,'EAT');'Thailand'=(7,'THA');'Togo'=(0,'GMT');'Tonga'=(13,'');'Trinidad and Tobago'=(-4,'');'Tunisia'=(1,'CET');'Turkey'=(2,'EET');'Turkmenistan'=(5,'');'Tuvalu'=(12,'');'Uganda'=(3,'EAT');'Ukraine'=(2,'EET');'United Arab Emirates'=(4,'');'Uruguay'=(-3,'');'Uzbekistan'=(5,'Uzbekistan');'Vanuatu'=(11,'');'Vatican City'=(1,'CET');'Venezuela'=(-4,'');'Vietnam'=(7,'Indochina');'Yemen'=(3,'');'Zambia'=(2,'CAT');'Zimbabwe'=(2,'CAT')} ``` Takes input `$a` as a string in 24hr format, `$b` as an explicit array of strings, and the dictionary `$x`. Loops through `$b`, and for each creates a new `Date` based on `$a`, then calls `.AddHours`, indexing into the dictionary to determine how many, and uses the `-f`ormat operator to pull out the correct information. ### Example ``` PS C:\Tools\Scripts\golfing> .\world-time-conversion.ps1 '12:00' @('United States','Italy','Russia','Nepal') $x 7:00 AM EST 1:00 PM CET 3:00 PM Moscow 5:45 PM Nepal ``` [Answer] # Python 2, ~~154 153 151 148 147 138 134 131 123 121~~ 116 bytes -4 bytes thanks to @Shebang (missed a div `//` to `/` Py3 -> Py2 conversion; print time zone using unpacking; use map to replace two `int` casts) ``` def f(t,c,d): for x in c:a,b=map(int,t.split(':'));e,z=d[x];v=60*a+b+e;print`v/60%12`+':'+`v%60`,'pa'[v%1440<720],z ``` **[repl.it](https://repl.it/Dvck/10)** (I only bothered with a tiny subset of countries, as that's a chore and I'm lazy - but I included Nepal to have a non-standard offset in there & Tuvalu with it's +12:00 one). Input is `t` the time string in 24 hr format; `c` the list of countries; and `d` a dictionary of country string to tuple of minutes offset and time zone name. Prints a 12hr format plus time zone for each country split by new lines. Leading zeros are not printed `AM`/`PM` indicator is just `a`/`p` (e.g. 08:06 in Nepal prints as `8:6 a Nepal Time`) [Answer] # bash (126 bytes) ``` w(){ cd /u*/sh*/z* join -o2.2 <(egrep "$2" i*) <(cut -sf1,3 zone.*)|while read z do TZ=$z date -d"UTC$1" +"%z %r";done|uniq;} w 12:00PM "United States|Italy|Russia" ``` uses GNU date and file:/usr/share/zoneinfo/{iso3166,zone}.tab ]
[Question] [ # Introduction [*Maximum-length sequences*](https://en.wikipedia.org/wiki/Maximum_length_sequence), usually known as *m-sequences*, are binary sequences with some interesting properties (pseudo-noise appeareance, optimal periodic autocorrelation) which make them suitable for many applications in telecommunications, such as spread-spectrum transmission, measurement of impulse responses of propagation channels, and error-control coding. As a specific example, they are the basis for the synchronization signals used in the [(4G) LTE](https://en.wikipedia.org/wiki/LTE_(telecommunication)) mobile communication system. These sequences are best understood as generated by means of an *L*-stage *binary shift register with linear feedback*. Consider the following figure (from the linked Wikipedia article), which shows an example for *L*=4. [![enter image description here](https://i.stack.imgur.com/OoBOp.png)](https://i.stack.imgur.com/OoBOp.png) The *state* of the shift register is given by the content (`0` or `1`) of each stage. This can also be interpreted as the binary expansion of a number, with the most significant bit at left. The shift register is initiallized with a certain state, which we will assume to be `[0 ... 0 1]`. At each discrete-time instant, the contents are shifted to the right. The value of the rightmost stage is the output, and gets removed from the register. The successive values of the rightmost state constitute the output sequence. The leftmost part is filled with the result of the feedback, which is a modulo-2 (XOR) combination of certain stages of the register (in the figure they are the two rightmost stages). The stages that are actually connected to the modulo-2 adder will be referred to as the *feedback configuration*. A sequence produced by a shift register is always periodic. Depending on the feedback configuration, different sequences result. For certain configurations the period of the resulting sequence is the maximum possible, that is, an m-sequence results. This maximum is 2*L*-1: the register has 2*L* states, but the all-zero state can't be part of the cycle because it is an *absorbing state* (once it is reached it is never abandoned). A shift-register sequence is defined by the number of stages *L* and the feedback configuration. Only certain feedback configurations give rise to m-sequences. The example above is one of them, and the sequence is `[1 0 0 0 1 0 0 1 1 0 1 0 1 1 1]`, with period 15. It can be assumed that the last stage is always part of the feedback, otherwise that stage (and possibly some of the preceding) would be useless. There are several ways to describe the feedback configuration: * As a binary array of size *L*: `[0 0 1 1]` in the example. As indicated, the last entry last will always be `1`. * As a number with that binary expansion. But since it would not be possible to distinguish for example `[0 1 1]` and `[0 0 1 1]`, a dummy leading `1` is added. In the example, the number defining the feedback configuration would be `19`. * As a polynomial (over the field GF(2)). Again, a leading 1 coefficient needs to be introduced. In the example, the polynomial would be *x*4+*x*+1. The exponents increase to the left. The description in terms of polynomials is interesting because of the following characterization: the sequence generated from the shift register will be an m-sequence if and only if the polynomial is [*primitive*](https://en.wikipedia.org/wiki/Primitive_polynomial_(field_theory)). # TL;DR / The challenge Given a feedback configuration with *L*>0 stages, generate one cycle of the resulting sequence, starting from the `0···01` state as described above. The feedback configuration will always correspond to an m-sequence, so the period will always be 2*L*-1. **Input** can be given by any means, as long as it is not pre-processed: 1. Binary array. In this case *L* is not explicitly given, because it is the length of the vector. 2. You can choose to include a dummy leading `1` in the above array (and then *L* is the length minus 1). 3. Number with dummy leading `1` digit in its binary expansion. 4. Number without that dummy `1` *and* a separate input explicitly giving *L*. 5. Strings representing any of the above. ...or any other reasonable format. The input format used must be the same for all possible inputs. Please indicate which one you choose. For reference, [A058947](https://oeis.org/A058947) gives all possible inputs that give rise to m-sequences, in format 2 (that is, all primitive polynomials over GF(2)). The **output** will contain 2*L*-1 values. It can be an array of zeros and ones, a binary string, or any other format that is easily readable. The format must be the same for all inputs. Separating spaces or newlines are accepted. Code golf. Fewest best. # Test cases Input in format 2, input in format 3, output as a string: ``` [1 1] 3 1 [1 0 0 1 1] 19 100010011010111 [1 0 1 0 0 1] 41 1000010101110110001111100110100 [1 0 0 0 0 1 1] 67 100000100001100010100111101000111001001011011101100110101011111 ``` [Answer] ## Haskell, ~~88~~ 82 bytes ``` r@(h:t)%m=h:(t++[mod(sum[v|(v,1)<-zip r m])2])%m l#x=take(2^l-1)$(1:(0<$[2..l]))%x ``` I'm using input method 1 (but in reverse order, because I'm shifting to the left) together with `L` as an explicit parameter. Usage example (test case #2): `4 # [1,1,0,0]` -> `[1,0,0,0,1,0,0,1,1,0,1,0,1,1,1]`. How it works: `%` does the work. First parameter is the content of the shift register, second parameter is the feedback configuration. `#` starts the whole process by building the initial register content, calling `%` and taking the first `2^L-1` elements. ``` main function #: 1:0<$[2..l] -- initial register content: one 1 followed -- by L-1 0s %x -- call the helper function with the -- feedback configuration take(2^l-1) -- and take the first 2^L-1 elements helper function % (bind r to the whole register set, h to the first register a0 and t to register a1..aL. Bind m to the feedback config): h: -- next element is h, followed by %m -- a recursive call of %, where the new register is t++ -- t followed by [v|(v,1)<-zip r m] -- the elements of l, where the corresponding -- elements of m are "1" mod(sum ... )2 -- xored ``` [Answer] # Pyth, 19 bytes ``` eM.u+xF*VQNPN+m0tQ1 ``` Try it online: [Demonstration](http://pyth.herokuapp.com/?code=eM.u%2BxF*VQNPN%2Bm0tQ1&input=[0%2C%200%2C%201%2C%201]&test_suite_input=[1]%0A[0%2C%200%2C%201%2C%201]%0A[0%2C%200%2C%200%2C%200%2C%201%2C%201]&debug=0) or [Test Suite](http://pyth.herokuapp.com/?code=eM.u%2BxF*VQNPN%2Bm0tQ1&input=[0%2C%200%2C%201%2C%201]&test_suite=1&test_suite_input=[1]%0A[0%2C%200%2C%201%2C%201]%0A[0%2C%200%2C%200%2C%200%2C%201%2C%201]&debug=0) ### Explanation: ``` eM.u+xF*VQNPN+m0tQ1 implicit: Q = input list in format 1 m0tQ create a list with len(Q)-1 zeros + 1 and append a one at the end this is the starting sequence .u apply the following statement repeatedly to the starting seq. N: *VQN vectorized multiplication of Q and N xF xor all this values + PN remove the last value of N and prepend the new calculated one .u stops, when it detects a cycle and returns a list of all intermediate states of N eM take the last element of each state and print this list ``` [Answer] # Jelly, 18 bytes ``` æḟ2µ&³B^/+ḤµḤ¡BḣḤṖ ``` This takes a single integer, encoding **a0** in its MSB and **aL-1** in its LSB. The test cases become **1**, **12**, **18** and **48** in this format. [Try it online!](http://jelly.tryitonline.net/#code=w6bhuJ8ywrUmwrNCXi8r4bikwrXhuKTCoULhuKPhuKThuZY&input=&args=MTg) ### How it works ``` æḟ2µ&³B^/+ḤµḤ¡BḣḤṖ Main link. Argument: n (binary-encoded taps) æḟ2 Round n down to k = 2 ** (L - 1), the nearest power of 2. µ Begin a new, monadic link. Argument: r = k &³ Bitwise AND r with n. B Convert to binary. ^/ Bitwise XOR all binary digits. Ḥ Unhalve; yield 2r. + Add the results to left and right. µ Convert the previous chain into a single link. Ḥ Unhalve; yield 2k = 2 ** L. ¡ Execute the link 2k times, updating r in each iteration. B Convert the final value of r to binary. ḣḤ Keep only the first 2k binary digits. Ṗ Pop; discard the last digit. ``` [Answer] # [MATL](https://esolangs.org/wiki/MATL), 26 bytes ``` g`tGZ&Bs2\2GBnq^*+H#2\tq]x ``` This works in [current version (15.0.0)](https://github.com/lmendo/MATL/releases/tag/15.0.0) of the language. Input is a number describing the feedback configuration, using format 3 as described in the challenge. Output is separated by newlines. [**Try it online!**](http://matl.tryitonline.net/#code=Z2B0R1omQnMyXDJHQm5xXiorSCMyXHRxXXg&input=MTk) ### Explanation This uses numbers to represent the register contents, and a bitwise XOR operation to compute the feedback bit. At each iteration the fed-back bit is introduced at an "extra stage" at the left of the leftmost stage. A divmod operation by `2` then gives the new contents (division quotient) and the output (division remainder). The stack holds the already produced output and the current state on top. Instead of looping a fixed number (2*L*-1) of times, a "do...while" loop is used, which in this case requires fewer bytes. The loop exits when the `1` state is reached again. ``` g % take input. Convert to logical: gives 1, because input is nonzero. % This is the initial state. The input has been copied into clipboard G ` % do...while t % duplicate G % push input Z& % bitwise XOR Bs2\ % convert to binary, sum, compute parity. The result is the feedback bit 2GBnq^ % compute next power of two that exceeds the register size. This is used % for introducing the fed-back bit in a leftmost stage "outside" the % register, which will be immediately shifted right *+ % multiply by feedback bit and add to register state H#2\ % divmod by 2. Gives output bit and new state on top tq % duplicate and subtract 1. This is falsey if state is 1 (loop will be % exited in that case) ] % end do...while. Exit if top of stack is falsey x % delete current state. Implicitly display sequence ``` [Answer] ## JavaScript (ES6), 100 bytes ``` (l,f)=>[...Array((1<<l)-1)].map((_,i)=>(v=i?(x=v&f,[1,2,4,8,16].map(n=>x^=x>>n),x&1)<<l-1|v>>1:1)&1) ``` Takes type 4 input (length and feedback without the leading 1; well, the 1 is optional.) Returns an array of 0s and 1s. The parity calculation is annoying; I wanted to use `reduce` but that turns out to be 2 bytes longer, because the precedence of `<<` is wrong for my use case. [Answer] # [Kotlin](https://kotlinlang.org), 93 bytes (91 + len(str(Number))) Input `Number` is hardcoded in the source, without leading `1` and in reverse bit order (like @Dennis' answer). Input `L` is not needed! The test cases become `1`, `12`, `18`, `48`. ``` fun main(a:Array<String>){var v=1 do{print(v and 1) v=(v shr 1)xor 48*(v and 1) }while(v!=1)} ``` [Try it online!](http://try.kotlinlang.org/#/UserProjects/rk13bp7k38e8ta7e114f0m2mhu/p591340m5t537ejec2jge5bseg) Result appears rotated left by `L` bits: ``` 100001100010100111101000111001001011011101100110101011111100000 ``` Compare with original: ``` 100001100010100111101000111001001011011101100110101011111100000 100000100001100010100111101000111001001011011101100110101011111 1010111011000111110011010010000 1000010101110110001111100110100 100110101111000 100010011010111 ``` ]
[Question] [ The challenge is simple: given two parameters, *x* and *y*, output *y* staircases with *x* steps. For example: f(3,1) - 1 staircase with 3 steps. ``` _ _| _| ``` f(5,2) - 2 staircases with 5 steps. ``` _ _ _| _| _| _| _| _| _| _| ``` Make sure you output the staircases just like, this and that there is no extra space between staircases. Note that there is **one empty line** at the top. **But there's a twist.** We are going to use a special kind of scoring called **staircase scoring**. In staircase scoring, as long as the character code (in the encoding your language uses) of each character is higher than the previous character you don't accumulate any points. You get a 1 point penalty for using a character with a code that is less than or equal to that of the previous character. Lowest score wins. **E.g.** (Assume we are using Unicode). * "abcd" - 0 points (every character is higher than the previous) * "bbbb" - 3 points (the three last b's are not higher than the first) * "aBcD" - 2 points (remember that in [ASCII](http://www.asciitable.com) lowercase letters have higher values than uppercase letters). * "™©" - 1 point (in Unicode the TM symbol has a value of 8482, where as the copyright symbol has value of 169.) You can use the following snippet to check your score, as well as get the Unicode values of different characters, using the "Show Codes" toggle. (**Note**: This snippet scores using the Javascript UTF-16 encoding. It will break up some complex characters into multiple surrogate characters. If you do not want this, you must score yourself.) : ``` function showCodes() { if(!check.checked) return; var val = program.value; var c = ""; for(var i = 0;i<val.length;i++) { c+= val.charCodeAt(i) + " "; } codes.textContent = c; } function toggle() { if(!check.checked) codes.textContent = ""; else showCodes(); } function getScore() { var val = program.value; var score = 0; for(var i = 0;i<val.length-1;i++) { score += val[i+1] <= val[i]; } alert(score); } ``` ``` <textarea rows=10 cols=40 id="program" oninput="showCodes()"></textarea> <input type="submit" value="Get Score" onclick="getScore()" /> Show Codes<input type="checkbox" id="check" onchange="toggle()" /> <div id="codes"></div> ``` ## Notes: * The input values *x* and *y* will always be > 0 [Answer] # CJam, 2 points ``` "qžɟ̬вխتܯࡗथ੻୾భ൓๟༫ဢᅟቼጢᐿᕽᙦᜥᠺᥳᩗ᭦᰼ᵓṦἫ⁦K≎〉"127f&~ ``` [Try it here.](http://cjam.aditsu.net/#code=%22q%C5%BE%C9%9F%CC%AC%D0%B2%D5%AD%D8%AA%DC%AF%E0%A1%97%E0%A4%A5%E0%A9%BB%E0%AD%BE%E0%B0%AD%E0%B5%93%E0%B9%9F%E0%BC%AB%E1%80%A2%E1%85%9F%E1%89%BC%E1%8C%A2%E1%90%BF%E1%95%BD%E1%99%A6%E1%9C%A5%E1%A0%BA%E1%A5%B3%E1%A9%97%E1%AD%A6%E1%B0%BC%E1%B5%93%E1%B9%A6%E1%BC%AB%E2%81%A6%E2%84%AA%E2%89%8E%E2%8C%AA%22%3Ai256f%25%3Ac~&input=3%205) It takes a long ascending UTF-8 string, gets all character values modulo 128, then evaluates it as CJam code. Removing the final `~` reveals the "real" program hiding underneath: ``` q~_,2m*/W%{~-S_+"_|"?}f%:sWf<Sf+f*N* ``` Which might not even be a very good golf, but luckily it doesn't matter. ^^ Saved a point thanks to Dennis! [Answer] # Headsecks - 0 points I took up @Mauris' idea. I didn't want to actually do this in brainfuck, so I used [bfbasic](http://brainfuck.cvs.sourceforge.net/viewvc/brainfuck/bfbasic/1.41/). Here is the Basic program: ``` INPUT A INPUT B A=A-2 B=B-2 J=0 DO I=0 DO IF I=0 THEN IF A-J>1 THEN K=0 DO PRINT " "; K=K+1 LOOP WHILE K<A-J-1 END IF ELSE K=0 DO PRINT " "; K=K+1 LOOP WHILE K<A-1 IF J=0 THEN PRINT " "; END IF END IF IF J=0 THEN PRINT "_"; ELSE PRINT "_|"; END IF I=I+1 LOOP WHILE I<B PRINT J=J+1 LOOP WHILE J<A PRINT ``` bfbasic was incrementing all my inputs by two for some reason. I then got this brainfuck code: ``` >+<+[>[>[-]+<-]>[<+>>>>>>>>>>>[-]<<<<<<<<<+[->,.----------[<+>>++++++[<------>-]>>>>>>>[<<<<<<<+>>>>>>>-]<<<<<<<[>>>>>>>++++++++++<<<<<<<-]<[>>>>>>>>+<<<<<<<<-]]<]>>>>>>>>>>>>[-]<<<<<<<<<<<<+[->,.----------[<+>>++++++[<------>-]>>>>>>>>>>[<<<<<<<<<<+>>>>>>>>>>-]<<<<<<<<<<[>>>>>>>>>>++++++++++<<<<<<<<<<-]<[>>>>>>>>>>>+<<<<<<<<<<<-]]<]>>>>>>>>[-]>[<+<<<<<<<<+>>>>>>>>>-]<<<<<<<<<[>>>>>>>>>+<<<<<<<<<-]>>>>>>>>-->[-]<[>+<-][-]>>>>[<<<<+<<<<<<<<+>>>>>>>>>>>>-]<<<<<<<<<<<<[>>>>>>>>>>>>+<<<<<<<<<<<<-]>>>>>>>>-->>>>[-]<<<<[>>>>+<<<<-][-]>>[-]<<[>>+<<-]<<<<<<<<<-]>>>>>>>>>>>>>>>>>>>>[<<<<<<<<<<<<<<<<<<<<<+>>>>>>>>>>>>>>>>>>>>>-]<<<<<<<<<<<<<<<<<<<<<[>[-]+<-]>[<+>>>>>>>>>>[-]>>>>>[-]<<<<<[>>>>>+<<<<<-]<<<<<<<<<-]>>>>>>>>>>>>>>>>>>[<<<<<<<<<<<<<<<<<<<+>>>>>>>>>>>>>>>>>>>-]<<<<<<<<<<<<<<<<<<<[>[-]+<-]>[<+>>>>>>>>>>[-]>>>>>[<<<<<+<<<<<<<<+>>>>>>>>>>>>>-]<<<<<<<<<<<<<[>>>>>>>>>>>>>+<<<<<<<<<<<<<-]>>>>>>>[-]>[<<<<<<<+>>>>>>>-]-<[<<<<<<-<+>>>>>>>-]<<<<<<<[>>>>>>>+<<<<<<<-]>[>>>>>>>+<<<<<<<[-]]<->>>>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>>[-]<<[>>+<<-][-]>>[<<+<<<<<<<<+>>>>>>>>>>-]<<<<<<<<<<[>>>>>>>>>>+<<<<<<<<<<-]>>>>>>>[-]>>[<<+<<<<<<<+>>>>>>>>>-]<<<<<<<<<[>>>>>>>>>+<<<<<<<<<-]>>>>>>>>[<<<<+>>>>-]<[<<<<<<+>+<<+>>>>>>>-]<<<<<<<[>>>>>>>+<<<<<<<-]>>[>>[<+<<<+>>>>-]<<<<[>>>>+<<<<-]+>>>[<<->>>-<<<<->>>[-]]<<<[>>[-]+<<-]>>-]<[>>>>>>>-<<<<<<<[-]]>>>[-]>>>>[>>>>>>>>>>>+<<<<<<<<<<<<<<<<<<<<<->>>>>>>>>>[-]]<<<<<<<<<-]<[>[-]+<-]>[<+>>++++++++++.[-]<<<->>-]<<] ``` I finished it by using this Python script in conjunction with [Multilang](https://github.com/TieSoul/Multilang)'s [headsecks implementation](https://github.com/TieSoul/Multilang/blob/master/headsecks.py): ``` import headsecks m=0 with open(input()) as p: p=p.read().strip() c="+-<>.,[]" h="" for i in p: h+=chr(c.index(i)+8*m) m+=1 with open('h.hs', 'w') as x: x.write(h) headsecks.execute(h) ``` And ended up with this headsecks program (It works in the snippet): <https://gist.github.com/anonymous/d956240df995f3cd7d86> xxd dump: <https://gist.github.com/anonymous/67e1fed9e53a770bb770> [Answer] # Python 2, 25 points Following Mauris' approach of unicode character conversion: ``` exec ''.join([chr(ord(unicode(c))%256) for c in u'dťɦ̠ѨԨٳܬ࡮ऩ਺ଊఠ൰๲ཀྵၮᅴሠ፮ᐪᔨᘧᜠᠧᤪᨲᬪᱳᴫḧὟ‧℩∊⌠⑦╯♲✠⡫⤠⩩⭮Ⱐ⵲⹡⽮でㅥ㈨㍳㐩㔺㘊㜠㠠㥰㩲㭩㱮㵴㸠㽮䀪䄨䈧䌠䐧䔪䘨䜲䠪䥳䨭䬲䰪䵫中伲倩儫刧卟呼唧嘫圧堠大娪嬨尲崪幫弫怱愩戩']) ``` Example input and output: ``` h(5,2) _ _ _| _| _| _| _| _| _| _| _| _| h(3,1) _ _| _| _| ``` [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal) `j`, Score 5 ``` ƛd‛_|↳¹d↲Ṫ⁰*;Ṙ ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=j&code=%C6%9Bd%E2%80%9B_%7C%E2%86%B3%C2%B9d%E2%86%B2%E1%B9%AA%E2%81%B0*%3B%E1%B9%98&inputs=5%0A2&header=&footer=) Using the Vyxal codepage, score is 5. [Answer] # TeaScript, 33 points ``` r(x)vm#pR(l*2)+"_"+(g=l==a.n-1?p:"|")+(pR(x*2-2)+"_"+g)R(y-1))j(n ``` This is unusually long because TeaScript 3 is fairly new and contains many bugs, especially with unicode shortcuts which kills the score. [Try it online](http://vihanserver.tk/p/TeaScript/#?code=%22r(x)vm%23pR(l*2)%2B%5C%22_%5C%22%2B(g%3Dl%3D%3Da.n-1%3Fp:%5C%22%7C%5C%22)%2B(pR(x*2-2)%2B%5C%22_%5C%22%2Bg)R(y-1))j(n%22&inputs=%5B%225%22,%223%22%5D&opts=%7B%22int%22:true,%22ar%22:false,%22debug%22:false%7D) ]
[Question] [ ## The Setup You are given a [simple web page](http://jsfiddle.net/nrek29rp/) with 11 elements: * 10 `input` elements with IDs `i1` thru `i10`, in order * one `output` element with ID `out` The input elements have `value` attributes defined in the HTML source. The value of any given input may be any integer from `0` to `10` inclusive. The webpage is equipped with the core jQuery 1.10.1 library (as seen in the fiddle), and executes a block of code as soon as the DOM is loaded. ## The Challenge Six specific challenges are presented below. In each case the objective is to compute some function of the `input`s and place the computation result into the inner HTML of the `output`. Each challenge should be solved independently from the others. The solution to a challenge is the block of code that implements the computation/output (e.g. the code in the "Javascript" window in the fiddle). The length of a solution is the length (in bytes) of this block of code. All this would seem very simple, if not for some rather interesting restrictions. ## Your Code May... 1. invoke the jQuery function `$()` and pass in arguments 2. define and use variables 3. use `this` 4. read any property of any jQuery object (with `.length` being the most useful) 5. define functions/lambdas, which may subsequently be invoked, stored in variables, and passed as arguments. Functions may accept arguments and `return` values if needed. 6. invoke any of the [jQuery DOM traversal methods](http://api.jquery.com/category/traversing/) 7. invoke any of the [jQuery DOM manipulation methods](http://api.jquery.com/category/manipulation/), excepting `width`, `height`, `innerWidth`, `innerHeight`, `outerWidth`, `outerHeight`, `offset`, `position`, `replaceAll`, `replaceWith`, `scrollLeft`, `scrollTop`, `css`, `prop`, `removeProp`, which may not be invoked 8. use the operators: object creation `{}`; array creation / index reference / field reference `[]`, function/method invocation `()`, string concatenation `+`, and assignment `=` 9. use string literals ## Your Code May Not... 1. use *any* operators except for those listed above 2. use *any* literals that are not string literals 3. invoke *any* function/method other than those specifically excepted above 4. use *any* control structure or keyword (e.g. `for`, `while`, `try`, `if`, `with`, etc.), excepting `this`, `var`, `let`, functions and lambdas 5. manipulate the DOM in *any* way that results in the injection of code (see more below) 6. access *any* non-user-defined variable or non-user-defined field/property excepting those listed above ## The 6 Challenges 1. Compute the sum of all `input` values that are even, placing the result in the inner HTML of the `output`. 2. Compute the maximum of all `input` values, placing the result in the inner HTML of the `output`. 3. Compute the product of all `input` values `<= 2`, placing the result in the inner HTML of the `output`. If all input values are `> 2`, place `0` into the inner HTML of the `output`. 4. Compute the modal value (i.e. the value with greatest frequency) of all `input` values, placing the result in the inner HTML of the `output`. If the modal value is not unique, place *any one* of the modal values in the inner HTML of the `output`. 5. Let `I1` be the value of input `i1`, `I2` be the value of input `i2`, etc. If the sequence of input values `I1` .. `I10` forms a [fence](http://en.wikipedia.org/wiki/Fence_%28mathematics%29) with `I1 < I2`, place `"TRUE"` into the inner HTML out the `output`; otherwise place `"FALSE"` into the inner HTML of the output. Specifically, the fence condition is `I1 < I2 > I3 < I4 > I5 < I6 > I7 < I8 > I9 < I10`. 6. Place a comma-separated list of all `input` values, sorted in ascending order, into the inner HTML of the `output`. ## Scoring The contest winner is the programmer who submits correct solutions to the greatest number of challenges. In the event of a tie, the winner is the programmer with the lowest total solution length (the sum of the lengths of all solutions). Hence this is a minor variant of code golf. ## Important Notes Solutions may mangle the DOM (e.g. delete `inputs`, create new elements that appear as visual detritus) so long as the final state of the DOM contains an `output` element with ID `out` and the correctly-computed value. Solutions may make use of any advanced jQuery selectors and CSS3, excepting features that evaluate expressions or execute code. Solutions may not modify the HTML source of the document. All DOM manipulation must occur in the script through jQuery. Solutions *may not* inject code of any kind during DOM traversal/manipulation. This includes (but is not limited to) writing out `script` elements, writing out event attributes containing code, or exploiting the `expression` (IE) or `calc` features of CSS3. This challenge is about creative thinking using sets and trees, and masterful use of jQuery; it is *not* about sneaking code into the DOM or making end runs around the operator restrictions. I reserve the right to disqualify any solution on this basis. All solutions are realizable, and each can be implemented in fewer than 400 bytes. Your solutions may of course exceed 400 bytes or be far shorter than 400 bytes. This is just my basic guarantee that all 6 problems are solvable using a reasonably small amount of code. Finally: **When in doubt, please ask.** :) ## Example Consider the hypothetical challenge: "If 3 or more `input` values equal 5, place `"TRUE"` into the inner HTML of the `output`; otherwise place `"FALSE"` into the inner HTML of the `output`." One valid solution is: ``` F = () => $('body').append( '<a>TRUE</a>' ); $('input').each( F ); F(); $('a:lt(3)').html( 'FALSE' ); $('#out').html( $('a:eq(' + $('input[value="5"]').length + ')') ); ``` **May the best jQuerier win! ;)** [Answer] ## 1. Sum of even inputs, ~~100~~ 94 bytes ``` a=$();(e=$('*:odd')).map(i=>a=a.add(e.slice('0',e.eq(i).val()).clone()));$(out).html(a.length) ``` How it works : * `a=$();` : Create a new object `a` * `e=$('*:odd')` : Get all odd elements on the page and assign it to `e`. Interestingly, all odd elements of page actualyl include all even input elements (amongst other things) ;) * `(e=..).map(i=>...)` : For each of the elements in the object `e`, run the given function where i is the index of the current element. * `a=a.add(e.slice('0', e.eq(i).val()).clone())` : get the value of the ith element in `e`, slice out that many objects from `e`, clone them and put add them to `a`. Interestingly, again, e has more than 10 elements, so it works for all values of the input boxes. For non input elements in `e`, it just slices 0 elements from `e`. * `$(out).html(a.length)` : `out` is a global created by browsers for each element with an id. So we just put the length of `a` in the output element's html. Note that jquery's $() acts as a set, but we are adding clones DOM elements, so it is accumulating and finally giving sum of all even input values. ## 2. Max of all, ~~79~~ 70 bytes ``` a=[];(e=$('*')).map(i=>a[e.eq(i).val()]=e);$(a).map(_=>$(out).html(_)) ``` How it works: * `a=[];` : create a new array `a` * `e=$('*')` : Query all elements on the page and store it in `e` * `(e=..).map(i=>...)` : For each of the elements in the object `e`, run the given function where i is the index of the current element. * `a[e.eq(i).val()]=e` : Get the value of the ith element in `e` (say V) and put `e` in the Vth index of `a`. We use `e` here just to save a byte. Otherwise, `a[e.eq(i).val()]=''` would also work. * `$(a).map(_=>$(out).html(_))` : This is basically putting each index of `a` into the html of the output element, overriding each time. This ends up with the output node having the value which corresponds to the last index of `a` which corresponds to the highest value in the inputs. ## 3. Product, ~~152 141 133~~ 132 bytes ``` f=(i,g=_=>p=$(i1))=>$('[value='+i+']').map(g);h=p=$();f('1');f('2');f('2',_=>p=p.add(p.clone()));f('0',_=>p=h);$(out).html(p.length) ``` 141 -> 133 reduction thanks to GOTO0 :) ## 4. Modal, ~~116 115~~ 102 bytes ``` a=[];(e=$('*')).map(i=>(v=e.eq(i).val(),a[$('[value='+v+']').length]=v));$(out).html($(a).last()['0']) ``` ## 5. Fence, 158 bytes ``` s="TRUE";g=_=>$("*").slice(A.val(),B.val()).map(_=>s="FALSE");f=a=>(A=$(a),B=A.prev(),g(),A=$(a),B=A.next(),g());f(i2);f(i4);f(i6);f(i8);f(i10);$(out).html(s) ``` ## 6. Sorted comma separated values, ~~133 85~~ 86 bytes ``` $('*').map(i=>$('[value='+i+']').map(_=>$(out).append(i+'<a>,')));$("a:last").remove() ``` How this works: * `$('*').map(i=>...)` : Take out all elements from the page and run the method for all of them where `i` is the index of the element. * `$('[value='+i+']').map(_=>...)` : For each `i`, get all elements whose value is `i` and run the method for each one of them. * `$(out).append(i+'<a>,')` : Append `i` and an anchor tag with `,` in it to the output element for each element whose value is `i`. * `$("a:last").remove()` : Remove the last anchor tag to remove the trailing `,` This works as it picks out all elements with values `i` = 0 through 19 (19 being total number of elements on page) and appends `i,` to the output element the number of times an element with value `i` appears. This takes care of all input element, sorting them in increasing order. --- Run them on the given JS fiddle page on a latest Firefox. Please comment if anything is violating rules. [Answer] Interesting challenge! Here are the first few to start us off: ### 1. Sum, 122 112 bytes ``` e=$('*') e.map(i=>e.slice('0',n=e.eq(i).val()).map(x=>e.eq(n).append('<a>'))) e.text($(':not(a):even>a').length) ``` For each input n, append n `<a>` elements to the nth `<input>` element. Then count the `<a>` elements in every odd `<input>` element. ### 2. Maximum, 91 79 bytes ``` e=$('*') s=$() e.map(i=>(s=s.add(e.slice('0',e.eq(i).val())))) e.text(s.length) ``` For each input n, join the first n `<input>` elements with the set `s`. Then count the elements in the set. ### 3. Product, 157 bytes ``` e=$(s='[value=0],[value=1],[value=2],#out') f=x=>e.slice('0',x.val()).each(i=>f(x.nextAll(s).first().append('<a>'))) f(e.first()) e.text($('#out a').length); ``` A recursive function that, given an element with value n, calls itself with the next element n times and appends an `<a>` to that next element. Then count the `<a>` elements in `<output>`. Let me know if there are any mistakes or rule breaches. ]
[Question] [ Read infinitely from stdin, and convert every number to the corresponding symbol on a US qwerty keyboard. No string or character literals anywhere are permitted. E.g. if the input is `117758326`, the output is `!!&&%*#@^`. Letters and symbols that aren't on numbers are left alone; `11g2;;'1g2311hh21930` turns into `!!g@;;'!g@#!!hh@!(#)` Shortest code, in bytes, wins. For those who don't have a US qwerty keyboard, use the following as a guide: ``` 1 -> ! 2 -> @ 3 -> # 4 -> $ 5 -> % 6 -> ^ 7 -> & 8 -> * 9 -> ( 0 -> ) ``` [Answer] ## C, 90 bytes The line between a character and an integer literal is a very fine one in C. ``` a[]={8,0,31,2,3,4,61,5,9,7};main(d){for(;~(d=getchar());)putchar(d>47&d<58?a[d-48]+33:d);} ``` [Answer] ## Perl - 74 57 42 Update thanks to core1024's comment: ``` s/\d/chr 33+(8,0,31,2..4,61,5,9,7)[$&]/eg ``` Run with: ``` perl -p program_name.pl ``` --- Update thanks to manatwork's comment: ``` say s/\d/chr@{[8,0,31,2,3,4,61,5,9,7]}[$&]+33/erg while<> ``` Test with: ``` perl -E 'say s/\d/chr@{[8,0,31,2,3,4,61,5,9,7]}[$&]+33/erg while<>' ``` --- Old attempts: ``` say s/[1234567890]/chr qw(41 33 64 35 36 37 94 38 42 40)[$&]/erg while(<>) ``` Using `qw` counts as a string literal though. Test: ``` perl -E 'say s/[1234567890]/chr qw(41 33 64 35 36 37 94 38 42 40)[$&]/erg while(<>)' ``` Another way: Perl 40 - I think this counts as a string literal as well. ``` say tr/1234567890/!@#$%^&*()/r while(<>) ``` Test with: ``` perl -E 'say tr/1234567890/!@#$%^&*()/r while(<>)' ``` [Answer] # JavaScript (ES6) - ~~79~~ ~~76~~ 87 *Edit* - bloated out by 11 chars after it was pointed out that it failed the "non-numbers are left alone" rule (thanks @soktinpk) *Warning* - you'll need to reload your browser after you run it since it's following the "Read infinitely from stdin" bit... ``` (f=x=>f(alert(+(p=prompt())+1?String.fromCharCode([8,0,31,2,3,4,61,5,9,7][p]+33):p)))() ``` Note that I've interpreted `prompt` as `stdin` & `alert` as `stdout` Tested in Firefox console. [Answer] # Pyth, 43 ``` W1sm?C+33@[8Z31 2 3 4 61 5tT7)vd}Cdr48 58dw ``` Uses 33+table lookup, instead of straight table lookup. No translate function here, just a normal map. Note that Z=0 and tT=9. [Answer] ## Scala, 106 bytes ``` def f{println(readLine.map{c=>try{(Seq(8,0,31,2,3,4,61,5,9,7)(c.toInt-48)+33).toChar}catch{case _=>c}});f} ``` Pretty-printed: ``` def f { println(readLine.map { c => try { (Seq(8,0,31,2,3,4,61,5,9,7)(c.toInt - 48) + 33).toChar } catch { case _ => c } }) f } ``` [Answer] # [pyg-i](https://gist.github.com/ids1024/8c3c3a0653566ada4149) (68) Here is a solution in pyg-i, a fork of pyg I created: ``` while 1:P(Ip().t(dict(Z(R(48,58),(41,33,64,35,36,37,94,38,42,40))))) ``` The python 3 equivalent would be this: ``` while 1:print(input().translate(dict(zip(range(48,58),(41,33,64,35,36,37,94,38,42,40))))) ``` Or, with a little cheating, it can be done in 50 bytes. Note that this is a *bytes* literal, not a string literal: ``` while 1:P(Ip().t(dict(Z(R(48,58),b"(!@#$%^&*(")))) ``` [Answer] # CoffeeScript (70) **Update**: This may be seen as reading between the lines, but while strings and characters aren't allowed, regexs are. (I just converted the regex to a string). ``` alert prompt().replace /\d/g, (t)->([]+/!@#$%^&*()/)[1...-1][(+t+9)%10] ``` Or (for infinite) ``` loop alert prompt().replace /\d/g, (t)->([]+/!@#$%^&*()/)[1...-1][(+t+9)%10] ``` The normal version (in case regex isn't allowed): ``` alert prompt().replace(/\d/g, (t) ->String.fromCharCode(([]+4133643536+3794384240).match(/\d{2}/g)[t])) ``` Test it out [here](http://coffeescript.org). But, according to the problem statement, > > Read **infinitely** from stdin > > > That will probably hang your browser eventually, but here it is (just prepend `loop`, extra 5 bytes, to the code): ``` loop alert prompt().replace(/\d/g, (t) ->String.fromCharCode(([]+4133643536+3794384240).match(/\d{2}/g)[t])) ``` [Answer] # Befunge 98 - 119 bytes This is also with the STRN fingerprint, that allows "S" to stand for a ***convert integer to string*** instruction. ``` v>0 NRTS 4( >&S v >$a,v 5 )!@#$%^&*( >:1 w1 v 7^ p< ^,g1--3*77< >*1-:30p80^ ^ < ``` [Answer] **Haskell, 89** ``` f 50=64 f 54=94 f 55=38 f 56=42 f 57=40 f 48=41 f x|x<48||x>57=x|0<1=x-16 g=map$chr.f.ord ``` tests: Prelude> g "11g2;;'1g2311hh21930" "!!g@;;'!g@#!!hh@!(#)" Prelude> g "117758326" "!!&&%\*#@^" [Answer] # CJam - 32 ``` qA,s26063649909601297730 95b:cer ``` Try it at <http://cjam.aditsu.net/> **Explanation:** `q` reads the whole input `A,` creates the array [0 1 ... 9] (A=10) `s` converts to string, obtaining "0123456789" `95b` converts the previous big number to an array of base-95 digits, which are the ASCII codes of the 10 symbols we want `:c` converts the ASCII codes to characters, obtaining the string `")!@#$%^&*("` `er` transliterates "0123456789" to ")!@#$%^&\*(" in the input string [Answer] # tcl, 156 ``` proc x n {format %c $n} while 1 {puts [string map "1 [x 33] 2 [x 64] 3 [x 35] 4 [x 36] 5 [x 37] 6 [x 94] 7 [x 38] 8 [x 36] 9 [x 40] 0 [x 41]" [gets stdin]]} ``` testable on <http://www.tutorialspoint.com/execute_tcl_online.php?PID=0Bw_CjBb95KQMRE4tMlc3cmJhNG8> [Answer] **PYTHON: 166 86** Not better than the current answers, but the shortest Python solution I can think of as of yet. (thanks to pseudonym117 for helping me shorten this significantly) ``` def g(s): d=')!@#$%^&*(' g='' for c in s: try:g+=d[int(c)] except:g+=c yield g ``` ]
[Question] [ **Closed**. This question needs to be more [focused](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Update the question so it focuses on one problem only by [editing this post](/posts/24101/edit). Closed 5 years ago. [Improve this question](/posts/24101/edit) Your goal is to write a program / script which "converts" real images into ascii art. **General:** Your program will get a path to a image file over stdin or as parameter (whatever you prefer). The format will be jpeg. It should "convert" it to ascii art and save it to the harddrive. The image will be in grayscale. You don't have to check if the input file exists or the file is a valid image. You can use any utf-8 character in your outputfile. **Rules:** * You must be able to recognize the output image. * Your program must recognize the path on `stdin` or parameters * The content of the original image must be read from the drive (you get only the path to the file) * No user interaction (except giving the parameters at startup) allowed * Must terminate without any error message * The output must be written to the harddrive (output name is up to you) * Only turing complete languages allowed. * If you require any special language version for your program you have to add it to your answer. Otherwise the newest stable version will be used (e.g. python = python 3.3) **Bonus points:** * -10 Points for every additional image format your program can convert (please write down which formats can be recognized) * -25 Points if your program can change the output size (width / height parameters at startup in characters) * -100 Points if you don't use any Image Processing libraries (e.g. PIL, ImageMagic, GD...) * -50 Points if your program source looks like ascii art itself ;) **Formula to calculate your points:** `points = floor(programSize (in Bytes) * avgRuntimeOnTestInput (in seconds) - BonusPoints)` **How your program will be tested:** All programs will run on a new virtual machine running Debian x64 (current version) with 512MB memory, 2x3,4Ghz CPU. The time will be calculated on an average of three pictures per format with different size and content (every program will be use the same files). Please write your programcall into your answer so i can check it (and if required the needed compile parameters). Example program call (with bonus parameters): `python ascii.py -file /home/chill0r/test/MyPicture.jpeg -width 1000 -height 750 -out /home/chill0r/test/MyPictureAscii.txt` I'll check the answers every few days and post a 'low score' (*high score* doesn't really fit on code golf...). (Meaning you don't have to calculate your points on your own) [Answer] # Mathematica `asciiPhoto[image_,rastersize_:125,shades_:3]` scans the image according to the raster size (default=125), quantizes it into up to 7 shades (3 by default), then replaces the shading with ASCII characters of varying darkness. Hints about relative darkness found [here](https://codegolf.stackexchange.com/questions/23362/sort-characters-by-darkness/23375#23375). The characters are stored in `shades`; for some reason, 2 of them disappeared in the cut and paste to SE. ``` asciiPhoto[image_,rastersize_:125,shades_:3]:= Module[{chars,gray}, chars={{},{"M"," "},{"","/"," "},{"P","o","/"," "},{"W","o","/",""," "}, {"","b","o","/",""," "},{"","M","b","o","/",""," "},}; gray=ImageData[ColorQuantize[Rasterize[image,RasterSize->rastersize+1, ImageSize->rastersize],shades]]; GraphicsGrid[gray/.Thread[Union@Flatten[gray,1]->chars[[shades]]],ImageSize->500]] ``` ## Examples Render the merganser with a raster size of 35 in 4 shades; compare it to a raster size of 85 with 5 shades. ![merganzer](https://i.stack.imgur.com/nbwbu.png) ``` {asciiPhoto[merganzer, 35, 4], asciiPhoto[merganzer, 85, 5]} ``` --- ![merg2](https://i.stack.imgur.com/gMG0S.png) --- Raster size of 125 in 2 shades; same raster size with 7 shades. ``` {asciiPhoto[merganzer, 125, 2], asciiPhoto[merganzer, 125, 7]} ``` ![merganzer3](https://i.stack.imgur.com/lru1j.png) --- Let's not forget Greta. ![greata](https://i.stack.imgur.com/6UtiL.png) ]
[Question] [ Write a plain TeX program that lists the first two hundred primes (in base-10 notation). Including external files/resources is not permitted. The output may be to the terminal, the log file, or the actual dvi/pdf file, at your option, but should be easily readable to a human; in particular, there must be some delimiter (comma, space, newline,...) between consecutive primes. e-TeX and pdfTeX primitives are permitted. See [this answer](https://tex.stackexchange.com/a/96001/484) for a starting place. Hard-coding the result is permitted, although I do not expect such an answer to win. The answer with the lowest byte count wins. [Answer] ## 176 bytes (plain TeX without e-TeX or pdfTeX) ``` \let\n\newcount\n~\n\j\n\k2~3\loop\ifnum~<1224{\let\x.\j3\loop\ifnum\j<~\k~\divide\k\j\multiply\k\j\ifnum\k=~\let\x!\fi\advance\j2\repeat\ifx\x., \the~\fi}\advance~2\repeat\end ``` ## Algorithm The algorithm is quite simple. It outputs the first prime number 2 and goes from the next prime number 3 to the 200th prime number 1223. Each number *i* is tested, if the odd number is divisible by 3 up to *i*-1 without even numbers (thanks Howard for the removal of the even numbers). There is much room for optimizations of the run-time, e.g.: * The inner loop can be aborted, when the first divisor is found, see the comments. * The divisions only need to be done up to sqrt(*i*). The result is a paragraph with comma separated numbers: > > ![Result](https://i.stack.imgur.com/sovWZ.png) > > > ## Ungolfed version ``` % assign some count registers with short names \newcount\i \newcount\j \newcount\k % Output first prime number 2 2% % Start loop with second prime number 3 \i=3 % \loop \ifnum\i<1224 % 1223 is 200th prime number {% group with curly braces because of the nested \loop \let\x=. % \x is changed, if \i is not prime % Test for all 2 <= j < i: trunc(i/j)*j == i % If true, then j is divisor of i and i is not prime \j=3 \loop \ifnum\j<\i \k=\i \divide\k by \j \multiply\k by \j \ifnum\k=\i \let\x=! % \i is not prime % Optimization to break the loop: % \let\iterate\empty % Then also \x can be removed: If the loop is not aborted, % then \iterate will have the meaning \relax and the % test "\ifx\x." can be replaced by "\ifx\iterate\relax". \fi \advance\j by 2 \repeat \ifx\x. , \the\i % output prime number \fi }% \advance\i by 2 % test next odd number \repeat \end % end of job ``` ## Variant: Output in protocol file, 195 bytes ``` \let\n\newcount\n~\n\j\n\k~2\def\w{\wlog{\the~}}\w~3\loop\ifnum~<1224{\let\x.\j3\loop\ifnum\j<~\k~\divide\k\j\multiply\k\j\ifnum\k=~\let\x!\fi\advance\j2\repeat\ifx\x.\w\fi}\advance~2\repeat\end ``` The result is written to the `.log` file: ``` This is TeX, Version 3.1415926 (TeX Live 2013) (format=tex 2013.5.21) 11 MAR 2014 18:33 **test (./test.tex ~=\count26 \j=\count27 \k=\count28 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 101 103 107 109 113 127 131 137 139 149 151 157 163 167 173 179 181 191 193 197 199 211 223 227 229 233 239 241 251 257 263 269 271 277 281 283 293 307 311 313 317 331 337 347 349 353 359 367 373 379 383 389 397 401 409 419 421 431 433 439 443 449 457 461 463 467 479 487 491 499 503 509 521 523 541 547 557 563 569 571 577 587 593 599 601 607 613 617 619 631 641 643 647 653 659 661 673 677 683 691 701 709 719 727 733 739 743 751 757 761 769 773 787 797 809 811 821 823 827 829 839 853 857 859 863 877 881 883 887 907 911 919 929 937 941 947 953 967 971 977 983 991 997 1009 1013 1019 1021 1031 1033 1039 1049 1051 1061 1063 1069 1087 1091 1093 1097 1103 1109 1117 1123 1129 1151 1153 1163 1171 1181 1187 1193 1201 1213 1217 1223 ) No pages of output. ``` ## Variant: Counting prime numbers, 197 bytes The following variant also counts the prime numbers to get rid of the "hard-coded" 200th prime number. (I have added this variant at the end, because the question would also allow to hard-code *all* prime numbers.) ``` \let\a\advance\let\n\newcount\n\p\n~\n\j\n\k2\p1~3\loop\ifnum\p<200{\let\x.\j3\loop\ifnum\j<~\k~\divide\k\j\multiply\k\j\ifnum\k=~\let\x!\fi\a\j2\repeat\ifx\x., \the~\global\a\p1\fi}\a~2\repeat\end ``` ]
[Question] [ ## objective write a program that can perform addition, subtraction, multiplication, and division, using only bit-wise operators, by bit-wise operators i mean the equivalent of JavaScript `&`, `|`, `^`, `~`, `<<` ,`>>` ,`>>>`. (`AND`, `OR`, `XOR`, `NOT`, and `SHIFT`s) ## rules * you **can use other operators**, just not for the actual operation/output. (i.e. loop-indentation is ok). * it need not actually take input, just be technically functional. (i.e. functions that take arguments). * any output is OK, you can even return a object with the sum, difference, etc. * you need not return floats for division `int`s are ok as well, you can round anyway you like. * as short as you can. [Answer] # JavaScript, ~~124~~ 119 ``` a=(x,y)=>y?a(x^y,(x&y)<<1):x s=(x,y)=>a(x,a(1,~y)) m=(x,y)=>x?a(y,m(s(x,1),y)):0 d=(x,y)=>(x=s(x,y))>>31?0:a(1,d(x,y)) ``` Addition and Subtraction work for any signed numbers, multiplication and division only for unsigned (this hasn't been specified). The input is assumed to be 32 bit. I've been very strict and not even used comparison operators, except testing for equality with zero. It could probably be written a bit shorter otherwise. [Answer] ## C, 313 characters ``` s(a,b){return a&b?s(a^b,(a&b)<<1):a^b;} d(a,b){return s(s(a,~b),1);} P(a,b,c){return b?P(a<<1,b>>1,b&1?s(c,a):c):c;} p(a,b){return b<0?d(0,P(a,d(0,b),0)):P(a,b,0);} q(a,b,c,z){long v=b=(z=b<0)?d(0,b):b,w=1;for(a=a<0?z^=1,d(0,a):a;a>=v;v<<=1)w<<=1; for(c=0;b<=a;v<=a?a=d(a,v),c=s(c,w):0)v>>=1,w>>=1;return z?s(~c,1):c;} ``` The four functions are `s` = sum, `d` = difference, `p` = product, and `q` = quotient. `P` is an internal helper function used by `p`, and is not part of the API. (Note that despite `q`'s definition, it should be invoked with only two parameters.) Please note that `p` and `q` do not work by iterative addition/subtraction, but actually do the bitwise computation. (Otherwise `q` could be significantly shorter.) Thus their running time is a respectable O(log N). All four functions accept the full range of positive and negative integers as inputs. Dividing by zero will produce an infinite loop, since there's no portable way to raise the appropriate exception. Special note for C standards lawyers: The code assumes that sizeof(long) is strictly greater than sizeof(int), which is true more often these days than it used to be. *If* longs and ints are the same size, however, *and* the implementation sign-extends on right-shift (as most do), then `q`'s valid input range is decreased such that the absolute value of the second argument cannot have its highest (non-sign) bit set. (Since dividing by such values can only be equal to zero or one, this isn't too much of a restriction in practice.) ]
[Question] [ [We're back](https://codegolf.stackexchange.com/q/222560/43266)! And this time with an objective scoring criteria! --- 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 `combine` and `separate` with respective types `String × String → String` and `String → String × String` such that `separate ∘ combine = id`. More precisely, 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. * The functions need not actually be named `combine` and `separate` ## 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 [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"); the answer with the lowest score wins. Score is defined as number of bytes, **except that it's -75% if** `combine ∘ separate = id` as well (i.e., if `combine` is bijective and `separate = combine⁻¹`). For brownie points, also try making your solution, in principle, * work on any alphabet rather than `char`, possibly including alphabets of size- 0, 1, or 2 * generalize nicely to \$n\$-tuples or lists --- Have fun! [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 2 bytes ## `combine` ``` Ṿ ``` [Try it online!](https://tio.run/##y0rNyan8///hzn3/j056uHPGw50tD3fOPtalcLhdASzw/79SYlLyo4Y5SjoKSimpaUoA "Jelly – Try It Online") ## `separate` ``` V ``` [Try it online!](https://tio.run/##y0rNyan8/z/s/9FJD3fOeLiz5eHO2ce6FA63K4AF/v@PftQwN1EHSCSBiGQQ8ahhTiyQnpOSmgbkAQA "Jelly – Try It Online") A boring, but short, solution. Uses Jelly's `repr` and `eval` atoms. `Ṿ` is the right-inverse of `V`, meaning that `ṾV` (the Jelly way of composing 2 functions) returns the argument unchanged. Therefore, if passed `[A, B]`, `ṾV` will return `[A, B]` The first program takes input as a pair `[A, B]` and unevals it. The second takes a string as input and evals it as a Jelly program --- Just a quick precursor on strings and Jelly. Jelly does not like strings. At all. Internally, strings are just lists of characters to Jelly, and when outputting, Jelly will do all it can to "mash" everything together so that it doesn't look like it should. [An example](https://tio.run/##y0rNyan8//9Rw5zEpORHDXN1jP7/BwA) that you'd expect to output `['a', 'b', 'c', 2]`, or even `['abc', 2]`. As such, the Footers of the two programs above contain code to print the strings as-is, as lists of characters. Unfortunately, this can make them difficult to read. But how do the programs work? Well, most of the work is done by the `combine` function. The `separate` function is simply "eval the argument as Jelly code". ## `Ṿ` `Ṿ` is a weird atom, as Jelly atoms go. It's entire purpose is to act as the inverse to `V` (as a side note, if an character has an "underdot" below it in Jelly, it's likely to be the "inverse" to the atom without that underdot. For example, `O`/`Ọ` (ord/chr) or `Y`/`Ỵ` (join/split at newlines)) and the function it uses in the interpreter, `jelly_uneval`, is only used by one other atom, `Ṙ`, which just prints the same value as `Ṿ`. However, `Ṿ` does a pretty good job at yielding some Jelly code that, when evaluated, yields it's argument. I won't break down into the exact details, but it's able to handle when string delimiters such as `“` are contained in the input, so is a pretty solid "uneval" atom, as these things go. [Answer] # [R](https://www.r-project.org/), ~~280~~ ~~202~~ ~~207~~ 196 (39+157) bytes *Edit: +5 bytes to fix bug pointed-out by ChartZ Belatedly* **Combine, 39 bytes** ``` function(a,b,`-`=nchar)paste(-a,-b,a,b) ``` [Try it online!](https://tio.run/##pVDLbsMgELzzFZQTq0Akp7dKfEkUyYuDE1obbC9OQ5V/d3Ffyb230czsjHampYm99cGZpZ1Dk3wMEpVVta5NaM44wYCUnNSotFVFgYXcgBMmZ9jfxfXuV2RotpQmH05qNEjbY5xt56TrZGFp6HwqfsEFwL562R1AZUOFobmXz0qPAFD7tpYYsvS0DSgLdbvp/GRWywibSjVrggBFMhdcqXFfHTY7KHhFSucSwhgakc6Oj7Nv3rid4nvgbbwKZo14nfuBeLy4ia@WDj8yP8aTYOz3O4lwxxbYz0zrOA/CI/vd2GJo8lfHgCHRPxOXTw "R – Try It Online") **Separate, 157 bytes** ``` function(x,`-`=nchar,s=substring,q=as.double(el(strsplit(x," "))[1:2]),y=s(x,sum(3,-q)))`if`(any(is.na(q))||-y!=sum(q)+1,c(x,""),s(y,c(1,q[1]+2),c(q[1],-y))) ``` [Try it online!](https://tio.run/##pZDBbsMgEETvfAXlBApEcnqrxJdEkbwQnNDaYHuhDVX@3cVpm/Te22h29Ga084JuhBmS00uXg00@Bn6RrWp1sGeYJWrMBtPsw0lOGnB7jNn0jrueVxfH3qeaZ5QJsW9edgchi8bqYB74s1STEKL1XcshFO5xG4BX63pV5UmvkUlsGmlXAhMSeam6kdO@OWx2oupVSVUqZLFxMD44Te4zQZrHUDECJscVSGVkvQhCQLN0dnTK3r5RM8ePQLt4YcRo9pqHEWl8dzNdIz18FnqMJ0bI7zs4iIeutJ96fkPfD3/d78YOgi23jhFCwn8Sly8 "R – Try It Online") Not bijective and probably not shorter than a [Cantor-pairing](https://en.wikipedia.org/wiki/Pairing_function#Cantor_pairing_function) based approach, but I like this because all the output is kind-of readable. `combine` function calculates the lengths of strings `a` and `b`, encodes them as printable-ASCII, and prefixes them to the concatenated strings (with single space separators). `separate` reads the characters before the first spaces, converts these to expected string-lengths, and splits-up the string accordingly. If there are any problems (which will almost always occur if the string wasn't contructed using `combine`) it outputs a zero-length second string. --- # [R](https://www.r-project.org/), ~~111~~ 84 (41+43) bytes *Edit: -27 bytes by simply filling the first output string of 'separate' with an error message if the input string wasn't generated by 'combine'.* **Combine, 41 bytes** ``` function(a,b)capture.output(dput(c(a,b))) ``` [Try it online!](https://tio.run/##rY6xbsMwDER3fQWhRRIQFGjHAvqAzB2bDJJMp25jUZEox87Pu4nQNt3bhTjwjnyX10CjHyLata8x8EBRu403wSWuGR@ocqqsu9sIzTFmLZhcdoxW/NzMJmjOi8bJHfXVLajZztfwRinz@vj8tBfCWclvCKc6hA/wmc4Repql8Fa@1zEVoAkz3CJHd1mgo4MU4pulnblrb8RX7VbpbvzemkbsXQxLYyQXufzDx62aEA7EUGhE2MlTJcaykw3yQqA6UrD9K2j9BA "R – Try It Online") **Separate, 43 bytes** ``` function(x)c(try(eval(parse(t=x))),'')[1:2] ``` [Try it online!](https://tio.run/##rY69bsMwDIR3PQWhRSIQFGjHAn6AzB2bDJJMp25jUZEox87Lu437k@7tQhC8432Xl0LJZSfULF2NQXqOdsJgJc@WRne0H2ohK82EiBtj8Pn@8WG/BB58H6lRP09u4zG4JDXTHVdJVWx7HWFVEJVyjZYXglPtwxv4zOcIHU9a@Ua/1iEV4JEyXC1Hd5mh5YNW6ruedXjbPaqvAmv4Tfh9/SR2LoZ5ZSQXpfxD4taMBAcWKDwQ7PSpslDZ6RXyxGBaNrD9K2h5Bw "R – Try It Online") Still not bijective, but a bit more competitive at the cost of being boring. A loose port of ChartZ's Jelly [eval-uneval](https://codegolf.stackexchange.com/a/222635/95126) approach, but adjusted so that it will yield 2 strings as output with any string, not just with `eval`-able [R](https://www.r-project.org/) code. `combine` function constructs a string expression representing [R](https://www.r-project.org/) vector containing the two strings `a` and `b`. `separate` tries to evaluate its argument as [R](https://www.r-project.org/) code, and puts an error message into an output string if it fails. It then appends an empty string, and returns the first two elements (so non-[R](https://www.r-project.org/) code, as well as valid [R](https://www.r-project.org/) code that would output more than one string-like return value, all finally output 2 strings). [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 44 bytes ``` c=lambda *args:repr(args) s=lambda x:eval(x) ``` [Try it online!](https://tio.run/##Pco7CoAwEEXR3lXINM6IhWAjAXdiM4migp8wEYmrj3@7d3nH7mu/zEVpJQRTjTzphuOUpXNKWit4LYrc93jVbjyip2BlmFcEhwY500QKsvgKYH0uqH2eAxFFrzOYOuTX3ZH89LHJqcMB "Python 3.8 (pre-release) – Try It Online") [Answer] # [Husk](https://github.com/barbuz/Husk), 59 (21+38) bytes -75% = score of 14.75 **Combine, 21 bytes:** ``` mcB128FS+ȯΣḣ+moB128mc ``` [Try it online!](https://tio.run/##yygtzv7/PzfZydDIwi1Y@8T6c4sf7lisnZsPEshN/v//f7RSYlKyko5SSmqaUiwA "Husk – Try It Online") **Separate, 38 bytes** ``` momcB128₁B128mc §e_o+₂¹-¹½S*→₂ ÷2←√→*8 ``` [Try it online!](https://tio.run/##yygtzv7/Pzc/N9nJ0MjiUVMjiMpN5jq0PDU@X/tRU9OhnbqHdh7aG6z1qG0SkMt1eLvRo7YJjzpmAflaFv///09MSk4BAA "Husk – Try It Online") Bijective functions: each functions converts the input string(s) to a number by interpreting the codepoints in base-128, and then applies [Cantor pairing](https://en.wikipedia.org/wiki/Pairing_function#Cantor_pairing_function) to exchange between an integer and a pair of integers, before converting back to a string. This can result in strings that contain unprintable characters, so the following testing links use modified versions that output the codepoints: [separate to codepoints](https://tio.run/##yygtzv7/P9fJ0MjiUVMjiMpN5jq0PDU@X/tRU9OhnbqHdh7aG6z1qG0SkMt1eLvRo7YJjzpmAflaFv///09MSk4BAA) = converts "abcd" into the strings with codepoints [6,5] and [1,24,21] [combine from codepoints](https://tio.run/##yygtzv7/PzfZydDIwi1Y@8T6c4sf7lisnQvi////PzraTMc0VifaUMfIRMfIMDYWAA) = converts that back to "abcd" [combine to codepoints](https://tio.run/##yygtzv7/38nQyMItWPvE@nOLH@5YrJ2bDxLITf7//3@0UmJSspKOUkpqmlIsAA) = converts strings "abc" and "def" to the string with codepoints [1,26,2,55,4,35,112] [separate from codepoints](https://tio.run/##yygtzv7/Pzc/N9nJ0MjiUVMjiOI6tDw1Pl/7UVPToZ26h3Ye2hus9ahtEpDLdXi70aO2CY86ZgH5Whb///@PNtQxMtMx0jE11THRMTbVMTQ0igUA) = converts that back to "abc", "def" Alternatively, here ([combine](https://tio.run/##yygtzv7/Pzc/WdvY0MnS3C1Y@8T6c4sf7lisnZsP5Ofm6xobJv///z9aKTEpWUlHKSU1TSkWAA) (27 bytes); [separate](https://tio.run/##yygtzv7/Pzc/Nz9Z29jQydL8UVMjkMzN1zU2TOY6tDw1Pl/7UVPToZ26h3Ye2hus9ahtEpDLdXi70aO2CY86ZgH5Whb///@vqzLStlAAAA) (44 bytes) - score of 17.75) are versions with input/output restricted to the printable ASCII values 32-126. [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 196 bytes ``` import itertools as i c=lambda a,b:(f:=chr(ord((sorted(a[-1:]+b[-1:])or'\x00')[-1])+1))+''.join(sum(i.zip_longest(a,b,fillvalue=f),start=())) s=lambda x:(x[1::2].rstrip(x[0]),x[2::2].rstrip(x[0])) ``` [Try it online!](https://tio.run/##ZY7BasMwEETv@Qrhi3ZrxVjppQj8Ja4psi03KrIldpXi9OcdpdBTT8MMw8xL93yN2@tbouPwa4qUhc@OcoyBhWXhT1MX7DrOVlg1GlhMN10JIs0AXNpuBtuftRnq8Vcwknzf21ZisQPWGrGWsvmKfgO@reCbH58@Qtw@HWcok2rxIXzbcHPdgoqzpdwBIp7473c3sPfamMvQEGfyqdh2QLX3l38hHon8loFhgmqsVGULjK4QlSCXqKQvDE9ALcsHHg8 "Python 3.8 (pre-release) – Try It Online") Slightly less boring than my other try, at the expense of being much longer. Unfortunately `c(s(x))` might not return exactly the same string, if a different fill value is specified than automatically would be determined. # How it works `c`(ombine) interleaves the two strings, with input `a` on the even positions and input `b` on the odd positions. As the strings need not be of equal lenght the shortest one is padded with fill character `f`. This is determined by taking the last character of both strings, sorting them and then taking the next codepoint as fillvalue. This fill value is then also prepended to the output to tell separate which characters to strip. `s` simply takes every other character from the second character on, and strips all occurences of the fill value that's stored in the first character of the input, and then does the same for every other character from the third character on. ]
[Question] [ [The McGill Billboard Project](https://ddmal.music.mcgill.ca/research/The_McGill_Billboard_Project_(Chord_Analysis_Dataset)/) annotates various audio features of songs from a random sample of the Billboard charts. I scraped this data to produce the following file of chord progressions: [`chords.txt`](https://www.dropbox.com/s/tdxdaoj9e9wgpxm/chords.txt) Write the shortest code that outputs the above file (or its contents). **Edit:** Here's a quick description of the notation to get you started: * `N` denotes no chord. * `A:min` denotes the A minor triad chord. * `C#:sus4(b7,9)` and other spicy chords are completely described [here](http://ismir2005.ismir.net/proceedings/1080.pdf). [Answer] # [Java (JDK)](http://jdk.java.net/), ~~295709~~ 47044 (gzipped file) + 943 (code) + 1 (file) + 67 (imports) = 48055 bytes Examining the file manually (with some help from notepad++), I found that there were 976 unique entries in the file, formed of 36 unique characters (plus newlines): `#(),/123456789:ABCDEFGNXabdghijmnsu` I then looked for common patterns, and created a dictionary as follows (key = value): > > `:maj = ¬` > > `:min = `` > > `\r\nA = "` > > `\r\nB = £` > > `\r\nC = $` > > `\r\nD = %` > > `\r\nE = ^` > > `\r\nF = &` > > `\r\nG = *` > > `\r\nN = _` > > `\r\nX = -` > > `:sus = +` > > `:hdim = =` > > `:dim = [` > > `(9) = }` > > `(#9) = ]` > > `:7 = {` > > `:5 = ~` > > `:aug = ;` > > `#11 = @` > > `b7 = '` > > `maj7 = <` > > `b13 = >` > > `:11 = ?` > > `(11) = \` > > `b:9 = Z` > > `¬^¬ = H` > > `¬%¬ = I` > > `¬$¬ = J` > > `¬"¬ = K` > > `£b¬ = L` > > `¬*¬ = M` > > `b¬"b = O` > > `¬&¬ = P` > > `b¬^b = Q` > > `+4(', = R` > > `¬£ = S` > > `+4(') = T` > > `%b¬ = U` > > `£`£ = V` > > ``7%`7 = W` > > `7"` = Y` > > `"b{] = c` > > `*`7 = e` > > `:13^b = f` > > ``7$ = k` > > `%` = l` > > `^` = o` > > `"` = p` > > `b`7^ = q` > > `b{% = r` > > `cc = t` > > `oo = v` > > `&#~ = w` > > `__ = x` > > `YY = y` > > `&#¬ = z` > > > I then find-and-replace using those items in order: ``` ()->{String s = "A LONG STRING THAT I CAN'T PASTE HERE - SEE TIO LINK"; String[] d=new String[]{"&#¬","z","YY","y","__","x","&#~","w","oo","v","cc","t","b{%","r","b`7^","q","\"`","p","^`","o","%`","l","`7$","k",":13^b","f","*`7","e","\"b{]","c","7\"`","Y","`7%`7","W","£`£","V","%b¬","U","+4(')","T","¬£","S","+4(',","R","b¬^b","Q","¬&¬","P","b¬\"b","O","¬*¬","M","£b¬","L","¬\"¬","K","¬$¬","J","¬%¬","I","¬^¬","H","b:9","Z","(11)","\\",":11","?","b13",">","maj7","<","b7","'","#11","@",":aug",";",":5","~",":7","{","(#9)","]","(9)","}",":dim","[",":hdim","=",":sus","+","\r\nX","-","\r\nN","_","\r\nG","*","\r\nF","&","\r\nE","^","\r\nD","%","\r\nC","$","\r\nB","£","\r\nA","\"",":min","`",":maj","¬"}; for (int i=0;i<d.length;i+=2){s=s.replace(d[i+1],d[i]);}return s;} ``` [TIO](https://tio.run/##7L3rcttIsi76fz/FhAVANuQOhm7EoXt6PD95AZeooWiHW2oIi/vonNjbjEVOrwkNxwjpZfpvP4VfbO/6MrMKhSsBkpLtHpNAVVZWVlYBBAt1ycv//s/7//zhf/@/H//P/1z853//95/G//m//iv5H3/60//6r3/c/fr//ef/vPvTfyD5pz9N//Hr//qv//9Pdy9f/ajSD/9DBf/xp//6009/@j8vX/3wl0Sy/1shXvzHerVyhvnT@/y7N3DH/tAZ3byQYCKYEqLhzYvPv1cTrlbr25tfb/5LhS/mn3@fdc4p9n8KnMRJvNhJOuc69uLO/JSBz7/9fZ7cvLgQypL8@cc4iOZvowvUPk9mLgGXSSTlgpmP@maBEweKOg64XnU@MCly/bliHaCyFoxSbvpqGsTqoPtw6zzKd9w5VXexc@ojcIYU2YhO4B2dCArBiZ@kZYYPjroQnIr6wUM8zCeXnfPVzQ39PDedQ0Gm@arKiQrHKuUPl4rSk@IlXOkcruUKhvT9/Pti4dFvzfGdwnTOQ/XrgGE@Gzg0/ZyeHX2RE6Tdj4BRcMKlOaRC5m48Z5VMU14mrXJ8q5vxlPX5xN/c@6V3EPsjDm9ejFDnwEWQT3QO8cN3uhSeuwNVAoXGquj45gXIBPP59yVouu5gv8zGupH4N1kkdYUakCic9CfuPH7AiX9n9@XhKx2r/y0fv7Q58de3T41Hb/BcPGw63Qv90vZC1v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/vWXf/v6x6NvT57Gf/v2b79/d72c//Cn6yd/fvPj0fH3X6no@6dfr99d//L3dz998bev1//59e9@98UXy7/P5j/@6Yu//fLDLyq6Wfz45y/@@sOPPz3R3/gfnsaK7YsvVIPc3vHXX/z4zbkKjo647Isv4FcxgHpPf//T76@fPP2a6aP/@Nsv13/9/eLvv/x@qQT@Mv9Jyta/g3P9n/8f) (sort of). **EDIT** By compressing the string, as suggested in the comments, this answer can then be made shorter. Using the GZIPped version of the string in a file "f" (size 45708 bytes), the code can then be as follows: `import java.io.*; import java.nio.file.*; import java.util.zip.*; ()->{String s="",l;try{BufferedReader b=new BufferedReader(new InputStreamReader(new GZIPInputStream(new ByteArrayInputStream(Files.readAllBytes(Paths.get("f"))))));while((l=b.readLine())!=null){s+=l;}}catch(Exception e){}String[] d=new String[]{THE SAME DICTIONARY AS THE PREVIOUS CODE - REDACTED HERE TO MAKE ANSWER SHORT ENOUGH};for (int i=0;i<d.length;i+=2){s=s.replace(d[i+1],d[i]);}return s;}` [Answer] # Python 3, 969 + 36208 (size of data file) = 37177 bytes A mix of encoding and traditional compression. I store each of the roots (the "letters") and index into an array to find them, then, if it's not N, X or the empty string (which don't have a "chord type" (combination of the quality and other stuff tacked on the end) and are immediately followed by a newline), I use the next byte to index a table of the "chord types". The data file (named "b") is available on my [GitHub](https://github.com/famous1622/CodeGolfData/blob/master/b). ``` import base64,zlib,io x,y=eval(zlib.decompress(base64.decodebytes(b"eNocyAEGgEAYBtGrxIc/7CWqKiAAsYLuf4jsg2dM71VtqgXhN1whN4TGjtA4IE+ExoXQuAdPva3XnJ+q+sAVI4SBAHqXdCQkC4xxOM53eu/3T3axB0dl5w3bu5SrvWgtsi4XF5q3uHhQD/BG1T3LOLKaFjI9rZ4tmvwroGnl/wuZ7K4+jk01anfsKV9TuSfXUW7YkR5QP+RDcWIH4gvS2CE75o69zJ68eNxacS0HRvwgXMRwxbKWQHw4DuXQerKGqx/DLtgp9R28Y+yQHXOHdU/2HJ7iqVeue+KneqkxUM+oxTDxDrni4c87jxdaQgsyzSQ+pWKhvaHXH7547D1t0+MR0oB1iCGB1IWkDu0V3l8GaBwaJwvsG/3y8NHDL5Z7gT7qpJGLabRVjqgnc7IkT7jmHdsK0uMR6gEOjIAEZkAD1iGGBiTQhBTCYGPHjHyh5dAP3uvKJM5FUExLcs3r24KpQwwNSKAJXafkUh9E4u6iEJ8q5Xgdm6alqEMMDUggda3IvG9/E+Ga5xFD49aHrx77KQRp5KK5WGp1YaUskuSZrMmGYo2Lm3qAAyMggRnQgDE0IYVeQhhsDSA5NE7WMDtmpF9wLwrmc5/UIYGwA41MV17zpVDq0IAEmpD1Qz5U54rMW1/UoQEJZHyozv24g1j6PJS//vzqkX6NvJjC1CGGxDUi/YFykqJY42pa0LPxP0cbuWEvu5mi4teChg2hS+74qKaRxhigDg1IIIVM/049NpYLAINXQ3I="))) f=io.BytesIO(zlib.decompress(open("b","rb").read())) while 1: a=x[f.read(1)[0]];print(a if not a or a in"NX"else a+y[f.read(1)[0]]) ``` Edit: I decided not to be lazy after all and go Google correct music terms. [Answer] # Python 3, 23 + 802213 (size of file we want to reproduce) + 1 Quite a naïve answer IMO ``` lambda s:open(s).read() ``` This function takes as argument the file we want to reproduce and then prints it xD Scoring as per [this](https://codegolf.meta.stackexchange.com/a/4934/75323) meta answer, linked by @Arnauld [Answer] # MATLAB, 55935 = 10 + 55924 + 1 Compress the text file as a 55924-byte zip file `c` and then run the code `unzip('c')` [We add a byte to the score to account for the extra file.](https://codegolf.meta.stackexchange.com/questions/4933/counting-bytes-for-multi-file-programs/4934#4934) [Answer] ## Python 3: 93943 = 91,752 + 1990 + 1 This is my messy attempt at a compression. Sadly still worse than simply zipping the file though XD. The information density of the file is not as great as it seems and there were several observable redundancies. Because of that I have doubts that there is a reasonable way to predict the data. I am prepared to be wrong though :-). The code by itself is not golfed that much, since the main portion of the cost is the size of the compressed files. The decompressor is only 1990 bytes long. The compression itself is done by Two separate huffman trees, implied ":" between them and two one-bit streams that act as a guides. Also there are few simple substitutions in place. 1. First huffman tree codes the first letter 2. Second huffman tree codes the portion that follows the ":" 3. First bit file (a) codes whether the line before the ":" consists of 0-1 or 2 characters 4. Second bit file (u) codes whether the second character before : is "b" or "#" Lastly, all the files are compressed via zip since on my work computer we don't have anything else. Might try other compressors later on. [zip-input](https://drive.google.com/file/d/1yCkv-08gBQNvOQefBUuLv9PH6TchIW8O/view?usp=sharing) This archive has to be in programs working directory. The code itself is tied tightly to the file. It does not cover full format specifications listed by the author of the question. (Also, I have hard-coded the input file size into the decoder - after I missed the proper termination one times too many.) There is definitely a room for improvements - for example few more substitutions tied to the numbers in brackets. There might be a missing trailing newline in the output, that I somehow keep missing while trying to debug. **Huffman tree generator:** ``` import heapq as h import numpy as np from bitarray import bitarray class List: def __init__(self, char, freq): self.char = char self.freq = freq self.leftSon = None self.rightSon = None def __lt__(self, other): return self.freq < other.freq def check(self,arr, prefix): if self.char is not None: arr.append((self.char, prefix)) else: self.leftSon.check(arr, prefix + "0") self.rightSon.check(arr, prefix + "1") def encode(self): if self.char is None: toRet = "0" toRet += self.leftSon.encode() toRet += self.rightSon.encode() else: toRet = "1" + np.binary_repr(ord(self.char), 8) return toRet class HuffmanTree: def __init__(self, inputList): a = [] for x in inputList: h.heappush(a, List(x[0], x[1])) while len(a) > 1: first = h.heappop(a) second = h.heappop(a) new = List(None, first.freq + second.freq) new.leftSon = first new.rightSon = second h.heappush(a, new) self.root = a[0] self.encodeArray = [] self.root.check(self.encodeArray, "") encodeDict = {} for x in self.encodeArray: encodeDict[x[0]] = x[1] self.encodeDict = encodeDict print(self.encodeArray) def encodeSelf(self): head = self.root bits = head.encode() x = bitarray() for b in bits: if b == "0": x.append(0b0) else: x.append(0b1) return x ``` **The code to generate the support files:** ``` import huffman from bitarray import bitarray a = "" with open("chords.txt") as chr: a = chr.read() def getCounts(l): counts = {} for x in l: if x in counts.keys(): counts[x] += 1 else: counts[x] = 1 res = [] for x in counts.keys(): res.append((x, counts[x])) return res def stringToBits(string): ret = bitarray() for x in string: if x =="0": ret.append(0b0) else: ret.append(0b1) return ret lines = a.split("\n") firstPart = [] secondPart = [] for i in lines: a = i.split(":") firstPart.append(a[0]) if len(a) > 1: secondPart.append(a[1] + "\n") ###First part Afile = "" huffFile = "" sharpFile = "" firstPartChars = "" fChar = [] sChar = [] for x in firstPart: firstPartChars += x if len(x) == 0: fChar.append("\n") Afile += "0" else: fChar.append(x[0]) if len(x) == 1: Afile += "0" if len(x) == 2: Afile += "1" sChar.append(x[1]) print([x for x in set(fChar)]) print([x for x in set(sChar)]) fCharCount = getCounts(fChar) sCharCount = getCounts(sChar) firstHuff = huffman.HuffmanTree(fCharCount) for char in fChar: code = firstHuff.encodeDict[char] huffFile += code for char in sChar: if char == "b": sharpFile += "0" elif char == "#": sharpFile += "1" else: raise Exception("error in sharp file") ####### #####Second part sPartFile = "" subs = {} subs["maj"] = "~" subs["min"] = "&" subs["sus"] = "^" subs["aug"] = "%" subs["dim"] = "$" subs["hdi"] = "@" spPart = [] secSubPart = "" for x in secondPart: c = x.replace("maj", "~").replace("min", "&").replace("sus", "^").replace("aug", "%")\ .replace("dim", "$").replace("hdim", "@") spPart.append(c) secSubPart += c secPartCounts = getCounts(secSubPart) secondHuff = huffman.HuffmanTree(secPartCounts) for x in secSubPart: sPartFile += secondHuff.encodeDict[x] aBits = stringToBits(Afile) huffBits = stringToBits(huffFile) sharpBits = stringToBits(sharpFile) sPartBits = stringToBits(sPartFile) print("test") with open("a", "wb") as t: aBits.tofile(t) with open("h", "wb") as t: huffBits.tofile(t) with open("u", "wb") as t: sharpBits.tofile(t) with open("f", "wb") as t: sPartBits.tofile(t) with open("i", "wb") as t: a = firstHuff.encodeSelf() a.tofile(t) with open("j", "wb") as t: b = secondHuff.encodeSelf() b.tofile(t) ``` **Finally the code itself:** ``` from bitarray import bitarray as b import zipfile with zipfile.ZipFile("h.zip", 'r') as z: z.extractall(".") class N: def __init__(s): s.c = None s.l = None s.r = None def i(s): return s.l == None def d(s, r): if s.i(): return s.c else: if r.b() == 0: return s.l.d(r) else: return s.r.d(r) class R: def __init__(s, bits): s.d = bits s.i = 0 def b(s): t = s.d[s.i] s.i += 1 return t def B(s): toRet = s.d[s.i:s.i + 8] s.i += 8 return toRet def rn(r): if r.b() == 1: n = N() n.c = r.B().tostring() else: left = rn(r) right = rn(r) n = N() n.l = left n.r = right return n def bff(i): with open(i, "rb") as f: c = b() c.fromfile(f) return c def huffRead(a): c = bff(a) r = R(c) n = rn(r) return n fh = huffRead("i") fp = R(bff("h")) sh = huffRead("j") sp = R(bff("f")) af = R(bff("a")) bp = R(bff("u")) ft = "" test = open("test", "w") i=0 while i < 125784: i += 1 tp = "" n = "\n" s = "#" b = "b" t = fh.d(fp) spr = True if af.b() == 0: if t == n: tp += t spr = False elif t == "N" or t == "X": tp += t + n spr = False else: tp += t + ":" else: tp += t if bp.b() == 1: tp += s + ":" else: tp += b + ":" if spr: x = sh.d(sp) while x != n: tp += x x = sh.d(sp) tp += x tp = tp.replace("~", "maj").replace("&", "min").replace("^", "sus")\ .replace("%", "aug").replace("$", "dim").replace("@", "hdim") ft += tp print(ft) ``` [Answer] # bash, 802213 + 5 + 1 = 802219 bytes ``` cat<b ``` With a file named `b` containing the contents of `chords.txt`. [Answer] # [Bash](https://www.gnu.org/software/bash/), 39098 bytes ``` xz -c -d a ``` [Try it online!](https://tio.run/##FJrHjoPYFkXn/oqeo5bJhsmTyDlnZiSTc@bn@7mGDiqB7zl7r2VXmqzVf2myFjj6z7/5P//7J/nvev75N/t7kPz339vN8YAfKYpye2ixBaqkKso@f48p64EaDe@bTy@QOcVkzFA6TOZ2Fnd@eBJ8dzteUZAkxFoQLjD1LK8FHSC7nna844mabyqqx4wEcas0EFWmJLZxV0bnMoMDQWdAtAsJmSHVgDPuXF1ZlVasA9C3bDVY4oYvOd8K1MkAq5BaVZInONZNIJIyHlF27pgq52t64sV4wCUlpRbCvi3fhs@qEUUeJ4I4OuC6NBMmrNoxr8NH660mNWsV8x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KX2ojPwQRSMdoGIQxfbmTI7nnVz9h2Q5K@hWL8lbajyGApn/xX9IWjyhvYdxsDh/o94Dn2b0kC/m4@Zj5YnsDIQE2WIDO@X7@n@y8CIU0a6@jTVoBxsfaSWuFYj0ZLJS4o10kCtq6f8ZCrRI2/l5aYRG1zgq7zygjJ0A4c3j25iCAFl7tn5VsuES2CXjRSyua1YOeRBu0kKlDB@5SkqdZFqK81xGg/Kj5@Khxz02p4AAYX1hYEgM/ieLnkGz8OhmHeY@2QL@4sifNg2IrkOUjnx/h@smOW@AhaOOb/Y0V@8e/ffw "Bash – Try It Online") General compressing tool, also make them able to find source ]
[Question] [ # Challenge The challenge is to write a function that prints the number of **repeats** a given array of integers has. ### What are repeats? Repeats of a slice (as in a section of an array) `[ a1, a2, a3, ..., an]` are any other non-overlapping slices of the forms `[ a1+an, a2+an, a3+an, ..., an+an]`, `[ a1+2an, a2+2an, a3+2an, ..., an+2an]`, and so on. Incomplete repeats, e.g. `[ a1+3an, a2+3an]`, are not counted. ### Input and output Inputs should be ordered collections of integers, e.g. arrays, lists, tuples, etc. The integers will be sorted and unique. Output a single integer that is the number of repeats that covers the whole input. The output should correspond to the greatest possible number of repeats. E.g. certain inputs could be modeled to have 3 repeats of a 4-element slice, or 6 repeats of a 2-element slice; 6 should be the output because it is greater than 3. # Examples ``` Input -> Output [ 1, 3, 5, 6, 8, 10, 11, 13, 15, 16, 18, 20] -> 4 [ 3, 5, 7, 10, 13, 15] -> 1 [1, 2, 3] -> 3 [1,2,4] -> 1 [ 3, 5, 7, 9, 12,14,16,18] -> 2 ``` This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge, so the shortest code possible wins If you have any questions related to the challenge feel free to ask. I know that my attempts to explain something can be difficult to understand sometimes. [Answer] # Perl, ~~48~~ 47 bytes Includes +3 for `-p` Give input as a list of numbers on STDIN ``` repeats.pl <<< "3 5 7 9 12 14 16 18" ``` `repeats.pl`: ``` #!/usr/bin/perl -p s//0 /;s/\d+/$'-$&/eg;/(.+?)\1*-/;$_=s/$1//g ``` Does not work if the input is a single 0 (not clear if that is a valid input). Fixing that takes 2 more bytes: ``` #!/usr/bin/perl -p $_=s//0 /%s/\d+/$'-$&/eg-/^(.+?)\1*-/||s/$1//g ``` ## Explanation Adds a 0 in front of the sequence and then constructs a list of differences. The example input ``` 3 5 7 9 12 14 16 18 ``` becomes: ``` 3 2 2 2 3 2 2 2 -18 ``` The -18 is because the last difference is calculated relative to the end of the string which in perl will behave like 0. On this transformed list the problem is equivalent to finding the most often repeating substring before the `-` sign (this is why a single `0` as input does not work because only in that case there is no minus sign) [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), ~~21~~ 20 bytes ``` 0)«¥©v®NôÙgi®Nôg}})Z ``` **Explanation** ``` 0)« # prepend a 0 to the beginning of the list ¥© # calculate deltas and store in register v } # for each N in range(0, len(deltas)) ®Nô # split deltas into N chunks Ù # uniquify list gi } # if length == 1 ®Nôg # push chunk length )Z # return max chunk length ``` [Try it online!](http://05ab1e.tryitonline.net/#code=MCnCq8Klwql2wq5Ow7TDmWdpwq5Ow7RnfX0pWg&input=WyAxLCAgMywgIDUsICA2LCAgOCwgMTAsIDExLCAxMywgMTUsIDE2LCAxOCwgMjBd) [Modified test suite](http://05ab1e.tryitonline.net/#code=fHYwwrh5I8KrwqXCqWdGwq5Ow7TDmWdpwq5Ow7RnfX0pWixc&input=MSAzIDUgNiA4IDEwIDExIDEzIDE1IDE2IDE4IDIwCjMgNSA3IDEwIDEzIDE1CjEgMiAzCjEgMiA0CjMgNSA3IDkgMTIgMTQgMTYgMTg) [Answer] ## [Retina](http://github.com/mbuettner/retina), 38 bytes ``` \d+ $* (?<=(1*) )\1 (.+?)(| \1)+$ $#2 ``` Input should be space-separated. [Try it online!](http://retina.tryitonline.net/#code=JShHYApcZCsKJCoKKD88PSgxKikgKVwxCgooLis_KSh8IFwxKSskCiQjMg&input=MSAzIDUgNiA4IDEwIDExIDEzIDE1IDE2IDE4IDIwCjMgNSA3IDEwIDEzIDE1CjEgMiAzCjEgMiA0CjMgNSA3IDkgMTIgMTQgMTYgMTg) (The first line enables a linefeed-separated test suite.) ### Explanation ``` \d+ $* ``` Convert input to unary by replacing each number `n` with `n` copies of `1`. ``` (?<=(1*) )\1 ``` Compute consecutive differences, by removing from each number the previous number. ``` (.+?)(| \1)+$ $#2 ``` Try to match the entire input as a repetition of difference (favouring more repetitions of fewer differences) and replace it with the number of repetitions. ]
[Question] [ ## Statement Given an input like this `35 15 0 0 10` that matches the following constrains: * `Width` in characters of the grid (5-50) * `Height` in characters of the grid (5-25) * Initial `X` position of the ball (0-(`Width`-1) * Initial `Y` position of the ball (0-(`Height`-1) * Number of movements to simulate Generate a grid that shows the trajectory of the ball, knowing it's direction is initially `DR` (down-right) and that colliding with a wall will reverse the increment being applied to that axis. In other words, if we are going `DR` and hit the bottom we will now be going `UR` until we collide again. The trajectory is not affected by passing twice over the same point since it's not the game snake, it's the trajectory of an object in 2d. The input will be a string such as the one above and the output should be similar to this, not caring about which characters represent the wall, trajectory or ball, as long as they're consistent. [![enter image description here](https://i.stack.imgur.com/q3tEN.png)](https://i.stack.imgur.com/q3tEN.png) ### Points Your score is the length of your submission, in characters. ### Winners by language ``` var QUESTION_ID=81035,OVERRIDE_USER=19121;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] # [MATL](https://github.com/lmendo/MATL), ~~35~~ 34 characters ``` Z"42Gi:qi!+lGqE!/tYo-KM!*|QYoZ}X]( ``` [**Try it online!**](http://matl.tryitonline.net/#code=WiI0MkdpOnFpIStsR3FFIS90WW8tS00hKnxRWW9afVhdKA&input=WzE1IDM1XQo1MApbMCAwXQ) ### Explanation This takes care of the reflections using the formulas ``` nx = 2*(Nx-1) px = abs(t/nx-round(t/nx))*nx ``` where `t` is a time variable that increases in steps of `1`, `Nx` is the maximum size along the `x` direction and `px` is the computed `x` position. Analogous formulas are used for the `y` coordinate. A char matrix of spaces is initially created, and then it is filled with character `*` at the computed `x` and `y` positions. ``` Z" % Implicitly take [width height]. Push char matrix of spaces with that size 42 % Push 42. ASCII for character `*` G % Push first input again, that is, [width height] i % Take number of movements, M :q % Range [0 1 ... M-1] i! % Take initial position [x y]. Transpose into column vector + % Add element-wise with broadcast. Gives 2-row vector lG % Push first input, [width height] qE! % Transform into column vector [2*width-2; 2*height-2] / % Divide element-wise with broadcast tYo % Duplicate. Round to closest integer - % Subtract KM! % Push [2*width-2; 2*height-2] again * % Multiply element-wise with broadcast | % Absolute value Q % Add 1 Yo % Round to closest integer Z} % Separate 2-row array into two row arrays. These contain row and column % indices, respectively, of the ball positions X] % Convert row and colummn indices to linear index ( % Assign 42 to those positions of the matrix of spaces ``` [Answer] ## Python 180 ~~172~~ ~~171~~ ~~163~~ 145 Bytes ### (-2 Bytes with Python3) ``` def r(m,n,x,y,t): s=([' ']*m+['\n'])*n;a=b=1 for c in'o'*(t-1)+'x':s[x+y*m+y],x,y=c,x+a,y+b;a*=2*(0<x<m-1)-1;b*=2*(0<y<n-1)-1 print''.join(s) ``` To save 2 more bytes with Python3 (thanks to shooqie) replace second line with ``` s=[*' '*m,'\n']*n ``` Had to use a list of characters because python does not support string item assignement. The `x+y*m+y` part is from `x+y*(m+1)` because of the '\n' add each line end Edit1: right after posting, saw how to get rid of the overwriting 'x' Edit2: space after print Edit3: using `<` and `>` instead `==`, also tabs for 2nd indentation Edit4: Replaced the if statements with assignements, daisy-chaining less-than and placing the loop in one line (thanks to RootTwo) [Answer] # JavaScript, ~~293~~ 279 Nothing too clever going on here. EDIT: Saved 14 characters by initialising the 2D array differently. ``` p=prompt().split(' ') a=[];for(i=0;i++<p[1];)a.push(new Array(~~p[0]).fill(' ')) x=~~p[2];y=~~p[3] d=e=1 for(i=0;i++<p[4];){a[y][x]=i==p[4]?'x':'o' if(x<1&&d<0||x>p[0]-2&&d>0)d*=-1 if(y<1&&e<0||y>p[1]-2&&e>0)e*=-1 x+=d;y+=e}o='' for(i=0;i++<p[1];)o+=a[i-1].join('')+'\n' alert(o) ``` [Answer] # R, 156 bytes/chars As an unnamed function. It's quite long but I quite like the method. There's probably a better way to do the 1 to w to 1 vector. ``` function(w,h,x,y,i)cat(c(' ','o')[1:(w*h)%in%(rep(c(c(1:w),c((w-1):2)),i)[x:((i=i-1)+x)+1]+(rep(c(c(1:h),c((h-1):2)),i)*w-w)[y:(i+y)+1])*1+1],fill=w,sep='') ``` Brief explanation of function internals ``` cat( # output to STDOUT c(' ','o') # vector of characters [1:(w*h)%in%( # number of characters in the board rep(c(c(1:w),c((w-1):2)),i)[x:((i=i-1)+x)+1]+ # oscillating vector of x to w to 1 to x (rep(c(c(1:h),c((h-1):2)),i)*w-w)[y:(i+y)+1] # similar to above but in steps of w *1+1] # cause a vector of 1 or 2 to pick char ,fill=w,sep='') # print width of w, no separator ``` Like the other current answers this doesn't output the border, but I will add one if required. [Answer] # Javascript ES6 ~~202~~ ~~181~~ 177 chars ``` (w,h,x,y,s)=>(a=(r=Array)(h).fill().map(_=>r(w).fill` `),eval("for(vx=vy=1;s--;x+=vx,y+=vy,a){a[y][x]=0;if(!x||x==w-1)vx*=-1;if(!y||y==h-1)vy*=-1;}"),a.map(r=>r.join``).join` `) ``` ~~Not very golfed, I take a another look at it once I get home.~~ [Answer] ## C++11, 355 Bytes Takes input string as command line arguments ``` #include <iostream> #define A(n,i) int n=atoi(a[i]); int main(int,char**a) { A(w,1)A(h,2)A(x,3)A(y,4)A(n,5) int d=1,r=1; auto b=new int64_t[h]; while(--n>1){ b[y]|=1<<x; if(r)x++;else x--; if(d)y++;else y--; if(x==0||x==w-1)r=!r; if(y==0||y==h-1)d=!d; } for(int i=0;i<h;++i){ for(int j=0;j<w;++j){ std::cout<<(x==j&&y==i?'x':b[i]&(1<<j)?'o':' '); } std::cout<<'\n'; } } ``` Don't worry about the newlines, they are already removed from the count. Storing the rows as 64-Bit integer is okay since maximum width is 50. [Answer] ## Q, 94 Bytes (kx.com) `{[w;h;i;j;n]./[(1+h,w)#" ";+{z#y_+\0,-1 1@{x=2*_x%2}'&(-_-(z+y)%x)#x}.'(h,j,n;w,i,n);:;"*"]}.` Defines a lambda with parameters w (width), h (height), i (initial x), j (initial y), and n (number of movements). Lambda is delimited with `{}` Final `.` (after `}`) allows to use a sequence as argument. Standard function invocation is `f[arg;arg;..;arg]`, but we can also invoque as `f . sequence`. An integer sequence is `v v .. v`, so we can invoque as `f . w h i j n`. If we define `f:{..}.` we can invoque as `f w h i j n` (as required by the question) Solution uses 'K mode' of Q. K is the functional inner core of Q (Q is more readable, verbose and with a lot of additional libraries, but K is compact). To execute in K mode we must use scripts with k extension (vs q extension for q mode). Interactive interpreter starts in Q mode (-> q) prompt). We can load code from k script, and execute test directly on interactive interpreter (even in q mode, as shown in test). There is also a k mode at interactive interpreter level, but it's not worth in this case. **TEST** NOTE.- to avoid display cluttering, we assume f name associated to lambda (f:{..}.) ``` q)f 35 15 0 0 49 "* * " " * * * " " * * * " " * * * " " * * * " " * * *" " * * * " " * * * " " * * * " " * * * " " * * * " " * * * " " * * * * " " * * * * " " * * * * " " * * " q)f 35 15 4 2 49 " * " " * * " " * * * " " * * *" " * * * " " * * * " " * * * " " * * * " " * * * " " * * * " " * * * * " " * * * * " " * * * " " * * * * " " * * * * " " * * " ``` **EXPLANATION** We define a lambda for 1D movement that accepts args [max;init;n] (legal positions 0..max-1, initial pos init, n movements) and returns a sequence of positions (after computing rebounds). Later apply that lambda to y and x axes (with args [h;j;n] and [w;i;n] respectively). * Initially assume starting at 0 pos. We calculate number of rebounds to accomplish n movements, and generate a sequence with repeated increasing numbers (0 0 ...0; 1 1 .. 1; 2 2 .. 2; ..). * Each subsequence has w items, so there are rebounds just between subsequences. For each number determine if is even, and sustitutes even results by 1 and even results by -1. (1 1 .. 1; -1 -1 .. -1; 1 1 .. 1; ..) * We join subsequences and calculate accumulated sums starting with 0 -> 0 1 2 3 .. 35 34 33 32 .. 0 1 2 .. * finally we drop starting i movements and take exactly n movements Last, we define a (h x w) char matrix filled with blanks, and for each position (resulting of applying 1D lambda on y and x) we replace character with "\*" ]
[Question] [ I used to play the oboe, the instrument that is, for some reason, used to tune the orchestra to A440. Anyways, continuing on with my story, I was bad at it and quit. Write a program that generates a valid, full scale, 5 second, [WAV file](http://en.wikipedia.org/wiki/Waveform_audio_format) with a sample rate of 44.1 kHz that plays a 440 Hz ([+3/-1 Hz](https://music.stackexchange.com/questions/776/why-are-orchestras-tuned-differently)) tone. Your code is responsible for generating the structure of the file format; no external resources. +75 penalty if the tone does not approximate a sine wave (harmonic power must be less than 1% of the fundamental--a good polynomial approximation should be able to exceed 20 dB; I think parabolic is about -28 dB) [Answer] # GolfScript, 89 bytes This GolfScript program contains non-printable characters, so I'm providing it as a hex dump. On Unixish systems with the [xxd](http://www.tutorialspoint.com/unix_commands/xxd.htm) program installed, you can feed this hex dump to `xxd -r` to reconstruct the actual program. ``` 0000000: 2752 4946 4678 5d03 0057 4156 4566 6d74 'RIFFx]..WAVEfmt 0000010: 2010 0000 0001 0001 0044 ac00 0044 ac00 ........D...D.. 0000020: 0001 0008 0064 6174 6154 5d03 0027 2784 .....dataT]..''. 0000030: 8c94 9ba3 abb2 bac1 c7ce d4da e0e5 e9ee ................ 0000040: f2f5 f8fa fcfe ffff 272e 2d31 252b 2e7b ........'.-1%+.{ 0000050: 7e7d 252b 3232 3035 2a ~}%+2205* ``` The output of this program is a [220,545 byte 44.1 kHz 8-bit PCM WAV file](http://vyznev.net/misc/440.wav) that should play a 441 Hz tone for five seconds. The code itself simply consists of two literal single-quoted strings: the first one contains a minimal WAV header, while the second 25-byte string, representing a quarter of the sine wave, is cloned, reversed, joined to the original, cloned again, inverted, joined again and finally repeated 2205 times to produce the actual audio data. Ps. The output of the program above includes as extra trailing 0x0A byte (i.e. a line feed), which is technically not part of the WAV data. Since it lies past the end of the RIFF chunk, reasonable decoders should ignore it. (This could be fixed, at the cost of two extra bytes of code.) [Answer] # C, 204 bytes Won't win, but here it is anyway :-) ``` x;main(i){char *h="riff\xec\xda& wave\x86\x8d\x94@0 ! ! d\xcc \xa8x! \" 0 \x84\x81\x94\x81\xc8\xda& ";for(i=45;--i;)putchar(*h++-' ');for(;i++<220500;){x=(32767*sin(i/15.952));printf("%c%c",x,x>>8);}} ``` Needs to be compiled with the maths library, of course. Outputs a 5-second WAV file to `stdout` (16-bit samples, 44.1 kHz sampling), but this can easily be redirected to a file (e.g., `./a.out >foo.wav`) [Answer] ### R, 285 characters ``` S=44100;s=sin(0:(5*S-1)*pi*880/S);c=32767*s/max(abs(s));a=file("c.wav","wb");w=writeChar;W=function(x,z)writeBin(as.integer(x),a,z,e="little");w("RIFF",a,4,NULL);W(441036,4);w("WAVEfmt ",a,8,NULL);W(16,4);W(c(1,1),2);W(S*1:2,4);W(c(2,16),2);w("data",a,4,NULL);W(S*10,4);W(c,2);close(a) ``` Create a wav file called c.wav in the working directory. Indented: ``` S=44100 s=sin(0:(5*S-1)*pi*880/S) #Sin Wave c=32767*s/max(abs(s)) #Normalized a=file("c.wav","wb") #Open connection with empty wav file w=writeChar #Write characters W=function(x,z)writeBin(as.integer(x),a,z,e="little") #Write binary data w("RIFF",a,4,NULL) W(441036,4) w("WAVEfmt ",a,8,NULL) W(16,4) W(c(1,1),2) W(S*1:2,4) W(c(2,16),2) w("data",a,4,NULL) W(S*10,4) W(c,2) close(a) ``` ]
[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/7105/edit). Closed 1 year ago. [Improve this question](/posts/7105/edit) Pretty fun and simple challenge here given any input, create an acrostic poem for that input. you may use any word list of your choosing, and include any code you want to help "smarten" up your acrostic. ``` EXAMPLE Every Xylophone Always Makes Powerfully Low Emissions ``` the winner will be the code chosen by most up-votes, please up-vote for creativity, problem solving in making the acrostics make sense, and humor. most important of all, have fun! (please test your program using the following 3 words, and any other word or 2 you want to add - laughable ; codegolf ; loremipsum) [Answer] # Python 2.7 ``` import random import string import sys import re class Markov(object): def __init__(self,filename): with open(filename,'r') as f: self._words = f.read().split() self._wordCount = len(self._words) def getWordList(self,seedWord=None,pattern=r'^.*$'): if seedWord is not None: chainWords = [self._words[i+1] for i in range(self._wordCount-1)\ if seedWord == self._words[i].lower()] else: chainWords = self._words p = re.compile(pattern,re.IGNORECASE) return filter(p.match,chainWords) def getRandWord(self,seedWord=None,pattern=r'^.*$'): wordList = self.getWordList(seedWord,pattern) if len(wordList) == 0: return None return random.choice(self.getWordList(seedWord,pattern)) def main(): list = Markov('AStudyInScarlet.txt') for word in sys.argv[1:]: poem = [] for letter in word: if len(poem) == 0: nextWord = list.getRandWord(pattern=r'^[{0}.*$]'.format(letter)) else: nextWord = list.getRandWord(poem[-1],r'^{0}.*$'.format(letter)) if nextWord is None: nextWord = list.getRandWord(pattern=r'^{0}.*$'.format(letter)) nextWord = ''.join(ch for ch in nextWord if ch not in string.punctuation) poem.append(nextWord) print word print '='*len(word) for line in poem: print line print '' if __name__ == '__main__': main() ``` Loads a text file called ['AStudyInScarlet.txt'](https://raw.github.com/mfilmer/acrostic/master/AStudyInScarlet.txt). Only words used in that document will be candidates for incorporation into the final poem. (currently there are no words starting with `x` in this document, I will add some soon) This program tries to find words in the text file that follow the previous word in the poem. For example, if the acrostic word is 'pita' and so far the poem is "Private," a possible next word is "inquiry" as the two word phrase "private inquiry" is found in the text document. If no matching word pairs are found, any random word starting with the right letter is chosen. A word is chosen from a list of words that meet the desired qualifications. If a word shows up multiple times in the list of acceptable words, it is more likely to be chosen than one that does not. ## Usage Words to create poems from should be specified as command line arguments. One poem will be printed for each word specified on the command line. ### Example: ``` $ acrostic.py laughable codegolf loremipsum laughable ========= Looking a Union grievous his agitation be likely enough codegolf ======== couple of discoloured evident goes or late from loremipsum ========== learn of revenge engine me it proved smartest up my ``` [Answer] ## PHP ``` <?php $dict = array( 'a' => 'and', 'i' => 'if', 'o' => 'or', 'n' => 'not', 'l' => 'list' ); $funcs = get_defined_functions(); $word = rtrim(fgets(STDIN), "\n"); echo "\n"; foreach(str_split($word) as $char) foreach($dict + $funcs['internal'] as $func) if($func[0] == $char){ echo $func . "\n"; break; } ``` I admit it does not always make sense, but I am too lazy to look for a real word list, so I used PHP function names plus a couple of PHP reserved words. Examples: ``` laughable list and user_error get_class hash and bzopen list each codegolf class_exists or define each get_class or list func_num_args loremipsum list or restore_error_handler each method_exists if property_exists strlen user_error method_exists neurotic not each user_error restore_error_handler or trigger_error if class_exists diplomat define if property_exists list or method_exists and trigger_error ``` ]
[Question] [ In the game manufactoria, take in a binary number and output that number of red pieces. The catch? The board-size is only 7x7: Here's the manufactoria code for the problem: <http://pleasingfungus.com/Manufactoria/?ctm=Razors;Treat_the_input_as_a_binary_number_and_output_that_number_of_reds;b:r|brr:rrrr|brb:rrrrr|brbb:rrrrrrrrrrr|:|brrrr:rrrrrrrrrrrrrrrr|brbr:rrrrrrrrrr;7;3;0>; I have a solution, so it most definitely exists. EDIT: Least "total parts" wins (as reported by manufactoria engine) [Answer] # ~~21~~ ~~20~~ 19 parts! Ha! ![Screenshot of Manufactoria binarty-to-unary converter](https://i.stack.imgur.com/MBv4S.png) <http://pleasingfungus.com/Manufactoria/?lvl=32&code=q12:9f0;c12:8f3;g9:8f1;q9:9f4;b10:8f3;p10:9f0;r10:10f1;y11:9f0;g12:5f3;c12:6f3;r9:6f3;c9:7f2;r10:6f0;p10:7f2;q11:7f1;i12:7f7;p13:7f6;r13:6f0;c13:8f0;&ctm=Razors;Treat_the_input_as_a_binary_number_and_output_that_number_of_reds;b:r|brr:rrrr|brb:rrrrr|brbb:rrrrrrrrrrr|:|brrrr:rrrrrrrrrrrrrrrr|brbr:rrrrrrrrrr;7;3;0>; **Edit 2:** Back to the original design, but with two parts shaved off by creative reuse of conveyors. The 7 × 7 board really does start to feel confining — I've come up with several ways to shrink this further, if I only had one more row of vertical space... [Answer] # 30 26 24 22 Parts ![my entry 4](https://i.stack.imgur.com/0HC5h.png) Here is my entry, with 22 parts and a time of 4:16. This can be rearranged slightly to fit into a 5 wide by 7 tall space. It works by dividing the tape into three sections: the instructions (blue and red), the data (green), and a data terminator symbol (yellow). Each cycle of operation, it reads and replaces the first instruction. It then cycles the rest on the instructions to the back of the tape until it reaches the data. For each data symbol read, it adds two of them to the back of the tape. Once the data terminator is read, the instructions are once again at the front of the tape. It deletes the first instruction (which was just executed). It then adds one more data symbol to the end of the tape if the current instruction (read earlier) is blue. The yellow symbol is then re-appended. Once there are no more instructions, then all of the green symbols are converted to red and are output. ``` Example: input is BBR (110 or 6) These are the important steps in execution, in more detail than before BBR BBRY #yellow is appended YBBR #the instructions are cycled through, execution is on the left half YBBR #all of the greens (none yet) are duplicated BRG #Y and B are removed and a G appended BRGY #yellow is appended GYBR #instructions are cycled, execution is on left half YBRGG #Gs are duplicated RGGG #Y,B removed; G added RGGGY #Y added GGGYR #instructions are cycled, execution is on RIGHT half YRGGGGGG #Gs duplicated GGGGGG #YR removed, G NOT added GGGGGGY #Y added YRRRRRR #Greens are changed to red RRRRRR #output ``` [Answer] I managed 27 parts, but it would fit on a 5x7 grid: ![Razors solution](https://i.stack.imgur.com/3QibT.png) I'm using the double-and-add method. Start by putting a green to mark the start of the number and then a green or a yellow to determine whether the next digit pulled off is a zero or a one. Skip past the rest of the number and then double the number of reds currently in place. Finally add one more if the next piece is yellow. Repeat until the number goes to zero. [Answer] ## 17 13 parts I took some liberty with the specification. I'm going to define the input binary number to appear in little-endian order. You never say explicitly whether the input is little or big endian, but it appears you assume big endian because your tests assume that. I'm going to use these little-endian tests instead. <http://pleasingfungus.com/Manufactoria/?ctm=RazorsLE;Treat_the_input_as_a_little_endian_binary_number_and_output_that_num_of_red;b:r|rrb:rrrr|brb:rrrrr|bbrb:rrrrrrrrrrr|:|rrrrb:rrrrrrrrrrrrrrrr|rbrb:rrrrrrrrrr;7;3;0>; ![enter image description here](https://i.stack.imgur.com/EbGQZ.png) The code works by decrementing the binary number by 1 each loop and adding one yellow mark. At the end, it replaces the yellow with red and deletes the binary number (all blue at this point, representing -1). ]
[Question] [ ## Background This challenge is about [Convolutional neural networks](https://en.wikipedia.org/wiki/Convolutional_neural_network), and its two main building blocks, namely [Convolutional layer](https://en.wikipedia.org/wiki/Convolutional_neural_network#Convolutional_layer) and [Pooling layer](https://en.wikipedia.org/wiki/Convolutional_neural_network#Pooling_layer). For simplicity, we ignore the "depth" of the images and intermediate tensors, and just look at the width and height. ### Convolutional layer A convolutional layer works like a [kernel](https://en.wikipedia.org/wiki/Kernel_(image_processing)) in image processing. It is defined by kernel width and height, and kernel mode (min, mid, or max). A *min kernel* extracts values at positions where the entire kernel overlaps with the original image. For a *mid kernel*, the center of the kernel is placed over each pixel of the image; for a *max kernel*, all positions where any pixel overlaps with the kernel is considered. One pixel per positioning of the kernel is produced, resulting in a 2D array which can be smaller than (min), equal to (mid), or larger than (max) the input image. ``` Kernel (C is the center) ### #C# ### Image ***** ***** ***** ***** ***** Min kernel convolution (results in 3x3) ###** **### #C#** **#C# ###** ... **### ***** ***** ***** ***** ... ... ***** ***** ***** ***** ###** ... **### #C#** **#C# ###** **### Mid kernel convolution (results in 5x5) ### ### #C#*** ***#C# ###*** ***### ***** ... ***** ***** ***** ***** ***** ... ... ***** ***** ***** ***** ***** ... ***** ###*** ***### #C#*** ***#C# ### ### Max kernel convolution (results in 7x7) ### ### #C# #C# ###**** ****### ***** ***** ***** ... ***** ***** ***** ***** ***** ... ... ***** ***** ***** ***** ***** ... ***** ***** ***** ###**** ****### #C# #C# ### ### ``` If the input image has `IR` rows and `IC` columns, and the kernel has `KR` rows and `KC` columns, the output dimensions are defined as follows: * Min kernel: `IR - KR + 1` rows, `IC - KC + 1` columns; invalid if the resulting rows or columns are zero or negative * Mid kernel: `IR` rows, `IC` columns; error if either `KR` or `KC` is even * Max kernel: `IR + KR - 1` rows, `IC + KC - 1` columns ### Pooling layer A pooling layer is defined by window width and height, and the horizontal and vertical stride size (how many units to move at once in either direction). See the following illustration: ``` 3x3 window, 2x2 stride pooling on a 7x7 image ###**** **###** ****### ###**** **###** ****### ###**** **###** ****### ******* ******* ******* ******* ******* ******* ******* ******* ******* ******* ******* ******* ******* ******* ******* ******* ******* ******* ###**** **###** ****### ###**** **###** ****### ###**** **###** ****### ******* ******* ******* ******* ******* ******* ******* ******* ******* ******* ******* ******* ******* ******* ******* ******* ******* ******* ###**** **###** ****### ###**** **###** ****### ###**** **###** ****### ``` If the input image has `IR` rows and `IC` columns, and the pooling layer has the window of `WR`/`WC` rows/columns and `SH`/`SV` horizontal/vertical stride, the output dimensions are defined as follows: * Rows: `(IR - WR)/SV + 1`, error if `(IR - WR) % SV != 0` or `WR < SV` * Cols: `(IC - WC)/SH + 1`, error if `(IC - WC) % SH != 0` or `WC < SV` ### Stacking multiple layers The convolutional and pooling layers can be stacked in any arbitrary way, so that the output of the previous layer becomes the input of the next layer. The dimensions of the input image to the entire stack is provided, and the dimensions of each intermediate image should be calculated sequentially. A stack of layers is valid if no error occurs at any layer. The final output size does not matter, as long as it can be calculated without error. The following stack is valid: ``` Input image 25x25 1. Min Convolution 3x3 => Intermediate image 23x23 2. Pooling 3x3 with stride 2x2 => Intermediate image 11x11 3. Max Convolution 3x3 => Intermediate image 13x13 4. Max Convolution 4x4 => Intermediate image 16x16 5. Pooling 2x2 with stride 2x2 => Intermediate image 8x8 6. Min Convolution 5x5 => Intermediate image 4x4 7. Pooling 4x4 with stride 3x3 => Output image 1x1 ``` Taking any contiguous subsequence of the stack, starting with the respective (intermediate) image as the input, is also valid. (e.g. steps 2, 3, 4, 5 with input image `23x23`) Any of the following modifications to the 7-layer stack above will result in an invalid stack: * Replace step 2 with stride `4x4` or `2x4`: stride is larger than window in at least one dimension * Replace step 3 with `mid` convolution: image size becomes too small at step 7 * Replace step 4 with `mid` convolution: mid convolution with even kernel dimension is an error * Replace step 6 with kernel size `9x5` or larger: kernel does not fit in the image (`IR-KR+1` is zero or negative, which is an error) ## Challenge Given the input dimensions and the description of a stack of convolutional/pooling layers, determine if it is a valid configuration, i.e. not an error. The description of the stack can be taken in reasonable ways to represent * a list (sequence) of two kinds of layers * for a convolutional layer, the kernel size (width/height; two numbers) and mode (min/mid/max) * for a pooling layer, the window size (width/height) and stride (horizontal/vertical; four numbers in total) All numbers (kernel size, window size, stride) are guaranteed to be positive integers. You may output truthy/falsy by following your language's convention or selecting two distinct values for true/false respectively. Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins. [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), ~~138~~ ~~134~~ 118 bytes ``` lambda s,l:[s:=[(r:=(I-(m:=M-(M>1))*k)/S+m+0%(k%2+m**2))+(r%1+(S>k)and E)for I,k,S,*_ in zip(s,*L,(1,1))]for M,L in l] ``` [Try it online!](https://tio.run/##1ZVNa4NAEIbv/oqBEFh1Q@NXaQRzayGQnNKblWJ1QxbXD3ZNmuTPW1epDWntoYQGvezsvDPvsg/qFMdym2fWQ8GrjfdSsTB9i0MQmLm@cD0fcddDiwlKXW81Qau5oapaot6t9VSfjlEyNvVU00xV1REfGzpazxM1zGJ4VDc5hwVO8Bprr0AzONECCawtMTJwbRJIfYWXUmJBFYWCCPDAV6B@fBjBPmQ0bnZNxnQwmE6AvzJd1OwMDL5vYSsIzmrazk8Fy9j8XjDp720lG9s9ttKvz7ZpdbDT0ypN67U9ttPbSApyHQEnBQsjAqIkBZjwTsttHXMaE7AP9rXx/HjRgeIxr4/HHDQeq8WT0hiiPNvnbFfSPPuXL2w6EET27RD98hpNb4fogs99yychPCMMBD0RmB2cwf@kZ38DpASKIqeY5ICBhUfChRxnzSxzm5qSH92ubYPOK9UuX3CaleiZ70ibI4eIFKV7oT@FTNQF1Qc "Python 3.8 (pre-release) – Try It Online") Anonymous function that throws an error only if the given layers are in error. Takes a list of layers, where each layer is either: * `[mode, [KR,KC]]` where mode is `-1`,`0`,or`-1` corresponding to a max,mid, or min convolutional layer, or * `[2, [WR, WC], [SR, SC]]` where the 2 indicates a pooling layer I could save a few bytes if `(1,1)` could be added as a third element of convolutional layers, but I feel that's redundant information with the `mode` already differing it from pooling layers. ### Commented ``` f=\ lambda s,l:\ [ s:=[ # set s (size) to: ( r:= # an optimized calculation of the new size (r) along width (i=0) or height (i=1) # (need to set this to r because s is not updated until finishing this element) # [IR - KR + 1, IR, IR + KR - 1, (IR - WR)/SV + 1] # <--> (IR - m * KR)/(SV or 1) + m where m is -1 for max, 0 for mid, 1 for min, and 1 for pool (I- # (IR- (m:=M-(M>1)) # m # (need to convert pool(M=2) to 1, leave -1,0,1 unchanged) # maybe something with `M&2` might shorten *k)/ # * KR)/ S # SV +m # + m +0%( # error if k is even and m==0 (mid): k%2+m**2 # This sum gives 0 iff k is even and m==0 ) # 0 mod the sum throws ZeroDivisionError if the sum is 0 ) # otherwise it is equal to 0 and does not affect the sum +( r%1+(S>k) # True if r is not an integer or the stride size is greater than the window size and E # throw NameError (E is not defined) if the above is true ) # otherwise, False equals 0 in sums, so this does not affect the sum for I,k,S,*_ in zip(s,*L,(1,1)) # repeat for rows and columns # The (1,1) provides the default value of S ] for M,L in l # repeat for each layer ] ``` ### Named function + traditional for-loop approach for the same bytecount: ``` def f(s,l): for M,L in l:s=[(r:=(I-(m:=M-(M>1))*k)/S+m+0%(k%2+m**2))+(r%1+(S>k)and E)for I,k,S,*_ in zip(s,*L,(1,1))] ``` ### Ungolfed ``` def f(size, layers): while layers: [mode, *layer] = layers.pop(0) if mode < 2: # convolutional, mostly eq to pooling with S=(1,1) layer += [(1,1)] kernel, stride = layer m = 1 if mode > 1 else mode for i in 0,1: size[i] = (size[i] - m*kernel[i])/stride[i] + m # check for fractions if size[i] % 1: return False # can't have even kernel dimension on a mid window if m==0 and kernel[i]%2==0: return False # stride can't be larger than kernel if stride[i] > kernel[i]: return False return True ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 45 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` sεÐgiĀ«]vyн³Dp-Nè©*-yθ/®+ÐïÊyнÈ®_*y`‹«à~i0q]1 ``` Inspired by [*@fireflame241*'s ungolfed Python answer](https://codegolf.stackexchange.com/a/206458/52210), so make sure to upvote him! Three loose inputs: 1. The window dimensions `[w,h]` 2. List of layers, where `[[r,c]]` is a convolutional layer and `[[r,c],[r,c]]` is a pooling layer. 3. List of kernel modes, where `-1` is max; `0` is mid; `1` is min; and `2` is a pooling layer. [Try it online](https://tio.run/##yy9OTMpM/f@/@NzWwxPSM480HFodW1Z5Ye@hzS4Fun6HVxxaqaVbeW6H/qF12ocnHF5/uAsod7jj0Lp4rcqERw07D60@vKAu06Aw1vD//2gjUx0j01iu6OhoYx3j2FgdBQhDJ9pIxwjBBTNMdEwgDJAUkgJTHVOEAh2IeqCJhjpGOrqGIGSkA8SxAA). (No test suite due to the `q`, but I've manually checked the four falsey examples.) **Explanation:** ``` s # Swap to get the first two (implicit) inputs onto the stack, # with the second input at the top ε # Map over each layer: Ð # Triplicate the layer gi # If it's length is 1 (thus a convolutional layer): Ā # Truthify both integers, so we have a pair of 1s: [1,1] « # Merge it to the layer ] # Close the if-statement and map v # Loop over each layer `y`, consisting of two pairs [kernel,stride]: yн # Get the first pair (the kernel) ³ # Push the third input-list of modes Dp- # Transform the 2s into 1s (by checking for prime, and subtracting) Nè # Get the mode at the current loop-index © # Store it in variable `®` (without popping) * # Multiply this mode to the kernel-pair - # Subtract each from the dimensions-pair yθ # Get the last pair (the stride) / # Divide the dimension-pair by the stride-pair ®+ # And add the modified mode `®` to each Ð # Triplicate the modified dimensions-pair ï # Cast the values in the top copy to integers Ê # Check if the top two pairs are NOT equal # (1 if the dimension-pair contains decimal values; 0 if integers) yн # Push the kernel again È # Check for both values if they're even (1 if even; 0 if odd) ®_ # Check if `®` is 0 (1 if 0; 0 if not) * # Multiply the checks y` # Push the kernel-pair and stride-pair separated to the stack ‹ # Check if [kernel-row < stride-row, kernel-column < stride-column] « # Merge the pairs of checks together à # Check of any are truthy of this quartet by taking the maximum ~ # Check if either is truthy by taking the bitwise-OR i # If this is truthy: 0 # Push a 0 q # And stop the program # (after which this 0 is output implicitly as result) ] # Close the if-statement and loop 1 # And push a 1 # (which will be output implicitly if we didn't encountered the `q`) ``` [Answer] # [J](http://jsoftware.com/), 84 bytes Takes in a list of layers; `mode x y` for convolution, with `_1 0 1` for `min mid max`, and a 2x2 matrix `wx wy ,: sx sy` for pooling, and `x y` for the initial image. Returns 0 if it is a valid description, 1 otherwise. ``` _ e.&>(1(+_*[><.)@+(-{.)%(]*>:)/@])`((+_*1>])@+}.(]-~*+_*(2|[)+:|@]){.)@.(]3=#)~&.>/ ``` [Try it online!](https://tio.run/##pZBBa8JAEIXv/RWPanUmMWuy2S240SVU6Ek8eJUQD0awrT3YHoRa/3o6JrdCqa0MM8y@9/hY5qm@Vf0NJg59DBDDSUcK08XssS5RqZ6nhMIyWPqx4jyk6EPxHRWBdzzMC17R2Ux8Id6noiI6BfImfVxy6I4SkHguejrp8Kmn/LDmegMiDd01MEiRclYmsLBZI0qfi7NEXCNTEq0jS@uUragttOWbq2jmGw3zBwXt8Pa@364r6IP5Ez/@7bcNP3XYbdcXguPLztCAzc/g0X/v24DvHZ6r/Wv1gtHBfgE "J – Try It Online") ### How it works ``` (…)`(…)@.(]3=#)~&.>/ ``` We fold the list from the right (where initially the `25 25` stands), and based on the left length (3 for convolution, 2 for pooling), we choose from two functions. Whenever we encounter an error, we set to row or column dimension to infinity. For convolution with example `_1 3 3` (min 3x3): ``` ((+_*1>])@+}.(]-~*+_*(2|[)+:|@]){.) }.( ){. split into 3 3 and _1 as arguments |@] mode != 0? 2|[ 3 3 even? +: not-or, so 1 iff mode = 0 and dimension even _* if this^ returns 1, convert it to infinity *+ add to this dim * mode (_3 _3) ]-~ subtract the mode (_2 _2) + add to the image dimension (23 23) (+_*1>]) if the dimensions are less than 1, add infinity ``` For pooling, with for example `3 3,:2 2` on the left side, `23 23` on the right side: ``` (1(+_*[><.)@+(-{.)%(]*>:)/@]) (]*>:)/@] multiple stride with (window greater/equal stride?) (-{.)% (image - window)% mstride, is infinity iff mstride is 0 1 + add one (+_*[><.) add infinity if flooring a dimensions changes it ``` An the end, after applying each layer: ``` _ e.&> unbox and check if at least one dimension is infinity ``` ]
[Question] [ Given a positive integer, write it as the sum of numbers, where each of them is in \$\{kt|k\in{1,9,81},t\in{1,2,3,...,64}\}\$. How many numbers at least are used? Shortest code win. Samples: ``` Input Output Method 1 1 1 2 1 2 64 1 64 65 2 64+1 72 1 72 343 2 342+1 576 1 576 577 2 576+1 5184 1 5184 46656 9 5184+5184+5184+5184+5184+5184+5184+5184+5184 5274 2 5184+90 ``` [![enter image description here](https://i.stack.imgur.com/OnHK6.png)](https://i.stack.imgur.com/OnHK6.png) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 17 bytes ``` 64R×9;Ɗ⁺ff€¥@ŒṗẈṂ ``` [Try it online!](https://tio.run/##ASsA1P9qZWxsef//NjRSw5c5O8aK4oG6ZmbigqzCpUDFkuG5l@G6iOG5gv///zU4 "Jelly – Try It Online") -1 thanks to [Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan). Explanation (you can't test for inputs larger than `58` over TIO): ``` 64R×9;Ɗ⁺ff€¥@ŒṗẈṂ Arguments: x 64R [1..64] ×9;Ɗ Multiply by 9, prepend to original list ⁺ Do the above once more Œṗ Positive integer partitions of x ¥@ Call with reversed arguments (x = partitions, y = flattened outer product) f€ For each partition in x, keep the elements that are in y f Keep the elements of x that have remained intact after the above Ẉ Lengths of the remaining partitions Ṃ Minimum ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 47 bytes ``` {+($_,(*X-(1,9,81 X*^65)).grep(*>=0).min...^0)} ``` [Try it online!](https://tio.run/##HYtNCsIwEIX3nmIWIpk4hsYkkxSp5@iq4qIRwdqSrop49pi4eB@P97OM6cV52uAQocufo9jfSMj@JDS1FDT0cmCHqB5pXIS8dg2q6flWSg0NfvNlt943iOWEEOcEmuBMwLbIEfjijTUEznOFL9ChlJbZcd2FivYfm/wD "Perl 6 – Try It Online") A greedy algorithm seems to work. [Answer] # JavaScript (ES6), ~~72~~ ~~66~~ ~~57~~ 56 bytes *Saved 1 byte thanks to @nwellnhof* ``` f=n=>n&&1+f(n<5184?n>64&&n%(n<576?9:n>719?81:72):n-5184) ``` [Try it online!](https://tio.run/##jZDRCoMgFEDf9xW@TJRood20YtW3RKuxEdexxn7fKcGw3MN8EOQczsV779/9Mjxvj1eK5jJaOzXYtEipSCaG50KU0GGrgFI8@rdWXVVjq0XVlaLWkteYeonbweBi5vE0myubmCDucE6yjAjCBD9ssdxguccKQqwg4sWXS8@TaICWYUFHE3LIg0IOMk64vwYJ94oFHTSc8KPhVhM0/KJ2BihVqNWoViP58@L2Aw "JavaScript (Node.js) – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~30~~ 27 bytes ``` ŽK≠‰`91vDy64*›i1sy9*%]64/îO ``` [Try it online!](https://tio.run/##ATQAy/9vc2FiaWX//8W9S@KJoOKAsGA5MXZEeTY0KuKAumkxc3k5KiVdNjQvw65P/8Ov/zQ2NjU2 "05AB1E – Try It Online") or [verify all test cases](https://tio.run/##yy9OTMpM/a9cVvn/6F7vR50LHjVsSLA0LHOpNDPRetSwK9OwuNJSS7W21sxE//A6//@H1@v8N1AwVDBSMDNRMDNVMDdSMDYxVjA1NwNicwVTQwsTEGGqYGpkbqJgYmZmagYA "05AB1E – Try It Online") *-3 bytes thanks to Kevin Cruijssen* This is my first 05AB1E submission, so I am sure that this can be optimized. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 66 bytes ``` Min[Length/@IntegerPartitions[#,All,Union[#,9#,81#]&@Range@64,#]]& ``` [Try it online!](https://tio.run/##DYrLCsIwEEV/ZSDQ1Uhpm0ddKHEpKBTBVegiSNoG2hHq7MRvj7M795y7RV7SFjm/YpngVO6Zwi3RzEvtr8RpTvsQd86c3/QJCi/rik@SIXxU2DdqrPwj0py81ajGsSrDnomDgsMZpiAGKqg9fBuEFkFOYA2CE@50h2CcFeOcUNNL1NYaMaZ1@lf@ "Wolfram Language (Mathematica) – Try It Online") ]
[Question] [ # Introduction A childhood game designed to help children learn to count in french in Canadian schools is played as follows: * Students go around the room counting up to 11 * A number greater than 11 cannot be said * A student can say either 1, 2, or 3 numbers * If a student says the number 11 then they are removed from the next round and play begins again at 1 * The game continues until there is 1 player remaining Consider the simple example: ``` Player1 | Player2 01 | 02 | 03 | | 04 | 05 | 06 07 | 08 | | 09 10 | | 11 Player 1 wins ``` # The rules * Design a program which takes in an integer greater than or equal to 2 and less than or equal to 99 (for formatting reasons) and outputs the game played by this number of bots * Play will begin with bot1 and increase to the highest number bot * Play will cycle back to the beginning when the final bot is reached * Bots will randomly output the next 1, 2, or 3 numbers **UNLESS** + Outputting 2 or 3 numbers will cause them to lose on that turn. - If the count is 8 when it reaches a bot, it should only decide between `9` and `10` + Outputting 2 or 3 numbers will cause them to go over 11 * Output numbers and bot numbers should be formatted to take two characters (i.e. you can format numbers to be `01`, `_1`, or whitespace, whatever makes you happy) * Each column should be 2 characters wide separated by `|` as well as a `|` at the beginning and ends of rows * Once a bot is out the remainder of their column should be filled by `xx` * When there is only one bot remaining he is the winner * The program will announce which bot was the winner in the form of `Bot #N is the winner` * This is code-golf so shortest byte count wins # Formatting examples ``` |01|02|03| |01| | | |02| | | |03| | | | |04| | | | |05| | | |06| |07| | | | |08| | | |09| | | |10| | | | |11| |01| |xx| |02| |xx| |03| |xx| | |04|xx| | |05|xx| |06| |xx| | |07|xx| |08| |xx| | |09|xx| | |10|xx| |11| |xx| Bot #2 is the winner ``` **Option** The outputs can get long so you are permitted to output only the final number of the bots turn for example the above output becomes instead: ``` |01|02|03| |03| | | | |04| | | | |06| |07| | | | |10| | | | |11| |03| |xx| | |05|xx| |06| |xx| | |07|xx| |08| |xx| | |10|xx| |11| |xx| Bot #2 is the winner ``` With 5 bots: ``` |01|02|03|04|05| |01| | | | | | |04| | | | | | |05| | | | | | |07| | | | | | |10| |11| | | | | |xx|01| | | | |xx| |03| | | |xx| | |06| | |xx| | | |09| |xx|10| | | | |xx| |11| | | |xx| |xx|02| | |xx| |xx| |03| |xx|05|xx| | | |xx| |xx|07| | |xx| |xx| |08| |xx|10|xx| | | |xx| |xx|11| | |xx| |xx|xx|01| |xx|03|xx|xx| | |xx| |xx|xx|04| |xx|07|xx|xx| | |xx| |xx|xx|08| |xx|10|xx|xx| | |xx| |xx|xx|11| Bot #2 is the winner ``` With 10 players: ``` |01|02|03|04|05|06|07|08|09|10| |01| | | | | | | | | | | |04| | | | | | | | | | | |05| | | | | | | | | | | |08| | | | | | | | | | | |09| | | | | | | | | | | |10| | | | | | | | | | | |11| | | | | | | | | | |xx|02| | | | | | | | | |xx| |04| | | | | | | | |xx| | |07| |09| | | | | |xx| | | | | |10| | | | |xx| | | | | | |11| | | |xx| | | | | | |xx|01| | |xx| | | | | | |xx| |02| |xx| | | | | | |xx| | |03|xx| | | | | | |xx| | | |xx|04| | | | | |xx| | | |xx| |07| | | | |xx| | | |xx| | |08| |09| |xx| | | |xx| | | | | |10|xx| | | |xx| | | | | | |xx|11| | |xx| | | | | | |xx|xx|02| |xx| | | | | | |xx|xx| |03|xx| | | | | | |xx|xx| | |xx|05| | | | | |xx|xx| | |xx| |08| | | | |xx|xx| | |xx| | |09| |10| |xx|xx| | |xx| | | | | |11|xx|xx| | |xx| | | | | |xx|xx|xx|03| |xx| | | | | |xx|xx|xx| |05|xx| | | | | |xx|xx|xx| | |xx|08| | | | |xx|xx|xx| | |xx| |10| | | |xx|xx|xx| | |xx| | |11| |01|xx|xx|xx| | |xx| | |xx| | |xx|xx|xx|03| |xx| | |xx| | |xx|xx|xx| |06|xx| | |xx| | |xx|xx|xx| | |xx|08| |xx| | |xx|xx|xx| | |xx| |09|xx| |10|xx|xx|xx| | |xx| | |xx| | |xx|xx|xx|11| |xx| | |xx| | |xx|xx|xx|xx|03|xx| | |xx| | |xx|xx|xx|xx| |xx|05| |xx| | |xx|xx|xx|xx| |xx| |06|xx| |08|xx|xx|xx|xx| |xx| | |xx| | |xx|xx|xx|xx|09|xx| | |xx| | |xx|xx|xx|xx| |xx|10| |xx| | |xx|xx|xx|xx| |xx| |11|xx| |02|xx|xx|xx|xx| |xx| |xx|xx| | |xx|xx|xx|xx|05|xx| |xx|xx| | |xx|xx|xx|xx| |xx|08|xx|xx| |09|xx|xx|xx|xx| |xx| |xx|xx| | |xx|xx|xx|xx|10|xx| |xx|xx| | |xx|xx|xx|xx| |xx|11|xx|xx| |01|xx|xx|xx|xx| |xx|xx|xx|xx| | |xx|xx|xx|xx|04|xx|xx|xx|xx| |07|xx|xx|xx|xx| |xx|xx|xx|xx| | |xx|xx|xx|xx|10|xx|xx|xx|xx| |11|xx|xx|xx|xx| |xx|xx|xx|xx| Bot #6 is the winner ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~295~~ ~~291~~ 290 bytes ``` from random import* n=input() r=range(n) p=r[:] b=[1]*n;s='%02d' def P(l):print'|%s|'%'|'.join(l) P(s%-~j for j in r) x=0 while sum(b)>1:i=p.pop(0);g=choice(range(x+1,11)[:3]or[11]);P([2*'x '[b[j]],s%g][j==i]for j in r);x=g%11;b[i]=g<11;p+=[i]*b[i] print'Bot #%d is the winner'%-~b.index(1) ``` [Try it online!](https://tio.run/##TY6xboMwFEV3f4WlyrJNUoTpBn0d@gXslocSHHgo2JZxFCqh/jp1laXTvTp3ODd8p8m7@jiu0S80frkhBy7Bx1QQB@jCPQlJIuRptMJJEiDqxpAetDKFa1fgrKoHTgZ7pZ24ySZEdInvbN054zsvZ48uc9KJlb3@zPTqI50pOhol2aAijwlvlq73RfTyQzUIoQw@iEq2I1wmjxcrnvLtpM5KSd28GR@1Uka2ndB1wTfKda9nY84rG42eAdD8s7QbjEypttdoYHzPLZwg9@IPkOfdT5/oCxsorjRNlj7QORt5/tuX6Aa7CSWPo65@AQ "Python 2 – Try It Online") * -1 byte, thanks to Kevin Cruijssen [Answer] # [JavaScript (Node.js)](https://nodejs.org), 269 245 240 233 232 231 bytes * thanks to @Kevin Cruijssen for reducing by 1 byte ``` N=>{for(S=d=[],D=n=i=0;D<N-1;){for(R=n>8?1:(n>7?2:3)*Math.random()+1|0;R--;)S+="|"+[...Array(N)].map((x,I)=>i^I?d[I]?"xx":" ":++n>9?n:"0"+n).join`|`+`| ` for(n>10&&(d[i]=++D,n=0);d[i=++i%N];);}return S+`Bot #${i+1} is the winner`} ``` [Try it online!](https://tio.run/##VY1BT4MwGEDv/Iqm6tLPQgPuoFIL0XDhIIdxJBjIANdl@7oUVMzgt@P05vG9d3j7@rPut1afBg9N0y6dWjIVnTtjWa4aVZRuolBp5cvkKfMCCX9pozB6iIOQYXQf34VruH2th52wNTbmyIAHky83nich54pOlBdCiGdr62@WQSmO9Ymx0U1BRfotjZsiLWM6jjSkhNCQc4weYwypTzmC2BuN1VTxanIq5/eNUeCvVqwpdKk4T1xUPsgLXUDfZKUEOdt2@LBIcl69mIFcXZ81D2aiezLsWvKlEVtbzcvWYG8OrTiYd9axNYDz3wQ@wPID "JavaScript (Node.js) – Try It Online") [Answer] # [C (clang)](http://clang.llvm.org/), ~~288~~ ~~283~~ ~~282~~ 266 bytes ``` f(n){int i,j,p[99]={},m,k,x;for(i=j=k=0;k<n;printf("|%02d",k++));for(puts("|"),m=n;x=i>7?10-i:3,i=x?clock()%x-~i:0,m>1;){for(k=~0;++k<n;printf(p[k]?"|xx":k-j?"| ":"|%02d",i?i:11));puts("|"),!i&&m--*p[j]++;do j++,j%=n;while(p[j]);}printf("Bot #%d is the winner",j);} ``` [Try it online!](https://tio.run/##TVHLboMwELz7K7ZURHZsBLSHKjgOUn8jzYHyaBYHgwhRkEjy69TQps3N6xnPzI5TLz0k5mscC2rYgKYDFKVotqvVTg1XUQktelnULUVVKq0CqddGNq0lFtS5uMFL5gjNOWMzqTl1R3vtMFEpI3uFm7c4DDyMXgWqPk4Pdaopc3vvhlEgqk0o2TC90@oWSM4ftJut3sXOpe@dSHulPQE40d0QY4zC0Hr@@z3hYlF53rLZljvOZVZDybkoXRvjvMdDTieAyes9@nvdwbObAR6h2@dwRmPy1hGlpYy@/2nRtM5ykshPimwgkDzsItu8O7UGkr@FknkhSa6EkKnDKkFDGQzEX5IftS4/djOEksx1goJAAsIawlCibdCy4Z7OBvM24GYfxhH2Q2AKwSb5pU9IQcPADr8hJtfxGw "C (clang) – Try It Online") Bots are 0 indexed. Following will do 1-indexed for+2 bytes ``` f(n){int i,j,p[99]={},m,k,x;for(i=j=k=0;k<n;printf("|%02d",++k));for(puts("|"),m=n;x=i>7?10-i:3,i=x?clock()%x-~i:0,m>1;){for(k=~0;++k<n;printf(p[k]?"|xx":k-j?"| ":"|%02d",i?i:11));puts("|"),!i&&m--*p[j]++;do j++,j%=n;while(p[j]);}printf("Bot #%d is the winner",j+1);} ``` [Answer] # VBA (Excel), 551 bytes `CellA1` as input and output in immediate window. ``` Sub k() Z = [A1] - 1 ReDim p(Z) For b = 0 To Z p(b) = " " Next Do Until i = Z Do Until a >= 11 Randomize a = a + CInt(IIf(a > 8, 1, IIf(a > 7, 1 + Rnd, 1 + (Rnd * 2)))) Do Until p(d) = a p(y) = IIf(p(y) = "xx", p(y), a) d = y y = IIf(y = Z, 0, y + 1) Loop For b = 0 To Z c = c & IIf(p(b) < 10, 0 & p(b), p(b)) & "|" g = IIf(p(b) = " ", b, g) p(b) = IIf(p(b) = "xx", "xx", " ") Next Debug.Print "|" & c Application.Wait Now + #12:00:01 AM# DoEvents c = "" Loop p(d) = "xx" i = i + 1 a = 0 Loop Debug.Print "Bot #" & g + 1 & " is the winner." End Sub ``` ]
[Question] [ It's annoying when you have to search for a language homepage, get its link, and add it to your SE comment/answer, right? Let's write a script to do that for you! # Challenge For each language name (intentional or not) in the input, replace it with the markdown link to the language home page, defined by TIO. # Rules * (important) You can only connect to `https://tio.run`. * Use the language list on TIO at the time your program is run. * The input is a string. Assume no newline (because multiline messages can't have markdown anyway). Unicode characters may be inside the string because they can exist in chat messages ([example](https://chat.stackexchange.com/transcript/message/42577306#42577306)). * The input is valid markdown, but it is unlikely that this is related to the challenge. * You can assume there is no link inside the input. (Whoops, I missed this when the challenge was in the sandbox, thanks [mercator](https://codegolf.stackexchange.com/users/76878) for pointing that out. As far as I can see this should not invalidate any existing answers) * Case sensitive or insensitive, whatever you choose. * Only word breaks (not both adjacent to an English letter) are considered. (for example, `matlab` should not be converted to `[matl](https://github.com/lmendo/MATL)ab`, `47` should be converted to `[4](https://github.com/urielieli/py-four)[7](https://esolangs.org/wiki/7)`) > > Note: It's too hard to define what's a "character" in Unicode, so your program can detect a word break or not if one of the two surrounding characters are not printable ASCII. > > > * Only use markdown `[...](...)`, not HTML link `<a href="...">...</a>` because the latter doesn't work in chat. * Markdown components (`*` / `_` for italic, `**` for bold, `---` for strikethrough (in chat)) in messages should not matter, because AFAIK there are no languages with such names on TIO. * Use the language name (`Wolfram Language (Mathematica)`), not language ID. * No overlapping replacement. * In case there are multiple output, pick whichever. See example below. * Although by default chat markdown doesn't allow links in code blocks, for simplicity I would just assume that they don't need to be treated specially. # Winning criteria [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). # Test cases ``` Input -> Output matlab -> matlab 47 -> [4](https://github.com/urielieli/py-four)[7](https://esolangs.org/wiki/7) /// -> [///](https://esolangs.org/wiki////) //// -> [///](https://esolangs.org/wiki////)/ or /[///](https://esolangs.org/wiki////) ////// -> [///](https://esolangs.org/wiki////)[///](https://esolangs.org/wiki////) or //[///](https://esolangs.org/wiki////)/ Uṅıċȯḋė -> Uṅıċȯḋė ``` # More test cases (suggested by [Adám](https://codegolf.meta.stackexchange.com/users/43319/ad%c3%a1m). Any replacement is fine as long as they don't overlap (valid markdown source)) ``` \/// S.I.L.O.S.I.L.O.S Del|m|t Del|m|tcl ``` [Answer] # Javascript (ES6) + jQuery, 247 bytes ``` s=>c=>$.getJSON('https://tio.run/static/645a9fe4c61fc9b426252b2299b11744-languages.json',data=>{for(l of Object.values(data))s=s.replace(eval(`/([^a-zA-Z]|^)${l.name.replace(/[\\/+.|()]/g,"\\$&")}(?![a-zA-Z])/g`),`$1[${l.name}](${l.link})`);c(s)}) ``` ## Explanation (less golfed) ``` s=>c=> // Load TIO languages using jQuery $.getJSON('https://tio.run/static/645a9fe4c61fc9b426252b2299b11744-languages.json',data=>{ // For every language for(l of Object.values(data)) { // Construct a regex that matches the language name var regex = eval(`/([^a-zA-Z]|^)${l.name.replace(/[\\/+.|()]/g,"\\$&")}(?![a-zA-Z])/g` // Replace all occurences of the language name with the language name and link s=s.replace(regex),`$1[${l.name}](${l.link})`) } // Return using callback c(s); }); ``` ``` f= s=>c=>$.getJSON('https://tio.run/static/645a9fe4c61fc9b426252b2299b11744-languages.json',data=>{for(l of Object.values(data))s=s.replace(eval(`/([^a-zA-Z]|^)${l.name.replace(/[\\/+.|()]/g,"\\$&")}(?![a-zA-Z])/g`),`$1[${l.name}](${l.link})`);c(s)}) f("47")(console.log); f("///")(console.log); f("////")(console.log); f("//////")(console.log); f("Uṅıċȯḋė")(console.log); f("\///")(console.log); f("S.I.L.O.S.I.L.O.S")(console.log); f("Del|m|t")(console.log); f("Del|m|tcl")(console.log); ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> ``` [Answer] # Python + Selenium, 496 bytes I decided using the front end of the website would be cooler. And since nearly everything is loaded via JavaScript, Selenium was my best bet. ``` from selenium import webdriver from re import* d=webdriver.Chrome("a.exe") d.get("https://tio.run/#") t={e.text.lower():e.get_attribute("data-id")for e in d.find_elements_by_xpath('//*[@id="results"]/div')} def q(reg):s=reg.group(0);d.get("https://tio.run/#"+t[s.lower()]);d.find_element_by_id("permalink").click();a=d.find_elements_by_tag_name("textarea")[4].get_attribute('value');return"["+s+"]("+search(': (ht.*)\n',a).group(1)+")" print(sub('|'.join(map(escape,t.keys())),q,input(),flags=I)) ``` # Pseudo-Ungolfed Version I thought providing an in-between would be useful for understanding. ``` from selenium import webdriver import re import itertools input = lambda:"47////////" s = input() driver = webdriver.Chrome("chromedriver.exe") driver.get("https://tio.run/#") temp = {ele.text.lower():ele.get_attribute("data-id")for ele in driver.find_element_by_id("results").find_elements_by_tag_name("div")} def abc(reg): s=reg.group(0) driver.get("https://tio.run/#"+temp[s.lower()]) ele = driver.find_element_by_id("permalink").click() a = driver.find_elements_by_tag_name("textarea")[4].get_attribute('value') return"["+s+"]("+re.search(': (ht.*)\n',a).group(1)+")" bob = re.sub('|'.join(map(re.escape,temp.keys())),abc,s,flags=re.I) print(bob) ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~291~~ 301 bytes ``` import json,urllib s=raw_input().decode('u8');m=json.loads(urllib.urlopen('https://tio.run/languages.json').read());n=0 while n<len(s): for l in sorted(m,None,lambda x:m[x]['name'],1): L=m[l]['name'];r='[%s](%s)'%(L,m[l]['link']) if s.find(L,n)==n:s=s[:n]+r+s[n+len(L):];n+=len(r)-1 n+=1 print s ``` Doesn't strictly speaking follow the rules, since it doesn't consider word breaks. It always takes the longest possible match first. ]
[Question] [ **Background** Here you have another work-inspired challenge, but from my wife's work in this case. Imagine you have a service that returns the list of nodes in a tree structure (much like the files and folders in a file system), but in no particular order. For every node you get a tuple with its name and the name of its parent. So if you get `[["C","B"],["D","C"],["A",""],["B","A"]]` (format: `[NodeName,ParentName]`), you could rebuild the tree structure and get a leaf with the path `/A/B/C/D` (`A` has no parent, then it is at the top level, then `B` is a child of `A`, `C` is a child of `B` and `D` is a child of `C`). You could also get `[["C","B"],["D","C"],["A",""],["B","A"],["E","B"]]`, so the rebuilt tree would contain two leaves: one with the path `/A/B/C/D` (the same as in the previous example) and a new one with the path `/A/B/E` as the node `E` has `B` as its parent. Note that the nodes in the list are not duplicated (the leaves `D` and `E` have parts of their paths coincident but the common parts do not appear twice in the original list of nodes). **Challenge** Given a list of nodes as described above, rebuild the tree and output the paths for all the leaves in the tree structure, in no particular order as long as you return them all. **Rules** * The input will be a list of tuples with two elements each: the name of the current node and the name of its parent. If you don't like strings you can use arrays of chars. You can choose the order of the elements in the tuple (the node name first or the parent name first). * The output format can be: a list of paths as strings like `["/A/B/C/D","/A/B/E"]` for the second example; a list of path nodes for each leaf, as in `[["A","B","C","D"],["A","B","E"]]` for the same example; or even a dictionary (something like `["A":["B":["E":[],"C":["D":[]]]]]`). Or you can just print the list of paths to STDOUT. * There won't be nodes without a parent given explicitly. * The node names will be strings of alphanumeric ASCII characters `[a-zA-Z0-9]` of any length. So you can use any other printable ASCII character as separator if you decide to print or return the paths as strings. * There won't be duplicated tuples in the list. * There won't be cyclic paths in the list of nodes. * The node names are unique and case sensitive. Nodes `aa` and `AA` are not the same node. * If you get an empty list of nodes, return an empty list/dictionary of leaves (or just print nothing). **Test cases** ``` In: [["C","B"],["D","C"],["A",""],["B","A"],["E","B"]] Out: /A/B/C/D /A/B/E Alt: [["A","B","C","D"],["A","B","E"]] Alt: ["A":["B":["E":[],"C":["D":[]]]]] In: [["D3","D8"],["D5","d1"],["s2","S1"],["S1",""],["d1",""],["D8","D5"],["F4","s2"],["F7","S1"],["e3","D5"]] Out: /d1/D5/D8/D3 /d1/D5/e3 /S1/s2/F4 /S1/F7 Alt: [["d1","D5","D8","D3"],["d1","D5","e3"],["S1","s2","F4"],["S1","F7"]] Alt: ["d1":["D5":["e3":[],"D8":["D3":[]]]],"S1":["F7":[],"s2":["F4":[]]]] In: [["Top",""]] Out: /Top Alt: [["Top"]] Alt: ["Top":[]] In: [] Out: Alt: [] Alt: [] ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so may the shortest code for each language win! --- This comes from [the sandbox](https://codegolf.meta.stackexchange.com/a/14613/70347) (for those who can see deleted posts). [Answer] # [Haskell](https://www.haskell.org/), 53 bytes ``` (""#) e[]=[[]] e a=a p#l=[s:c|(q,s)<-l,p==q,c<-e$s#l] ``` [Try it online!](https://tio.run/##HcpBDsIgEEDRPaeYDF1AMlzAdBat9RTIghDQRmyouPTsInbz8xb/7usj5twSX5tClFpE69ha50QEz14UmdnWU/ionaoeTabCvFMYTRyqzK49/boBQ3mt2xsGSGAVzkh4Rk2ql3A51DEdmLrmQ//tgtq1b0jZ32ozoZQf "Haskell – Try It Online") Takes input as a pair `(parent,child)` because I find that order easier to read. Output is the "list of lists of strings" style. The `#` operator takes a parent name on the left and the list of nodes on the right. First it iterates through the nodes that have that parent. Then it recurs, looking for that node's children and prepending the node to the list. If it has no children `e` will put in an empty list to terminate the sublist (otherwise nothing would ever get added to the output). This code assumes that node names are unique which I thought must be the case because if there were two nodes like `/foo/bar/baz` and `/bar/baz` it would be impossible to tell where to put "baz". [Answer] ## JavaScript (ES6), 59 bytes ``` a=>a.map(([c,p])=>g(p)[c]=g(c),g=s=>g[s]||(g[s]={}))&&g[''] ``` Returns `undefined` if there are no top-level nodes. (+4 bytes to return an empty dictionary.) [Answer] # Pyth, 21 bytes ``` J.dQVf!}T_JJNWN=N@JNN ``` If we could take a dictionary, we could drop the first 4 bytes and replace the `J`s with `Q`s. [Try it online](http://pyth.herokuapp.com/?code=J.dQVf%21%7DT_JJNWN%3DN%40JNN&input=%5B%5B%22C%22%2C%22B%22%5D%2C%5B%22D%22%2C%22C%22%5D%2C%5B%22A%22%2C%22%22%5D%2C%5B%22B%22%2C%22A%22%5D%2C%5B%22E%22%2C%22B%22%5D%5D&debug=0) ### Explanation ``` J.dQVf!}T_JJNWN=N@JNN J.dQ Convert the input to a dictionary and call it J. f!}T_JJ Find the leaves (the keys of J that aren't values). V N For each leaf, print the label... WN=N@JNN ... and climb the tree, printing along the way. ``` [Answer] # [Ruby](http://www.ruby-lang.org) 87 75 bytes ``` ->d{k=d.flatten;k.map{|i|k.count(v=i)<2&&loop{v=(d.assoc(p v)||break)[1]}}} ``` inspired by [this answer](https://codegolf.stackexchange.com/a/153600/77598) [Try it online!](https://tio.run/##lZBfa4MwFMXf8ylChKLgDGpLSzcHair0aQ/dm/XBNgrFTqX@gaF@dncbO1PY0/KSXw73nHvIrTl9j6lzHF/eeZc53EivcV0n@WtmfMVl11/6zDgXTV6rrXPR3qzF4loUZdc6KjfiqirOaolbre9PtyTOtNCMhmEYFbzPsYPDkPhEJx6J9JAwIF@QCyTAA3BJFCEFfzT1FlOXetSnDKH/BQDtprG/UQoWR7x3CM25zAYH20zJK2BuCq4s4MPEcD0W8ZnAot8Ndw6WwGAQvJa@xH7MyDrcpGxF2YYye640aYkUDiatLBosn4Vg/fwbn0UpishgUOTAr4xQGu7zaPwB) ]
[Question] [ # Description: A [non-integer representation](https://en.wikipedia.org/wiki/Non-integer_representation) of a number uses non-integer numbers as the bases of a positional numbering system. e.g. Using the golden ratio (the irrational number 1 + √5/2 ≈ 1.61803399 symbolized by the Greek letter φ) as its base, the numbers `1` to `10` can be written: ``` Decimal Powers of φ Base φ 1 φ0 1 2 φ1 + φ−2 10.01 3 φ2 + φ−2 100.01 4 φ2 + φ0 + φ−2 101.01 5 φ3 + φ−1 + φ−4 1000.1001 6 φ3 + φ1 + φ−4 1010.0001 7 φ4 + φ−4 10000.0001 8 φ4 + φ0 + φ−4 10001.0001 9 φ4 + φ1 + φ−2 + φ−4 10010.0101 10 φ4 + φ2 + φ−2 + φ−4 10100.0101 ``` Note that just as with any base-n system, numbers with a terminating representation have an alternative recurring representation. In base-10, this relies on the observation that 0.999...=1. In base-φ, the numeral 0.1010101... can be seen to be equal to 1 in several ways: Conversion to nonstandard form: 1 = 0.11φ = 0.1011φ = 0.101011φ = ... = 0.10101010....φ One representation in a non-integer base can be found using the [greedy algorithm](https://en.wikipedia.org/wiki/Greedy_algorithm). # Challenge: Given a number `n`, a non-integer real base `b` (`1 < b < 10`, **since, as @xnor pointed out in comments, representation in current format would be nonsensical**), and decimal places `l`, output a non-integer representation of `n` in base `b` to `l` decimal places. # Test Cases: ``` n=10, b=(1 + Sqrt[5])/2, l=5, -> 10100.01010 n=10, b=E, l=5, -> 102.11201 n=10, b=Pi, l=5, -> 100.01022 n=10, b=1.2, l=14, -> 1000000000001.00000000000001 n=10^4, b=Sqrt[2], l=12, -> 100001000010010000010000100.000000000001 ``` Note any valid representation is allowed. e.g. ``` n=450, b=E, l=6, -> 222010.221120 ``` or ``` n=450, b=E, l=6, -> 1002020.211202 ``` # Prohibitions: Calling [Wolfram Alpha](https://www.wolframalpha.com/input/?i=12+base+E) or any other external computational site is disallowed. Standard loopholes apply. This is Code Golf, so shortest code wins. [Answer] # [Python 3](https://docs.python.org/3/), ~~151~~ ~~134~~ 121 120 bytes ``` import math def f(n,b,l,r=''): for i in range(int(math.log(n,b)),-l-1,-1):r+="%i"%(n/b**i)+'.'*(0==i);n%=b**i return r ``` [Try it online!](https://tio.run/##ZY1BDoMgEEX3nGJiYmAQrabpxobDaAo6iQKZ0EVPT4vbbt9/eT998h7DvRQ6U@QM55J38XIevApmNYdhKyXOAnxkIKAAvITNKQpZVXc44lZNRNMf/WT6CWfubNNS06pwW7Um7OQgtRqtJXyG1lYmgF1@869WEteWV9NorvfBGXggij@e6BrKFw "Python 3 – Try It Online") Returns a string of the non-integer base representation. This can probably be golfed more; stay tuned. --- Special thanks to: * @LeakyNun for saving 13 bytes! * @Zacharý for saving 1 byte! [Answer] # Mathematica, 85 bytes ``` (r=RealDigits[#,#2,9#3];k=r[[2]];s=ToString/@r[[1]];""<>s[[;;k]].""<>s[[k+1;;k+#3]])& ``` # Mathematica, 86 bytes ``` (s=TakeDrop@##&@@RealDigits[#,#2,9#3];FromDigits@s[[1]].""<>ToString/@s[[2]][[;;#3]])& ``` **input** > > [450,E,6] > > > [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 47 [bytes](https://github.com/abrudz/SBCS) ``` {⌽⊃∘⍕¨⍺⍺(↑,'.',↓)⌊(⊣,⍨⍺×1|⊢)⍣(⍺⍺+z)⍨⍵÷⍺*z←⌊⍺⍟⍵} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///v/pRz95HXc2POmY86p16aMWj3l1ApPGobaKOup66zqO2yZqPero0HnUt1nnUC5I9PN2w5lHXIs1HvYs1IIq1qzTBUlsPbwfytKoetU0AagHLzQeK1v5PA4n09gFtObTeGGjyo76pwUHOQDLEwzP4/6PeuQpahgqZxQqpcYYKtgqpXHlA9YYGCo@6WxSSgEygJIiZA2SaciVp5CikaeYpKIC0GRoY6RkaGhkYgrWYmGLVY4aux8AICPWMQBqN0O0y1DOCazQ0wdAJB4Z6BsjAEAA "APL (Dyalog Unicode) – Try It Online") A dop that takes `n`, `b`, `l` as `⍵` (right arg), `⍺` (left arg), `⍺⍺` (left operand) respectively. Does greedy conversion from the most significant digit. ### How it works ``` {⌽⊃∘⍕¨⍺⍺(↑,'.',↓)⌊(⊣,⍨⍺×1|⊢)⍣(⍺⍺+z)⍨⍵÷⍺*z←⌊⍺⍟⍵} ⍝ ⍵←n, ⍺←b, ⍺⍺←l ⍵÷⍺*z←⌊⍺⍟⍵ ⍝ Part 1 ⌊⍺⍟⍵ ⍝ Floor of Log of n with base b ⍝ (number of digits above decimal point - 1) z← ⍝ Assign to z ⍵÷⍺* ⍝ Divide n by b^z, so that floor will give highest digit ⍝ Let's say the value is k (⊣,⍨⍺×1|⊢)⍣(⍺⍺+z)⍨k ⍝ Part 2 ( )⍣(⍺⍺+z)⍨k ⍝ Repeat l+z times, using k as both the ⍝ left arg (fixed) and right arg (moving)... 1|⊢ ⍝ Fractional part of right arg ⍺× ⍝ Multiply b ⊣,⍨ ⍝ Append left arg ⍝ The net effect is "prepend next significant digit, keeping fractional part" ⍝ Let's say the resulting array is v ⌽⊃∘⍕¨⍺⍺(↑,'.',↓)⌊v ⍝ Part 3 ⌊v ⍝ Floor each number in v ⍺⍺(↑,'.',↓) ⍝ Insert the decimal point after l digits ⊃∘⍕¨ ⍝ Convert each digit to a char ⌽ ⍝ Reverse, so that the highest digit comes first ``` [Answer] # [C (clang)](http://clang.llvm.org/), ~~129~~ ~~123~~ ~~121~~ ~~120~~ 118 bytes (115 + `-lm` compiler flag) ``` f(n,b,l,i,y,z)double n,b,l,z;{for(i=log(n)/log(b);~i<l;n=fmod(n,z))z=pow(b,i),printf(".%d"+!!~i--,y=n/z);puts("");} ``` [Try it online!](https://tio.run/##bY/LasMwEEX3/oqJS0FDZNkSyUpxd110UegfFL/kCGTZ9YMSh@TT6zo2CU7IXYyQOHMuSrzERDYfBkUsjamhmh5oj2nZxSaD@amXR1XWRIemzIlF/3LEKM96Z6QNVVGm426P2IdV@UtiqpFWtbatIi57Td31anXWnkcPofV7lFXXNsR1UZ6GF20T06UZ7Iqo3bP9m@OMa1BE2hKEowNjFOEBBcJhDc1P3ZItIvggKGxRgu8DD3gQsMvgC/7z@30m7jPxgnEuHuivjyf4RE9uIRY0Z2M73yB9Rt/CWbDMrS7b0PkjYhRwsei8Cq5jtl1v7E52Gv4SZaK8GTxT/AM "C (clang) – Try It Online") ~~7~~ ~~8~~ 10 bytes shaved off thanks to ceilingcat! ]
[Question] [ A CSS selector is made up of five elements: 1. The element type (tag name) 2. The id of the element 3. The classes of the element 4. The attributes of the element 5. Operators to chain these element selectors This challenge will only involve the first four--also taking into account operators would make more than one element be generated and that's a bit too complex for this challenge. Maybe a future one. ;) **Input**: A CSS selector, not including any operators. The element type will always be present, but the rest of the portions may not be. **Output**: An html element representing the selector. **Examples**: ``` In: div Out: <div></div> In: div[with-data="cool-data"][foo] Out: <div with-data="cool-data" foo></div> In: span.nice.tidy.cool Out: <span class="nice tidy cool"></span> In: button#great-button.fancy[data-effect="greatness"] Out: <button id="great-button" class="fancy" data-effect="greatness"></button> In: custom-element#secret[secret-attribute="secret value!!"] Out: <custom-element id="secret" secret-attribute="secret value!!"></custom-element> In: element#id.class1.class2[attribute1][foo="bar"] Out: <element id="id" class="class1 class2" attribute1 foo="bar"></element> ``` * You may assume that the input selector will always have the different parts in order (element type, id, class, attributes). * You may assume that the provided attribute selectors will never be an attribute text search (^=, $=, \*=). * You may assume that the input word characters (element type, attribute names, class names, ids) will always match the regex [a-z0-9\_-] * You may have extra whitespace anywhere *except* for inside strings (attribute values) This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer (in bytes) wins. [Standard loop-holes](https://codegolf.meta.stackexchange.com/questions/1061) apply. [Answer] # PHP, 125 119 bytes ``` <?=preg_replace(['/#([\w-]+)/','/\.([^[]+)/','/[.[\]]/','/(\S+).*/'],[' id="$1"',' class="$1"',' ','<$1></$1>'],$argn); ``` Just regex replacements. Saved 6 bytes thanks to Christoph. [Answer] # [Retina](https://github.com/m-ender/retina), ~~88~~ ~~76~~ 67 bytes ``` #([\w-]+) id="$1" \.([^[]+) class="$1" T`[].` ^(\w+).* <$&></$1> ``` [Try it online!](https://tio.run/nexus/retina#JctBCoAgFADRvacIlbAiw9blKdp9jawMBCsow@Mb1GrgwSTCQMVaVwXK3NpjKjBSnMEIHy3e3PevwwSaTxkamYpVwUvU0Vx2DRUyJevtbo9A3Mq/Q/ypWzAhXG5@ghUatvPs8WwurF8 "Retina – TIO Nexus") *-10 bytes thanks to @Neil* *-2 bytes thanks to @KritixiLithos* [Answer] # JavaScript (ES6), 193 bytes ``` s=>[[/#([\w-]+)/,` id="$1"`],[/((\.[\w-]+)+)/,(_,c)=>` class="${c.split`.`.join` `.trim()}"`],[/(\[.+?\])/g,(_,a)=>" "+a.slice(1,-1)],[/([\S]+)(.*)/,"<$1$2></$1>"]].map(r=>s=s.replace(...r))[3] ``` Longer than most since I preferred to output the HTML with all proper whitespace. Also works with the selector parts out of order (`div[attr].class#id`). ## Test Snippet ``` f= s=>[[/#([\w-]+)/,` id="$1"`],[/((\.[\w-]+)+)/,(_,c)=>` class="${c.split`.`.join` `.trim()}"`],[/(\[.+?\])/g,(_,a)=>" "+a.slice(1,-1)],[/([\S]+)(.*)/,"<$1$2></$1>"]].map(r=>s=s.replace(...r))[3] ;["","div",'div[with-data="cool-data"][foo]',"span.nice.tidy.cool",'button#great-button.fancy[data-effect="greatness"]','custom-element#secret[secret-attribute="secret value!!"]','element#id.class1.class2[attribute1][foo="bar"]'].forEach(s => S.innerHTML += `<option>${s}</option>`); ``` ``` <style>*{font-family:Consolas}</style> Test Cases: <select id="S" onchange="I.value=this.value,I.oninput()"></select><br><br> <input id="I" oninput="O.innerText=f(this.value)" size="75"> <pre id="O"></pre> ``` ]
[Question] [ Poke is a really simple incomplete-information game. It's like "Poker", but simpler. At the start of every round, each player is dealt a hand. To simplify things, a hand is a uniformly distributed random number between 0 and 1. Each player only knows their own hand. The player that wins the round is the one whose hand has the greatest value. Every turn, all the players who are still in the round make a bet that they're the player with the best hand. Each player has to decide whether or not to match the largest bet. If they match it, that amount is added to the pot from their account. If they choose not to match it, they drop out of the round. Even if they had the best hand, they can't win once they drop out, and they lose everything they had in the pot. At the end of the round, the player with the best hand out of those that haven't dropped wins. (Each player knows how many turns are gonna be in the round since the start of the round). The winner is the one that makes the most money after a large number of rounds (hundreds, or thousands). In order to compete, write a struct that inherits from this "player" class: ``` class player { private: double _hand; game* _owner = 0; public: //You must provide bool set_new_owner(game* current, game* new_owner) { if(current == _owner) { _owner = new_owner; return true; } return false; } bool set_new_hand(game* current, double new_hand) { if(current == _owner) { _hand = new_hand; return true; } return false; } double hand() const { return _hand; } virtual double bet(const round_info&) = 0; virtual bool take_bet(const round_info&) = 0; virtual std::string name() { return typeid(*this).name(); } virtual ~player() {} }; ``` All you need to do is specialize the "bet" function (which determines how much your player bets each turn), and the "take\_bet" function (which determines whether or not to take the bet. Here are some examples: ``` struct grog : player { //Always bets the minimum amount double bet(const round_info&) { return 1.0; } //Takes any bet bool take_bet(const round_info&) { return true; } string name() { return "Grog"; } }; struct bob : player { //Bet the minimum amount double bet(const round_info&) { return 1.0; } //Only take bets when you have a good hand bool take_bet(const round_info&) { return hand() > 0.95; } string name() { return "Bob"; } }; struct james : player { //Raise the bet a lot if you have a *really* good hand double bet(const round_info&) { if(hand() > 0.99) return 1000.0; else return 1.0; } //Only take bets when you have a *really* good hand bool take_bet(const round_info&) { return hand() > 0.99; } string name() { return "James"; } }; struct rainman : player { //Play it safe double bet(const round_info&) { return 1.0; } bool take_bet(const round_info& r) { double cost = r.current_max_bet(); double winnings = r.winnings() + r.current_max_bet() * r.n_active_players(); int players = r.n_players(); double hand = this->hand(); double p_win = pow(hand,players - 1); double p_loss = 1 - p_win; double gain = -(cost * p_loss) + p_win * winnings; if(gain > 0) return true; return false; } string name() { return "Rainman"; } }; ``` If all four people are playing, then over a few thousand games, James will be the winner and Rainman will do worse than anyone but Grog. But if only Bob, Grog, and Rainman are playing, Rainman will clean the floor with the other players (and win tons of money). **Edit:** Here is the code for `round_info` and for the class that will manage the game. <https://github.com/Artifexian/PokeGame> **Edit 2:** If you submit something not in C++, I can try to translate it into C++ for you. If you want me to, I will edit your answer and append my translated version. **Edit 3:** I will work to write a wrapper for non-c++ languages. Your solution must include 2 functions: something to determine how much to bet (which should return a floating point value), and something to determine whether or not to stay in the round (which should return true or false). Contact me about your preferring input format. I will write something to translate "round\_info" into text. The data provided as text will be the same data provided to everyone else. It will include: 1. The current turn number 2. The maximum number of turns (when the round ends) 3. The number of players 4. The number of players who haven't dropped out 5. The history of what each player has bet 6. A list of which players haven't dropped out 7. The size of the pot 8. The current maximum bet amount (what you have to put down to stay in the game) 9. Your hand **Edit 4:** Any bets made by players will be clipped to be between 1 and 10^6 [Answer] ## Frequent Folder The more players there are, the lower the odds of winning. Thus, this player only takes bets when he thinks his hand is high, using the starting number of players as a guideline. ``` struct frequent_folder : player { //Bets fairly heavily under same conditions a bet is taken //Bet varies based on how good hand is double bet(const round_info& r) { double numer = hand() - (1 - (1/r.n_players)), denom = 1 - (1 - (1/r.n_players)); double qty = 250 * (numer/denom); return qty > 1 ? qty : 1.0; } //Take bet only if likely to have highest hand //e.g. 2 players -> 0.5+, 3 players -> 0.67+, 4 players -> 0.75+ bool take_bet(const round_info& r) { return(hand() >= 1 - (1/r.n_players())); } string name() { return "Frequent Folder"; } }; ``` --- ## Bluffer Where the Frequent Folder plays a very conservative strategy, the Bluffer lives on the edge. He bets heavily with a hand he thinks can win... or a hand he *knows* will lose. He takes favorable bets more often than he bluffs, hoping this will mean net gain, but the probability of a bluff is high enough that strategies analyzing previous bets may be thrown off by the Bluffer's erratic behavior. ``` struct bluffer : player { //Bets hard with an excellent hand... or a very poor one! Small bet otherwise double bet(const round_info&) { (return hand() > 0.9 || hand() < 0.05) ? 500.0 : 1.0; } //Take bet with an excellent hand... or a very poor one! bool take_bet(const round_info& r) { return(hand() > 0.9 || hand() < 0.05; } string name() { return "Bluffer"; } }; ``` These are my first entries on KotH as well as SE as a whole. I hope everyone finds them up to snuff. [Answer] # Gambling Russian Simulates a person who is also playing Russian Roulette. There is a 1 in 6 chance he dies playing Russian Roulette, thus he will stop making bets once he has died. Every time he survives he gets so excited he bets as much as he possibly can because he believes he is on a good luck streak. If there is something smelly about my code let me know. ``` struct gambling_russian : player { bool alive = true; double bet(const round_info&) { return DBL_MAX; }; bool take_bet(const round_info&) { if(hand < (1.0/6.0)){ alive = false; } return alive; } string name() { return "Gambling Russian"; } } ``` [Answer] I'll get this started with a simple player, who will randomly take bets based on the quality of his hand. ``` struct ronald : player { double bet(const round_info&) { return fmax( 1.0, hand()*2 ); }; bool take_bet(const round_info&) { double p = (double)rand() / RAND_MAX; return hand()>p; } string name() { return "Ronald"; } } ``` [Answer] # The Thinker ``` struct theThinker: player { //Raise the bet depending on hand value, but less if the pot has a lot already double bet(const round_info&) { double b = hand() * hand() * 1000.0 - round_info.winnings() / 10.0; return b > 1.0 ? b : 1.0; } //Take bets when the pot and hand look better than the amount you may loose bool take_bet(const round_info&) { return hand() * (round_info.winnings() + 1000.0) > current_max_bet(); } string name() { return "The Thinker"; } }; ``` ]
[Question] [ This is a variant on the self-replicating program, defined here as a program that outputs its source (or a [quine](/questions/tagged/quine "show questions tagged 'quine'")). Below is an example of a self-replicating program in Python: ``` s = 's = %r\nprint(s%%s)' print(s%s) ``` When run from a file, this script should output itself. Instead of a self-replicating program, I want you to write a mutating, replicating program. This is a program that outputs something similar to its source, but with a mutation. The mutated source *must* also be able to replicate, but it should change the functionality of the program in some way. Here is an example: ``` s = 's = %r\ns = s.replace(s[-17],str(int(s[-17])+222))\nprint(s%%s)' s = s.replace(s[-17],str(int(s[-17])+222)) print(s%s) ``` When this Python script is run, it outputs the following program: ``` s = 's = %r\ns = s.replace(s[-17],str(int(s[-17])+224224224))\nprint(s%%s)' s = s.replace(s[-17],str(int(s[-17])+224224224)) print(s%s) ``` If you repeat a number of times, you will see that it continues to mutate but remain functional. Incorporating a raw dynamic environment variable in your code, like a comment with a timestamp, is boring. Don't do that. **Edit:** For that matter, let's follow the standard quine rule of no input. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest in bytes wins. **Clarifications:** I've been asked to clarify, but without much information I'm not sure what needs clarifying. Here's my best shot: * Each iteration should have source code that is different from the last. * The iteration must still run. * The iteration must still replicate according to the same rules. * Comments or strings can't be the only thing that changes. In [dzaima's answer](https://codegolf.stackexchange.com/a/118010/68623) the operations on the string are duplicated, not just the contents of the string--so that is valid. * Each iteration must be runnable in the same language you started in. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 4 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ⁾ṘȮṘ ``` **[Try it online!](https://tio.run/nexus/jelly#@/@ocd/DnTNOrAMS//8DAA "Jelly – TIO Nexus")** (Equivalent to the 5-byte: `“ṘȮ”Ṙ`) Exponentially spawns: ``` “ṘȮ”ṘȮ “ṘȮ”ṘȮṘȮ “ṘȮ”ṘȮ“ṘȮ”ṘȮṘȮ “ṘȮ”ṘȮṘȮ“ṘȮ”ṘȮ“ṘȮ”ṘȮṘȮ “ṘȮ”ṘȮ“ṘȮ”ṘȮṘȮ“ṘȮ”ṘȮṘȮ“ṘȮ”ṘȮ“ṘȮ”ṘȮṘȮ ``` Since `Ṙ` is a monadic atom which prints a Jelly representation of its input and then yields it's input, and `Ȯ` is a monadic atom which prints its input and yields it's input (neither printing any newlines), while `“...”` defines a list of characters. So each `“ṘȮ”Ṙ` prints `“ṘȮ”` and yields to the following `Ȯ` which prints `ṘȮ` and yields... a trailing `Ȯ` finally yields for the programs return value, which is implicitly printed, so the pattern will continue until resources no longer suffice. [Answer] # [SOGL](https://github.com/dzaima/SOGL), 9 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) ``` :+q$o”q$o ``` Explanation: ``` :+q$o” push that string q output it in a new line without popping $ push "”" o output that implicitly output the original string (in a new line) ``` The iterations go as (one per line) ``` :+q$o”¶:+q$o :+q$o:+q$o”¶:+q$o:+q$o :+q$o:+q$o:+q$o:+q$o”¶:+q$o:+q$o:+q$o:+q$o:+q$o:+q$o:+q$o:+q$o”¶:+q$o:+q$o:+q$o:+q$o:+q$o:+q$o:+q$o:+q$o ``` and the next one is [31424 characters long](https://pastebin.com/Bgdbdtjy). The first iteration is ``` :+q$o” push that string ¶ no-op :+ add the string to itself q output it in a newline without popping $o append "”" ``` and the next: ``` :+q$o:+q$o” push that string ¶ no-op :+ add the string to itself q output it in a newline without popping $o append "”" :+q$o the same ``` This should never break from what I can see (well except hitting javas string length limit or something), because only the last string is used and the rest of the code is just `multiply, output`. note: newlines and `¶` are completely interchangeable in SOGL. [Answer] # Python 2, 33 bytes ``` _='_=%r;print _%%_*2;';print _%_; ``` [Ideone](https://ideone.com/5Rvo5q) Doubles in size. (This is technically only true from the third iteration onwards) Based on [this](https://stackoverflow.com/questions/6223285/shortest-python-quine) Quine. Similar to [my Pyth answer](https://codegolf.stackexchange.com/a/118027/56557). ### iterations ``` _='_=%r;print _%%_*2;';print _%_; _='_=%r;print _%%_*2;';print _%_*2; _='_=%r;print _%%_*2;';print _%_*2;_='_=%r;print _%%_*2;';print _%_*2; _='_=%r;print _%%_*2;';print _%_*2;_='_=%r;print _%%_*2;';print _%_*2; _='_=%r;print _%%_*2;';print _%_*2;_='_=%r;print _%%_*2;';print _%_*2; _='_=%r;print _%%_*2;';print _%_*2;_='_=%r;print _%%_*2;';print _%_*2; _='_=%r;print _%%_*2;';print _%_*2;_='_=%r;print _%%_*2;';print _%_*2; _='_=%r;print _%%_*2;';print _%_*2;_='_=%r;print _%%_*2;';print _%_*2; _='_=%r;print _%%_*2;';print _%_*2;_='_=%r;print _%%_*2;';print _%_*2; ``` [Answer] # Pyth, 11 bytes ``` jN*2]"jN*4[ ``` [Try it](https://pyth.herokuapp.com/?code=.vw&input=jN%2a2%5D%22jN%2a4%5B&test_suite=1&test_suite_input=jN%2a2%5D%22jN%2a4%5B%0AjN%2a4%5B%22jN%2a4%5B%0AjN%2a4%5B%22jN%2a4%5B%22jN%2a4%5B%22jN%2a4%5B&debug=0) [Try it online](https://tio.run/nexus/pyth#@5/lp2USrUR38v9/AA) Gets exponentially longer. Based on [this](https://esolangs.org/wiki/Pyth#Quine) Pyth Quine. ## first 4 iterations ``` jN*2]"jN*4[ jN*4["jN*4[ jN*4["jN*4["jN*4["jN*4[ jN*4["jN*4["jN*4["jN*4["jN*4["jN*4["jN*4["jN*4["jN*4["jN*4["jN*4["jN*4["jN*4["jN*4["jN*4["jN*4["jN*4["jN*4["jN*4["jN*4[ ``` ## Explanation ``` jN*4]"jN*4[ "jN*4[ # The String "jN*4[" ] # Make it into a list with one element *4 # Quadruple that list jN # join on quote (N='"') jN*4["jN*4["jN*4["jN*4[ "jN*4[ # The string "jN*4[" [ # List with the string: ["jN*4["] *4 # Quadruple that list jN # Join on quote "jN*4[" # The string "jN*4[" [ # Put both strings into a list *4 # Quadruple that list jN # join on quote (N='"') ``` (I could probably prove this rigoriosly using induction, but I'm not in the mood for that.) This should (theoretically always work because) it's just even multiples of `jN*4["`. Every second occurence of that sequence of characters is interpreted as a string because of the `"` of the previous one. The `[` of the previous one then puts that string into a list together with what the next one produces. Then that list is repeated four times and joined to string with `"`. ]
[Question] [ Here in the absolutely made up country Rnccia we have a lot of good stuff, but the roads aren't good. There are lots of holes and only half of them get fixed. Even then, only half of the fixes are well done. Your task is to embrace the bad roads of this country and draw them for me. ## Input You receive two positive integers as input. One represents the length of the road, and the second represents the number of lanes in each direction. The length of the road is guaranteed to be an even number. ## Output Output or return an ASCII-art image of the road with as many holes as will fit. Read the next two sections to see how the road and holes should be generated. ## Road layout 1. Every road has a straight line of minuses(-) above and below it. 2. Every road has the same number of lanes in both directions. 3. Every road has a line of equal signs(=) down the middle. 4. Lanes have dashed lines between them (excep the special middle line from rule #3). One minus, one whitespace and so on. Starting with the minus. Examples of roads: ``` Road with one lane in both sides: -------------- ============== -------------- Road with two lanes in both sides: -------------- - - - - - - - ============== - - - - - - - -------------- ``` ## Hole layout 1. Every road has 7**n** total holes. **n** is the ceiling of the number of holes that will fit on the road divided by seven. 2. Every road has 4**n** unfixed holes. An unfixed hole is represented as double O (OO). 3. Every road has 2**n** holes that are fixed and represented as double # (##). 4. Every road also has **n** holes that are fixed well and represented as double H (HH). 5. Holes (in any state) appear on every lane in diagonal pattern, starting at the top right and moving down-across. A new line of holes should start in every 4th lane and every 8 characters in the top lane. See the examples for clarification. 6. The order of holes is irrelevant. 7. If 7**n** holes can't fit in road of given length, you may use #6 to choose which of the holes will not be visible. In this example we have 14 holes, 4 of which are fixed poorly, and 2 which are fixed well: ``` ------------------ OO HH OO - - - - - - - - - ## OO - - - - - - - - - ## OO ================== OO OO - - - - - - - - - OO ## HH - - - - - - - - - ## OO ------------------ ``` In this example we hava 9 holes, which is not multiple of 7. So your pool of holes to use is size 14 with 8 (OO), 4(##), 2(HH). You may use any holes from it to fill road. ``` ------------------ OO OO OO OO OO ================== OO OO OO ## ------------------ ``` Another corner example. Road can have only 3 holes. So pool is 7: 4(OO), 2(##), 1(HH). Again, any can be used: ``` ------ ## - - - ## ====== HH - - - ------ ``` ## Other rules 1. You may change the appearance of holes to two of any other character, except -, = and whitespace. Just mention it in your answer. 2. It's [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so make your code as compact as possible. [Answer] # [Python 2](https://docs.python.org/2/), ~~229~~ ~~213~~ ~~204~~ ~~200~~ 188 bytes ``` lambda n,l:"\n".join(["-"*l]+[i%2and"".join(j-i/2&1+2*(n>1)and" "or x.append(1)or"H0000##"[len(x)%7]*2for j in range(l/2))or((i-n*2and"- "or"=")*l)[:l]for i in range(1,n*4)]+["-"*l]) x=[] ``` [Try it online!](https://tio.run/nexus/python2#TY7BasMwDIbvfQqj0iG5Tht77QaB7Lx3cH3wSFIcPCWEHfL2mbwNOukg@PX90j@oVt22HD8/uqjY5AZuDKdxSoweKtA5HH06uMgd/Mljlc7uyR6dRn6zVDZKwbSo9RTnuecOLU0LvNdS@z343DOudHgN2g1CjSqxWiLfe8xnR4Iipor1z4uqHIIWSGfyTQ7FkB4Ga1hfSBL9JqPd2vqwFUiSF8wLYmsy6Iy9yngxzzWFZqek5iXxl4Agnf8pA4qZHsL2DQ "Python 2 – TIO Nexus") --- My longest [codegolf](/questions/tagged/codegolf "show questions tagged 'codegolf'") answer so far [Answer] # PHP, ~~160 186 178 173 170 168~~ 163 bytes ``` for(;$y<=2*$h=2*$argv[2];$y+=print" ")for($x=0;$x++<$w=$argv[1];)echo$y%2?($x+$y+$h*$y)%($h+2)>1|$x>($w&~1)?" ":UBUGUBU[$n++%14/2]:" -="[$y%(2*$h)?$y-$h?$x&1:2:1]; ``` takes input from command line; Run with `-nr`. The holes are `G`ood, `B`ad and `U`gly. **breakdown** ``` for(;$y<=2*$h=2*$argv[2];$y+=print"\n") # loop throug lines and lanes, post-print newline for($x=0;$x++<$w=$argv[1];)echo # loop from left to right and print ... $y%2 ? # lanes: ($x+$y+$h*$y)%($h+2)>1 # if not the position for a hole |$x>($w&~1) # or too close to the end ?" " # then space :UBUGUBU[$n++%14/2] # else hole :" -="[ # or lines: $y%(2*$h) # if neither top nor bottom line ? $y-$h # if not middle line ? $x&1 # then "- " : 2 # else "==" : 1 # else "--" ] ; ``` * `($x-$y)+$y*($h+2)` --> `($x+$y+$h*$y)` * `$w<$x+1&&$w&1` --> `$x>$w-($w&1)` --> `$x>($w&~1)` * `($y%(2*$h)?$y-$h?" -"[$x&1]:"=":"-")` --> `($y%(2*$h)?" -="[$y-$h?$x&1:2]:"-")` (thanks @Christoph) --> `" -="[$y%(2*$h)?$y-$h?$x&1:2:1]` [Answer] ## JavaScript (ES6), 158 bytes ``` f= (w,l)=>[...Array(l*4+1)].map((_,i)=>[...Array(w)].map((_,j)=>i%2?(i>>1)-j&3?` `:s[n%7]+s[n++%7]:i/2%l?`- `:i-l-l?`--`:`==`).join``,n=0,s=`O#OHO#O`).join`\n` ``` ``` <div oninput=o.textContent=f(+w.value,+l.value)><input id=w type=number min=1 value=1><input id=l type=number min=1 value=1><pre id=o>-- OO == -- ``` [Answer] ## Batch, 380 bytes ``` @echo off set h=O#OHO#O set r= for /l %%i in (1,1,%1)do call set r=--%%r%% set/an=%2*2-1 for /l %%j in (0,1,%n%)do call:c %1 %2 %%j echo %r% exit/b :c if %3==0 (echo %r%)else if %3==%2 (echo %r:-==%)else echo %r:--=- % set s= for /l %%i in (1,1,%1)do set/an=%3-%%i^&3&call:l echo(%s% exit/b :l if %n%==3 (set s=%s%%h:~,1%%h:~,1%&set h=%h:~1%%h:~,1%)else set s=%s% ``` ]
[Question] [ **This question already has answers here**: [Evaluate the nth hyperoperation](/questions/11520/evaluate-the-nth-hyperoperation) (15 answers) Closed 6 years ago. Inspired by [Expand exponentation](https://codegolf.stackexchange.com/questions/110596/expand-exponentiation). [Knuth's up arrow notation](https://en.wikipedia.org/wiki/Knuth%27s_up-arrow_notation) is used for big numbers such as Graham's number. If we look deeper, we can see how it makes big numbers. One arrow means exponentiation. e.g. 2↑3 equals 2^3 = 8. Two or more arrows means repeating the instructions of n-1 arrows. e.g. 2↑↑3 equals 2↑2↑2 equals 2^(2^2)=16. You will be given three integers, n, a, and m. n is the first number, a is the amount of arrows, and m is the second number. Your code should output the final answer, which is the calculation of `n ↑a m`(↑x means there are x up-arrows, where x is an integer) # Examples ``` 2 1 2 -> 4 2 1 3 -> 8 2 2 3 -> 16 2 3 3 -> 65536 ``` [Answer] # Java 7, 121 bytes ``` int c(int n,int a,int m){return(int)(a<2?Math.pow(n,m):d(n,a));}double d(int n,int a){return Math.pow(n,a<2?n:d(n,a-1));} ``` **Explanation:** ``` int c(int n, int a, int m){ // Main method with the three integer-parameters as specified by OP's challenge return (int) // Math.pow returns a double, so we cast it to an integer (a < 2 ? // if (a == 1): Math.pow(n, m) // Use n^m : // else (a > 1): d(n, a)); // Use method d(n, a) } double d(int n, int a){ // Method d with two integer-parameters return Math.pow(n, a < 2 // n ^ X where ? n // X = n if (a == 1) : d(n, a-1)); // X = recursive call d(n, a-1) if (a > 1) } // In pseudo-code: c(n, a, m){ if a == 1: return n^m if a > 1: return d(n, a); } d(n, a){ if a == 1: return n^n if a > 1: return d(n, a-1); } ``` **Test code:** [Try it here.](https://ideone.com/7WFfZM) ``` class M{ static int c(int n,int a,int m){return(int)(a<2?Math.pow(n,m):d(n,a));} static double d(int n,int a){return Math.pow(n,a<2?n:d(n,a-1));} public static void main(String[] a){ System.out.println(c(2, 1, 2)); System.out.println(c(2, 1, 3)); System.out.println(c(2, 2, 3)); System.out.println(c(2, 3, 3)); } } ``` **Output:** ``` 4 8 16 65536 ``` [Answer] # APL, 22 bytes ``` {×⍺⍺:(⍺⍺-1)∇∇/⍵/⍺⋄⍺×⍵} ``` This is an operator that takes `a` as its operand (`⍺⍺`), and `n` and `m` as its left and right arguments (`⍺` and `⍵`). Explanation: * `×⍺⍺`: if `⍺⍺` is positive: + `⍵/⍺`: replicate `⍺` `⍵` times + `(⍺⍺-1)∇∇/`: fold the `⍺⍺-1`-arrow function over the list. * `⋄`: otherwise (i.e. if `⍺⍺` is zero): + `⍺×⍵`: multiply the arguments [Answer] # JavaScript ES7, 53 44 bytes ``` f=(a,b,c)=>b<2||c<1?a**c:f(a,b-1,f(a,b,c-1)) ``` ``` f=(a,b,c)=>b<2||c<1?a**c:f(a,b-1,f(a,b,c-1)) console.log(f(2,1,2)); console.log(f(2,1,3)); console.log(f(2,2,3)); console.log(f(2,3,3)); ``` [Answer] ## Mathematica, ~~48~~ 40 bytes ``` If[#3>1<#,#0[#0[#-1,##2],#2,#3-1],#2^#]& ``` Order of arguments is `m, n, a` (using the notation from the challenge). [Answer] # julia, ~~41~~ 38 bytes ``` f(a,n,b)=b>1< n?f(a,n-1,f(a,n,b-1)):a^b ``` Thanks to @Martin 3 bytes saved. [Try it online!](https://tio.run/nexus/julia5#@5@mkaiTp5OkaZtkZ2iTZw/m6hrqQIV1DTU1rRLjkv4XFGXmleTkaaRpGOkY6xhrav4HAA "Julia 0.5 – TIO Nexus") **a,b** : operands **n**: number of arrows Previous answer: ``` f(a,n,b)=n<2||b<1?a^b:f(a,n-1,f(a,n,b-1)) ``` Modified formula from [Wikipedia](https://en.wikipedia.org/wiki/Knuth%27s_up-arrow_notation) [Try it online!](https://tio.run/nexus/julia5#@5@mkaiTp5OkaZtnY1RTk2RjaJ8Yl2QFFtU11IHK6hpqav4vKMrMK8nJ00jTMNIx1jEGigAA "Julia 0.5 – TIO Nexus") ]
[Question] [ **This question already has answers here**: [Find the nth decimal of pi](/questions/84444/find-the-nth-decimal-of-pi) (17 answers) Closed 7 years ago. **Task** Given an input `n`, calculate the n-th decimal digit of pi **Rules** * Answer can be a full program or a function. * Input must be taken from stdin or from function arguments. * Output must be either sent to stdout, the return value of a function, or written to a file. * all `n` values between 0 and 20000 must be supported (can be between 1 and 20001 for 1-indexed languages). * **Built-ins to calculate pi cannot be used**. This includes pi constants (e.g. `math.pi` in Python) and built-in functions that return either the value of pi, or the n-th digit of pi. This means that an algorithm which calculates pi, or the n-th digit of pi must be implemented in your answer. * Digits must be calculated at runtime. First digit (0-th or 1-th, depending on the language) is 3. This is code-golf, so shortest code in bytes wins. **EDIT:** This is not a duplicate of 'Find the n-th decimal of pi', since that challenge allowed built-ins. This one is focused around actually implementing an algorithm to find the digits, rather than relying on built-ins. [Answer] # Python 2, ~~182~~ 65 bytes ``` a=p=2*10**20004 i=3 while a:a=i/2*a/i;p+=a;i+=2 print`p`[input()] ``` **[repl.it](https://repl.it/EF0E/3)** Uses the [Leibniz formula](https://en.wikipedia.org/wiki/Leibniz_formula_for_%CF%80) to calculate 20000 correct digits (plus a handful to allow the algorithm to maintain accuracy) then prints the requested digit. --- Previous (182): ["The Spigot Algorithm For Pi"](https://www.jstor.org/stable/2975006) of Stanley Rabinowitz and Stan Wagon has the added bonus that it will work for any `n` when implemented as a generator ``` p=lambda n,r=3,a=0,b=1,c=1,d=1,e=3,f=3,i=0:i>n and r or p(n,e,*[((2*b+a)*f,b*d,c*f,d+1,(b*(7*d)+2+(a*f))/(c*f),f+2,i),(10*(a-e*c),10*b,c,d,((10*(3*b+a))/c)-10*e,f,i+1)][4*b+a-c<e*c]) ``` **[repl.it](https://repl.it/EFWc)** Reaches Python's default recursion limit for the 117th digit. Here is a non-recursive version for 198 bytes: ``` def p(n): a=i=0;b=c=d=1;e=f=3 while i<=n: r=e if 4*b+a-c<e*c:g=10*(a-e*c);e=((10*(3*b+a))/c)-10*e;b*=10;i+=1 else:g=(2*b+a)*f;h=(b*(7*d)+2+(a*f))/(c*f);b*=d;c*=f;f+=2;d+=1;e=h a=g print r ``` **[repl.it](https://repl.it/EFXf)** (first indent space, second indent tab), the digits could, of course, be generated by yielding `e` at the start of the `if` clause instead of tracking the last digit with `r`. [Answer] # Java 7, ~~260~~ 258 bytes ``` import java.math.*;int c(int n){BigInteger p,a=p=BigInteger.TEN.pow(20010).multiply(new BigInteger("2"));for(int i=1;a.compareTo(BigInteger.ZERO)>0;p=p.add(a))a=a.multiply(new BigInteger(i+"")).divide(new BigInteger((2*i+++1)+""));return(p+"").charAt(n)-48;} ``` [Copy from my answer here.](https://codegolf.stackexchange.com/a/97362/52210) Java's built-in `Math.PI` has a precision of 15 decimal points, so I was already forced to use an algorithm for the other challenge anyway.. Used [*@LeakyNun's* Python 2 algorithm](https://codegolf.stackexchange.com/a/84465/52210). **Ungolfed & test code:** [Try it here.](https://ideone.com/30GI5d) (The ideone can't handle the last two test cases, but it works within 2 sec in the Eclipse IDE.) ``` import java.math.*; class M{ static int c(int n){ BigInteger p, a = p = BigInteger.TEN.pow(20010).multiply(new BigInteger("2")); for(int i = 1; a.compareTo(BigInteger.ZERO) > 0; p = p.add(a), i++){ a = a.multiply(new BigInteger(i+"")).divide(new BigInteger((2 * i++ + 1)+"")); } return (p+"").charAt(n) - 48; } public static void main(String[] a){ System.out.print(c(0)+", "); System.out.print(c(1)+", "); System.out.print(c(2)+", "); System.out.print(c(3)+", "); System.out.print(c(4)+", "); System.out.print(c(11)+", "); System.out.print(c(101)+", "); System.out.print(c(600)+", "); System.out.print(c(761)+", "); System.out.print(c(1001)+", "); System.out.print(c(10001)+", "); System.out.print(c(20001)); } } ``` **Output:** ``` 3, 1, 4, 1, 5, 8, 8, 2, 4, 3, 5, 2 ``` ]
[Question] [ Your task is to make a histogram given a sample of arbitrary size. **Input** A float array or any other reasonable form of input with an arbitrary number of elements. **Output** The histogram; more to follow. **How to make a histogram** We'll use the sample: `[1.1, 3, 5, 13, 15.5, 21, 29.7, 63, 16, 5, 5.1, 5.01, 51, 61, 13]` To make a histogram, you first separate your observations into classes. The ideal number of classes is the lowest `k` such that `2^k > n`, where `k` is the number of classes, and `n` is the number of observations. In our case, `k = 4`. The number of bars is not final. This `k` value's purpose is only to find the width of each class. The width of each class is the range of your data set divided by the number of classes. The range of our data set is `63 - 1.1 = 61.9`, so the width of each class is `15.475`. This means that the first class is `[1.1, 16.575)`, the second is `[16.575, 32.05)` and so on. The last class is `[63.0, 78.475)`. The second value of the last class (`b` in `[a,b)`) must be greater than the max value of the set. Now we rearrange our data into the classes; for us: ``` [1.1, 16.575): [1.1, 3, 5, 5, 5.01, 5.1, 13, 13, 15.5, 16] [16.575, 32.05): [21, 29.7] [32.05, 47.525): [] [47.525, 63.0): [51, 61] [63.0, 78.475): [63] ``` And finally, we graph! For our purposes, a bar will be a `▉` stacked for the number of observations in the class (because I think that looks good). You can count the `▉` as one byte in your source code. There should be no space between bars (unless there is an empty bar), nor do you need to label axes or any of that fancy stuff. There can be trailing whitespace at the end of your output. In our case, that would be: ``` ▉ ▉ ▉ ▉ ▉ ▉ ▉▉ ▉▉ ▉ ▉▉ ▉▉ ``` **This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins!** [Answer] # Python 3, 139 Generates histogram with numpy, takes on account the strange last column rule and prints. ``` from numpy import* def f(l): h,_=histogram(l,'fd');h[-1]-=1 for i in zip(*((max(h)-i)*' '+i*'▉'for i in append(h,1))):print(''.join(i)) ``` [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), ~~50~~ ~~49~~ 52 bytes ``` g.²òD>Ýs¹ZsWs\©-s/*®+v¹y.S>_O})¥ZUv'▉y×ðXy-׫S})øRJ» ``` [Try it online!](http://05ab1e.tryitonline.net/#code=Zy7CssOyRD7DnXPCuVpzV3Ncwqktcy8qwq4rdsK5eeKAuU99KcKlWlV2J-KWiXnDl8OwWHktw5fCq1N9KcO4UsK7&input=WzEuMSwgMywgNSwgMTMsIDE1LjUsIDIxLCAyOS43LCA2MywgMTYsIDUsIDUuMSwgNS4wMSwgNTEsIDYxLCAxM10) **Explanation** First we calculate k as the inclusive round up of log2 of the input length. `g.²ò` We then construct a list of upper bounds of the classes. This is constructerd as `range[0 .. k+1]*((max(input) - min(input))/k)+min(input)` using the code: `D>Ýs¹ZsWs\©-s/*®+` Now we loop over this list counting the numbers of the input under these upper bounds. As we only want the numbers between each lower and upper bound we reduce this list by subtraction. Unfortunately due to a bug when comparing floats this becomes longer than it should be. `v¹y.S>_O})¥` Now that we have a list of the observation within each class we loop over these creating a matrix of the special char and fill them out with spaces so that each row in the matrix will have equal length. `v'▉y×ðXy-׫S})` This matrix has the staples of the histogram horizontally and we want them vertically. To remedy this, we transpose the matrix. This is the reason we filled the rows with spaces (as transpose need equal length lists). This gives us vertical bars starting from the top running down, so we reverse the order of the rows in the matrix. Now that we have the data in the correct order we print the matrix by joining the rows and joining the columns on newlines. `øRJ»` [Answer] # [CJam](http://sourceforge.net/projects/cjam/), ~~72~~ 71 bytes ``` l',-~$__,2b,\)\(:A\;-\d/:B;{AB+:A;_{A<},,_@>}h;]_:e>:M;{'▉*MSe[}%NM*a+z ``` [Try it online!](http://cjam.tryitonline.net/#code=bCcsLX4kX18sMmIsXClcKDpBXDstXGQvOkI7e0FCKzpBO197QTx9LCxfQD59aDtdXzplPjpNO3sn4paJKk1TZVt9JU5NKmEreg&input=WzEuMSwgMywgNSwgMTMsIDE1LjUsIDIxLCAyOS43LCA2MywgMTYsIDUsIDUuMSwgNS4wMSwgNTEsIDYxLCAxM10) --- ``` l',-~$ e# read and sorts the list __,2b, e# find k \)\(:A e# find max and min (keep min as A) \;-\d/:B; e# find width (keep as B) { e# while entries remain AB+:A; e# find intervals upper bound _{A<},, e# count entries below bound _@> e# remove entries below bound }h; e# end while ]_:e>:M; e# find maximum size {'▉*MSe[}% e# convert to bars and pad columns NM*a+z e# add newlines and transpose to display upright ``` [Answer] # Pyth, 76 bytes This code is absolutely disgusting. I've mentioned before how bad I am at golfing string-output challenges, right? ``` J_Mr8Smf>+*T/-h.MZQKh.mbQ.EllQKd)Q)=Y_.tUMme@+J]0xhMJdSheJ;jmj""m@"▉ "qk\ dY ``` Explanation to follow. [Test it out online!](http://pyth.herokuapp.com/?code=J_Mr8Smf%3E%2B%2aT%2F-h.MZQKh.mbQ.EllQKd%29Q%29%3DY_.tUMme%40%2BJ%5D0xhMJdSheJ%3Bjmj%22%22m%40%22%E2%96%89+%22qk%5C+dY&input=%5B1.1%2C+3%2C+5%2C+13%2C+15.5%2C+21%2C+29.7%2C+63%2C+16%2C+5%2C+5.1%2C+5.01%2C+51%2C+61%2C+13%5D&test_suite_input=%5B1.1%2C+3%2C+5%2C+13%2C+15.5%2C+21%2C+29.7%2C+63%2C+16%2C+5%2C+5.1%2C+5.01%2C+51%2C+61%2C+13%5D&debug=0) [Answer] # R, ~~105~~ 95 bytes (non-competing) Takes input from stdin, prints to stdout. As a bonus, outputs an actual histogram as well as the ASCII art. Was able to golf away 10 bytes thanks to partial argument matching (`c` instead of `counts`) and reworking the output so as to avoid using `apply`. ``` cat(t(cbind(sapply(h<-hist(scan())$c,function(i)c(rep(" ",max(h)-i),rep("▉",i))),"\n")),sep="") ``` Input: ``` 1.1, 3, 5, 13, 15.5, 21, 29.7, 63, 16, 5, 5.1, 5.01, 51, 61, 1 ``` Output: ``` ▉ ▉ ▉ ▉ ▉▉ ▉▉▉ ▉ ▉▉▉ ▉▉ ``` [![Graphics output; a histogram](https://i.stack.imgur.com/wRuOp.png)](https://i.stack.imgur.com/wRuOp.png) This version is non-competing because it just lets R decide what the best number of bins is, using Sturge's formula. (Sturges, H. A. (1926) The choice of a class interval. *Journal of the American Statistical Association* 21, 65–66.) The OP uses a specific method, which has the last bar reserved exclusively for the maximum value, which is bizarre. R makes it hard to do it this way (perhaps because it was built by statisticians), but it's still possible, in **165** bytes: ``` k=ceiling(log2(length(i<-scan()))) cat(t(cbind(sapply(h<-hist(i,br=min(i)+diff(range(i))/k*0:(k+1)-1e-5)$c,function(i)c(rep(" ",max(h)-i),rep("▉",i))),"\n")),sep="") ``` Example output: ``` ▉ ▉ ▉ ▉ ▉ ▉ ▉ ▉ ▉▉ ▉ ▉▉ ▉▉ ``` [![enter image description here](https://i.stack.imgur.com/MrenE.png)](https://i.stack.imgur.com/MrenE.png) ]
[Question] [ ## Challenge Write a program which takes the URL of a PPCG answer as input and outputs the length of the answer's first code block in bytes. ## Code Blocks There are three different ways of formatting code blocks: **Four spaces before the code (`-` represents a space, here)** ``` ----Code goes here ``` **Surrounding the code in `<pre>` tags:** ``` <pre>Code goes here</pre> ``` or: ``` <pre> Code goes here </pre> ``` **Surrounding the code in `<pre><code>` tags (in that order):** ``` <pre><code>Code goes here</code></pre> ``` ## Rules You should only use the first code block in answer. Assume that the supplied answer will always have a code block. You must find the length of the answer in *bytes*, not any other metric such as characters. Solutions using the Stack Exchange Data Explorer or the Stack Exchange API are allowed. URL shorteners are disallowed. Assume all programs use UTF-8 encoding. ## Examples ``` Input: https://codegolf.stackexchange.com/a/91904/30525 Output: 34 ``` [**Link**](https://codegolf.stackexchange.com/a/91904/30525) --- ``` Input: https://codegolf.stackexchange.com/a/91693/30525 Output: 195 ``` [**Link**](https://codegolf.stackexchange.com/a/91693/30525) --- ``` Input: https://codegolf.stackexchange.com/a/80691/30525 Output: 61 ``` [**Link**](https://codegolf.stackexchange.com/a/80691/30525) *Note:* Despite what the answer may say, due to APL using a different encoding, 33 bytes [isn't its UTF-8 byte count](https://mothereff.in/byte-counter#%28%E2%8C%BD%2C%7B1%2B%E2%8A%83%E2%8D%B5%7D%29%E2%88%98%7B%E2%8D%B5%2C%E2%8D%A83%C3%B7%E2%8D%A82%C3%97%E2%8A%83%E2%8D%B5%7D%283%C3%B7%E2%8D%A84%E2%88%98%C3%97%29%2C%E2%8A%A2) ## Winning The shortest code in bytes wins. [Answer] # C#, ~~249~~ 270 bytes ``` u=>{var c=new System.Net.Http.HttpClient().GetStringAsync(u).Result;var i=c.IndexOf("de>",c.IndexOf('"'+u.Split('/')[4]))+3;return System.Text.Encoding.UTF8.GetByteCount(c.Substring(i,c.IndexOf("<",i)-i-1).Replace("&gt;",">").Replace("&lt;","<").Replace("&amp;","&"));}; ``` I've made some assumptions based on observations of the HTML of pages. Hopefully they hold true for all answer posts. *+21 bytes to unencode `&amp;` to `&`. My answer failed to count it's own bytes. ;P* Ungolfed: ``` /*Func<string, int> Lambda =*/ u => { // Download HTML of the page. // Although new System.New.WebClient().DownloadString(u) looks shorter, it doesn't // preserve the UTF8 encoding. var c = new System.Net.Http.HttpClient().GetStringAsync(u).Result; // Using the answer id from the URL, find the index of the start of the code block. // Empirical observation has found that all code blocks are in <code> tags, // there are no other HTML tags that end with "de>", // and that '>' and '<' are encoded to '&gt;'/'&lt;' so no jerk can put "de>" // before the first code block. var i = c.IndexOf("de>", c.IndexOf('"' + u.Split('/')[4])) + 3; // Get the substring of the code block text, unencode '>'/'<'/'&' and get the byte count. // Again, empirical observation shows the closing </code> tag is always on a new // line, so always remove 1 character when getting the substring. return System.Text.Encoding.UTF8.GetByteCount(c.Substring(i, c.IndexOf("<", i) - i - 1).Replace("&gt;", ">").Replace("&lt;", "<")..Replace("&amp;", "&")); }; ``` Results: ``` Input: http://codegolf.stackexchange.com/a/91904/30525 Output: 34 Input: http://codegolf.stackexchange.com/a/91693/30525 Output: 195 (at the time of this answer the first post has 196, but I can't find the 196th byte, even counting by hand, so assuming 195 is correct) Input: http://codegolf.stackexchange.com/a/80691/30525 Output: 61 Input: http://codegolf.stackexchange.com/a/91995/58106 (this answer) Output: 270 ``` [Answer] # jQuery JavaScript, 97 Bytes ``` console.log((new Blob([$("#answer-"+location.hash.substr(1)+" code").eq(0).text().trim()])).size) ``` old version 151 Bytes ``` s=$('#answer-'+location.hash.substr(1)+' code').eq(0).text().trim();c=0;for(i=s.length;i--;)d=s.charCodeAt(i),c=d<128?c+1:d<2048?c+2:c+3;console.log(c) ``` old version 163 Bytes ``` s=$('#answer-'+location.hash.substr(1)+' code').first().text().trim();c=0;for(i=0;i<s.length;i++){d=s.charCodeAt(i);c=(d<128)?c+1:(d<2048)?c+2:c+3;}console.log(c); ``` input ist location and jQuery is active on the site [Answer] # Java 7, ~~314~~ 313 bytes ``` int c(String u)throws Exception{String x="utf8",s=new java.util.Scanner(new java.net.URL(u).openStream(),x).useDelimiter("\\A").next();int j=s.indexOf("de>",s.indexOf('"'+u.split("/")[4]))+3;return s.substring(j,s.indexOf("<",j)-1).replace("&gt;",">").replace("&lt;","<").replace("&amp;","&").getBytes(x).length;} ``` Shamelessly stolen from [*@milk*'s C# answer](https://codegolf.stackexchange.com/a/91995/52210) and ported to Java 7. NOTE: This assumes all code is in `<code>` blocks. Currently it won't work with just `<pre>` tags (but who uses those anyway?.. ;p). **Ungolfed & test cases:** ``` class M{ static int c(String u) throws Exception{ String x = "utf8", s = new java.util.Scanner(new java.net.URL(u).openStream(), x).useDelimiter("\\A").next(); int j = s.indexOf("de>", s.indexOf('"'+u.split("/")[4])) + 3; return s.substring(j, s.indexOf("<", j) - 1).replace("&gt;", ">").replace("&lt;", "<").replace("&amp;", "&") .getBytes(x).length; } public static void main(String[] a) throws Exception{ System.out.println(c("https://codegolf.stackexchange.com/a/91904/30525")); System.out.println(c("https://codegolf.stackexchange.com/a/91693/30525")); System.out.println(c("https://codegolf.stackexchange.com/a/80691/30525")); System.out.println(c("https://codegolf.stackexchange.com/a/91995/58106")); } } ``` **Output:** ``` 34 195 61 270 ``` ]
[Question] [ Given six unique non-negative integers, print the two 3-digit integers comprised of those numbers that sum to the smallest amount. Additionally, * If there is more than one set of numbers that meets the smallest-sum requirement, print the two that have the greatest difference. For example, `269 + 157 = 267 + 159 = 426`; however, `269 - 157 > 267 - 159`, so the first set should be printed. * Print the numbers on the same line largest -> smallest, separated by a single space. * Zero (`0`) cannot be used as a leading number. * Inputs will always be digits. # Testcases ``` input | output 2 6 5 1 9 7 | 269 157 1 9 5 0 8 3 | 359 108 1 2 3 4 5 6 | 246 135 ``` # Scoring As this is code golf, shortest entry wins. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 12 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` Ṣs3¬Þ€Fs2ZḌṚ ``` [Try it online!](http://jelly.tryitonline.net/#code=4bmiczPCrMOe4oKsRnMyWuG4jOG5mg&input=&args=MCwgMSwgMiwgMywgNCwgNQ) or [verify all test cases](http://jelly.tryitonline.net/#code=4bmiczPCrMOe4oKsRnMyWuG4jOG5mgo7IsOH4oKsRw&input=&args=WzIsIDYsIDUsIDEsIDksIDddLCBbMSwgOSwgNSwgMCwgOCwgM10sIFsxLCAyLCAzLCA0LCA1LCA2XQ). ### Background Consider six digits **a < b < c < d < e < f**. If **a ≠ 0**, a number pair of three-digit integers with minimal sum must clearly use **a** and **b** for the leftmost digits, **c** and **d** for the middle digits, and **e** and **f** for the rightmost digits. That gives eight possible arrangements with identical sums (**100(a + b) + 10(c + d) + (e + f)**). Since the difference should be as large as possible, all digits of the first integer should be larger than the corresponding digits of the second integer, leaving **bdf10, ace10** as the optimal arrangement (difference **100(b - a) + 10(d - c)+ (f - e)**). Finally, if **a = 0**, **a** should still occur as early as possible (as middle digit), and a similar process reveals that the pair **cdf10, bae10** is the correct solution. ### How it works ``` Ṣs3¬Þ€Fs2ZḌṚ Main link. Argument: <a, b, c, d, e, f> (in any order) Ṣ Sort; yield [a, b, c, d, e, f]. s3 Split into triplets; yield [[a, b, c], [d, e, f]]. ¬Þ€ Sort each triplet by logical NOT. If a ≠ 0, all digits have logical NOT 0, so this leaves the triplets unaltered. If a = 0, its logical NOT is 1, so the first triplet is sorted as [b, c, a], leaving [[b, c, a], [d, e, f]]. F Flatten; yield [a, b, c, d, e, f] or [b, c, a, d, e, f]. s2 Split into pairs; yield [[a, b], [c, d], [e, f]] or [[b, c], [a, d], [e, f]]. Z Zip; yield [[a, c, e], [b, d, f]] or [[b, a, e], [c, d, f]]. Ḍ Undecimal; convert each triplet from base 10 to integer. Ṛ Reverse the order of the generated integers. ``` [Answer] # Pyth, 17 bytes ``` _iRTChf*FhTcR2.pS ``` [Try it online](https://pyth.herokuapp.com/?code=_iRTChf%2aFhTcR2.pS&test_suite=1&test_suite_input=%5B2%2C6%2C5%2C1%2C9%2C7%5D%0A%5B1%2C9%2C5%2C0%2C8%2C3%5D%0A%5B1%2C2%2C3%2C4%2C5%2C6%5D) ### How it works ``` _iRTChf*FhTcR2.pS S sort input .p permutations in lexicographic order cR2 chop each permutation into groups of 2 f filter for results T such that: hT the first group *F has a truthy (nonzero) product h first result C transpose iRT convert both rows to base 10 _ reverse ``` [Answer] ## JavaScript (ES6), 59 bytes ``` a=>a[b=!!+a.sort()[0],2-b]+a[3]+a[5]+' '+a[1-b]+a[b+b]+a[4] ``` Takes input as a character array (e.g. `[..."195083"]`) and returns two space-separated numbers in a string. 57 bytes if I can return the smaller number first: ``` a=>a[b=+!+a.sort()[0]]+a[2-b-b]+a[4]+' '+a[1+b]+a[3]+a[5] ``` [Answer] ## Batch, 232 bytes ``` @if %1 gtr %2 %0 %2 %1 %3 %4 %5 %6 @if %2 gtr %3 %0 %1 %3 %2 %4 %5 %6 @if %3 gtr %4 %0 %1 %2 %4 %3 %5 %6 @if %4 gtr %5 %0 %1 %2 %3 %5 %4 %6 @if %5 gtr %6 %0 %1 %2 %3 %4 %6 %5 @if %1==0 (echo %3%4%6 %20%5)else echo %2%4%6 %1%3%5 ``` Mostly bubble sort. [Answer] ## Perl, ~~88~~ ~~66~~ ~~64~~ ~~66~~ 64 Bytes ``` @a[0..2]=@a[1,2,0]if!(@a=sort@ARGV)[0];say@a[1,3,5],$",@a[0,2,4] ``` ~~Prints the two numbers with no space between them :/~~ Needs -M5.01 flag Thanks to @msh210 and @Dada for helping to reduce byte count! [Answer] # [Perl 6](http://perl6.org), 82 bytes ``` *.permutations.map({my@a=.join.comb(3);@a if @a.all>100}).min({.sum,[R-] |$_}).put ``` ### Usage: ``` my &small = *.permutations.map({my@a=.join.comb(3);@a if @a.all>100}).min({.sum,[R-] |$_}).put; small [2,6,5,1,9,7]; # 269 157 small [1,9,5,0,8,3]; # 359 108 small [1,2,3,4,5,6]; # 246 135 ``` ### Explanation: ``` # Whatever lambda with input 「*」 *.permutations .map({ # join and split into 3 character chunks my @a = $_.join.comb(3); # return the values if neither start with 「0」 @a if @a.all > 100 }) # find the minimum .min({ # by sum first $_.sum, # and reversed subtraction second # ( biggest difference in reversed order ) [R-] |$_ }) # print it on a line, space separated .put ``` [Answer] # Ruby, 113 bytes [Try it online!](https://repl.it/CjUu/1) ``` ->a{(a.permutation(6).map{|c|c[0]*c[3]>0?[eval(c[0,3]*''),eval(c[3,3]*'')]:p}-[p]).min_by{|x,y|[x+y,-(x-y).abs]}} ``` [Answer] ## PowerShell v2+, ~~90~~ 68 bytes ``` $a,$b=(($n=$args|sort)-ne0)[0,1];"$b{1}{3} $a{0}{2}"-f($n-ne$a-ne$b) ``` Not quite as short as others, but showcases some nifty tricks. Takes input as command-line arguments `$args`, `sort`s them, saves that into `$n`. That's encapsulated in parens and used as the left-hand argument to `-ne0`, which pulls out all elements not equal to zero (in PowerShell, `array -comparator scalar` functions as a filter). That resultant array is re-captured in parens, and the `0`th(Hi Dennis) and `1`st elements plucked out, and uses multiple-assignment to store them into `$a` and `$b`. This ensures that the smallest non-zero element is in `$a` and the next smallest non-zero element is in `$b`, and those form the basis for our output string. The next portion is a string `"..."` using the `-f`ormat operator. We specify locations in the string `{0}` for where that particular item goes. We feed to the `-f` operator the original (sorted) array `$n`, except without elements `$a` and `$b`, so four elements, which correspond to the `1,3,0,2` of the brackets. That string is left on the pipeline and output is implicit. --- For a worked out example, let's assume that the OP meant *non-negative* input numbers, to match the test case of `1 9 5 0 8 3`. This starts by sorting the input array, so we have `0 1 3 5 8 9` and re-saving that into `$n`. We pluck out the non-zero elements, so `1 3 5 8 9`, and choose the `[0,1]` indices thereof. That means that `$a=1` and `$b=3`, and thus we'll always know `a < b` and neither `a` nor `b` are `0`. Those are replaced in the string, so we have `"3{1}{3} 1{0}{2}"` to start. The `-f` operator takes the result of our array operation. Since `$n` is already still sorted, the pair of `-ne` operators result in `0 5 8 9` being fed to `-f`. As we're wanting the smallest sum, we obviously want the smaller elements to be used first. But, as we're wanting the largest difference, we want the larger elements to be associated to `b`. Hence, the `{1}{3}{0}{2}` arrangement for the indexing. This results in the string `"359 108"`, the proper answer. [Answer] # Python3 97 bytes ``` def x(*s):d=sorted(s);i=(0,1)[not d[0]];print(d[1+i],d[3],d[5],' ',d[0+i],d[(2+i)%3],d[4],sep='') ``` The approach is based on the narrative of @Dennis answer. First try on Ideone with the code (I hope I did save it): [Try it!](http://ideone.com/3112TO) ]
[Question] [ # Columnar Transposition Cipher While I have plenty of programs I have written for more advanced ciphers, I just realised I don't actually have one for one of the simplest: [Columnar Transposition](https://en.wikipedia.org/wiki/Transposition_cipher#Columnar_transposition). The cipher, in case you don't know, works as follows: 1. First, you take the key, and write it as numbers. The numbers are made by replacing the letter which comes first in the alphabet with `1`, the letter that comes next `2` and so on, ignoring duplicates (the key `GOAT` would become `2314`). These numbers are the headers of the columns. ``` 2314 ---- ``` 2. Next, you write your message under the columns. ``` 2314 ---- Hell o Wo rld! ``` 3. Finally, rearrange the columns into the numerical order in which they would fall, and read the ciphertext across. ``` 1234 ---- lHel Wo o drl! ``` 4. Which will result in your encoded text: `lHelWo odrl!` ## Rules * Each submission should be either a full program or function. If it is a function, it must be runnable by only needing to add the function call to the bottom of the program. Anything else (e.g. headers in C), must be included. * There must be a free interpreter/compiler available for your language. * If it is possible, provide a link to a site where your program can be tested. * Your program must not write anything to STDERR. * Your program should take input as an argument or from STDIN (or the closest alternative in your language). * [Standard loopholes](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. ## Requirements * Case must be preserved. * Your cipher should be 'irregular', that is, if there are any spaces left after you have written out your message, it is treated as if it were a normal space character. * Only encryption is required, decryption may come in a later challenge. * Input should be taken from `STDIN` with the key on the first line, and the plaintext on the second. If you are taking input as an argument, please specify how this is done for your language. * The key can be in any case. * Duplicates in the key should be ignored - that is, `ABCDB` would become `ABCD`. Duplicates also apply in any case. * Trailing whitespace is included. ## Test Cases ``` CBABD, Duplicates are ignored. ==> puDlacit sea eriongr.de bDaEc, Key can be in multicase! ==> yKce aenbn mi tucliea s! ``` Full example, with 'surplus space' rule. ``` ADCB ---- "Goo d Mo rnin g!" he c alle d. ABCD ---- "ooG dom rnin g "! hc e aell d . Message: "ooGdom rning "!hc eaelld . ``` ## Scoring [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") is how we score this challenge! ## Submissions To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template: ``` # Language Name, N bytes ``` where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance: ``` # Ruby, <s>104</s> <s>101</s> 96 bytes ``` If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header: ``` # Perl, 43 + 2 (-p flag) = 45 bytes ``` You can also make the language name a link which will then show up in the leaderboard snippet: ``` # [><>](http://esolangs.org/wiki/Fish), 121 bytes ``` ## Leaderboard Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language. ``` /* Configuration */ var QUESTION_ID = 79810; // Obtain this from the url // It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe"; var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk"; var OVERRIDE_USER = 53406; // This should be the user ID of the challenge author. /* App */ var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page; function answersUrl(index) { return "https://api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER; } function commentUrl(index, answers) { return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER; } function getAnswers() { jQuery.ajax({ url: answersUrl(answer_page++), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { answers.push.apply(answers, data.items); answers_hash = []; answer_ids = []; data.items.forEach(function(a) { a.comments = []; var id = +a.share_link.match(/\d+/); answer_ids.push(id); answers_hash[id] = a; }); if (!data.has_more) more_answers = false; comment_page = 1; getComments(); } }); } function getComments() { jQuery.ajax({ url: commentUrl(comment_page++, answer_ids), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { data.items.forEach(function(c) { if (c.owner.user_id === OVERRIDE_USER) answers_hash[c.post_id].comments.push(c); }); if (data.has_more) getComments(); else if (more_answers) getAnswers(); else process(); } }); } getAnswers(); var SCORE_REG = /<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/; var OVERRIDE_REG = /^Override\s*header:\s*/i; function getAuthorName(a) { return a.owner.display_name; } function process() { var valid = []; answers.forEach(function(a) { var body = a.body; a.comments.forEach(function(c) { if(OVERRIDE_REG.test(c.body)) body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>'; }); var match = body.match(SCORE_REG); if (match) valid.push({ user: getAuthorName(a), size: +match[2], language: match[1], link: a.share_link, }); }); valid.sort(function (a, b) { var aB = a.size, bB = b.size; return aB - bB }); var languages = {}; var place = 1; var lastSize = null; var lastPlace = 1; valid.forEach(function (a) { if (a.size != lastSize) lastPlace = place; lastSize = a.size; ++place; var answer = jQuery("#answer-template").html(); answer = answer.replace("{{PLACE}}", lastPlace + ".") .replace("{{NAME}}", a.user) .replace("{{LANGUAGE}}", a.language) .replace("{{SIZE}}", a.size) .replace("{{LINK}}", a.link); answer = jQuery(answer); jQuery("#answers").append(answer); var lang = a.language; if (/<a/.test(lang)) lang = jQuery(lang).text(); languages[lang] = languages[lang] || {lang: a.language, user: a.user, size: a.size, link: a.link}; }); var langs = []; for (var lang in languages) if (languages.hasOwnProperty(lang)) langs.push(languages[lang]); langs.sort(function (a, b) { if (a.lang > b.lang) return 1; if (a.lang < b.lang) return -1; return 0; }); for (var i = 0; i < langs.length; ++i) { var language = jQuery("#language-template").html(); var lang = langs[i]; language = language.replace("{{LANGUAGE}}", lang.lang) .replace("{{NAME}}", lang.user) .replace("{{SIZE}}", lang.size) .replace("{{LINK}}", lang.link); language = jQuery(language); jQuery("#languages").append(language); } } ``` ``` body { text-align: left !important} #answer-list { padding: 10px; width: 290px; float: left; } #language-list { padding: 10px; width: 290px; float: left; } table thead { font-weight: bold; } table td { padding: 5px; } ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//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] # [MATL](https://github.com/lmendo/MATL), 12 bytes ``` kune2M&SY)1e ``` [**Try it online!**](http://matl.tryitonline.net/#code=a3VuZTJNJlNZKTFl&input=J2JEYUVjJwonS2V5IGNhbiBiZSBpbiBtdWx0aWNhc2UhJw) ### Explanation The code works using rows instead of columns. This is totally equivalent and fits better with MATL's column-major indexing. ``` k % Take first input (key) implicitly. Convert to lowercase u % Keep unique chars, stably n % Number of unique chars e % Take second input (message) implicitly. Reshape into char matrix % with the above number of rows, padding with zeros if needed 2M % Push string with unique chars of key again &S % Sort and push the indices of the sorting Y) % Use as row indices into char matrix 1e % Reshape into a row. Zeros are displayed as spaces ``` [Answer] # Python 3, 188 bytes. There's gotta be a saner way to do this. ``` from itertools import* def f(a,b):a,c,s=a.upper(),''.join,sorted;return c(map(c,zip_longest(*[v for k,v in s([(v,b[i::len({*a})])for i,v in enumerate(s({*a},key=a.find))])],fillvalue=''))) ``` Test cases: ``` assert f('goat', 'Hello World!') == 'lHelWo odrl!' assert f('GOAT', 'Hello World!') == 'lHelWo odrl!' assert f('GOAATAT', 'Hello World!') == 'lHelWo odrl!' assert f('CBABD', 'Duplicates are ignored.') == 'puDlacit sea eriongr.de' ``` Well that was a fun journey back to square one. [Answer] ## JavaScript (ES6), 170 bytes ``` (k,s)=>[...s].map((c,i)=>(i%l||(r+=t.join``,t=[]),t[[...k].sort().search(k[i%l])]=c),k=[...k=k.toLowerCase()].filter((c,i)=>i==k.search(c)),l=k.length,r=t=[])&&r+t.join`` ``` Preprocessing the key is a waste of 56 bytes... [Answer] ## Javascript, 155 ~~159~~ ~~149~~ ~~151~~ ``` (w,s)=>(a='',z=new Set,w=[...[...w].map(z.add,z)[0]].sort(),eval(`s.match(/.{1,${z.size}}/g)`).map(l=>[...l].map((c,i)=>a+=l[[...z].indexOf(w[i])]||'')),a) ``` * Saved 4 bytes thanks [@Bergi](https://stackoverflow.com/questions/37199019/method-set-prototype-add-called-on-incompatible-receiver-undefined#comment61931999_37199019). --- Here it goes, ungolfed and explained: ``` function ColumnarTranspositionCipher(word, sentence) { var answer = ""; // the own methods of Set does it shorter than a raw Object var z = new Set; // As Set only allows unique keys, we get the processed key by adding [...word].forEach(function(letter) { z.add(letter); }); // word now has the sorted key word = [...z].sort(), // divide sentence by the processed key's length sentence = sentence.match(RegExp(".{1," + z.size + "}", "g")); sentence.forEach(function(row) { [...row].forEach(function(letter, newIndex) { // get the old index - relative to the previous sorted/unsorted keys var oldIndex = [...z].indexOf(word[newIndex]); // and add to the answer answer += row[oldIndex] || ""; }); }); return answer; } r= code=> output.innerHTML += '\n> ' + code + '\n<- "' + eval(code) + '"\n'; r("ColumnarTranspositionCipher('GOAT', 'Hello World!')"); r("ColumnarTranspositionCipher('CBABD', 'Duplicates are ignored.')"); r("ColumnarTranspositionCipher('aBeCd', 'Key can be in multicase!')"); ``` ``` <pre id=output></pre> ``` [Answer] # Python 3.5, 139 ``` def f(a,b):a,s,j=a.lower(),sorted,''.join;a=s({*a},key=a.find);l=len(a);return j(map(j,[*zip(*s(zip(*zip(*[iter(a+[*b+' '*l])]*l))))][1:])) ``` Slightly more readable version: ``` def f(a, b): a = a.lower() # Remove duplicates a = sorted({*a}, key=a.find) l = len(a) # Add the key z = zip(*[iter(a + [*b, *[''] * l])]*l) # Sort tuples lexicographically, remove the key z = [*zip(*sorted(zip(*z)))][1:] return ''.join(map(''.join, z)) ``` [Answer] # J, 53 bytes ``` (3 :',/|:((/:tolower~.>0{y){|:((-#~.>0{y),\(>1{y)))') ``` Usage example: `(3 :',/|:((/:tolower~.>0{y){|:((-#~.>0{y),\(>1{y)))') ('ADCB';'"Good Morning!" he called.')` ==> `"ooGdoM rning "!hc eaelld .` I basically did exactly what the cipher does, no shortcuts. I had to transpose the matrix to deal with ranking the columns then transpose it back. [Try it Online!](http://webchat.freenode.net/?channels=jsoftware&randomnick=1 "Try it online!") (make sure to type "j-bot: " without quotes then paste the code.) [Answer] ## Haskell, ~~98~~ ~~84~~ 83 bytes ``` import Data.List h c=map snd.sort.zip((<$>nub((`mod`32).fromEnum<$>c)).(,)=<<[1..]) ``` Usage example: `h "CBAbD" "Duplicates are ignored."` -> `"puDlacit sea eriongr.de"`. How it works: ``` nub((`mod`32).fromEnum<$>c) -- turn key to lowercase and remove duplicates (<$> ).(,)=<<[1..] -- make pairs of (number , char from key) -- for every character in the key and every -- number starting with 1. This builds and -- infinite list, e.g. for the key "cba": -- (1,c),(1,b),(1,a),(2,c),(2,b),(2,a),(3,c)... zip( ) -- zip this list with input String, e.g. for -- the string "mnopq" with the key from above: -- ((1,c),m),((1,b),n),((1,a),o),((2,c),p),((2,b),q) -- zip stops at the end of the shorter list sort -- sort lexicographically map snd -- extract characters of the string ``` [Answer] # Ruby, 133 bytes Zip, sort, zip again, combine. ``` ->k,s{k=k.upcase.chars.uniq c,*r=k.zip(*s.scan(/.{1,#{k.size}}/).map(&:chars)).sort c.zip(*r.map{|e|e ?e:' '})[1..-1].map(&:join)*''} ``` [Answer] # R, 182 177 Here is the golfed version: ``` function(t,k){k=unique(unlist(strsplit(tolower(k),"")));t=unlist(strsplit(t,""));l=length(t);c=length(k);r=ceiling(l/c);t=c(t,rep("",c*r-l));cat(matrix(t,r,c)[order(rank(k)),])} ``` And ungolfed version, which shows how the function takes the data. ``` # test data key = "aBeCd" test = "ABCDEabcdeABCDEabcdeABC!" # t is the test phrase, k is the key cipher=function(t,k){ k=unique(unlist(strsplit(tolower(key),""))) t=unlist(strsplit(test,"")) l=length(t) c=length(k) r=ceiling(l/c) t=c(t,rep("",c*r-l)) cat(matrix(t,r,c)[order(rank(k)),]) } # Show that it works cipher(test,key) ## A B D E C a b d e c A B D E C a b d e c A B ! C ``` The test cases provided by the OP seem incorrect. I intentionally chose a test case here that makes it more clear what is happening to the letters, and this seems correct. [Answer] ## Q, 52 Bytes ``` f:{n:#u::?_x;,/+(+(0N;n)#(n*-_-(#y)%n)#y,n#" ")@<u} ``` NOTE.- defined as function named f to facilitate tests. As an anonymous function we delete chars f: (50 Bytes) **Test** Interpreter (evaluation but unrestricted) downloadable by not fee at kc.com (windows/linux/mac versions) ``` f["CBABD"]"Duplicates are ignored." /"puDlacit sea eriongr.de" f["bDaEc"]"Key can be in multicase!" /"yKce aenbn mi tucliea s!" ``` **Explanation** `n:#u:?_x` u is unique chars in lowercase key, and n its length `(n*-_-(#y)%n)#y,n#" "` appends blanks to accomplish 'space surplus' rule. `%` is division `-_-` implements ceil as negate floor negate, so `(n*-_-(#y)%n)` is the length required by space surplus. `y,n#" "` append n blank spaces to end of text, and then take length of that extended text ``` (0N;n)#.. takes items of sequence .. to fill a matrix of n columns by row ``` `+(..)` flip that matrix (traspose) to work by rows `@<u` selects row indexes by ascending index order of u ``` ,/(..) concatenates the resulting matrix to obtain a text ``` ]
[Question] [ # The Challenge: Just as the title says, your challenge is to use the printable ASCII characters to create a program that prints out a random polygon in the terminal based on the number of sides, *n* provided by the user, where n is an integer in the range `3 -> 10` including 3 and 10, in as few bytes as possible. **For example:** If n = 4 it should print out a 4 sided shape. For instance, it may print out a square, like so: ``` ______ | | | | |______| ``` However, if the program is called again with the same attribute of n=4, it should print out a different polygon based on the same number of sides. For instance, maybe a plain, old parallelogram this time, like so: ``` ______________ / / / / /_____________/ ``` As another example, consider n=6. At least once, it should print out a 6-sided polygon, such as the convex hexagon shown below: ``` ________ / \ / \ / \ \ / \ / \________/ ``` But another time, it should print out a visually different polygon with 6 sides, for instance, maybe a concave hexagon like the following: ``` ________ \ / \ / \ / / \ / \ /______\ ``` Finally, as a last example, if n=3, it may print out an isosceles triangle: ``` / \ / \ /_____\ ``` However, another call with the same attribute should print out another kind of triangle, maybe like the following right triangle: ``` /| / | /__| ``` **EDIT:** To fulfill @CatsAreFluffy's request, here is an example of an ASCII nine-sided polygon: ``` ___ / \ / \ / \ \ / \ / \ / / \ / \ / \ \ / \ / \ / \ / v ``` **NOTE: These are all just *examples*. Your polygons can be drawn in any style, as long as they meet the guidelines shown below.** # Guidelines: * Each number of sides, from 3-10, should have at least 2 different shapes associated with it. * The program should print out a random shape from the shapes associated with each number of sides each time the program is executed with a specific number of visually distinguishable sides in the range `3 -> 10` given as an argument. * The sides of the each polygon can be any length, such that every shape able to be drawn by the entire program has at least one side with the same length as all the others. For instance, a triangle should have at least one side with the same length as one of the sides of a parallelogram. So should the square, pentagons, rectangles, etc. with the parallelogram, and also with each other. As a reference, in the examples given in the challenge sections, each shape has at least one side with a length of 3 slashes. * Standard loopholes apply. [Answer] # Java, ~~1887~~ 1866 bytes [Try in on Ideone](http://ideone.com/waOFop) Saved 21 bytes due to unneeded "public" headers (Thanks to @Bálint!) Not exactly a golfing challenge, but hey, why not? I feel Java might actually be the best language for this challenge because no esolang could handle this, and many others don't have as good list manipulation (although Java's takes way more bytes). Golfed: ``` import java.util.*;public class A{public static void main(String[]args){System.out.print((new P()).b(Integer.parseInt((new Scanner(System.in)).next())).s());}}class P{S p;public S b(int w){p=new S(w);int j=-1,k=-1,f=(w%2)*2,t,y,x;for(x=0;x<w/2-2+w%2;x++){t=r();y=r();if(j==t|k==y|t==y){x--;continue;}g(t,true,2);g(y,false,2-f);f=0;j=t;k=y;}while(1>0){t=r();y=r();if(w<4&t<1&y<1)continue;if(j==t|k==y|t==y|j==y){x--;continue;}g(t,true,3);g(y,false,3+(w<4?0:(w%2)*2));break;}return p;}void g(int w,boolean b,int h){if(w<1)p.u(h,b);else if(w<2)p.r(h,b);else p.l(h,b);}int r(){return (int)(Math.random()*3);}}class S{List<List<Character>>q,a;int h,s,u,o,e,r,b,t,g,n,m,x,y;public S(int d){s=d;h=s+s%2-1;u=h;o=h;b=s>3?(int)(Math.random()*3*s)+1:0;q=new ArrayList<List<Character>>();a=new ArrayList<List<Character>>();for(x=0;x<h;x++){q.add(new ArrayList<Character>());a.add(new ArrayList<Character>());}i(0,q);i(0,a);e=1;r=1;t=0;g=0;n=0;m=0;}public String s(){String p="";for(x=0;x<e+b+r;x++)p+=x>t+(s<4?1:0)&x<e+b+g?'_':' ';p+="\n";for(y=0;y<h;y++){for(x=0;x<e;x++)p+=y>h-2&x>n?'_':q.get(y).get(x);for(x=0;x<b;x++)p+=y>h-2?'_':' ';for(x=0;x<r;x++)p+=y>h-2&x<m-1?'_':a.get(y).get(x);p+="\n";}return p;}void i(int i,List<List<Character>>z){for(List<Character>l:z)l.add(i,' ');if(z==q){e++;if(i<=t)t++;if(i<=n)n++;}else{r++;if(i<=g)g++;if(i<=m)m++;}}void u(int v,boolean i){if(i){u-=v;for(y=0;y<v;)q.get(u+y++).set(t,'|');}else{o-=v;for(y=0;y<v;)a.get(o+y++).set(g,'|');}}void l(int v, boolean i){if(i){x=v-t;while(x-->0)i(0,q);t=x>0?0:t-v;u-=v;for(y=0;y<v;)q.get(y+u).set(t+y++,'\\');}else{x=v-g;while(x-->0)i(0,a);g=x>0?0:g-v;o-=v;for(y=0;y<v;)a.get(y+o).set(g+y++,'\\');}}void r(int v,boolean i){if(i){t+=v;y=t;while(e<=y)i(e,q);t=y-1;u-=v;for(y=0;y<v;)q.get(u+y).set(t-y++,'/');}else{g+=v;y=g;while(r<=y)i(r,a);g=v<1?g:y-1;o-=v;for(y=0;y<v;)a.get(o+y).set(g-y++,'/');}}} ``` Must be in file called `A.java` (for obvious reasons). To run: 1. In the terminal, type `javac A.java` 2. Then, if it gives you no errors, type `java A` 3. Finally, type the number of sides. This program actually supports side lengths up to 65536 As you can see in the example output below, the corners tend to be more open, and the sides not as smooth, as compared to the polygons in the examples. Also, it cannot produce a square, but still follows the official guidelines. If there are any problems I can change the answer to fix them. Sample output: ``` 3 / | / | /___| 4 ____ / \ / \ /________\ 5 _________ / | / | / | \ | \ _________| 6 ____________ | \ | \ | \ / | /_______________ | 7 _____________________ \ / \ / \ / | / | / \ \ \ _____________\ 8 _______________ \ / \ / \ / | \ | \ / | /____________ | 9 __________ \ / \ / \ / | / | / / \ / \ | | |_____ | 10 ____ / \ / \ / \ | / | / \ | \ | / \ /________\ ``` EDIT: Finally! the ungolfed code is here! It's a bit long, but you probably already guessed that... I will get to the explanation soon. ``` import java.util.*; public class ASCII_Polygon_Driver { public static void main(String[] args) { System.out.print(P.b(Integer.parseInt((new Scanner(System.in)).next()))); } } class P { static S p; public static S b(int w) { p = new S(w); int l1=-1,l2=-1,f=(w%2)*2,r1,r2,x; for(x=0;x<w/2-2+w%2;x++) { r1=r(); r2=r(); if(l1==r1){x--;continue;} if(l2==r2){x--;continue;} if(r1==r2){x--;continue;} g(r1,true,2); g(r2,false,2-f); f=0; l1=r1; l2=r2; } while(true) { r1=r(); r2=r(); if(w<4&r1<1&r2<1)continue; if(l1==r1|l2==r2|r1==r2|l1==r2){x--;continue;} g(r1,true,3); g(r2,false,3+(w<4?0:(w%2)*2)); break; } return p; } static void g(int w,boolean b,int h) { if(w<1)p.goUp(h,b); else if(w<2)p.goRight(h,b); else p.goLeft(h,b); } static int r() { return (int)(Math.random()*3); } } class S { public List<List<Character>> area1; public List<List<Character>> area2; private int wid1; private int wid2; private int spcb; public int hght; private int top1; private int top2; private int bot1; private int bot2; private int mid1; private int mid2; public int sides; private int x; private int y; public int y1; public int y2; public S(int numSides) { sides = numSides; hght = sides+sides%2-1; y1=hght; y2=hght; spcb = sides>3?(int)(Math.random()*3*sides)+1:0; area1 = new ArrayList<List<Character>>(); area2 = new ArrayList<List<Character>>(); for(x=0;x<hght;x++) { area1.add(new ArrayList<Character>()); area2.add(new ArrayList<Character>()); } insertCollum1(0); insertCollum2(0); wid1 = 1; wid2 = 1; top1 = 0; top2 = 0; bot1 = 0; bot2 = 0; } public String toString() { String out =""; for(x=0; x<wid1+spcb+wid2; x++) { out+=x>top1+1&x<wid1+spcb+top2?'_':' '; } out+="\n"; for(y=0; y<hght; y++) { for(x=0; x<wid1; x++)out+=y>hght-2&x>bot1?'_':area1.get(y).get(x); for(x=0; x<spcb; x++)out+=y>hght-2?'_':' '; for(x=0; x<wid2; x++)out+=y>hght-2&x<bot2-1?'_':area2.get(y).get(x); out+="\n"; } return out; } private void insertCollum1(int index) { for(List<Character> line : area1) { line.add(index,' '); } wid1++; if(index<=top1)top1++; if(index<=bot1)bot1++; } private void insertCollum2(int index) { for(List<Character> line : area2) { line.add(index,' '); } wid2++; if(index<=top2)top2++; if(index<=bot2)bot2++; } /*private void setChar1(int x, int y, char character, List<List<Character>> which) { which.get(y).set(x,character); }*/ public void goUp(int howMany, boolean is1) { if(is1) { y1-=howMany; for(y=0;y<howMany;) { area1.get(y1+y++).set(top1,'|'); } } else { y2-=howMany; for(y=0;y<howMany;) { area2.get(y2+y++).set(top2,'|'); } } } public void goLeft(int howMany, boolean is1) { if(is1) { x = howMany-top1; while(x-->0)insertCollum1(0); top1 = Math.max(0,top1-howMany); y1-=howMany; for(y=0;y<howMany;) { area1.get(y+y1).set(top1+y++,'\\'); } } else { x = howMany-top2; while(x-->0)insertCollum2(0); top2 = Math.max(0,top2-howMany); y2-=howMany; for(y=0;y<howMany;) { area2.get(y+y2).set(top2+y++,'\\'); } } } public void goRight(int howMany,boolean is1) { if(is1) { top1+=howMany; y=top1; while(wid1<=y)insertCollum1(wid1); top1=y-1; y1-=howMany; for(y=0;y<howMany;) { area1.get(y1+y).set(top1-y++,'/'); } } else { top2+=howMany; y=top2; while(wid2<=y)insertCollum2(wid2); top2=howMany<1?top2:y-1; y2-=howMany; for(y=0;y<howMany;) { area2.get(y2+y).set(top2-y++,'/'); } } } } ``` ]
[Question] [ An [*linear discrete convolution*](https://en.wikipedia.org/wiki/Convolution#Discrete_convolution) is an operation that turns two vectors of numbers into a third vector of numbers by multiplying elements inside-out. Formally, for two vectors `a` and `b` with elements `0` to `n - 1`, the discrete linear convolution of `a` and `b` can be computed with this loop: ``` for i = 0 to 2*n - 2 c[i] = 0; for j = 0 to n - 1 if i - j >= 0 and i - j < n c[i] = c[i] + a[j] * b[i - j]; ``` As an example, the convolution of `a = { 1, 2, 3, 4 }` and `b = { 5, 6, 7, 8 }` is `c = { 5, 16, 34, 60, 61, 52, 32 }`. These convolutions appear when doing long multiplication, for example: ``` 1234 * 5678 = 20 24 28 32 15 18 21 24 10 12 14 16 5 6 7 8 -------------------- 5 16 34 60 61 52 32 -------------------- 32 52 61 60 34 16 5 -------------------- 7006652 ``` Your task is to write a program or function that, given two arrays (or similar) `a` and `b` of non-negative integers of equal length `n` and optionally, `n` and an output array `c`, computes the linear discrete convolution of `a` and `b` and returns it, assigns it to the parameter `c`. or prints it out. You may also take input from the user while or before your code is running. The following constraints apply: * Your program must run in subquadratic or o(*n* 2) time. An algorithm like the pseudo-code above that runs in quadratic time Θ(*n* 2) is invalid. * You may assume that all integers in in- and output are in the range from 0 to 65535, this also applies to `n`. * You may not claim that your algorithm runs in subquadratic time because `n` has an upper bound. * The results must be exact. * This is code golf, the shortest code in octets wins. * You may not use existing library routines or similar to compute a Fourier transform or a number theoretic transform or the respective inverse transformations. [Answer] ## Python 2, 250 bytes, n^log\_2(3) ``` s=lambda a,b,S=1:[x+y*S for x,y in zip(a,b)] def f(a,A): n=len(a);m=n/2 if m<1:return[a[0]*A[0]] if n%2:return f([0]+a,[0]+A)[2:] b,c=a[:m],a[m:];B,C=A[:m],A[m:];p=f(b,B);r=f(c,C);z=m*[0];return s(z+z+r,s(z+s(f(s(b,c),s(B,C)),s(p,r),-1)+z,p+z+z)) ``` This isn't well golfed, but more a proof of concept of the algorithm. Let's look at a more readable version. ``` s=lambda a,b,S=1:[x+y*S for x,y in zip(a,b)] def f(a,A): n=len(a) if n==1:return[a[0]*A[0]] if n%2:return f([0]+a,[0]+A)[2:] m=n/2 b,c=a[:m],a[m:] B,C=A[:m],A[m:] p=f(b,B) r=f(c,C) q=s(f(s(b,c),s(B,C)),s(p,r),-1) z=m*[0] return s(z+z+r,s(z+q+z,p+z+z)) ``` The idea is to divide and conquer adapting the [Karatsuba multiplication algorithm](https://en.wikipedia.org/wiki/Karatsuba_algorithm) to do convolution. As before, it runs in time `n^log_2(3)`, as it makes 3 recursive calls which shrink the input length in half. This isn't as good as the quasilinear of DFT, but still better than quadratic. We can think of convolution as multiplication of formal polynomials. Alternatively, if multiplication were done without regrouping, you'd get convolution. So, adapting the algorithm only requires doing vector addition and subtraction instead of the numerical operations. These additions are still linear-time. Unfortunately for Python, it doesn't have built-in vector addition and subtraction, so we hack together a function `s` to do both: addition by default, and subtraction when passed an optional argument of `-1`. Whenever we add, we make sure to pad with zeroes to avoid truncation. We handle odd list lengths by padding with a zero to an even length, removing the extraneous zeroes that result. [Answer] # J, 79 bytes, *O*(*n* log *n*) ``` f=:_2&(0((+,-)]%_1^i.@#%#)&f/@|:]\)~1<# <:@+&#$9(o.f%#)[:+@*/;f@{.&>~2^#@#:@+&# ``` Uses the Convolution theorem which states that the Fourier transform of the convolution of two sequences is equal to the Fourier transform of each sequence multiplied together elementwise. ``` Fourier( Convolve(a, b) ) = Fourier(a) * Fourier(b) Convolve(a, b) = InverseFourier( Fourier(a) * Fourier(b) ) ``` Also uses the fact the the inverse Fourier transform can be applied by using the Fourier transform of the conjugate. ``` InverseFourier(a) = Conjugate( Fourier( Conjugate(a) ) ) / Length(a) ``` I used the FFT implementation from a previous [solution](https://codegolf.stackexchange.com/a/12475/6710). That implementation uses the Cooley-Tukey [algorithm](https://en.wikipedia.org/wiki/Cooley%E2%80%93Tukey_FFT_algorithm) for sequences where the length is a power of 2. Therefore, I have to zero-pad the input sequences to the a power of 2 (typically the minimal value that is valid) such that their lengths are greater than or equal to the sum of the lengths of the input sequences. ## Usage ``` f =: _2&(0((+,-)]%_1^i.@#%#)&f/@|:]\)~1<# g =: <:@+&#$9(o.f%#)[:+@*/;f@{.&>~2^#@#:@+&# 1 2 3 4 g 5 6 7 8 5 16 34 60 61 52 32 2 4 5 6 1 g 1 2 4 7 2 8 21 46 61 61 46 7 ``` [Try it online!](https://tio.run/##JcpLDoIwFIXhOas4yZWmtVpsfaAVzd2HPAbGok5YgIat14LD853/HWPAxaNzQm6k1Ku1avLOti/DlJMSoeCvb2o12oqyfiorz1rQ4iQHE1Jx85qXxTnwx4jr6FpimoMse9yfAywcttihxx4HlDj@2SWawKbDzquM8Qc) ## Explanation An explanation for the FFT portion in J is included in my previous [solution](https://codegolf.stackexchange.com/a/12475/6710) to a different challenge. ``` <:@+&#$9(o.f%#)[:+@*/;f@{.&>~2^#@#:@+&# Input: A on LHS, B on RHS # Get the lengths of A and B +& Sum them #:@ Get list of binary digits #@ Length 2^ Raise 2 to that power, call it N ; Link A and B as a pair of boxed arrays &>~ For each box {. Take N values, extending with zeros f@ Apply FFT to it [: */ Reduce using multiplication +@ Conjugate f Apply FFT % Divide by # Length 9 o. Take the real part # Get the lengths of A and B +& Sum them <:@ Decrement $ Shape to that length and return ``` [Answer] # Mathematica, 214 bytes, O(n log n) ``` f@{a_}:={a} f@a_:=#~Join~#+Join[#2,#2]Exp[2.Most@Range[0,1,1/Length@a]Pi I]&@@f/@Thread@Partition[a,2] (l=Length@#;RotateLeft[Round[#/Length@#]][[-1;;(1-2l);;-1]]&@f[Times@@(f@PadRight[#,2^Floor[2+Log2@l]]&/@{##})])& ``` Function `f` performs FFT, which is called several times. No built-in FFT is used here. ``` %[{1,2,3,4},{5,6,7,8}] (* {5,16,34,60,61,52,32} *) ``` ]
[Question] [ Consider the following ASCII image of five concentric anti-aliased ASCII aureoles: ``` ........ .@..............@. ..... ..... .@.. ...@@@@@@@@... ..@. .@. ..@@.. ..@@.. .@. .@. .@@. ........ .@@. .@. .@ @@ .@@@@@..@@@@@. @@ @. .@ @. .@@. .@@. .@ @. @. @@ @@. @@@@@@@@ .@@ @@ .@ .@ .@ .@. @@@. .@@@ .@. @. @. .@ @@ @@ @@ @@ @@ @@ @@ @. .@ @@ @@ @@ @@ @@ @@ @@ @. .@ .@ .@. @@@. .@@@ .@. @. @. @. @@ @@. @@@@@@@@ .@@ @@ .@ .@ @. .@@. .@@. .@ @. .@ @@ .@@@@@..@@@@@. @@ @. .@. .@@. ........ .@@. .@. .@. ..@@.. ..@@.. .@. .@.. ...@@@@@@@@... ..@. ..... ..... .@..............@. ........ ``` You must write a program to draw a given subset of the above circles in as few characters as possible. The input is either five booleans in your choice of formatting (be it `1 1 1 1 1` or `[False, True, False, False, True]`), with the first boolean corresponding to the inner-most circle, or an integer where the least-significant bit corresponds to the inner circle (e.g. `1 0 0 1 1` is equivalent to `25`). Output for `1 1 1 1 1`/`31`: see above. Output for `1 0 1 0 1`/`21`: ``` ........ .@..............@. ..... ..... .@.. ..@. .@. .@. .@. ........ .@. .@ .@@@@@..@@@@@. @. .@ .@@. .@@. @. @. @@. .@@ .@ .@ .@. .@. @. .@ @@ @@ @@ @. .@ @@ @@ @@ @. .@ .@. .@. @. @. @@. .@@ .@ .@ .@@. .@@. @. .@ .@@@@@..@@@@@. @. .@. ........ .@. .@. .@. .@.. ..@. ..... ..... .@..............@. ........ ``` Output for `0 0 0 1 0`/`8` (note the leading whitespace): ``` ...@@@@@@@@... ..@@.. ..@@.. .@@. .@@. @@ @@ @. .@ @@ @@ .@ @. @@ @@ @@ @@ .@ @. @@ @@ @. .@ @@ @@ .@@. .@@. ..@@.. ..@@.. ...@@@@@@@@... ``` The aureoles themselves must be exactly as presented above. However, trailing whitespace is optional. Also, if some outer aureoles are missing, it is up to you whether your program outputs the leading empty lines or the trailing empty lines. [Answer] # JavaScript (ES5), 359 bytes Place input into `I`, get output on stdout/console. ``` I=[1,1,1,1,1];a='----- 88880----8988888880-- 88888-- 0--8988- 66677770- 898- 667766- 0-898-6776- 44440 89- 77- 45555540 89- 76-4554- 0 98-77-554-3333089-67-454-3332 089-77-55-33-1'.replace(/-/g,' ').split(0);for(i=11;i--;)a.push(a[i]+=a[i].split('').reverse().join(''));console.log(a.join('\n').replace(/\d/g,function(d){return I[d>>1]?'.@'[d&1]:' '})) ``` [Answer] # JavaScript (E6) 272 ~~314~~ On par with the other JS answers, a function returning a string. Add 13 byte if an output statement is requested (console.log()). The function parameter is an array of 5 truthy/falsy values. **Edit** Shorter implementation of the same algorithm The string at line 2 codify the lower right quarter of the rings. The others are obtained thanks to simmetry * ' ' space mark line end * digit (1..9) mark a sequence of blank spaces * hex digit (A..F or a..f) mark a sequence of symbols, if lowercase '.' else '@' Rendering the lines, it checks the boolean params and output symbols or an equal number of spaces ``` F=f=> [for(c of(l=d=0,o=t=[],'A3B3B3B3Aa 1aC3aAa3Aa3Aa D3aB3B3aA1 5aBa3aA4Aa1 aEa4B4Aa2 d4aBa3aAa3 4bBb4aAa4 Dc4bAa6 8e8 cdAa66 d89 ')) c<'1'?(l=(t=[o,...t,o]).length/5.1|0,d=1,o='') :o=(p=(-c||!f[l+=d]?' ':c>'F'?'.':'@').repeat(-c?(d=1,c):(d=0,'0x'+c-9)))+o+p] &&t.join('\n') ``` **Test** In FireFox/FireBug console ``` F([1,0,1,0,1]) (or F[1,,1,,1]) ``` *Output* ``` ........ .@..............@. ..... ..... .@.. ..@. .@. .@. .@. ........ .@. .@ .@@@@@..@@@@@. @. .@ .@@. .@@. @. @. @@. .@@ .@ .@ .@. .@. @. .@ @@ @@ @@ @. .@ @@ @@ @@ @. .@ .@. .@. @. @. @@. .@@ .@ .@ .@@. .@@. @. .@ .@@@@@..@@@@@. @. .@. ........ .@. .@. .@. .@.. ..@. ..... ..... .@..............@. ........ ``` [Answer] ## JavaScript ES6, 567b (WIP) Execute this code in the JS/NodeJS console to display the result in the console. the array "a" at the beginning contains the input. ``` a=[1,0,1,0,1];(z=a=>a+a.split("").reverse().join(""))(b=[" 0000"," 010000000"," 00000 "," 0100 2223333"," 010 223322 "," 010 2332 4444"," 01 33 4555554"," 01 32 4554 "," 10 33 554 7777","01 23 454 7776 ","01 33 55 77 9",""].map(z).join("\n")[r="replace"](/0/g,a[0]?".":" ")[r](/1/g,a[0]?"@":" ")[r](/2/g,a[1]?".":" ")[r](/3/g,a[1]?"@":" ")[r](/4/g,a[2]?".":" ")[r](/5/g,a[2]?"@":" ")[r](/6/g,a[3]?".":" ")[r](/7/g,a[3]?"@":" ")[r](/9/g,a[4]?"@":" "))[r]("\n\n","\n") ``` ]
[Question] [ *Initech* are setting up an office of 36 employees in a soul-crushingly efficient square of cubicles, 6 desks long and 6 desks deep. Management has bought wireless keyboards in bulk from a cheap, international wholesaler. IT are quickly discovering that the wireless keyboards only operate on 3 different radio frequencies, and each individual keyboard is hardwired to a particular frequency. When two keyboards on the same frequency are too close to each other, they interfere with each other. The only identifying mark on the keyboards is a unique serial number which gives no clues as to the keyboard's radio frequency. Thankfully there are an equal number of keyboards operating on each frequency. A keyboard can be defined by the following class. ``` sealed class WirelessKeyboard { private int frequency; private int serialNum; public WirelessKeyboard(int frequency, int serialNum) { this.frequency = frequency; this.serialNum = serialNum; } public bool InteferesWith(WirelessKeyboard other) { return this.frequency == other.frequency; } public int getSerialNum() { return serialNum; } } ``` Your function must accept an array of 36 `WirelessKeyboard` objects. Each is predefined with a unique serial number and one of the three frequencies (12 keyboards of each frequency). The array is in random order. The only way to determine a keyboard's frequency is to test if it interferes with another keyboard. Your function must: * Not modify or extend the `WirelessKeyboard` class beyond translating it into your programming language of choice. * Accept an input array of `WirelessKeyboard` objects. * Not create or alter any `WirelessKeyboard` objects. Only those in the input may be used. * Not use any means (eg. reflection) to read a keyboard's frequency. * Output a 6x6 array (or equivalent) populated with `WirelessKeyboard` objects, which: + Contains all 36 unique keyboards. + `InteferesWith(other)` must return false for all horizontally and vertically adjacent keyboards. For the sake of code golf, the `WirelessKeyboard` class may be aliased as `K` and code may be written as a function. For example, in C/Java, ungolfed and golfed: ``` WirelessKeyboard[,] FindMap(WirelessKeyboard[] collection) { ... } K[,]F(K[]c){ ... } ``` The shortest code in a week gets the points. Please post your implementation of the `WirelessKeyboard` class if it differs significantly from the sample above, but do not count it towards your score. The function and any dependant declarations (eg. library imports) count towards your score. [Answer] # Julia, 97 chars ``` s(k)=while any([k[j]>k[j-1]||j>6&&k[j]>k[j-6] for j=2:36]);i,j=rand(1:36,2);k[[i,j]]=k[[j,i]];end ``` Checks if the array is in an acceptable final state state, if not, randomly flips two entries. It's super slow, which I find highly amusing. Does an in place alteration on the input array `k`. InterferesWith is implemented as `>`. As I said, it's really slow. I tested it with more frequencies and smaller boards with 3 frequencies, but it hasn't returned in over 30 mins on the actual problem. I suspect that it won't return overnight, but I'll update if it does. Update: Yes it did finish in less than 12 hours, and yielded an answer that I added to the gist. Gist with commented code, and includes 3x3 test case that finishes fast: <https://gist.github.com/ggggggggg/8679916> [Answer] ## Ruby, 108 Here's my WirelessKeyboard class, similar to @gggg I have used a shorter alias for the `InterferesWith` method. ``` class K attr_reader :freq, :serial protected :freq def initialize freq, serial @freq, @serial = freq, serial end def interferes_with other self.freq == other.freq end alias :i :interferes_with def inspect '%3i:%i' % [serial, freq] end end ``` My actual code: ``` f=->k{r=k.group_by{|e|e.i(a=k[0])?0:e.i(k.find{|e|!e.i a})?1:2} (v=0..5).map{|y|v.map{|x|r[(x+y%2)%3].pop}}} ``` Test run: ``` keyboards = (0..35).map { |i| K.new(i%3, i) }.shuffle puts f[keyboards].map { |r| r.map { |c| c.inspect }*' ' } ``` Result: ``` 23:2 34:1 33:0 8:2 25:1 24:0 19:1 12:0 20:2 4:1 21:0 29:2 2:2 16:1 18:0 35:2 7:1 27:0 28:1 0:0 17:2 13:1 15:0 5:2 26:2 22:1 6:0 32:2 10:1 3:0 1:1 30:0 11:2 31:1 9:0 14:2 ``` [Answer] ## PHP 200 ``` <? function O($K){$O=[[],[],[]];foreach($K as$v){foreach($O as&$d){if(!$d||$v->I($d[0])){$d[]=$v;break;}}}$i=6;while($i--){$j=6;while($j--){$v=$j%3+$i%3;$v>2&&$v-=3;echo array_pop($O[$v]);}echo"\n";}} ``` sample result ``` 10-1 32-2 6-0 1-1 20-2 15-0 2-2 24-0 19-1 11-2 30-0 28-1 18-0 25-1 29-2 21-0 4-1 5-2 16-1 35-2 3-0 22-1 14-2 12-0 8-2 9-0 7-1 17-2 33-0 13-1 0-0 31-1 23-2 27-0 34-1 26-2 ``` testcase+class <http://codepad.org/UtjNt7qV> (the class has a `__toString` to be `echo`able [Answer] ## C#, 269 bytes ``` using System.Linq; WirelessKeyboard[,] FindMap(WirelessKeyboard[] collection) { var list = collection.ToList(); var map = new WirelessKeyboard[6, 6]; map[0, 0] = list[0]; list.Remove(map[0, 0]); map[1, 0] = list.First(keyboard => !keyboard.InteferesWith(map[0, 0])); list.Remove(map[1, 0]); map[2, 0] = list.First(keyboard => !keyboard.InteferesWith(map[0, 0]) && !keyboard.InteferesWith(map[1, 0])); list.Remove(map[2, 0]); for (int y = 0; y < 6; y++) { int x = y == 0 ? 3 : 0; for (; x < 6; x++) { map[x, y] = list.First(keyboard => keyboard.InteferesWith(map[(x + y) % 3, 0])); list.Remove(map[x, y]); } } return map; } ``` The golfed code with `InterferesWith` defined as `I`: ``` using System.Linq; K[,]F(K[]c) { var l=c.ToList(); var m=new K[6,6]; l.Remove(m[0,0]=l[0]); l.Remove(m[1,0]=l.First(k=>!k.I(m[0,0]))); l.Remove(m[2,0]=l.First(k=>!k.I(m[0,0])&&!k.I(m[1,0]))); for(int x=2;++x<36;){ l.Remove(m[x%6,x/6]=l.First(k=>k.I(m[(x+x/6)%3,0]))); } return m; } ``` It populates the first three cubicles with keyboards with different frequencies, then fills the rest with a diagonal-stripe pattern using the first three as a template: ``` 11-2 13-1 33-0 5-2 7-1 12-0 16-1 15-0 20-2 22-1 0-0 17-2 18-0 35-2 10-1 27-0 32-2 28-1 14-2 31-1 9-0 29-2 4-1 3-0 25-1 30-0 2-2 1-1 21-0 26-2 24-0 23-2 34-1 6-0 8-2 19-1 ``` ]
[Question] [ **Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/3163/edit). Closed 5 years ago. [Improve this question](/posts/3163/edit) Real-world programs often use libraries like [ICU](http://en.wikipedia.org/wiki/International_Components_for_Unicode) to support Unicode. The puzzle is to create the smallest possible function that can determine whether a given Unicode character is lowercase, uppercase, or neither (a commonly used Unicode character property). You may indicate the property in any way (whatever is shortest for your language); just explain what the output means in your answer. Of course, using a language feature or a function from the standard library that already provides this distinction is forbidden. This could potentially have some practical use, since some embedded programs have to choose between including a bulky library and not supporting Unicode. [Answer] # C & C++, 1922 1216 bytes/chars (BMP only 1451 1005 bytes/chars) This is the "shortest" solution that came to mind that is both valid C and C++ and that supports all of Unicode version 6.1, not just the BMP: ``` int s[]={-74,-68,31054,-50,-49,-48,-47,-46,-44,-43,-39,-38,-37,-34,-33,-32,-30,-29,-28,-27,-26,-25,-24,-23,-22,-17,-16,-13,-12,-11,-10,-9,-8,-7,-6,-5,-4,-3,-2,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,16,19,20,27,28,29,53195,31,34,36,42,49,50,52,54,58,59,62,64,66,73,81,98,102,103,140,194,263,275,290,1066,1222,1230,2685,2732,2890,3379,6009,21254,22391,30996,53209}; char l[]="l5Hf`7HIAH2IH@IH7IJFIFHJIJKHLJKFHFJFIJIHIJKIJHJFHNFJ@IH?IHJIK1IBHFJHILDI!HI4HpIFKFHWZ-HIHKFH<IDHIFJHc&H9IQ4IJBIH(Ie+H{)Hh<HI.Hn I@H$I@HPCHRAHPAHPCHRAHPAHP;HJAHPAHPAHPDHIHNKFHIHPEHJHPAHRFHIHrKHKZFLJHPEHLdx'HJKHEILIHICHM$IHOILT,HIM~8IX=IoBIFH/IAHFIJDILIJIUDIk|BHTDHt5Hv*H\\5HYBHI9HY5HYEHFIBHI>HY5HY5HY5HY5HY5HY5HY5HY5HY3H[6HICHY6HICHY6HICHY6HICHY6HICHIG"; char u[]="i5Hm8HIBH^3IJAIJ7IHFIKHFIHIFHJEHIHIFHKHIHEIHIJIHIFHFIHKOEJAIJ@IFJIFH1IOHIHJIEHDIsIKVIFHFIHI:HI@H_JFHK=IMJIHJ#Ha:IQ3IHBIJ)IR,Hy,HIMz IQ%IQAHPCHRAHPAHPCHSEIPAHjEHTEHTEHTDHSEHqLKFHJFHJKDHNEIEHJEHRHMgw'HbIFHJEIEHIJPFH$IPIL\"8IX=IoBIK0IRFIHDILIJIUCI}5Hu*H\1775HY5HY5HYIHFJHJEHIAHY5HYHIEHJAHIBHZHIEHIDHIKBHZ5HY5HY5HY5HY5HY5H]6H^6H^6H^6H^6H^G"; int x(int a,char*p){int c=0,i=0,b=-1;while(c>0||s[*p-32]){if(!c)c=s[*p-32]<0?-s[*p++-32]:1,i=s[*p++-32];b+=i,--c;if(a==b)return 1;}return 0;} ``` Please note that "shortest" in this case does not mean that the solution is in any way efficient; it simply means that it is the shortest source code solution. It does not require any Unicode support in the standard library, and in fact does not use the standard library at all. (Which I now understand is what code golf means ... I'm a newbie around here, what can I say.) To build the lower and upper case data tables I worked as follows: 1. Downloaded UnicodeData.txt. 2. Extracted a list of all lines that included the text ";Ll;" or ";Lu;" to indicate a lower case letter or upper case letter respectively. 3. Built two vectors of code points using the data from step 2. 4. Converted each absolute code point value to a relative value, the difference between the previous code point and this code point. Because it is convenient for the difference to always be a positive integer (not zero or negative), I use -1 as the value of the first previous code point. In this way zero will not appear anywhere in the sequence. 5. Used a form of run length encoding to compress runs of identical values into a pair of values. If the next value appears two or more times consecutively, replace the sequence with the negative of the length of the sequence and the value. Otherwise the value only appears once, so just use it as is. 6. Terminated the compressed vector with zero to mark the end of the sequence. 7. I noticed there were 96 unique values in the run length encoded vectors, so I built an array of the unique integers and used the index into that array for the lower and upper case vectors. The above process compressed the vector of lower case code points from 1751 unique values to 350 mostly small non-unique values. In like fashion, the upper case code point vector went from 1441 values to 331 values. Next I wrote the unique value vector out as a comma separated list of integers suitable for including in source code. I assumed int was 32 bits to avoid using long so that I could save an additional four characters / bytes of source code. Then I wrote out the lower and upper case vectors as strings, where each character in the string has a code 32 greater than its index into the unique integer array. This saves about half the characters necessary to encode the lower & upper case array through omission of comma characters. Three of the characters used have to be escaped (\", \, and \177). They are assigned to unique integers that only appear once in the data so as to minimize the size of the string literals. What I wound up with was a global array of integers, two global arrays of characters, and a function. An array named s for the unique signed integers, an array named u for the character based upper case code point indexes, and another array named l for the character based lower case code point indexes. The function x takes code point a and pointer to an array of characters p and returns 1 if the code point is in the decompressed / normalized array of code points or 0 otherwise. If you want to determine if code point cp is lower case, you call "x(cp, l)". If you want to determine if it is upper case, you call "x(cp, u)". Since the point to this exercise is to make the smallest code to accomplish the task, I never save the decompressed / normalized data. I decompress it piecemeal as I need it every time I call it. It would be possible to terminate the while loop early if the code point I'm checking has already been passed by during decompression. That would add extra code so I didn't bother, deciding I'd rather pay the speed penalty. I admit the code is ugly. I did not write it this way originally. Here is the C++ version that I derived the compact C version from: ``` const int Ii[] = {-74,-68,31054,-50,-49,-48,-47,-46,-44,-43,-39,-38,-37,-34,-33,-32,-30,-29,-28,-27,-26,-25,-24,-23,-22,-17,-16,-13,-12,-11,-10,-9,-8,-7,-6,-5,-4,-3,-2,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,16,19,20,27,28,29,53195,31,34,36,42,49,50,52,54,58,59,62,64,66,73,81,98,102,103,140,194,263,275,290,1066,1222,1230,2685,2732,2890,3379,6009,21254,22391,30996,53209}; const char Ll[] = "l5Hf`7HIAH2IH@IH7IJFIFHJIJKHLJKFHFJFIJIHIJKIJHJFHNFJ@IH?IHJIK1IBHFJHILDI!HI4HpIFKFHWZ-HIHKFH<IDHIFJHc&H9IQ4IJBIH(Ie+H{)Hh<HI.Hn I@H$I@HPCHRAHPAHPCHRAHPAHP;HJAHPAHPAHPDHIHNKFHIHPEHJHPAHRFHIHrKHKZFLJHPEHLdx'HJKHEILIHICHM$IHOILT,HIM~8IX=IoBIFH/IAHFIJDILIJIUDIk|BHTDHt5Hv*H\\5HYBHI9HY5HYEHFIBHI>HY5HY5HY5HY5HY5HY5HY5HY5HY3H[6HICHY6HICHY6HICHY6HICHY6HICHIG"; const char Lu[] = "i5Hm8HIBH^3IJAIJ7IHFIKHFIHIFHJEHIHIFHKHIHEIHIJIHIFHFIHKOEJAIJ@IFJIFH1IOHIHJIEHDIsIKVIFHFIHI:HI@H_JFHK=IMJIHJ#Ha:IQ3IHBIJ)IR,Hy,HIMz IQ%IQAHPCHRAHPAHPCHSEIPAHjEHTEHTEHTDHSEHqLKFHJFHJKDHNEIEHJEHRHMgw'HbIFHJEIEHIJPFH$IPIL\"8IX=IoBIK0IRFIHDILIJIUCI}5Hu*H\1775HY5HY5HYIHFJHJEHIAHY5HYHIEHJAHIBHZHIEHIDHIKBHZ5HY5HY5HY5HY5HY5H]6H^6H^6H^6H^6H^G"; bool isXx(int cp, const char* Xx) { int count = 0, step = 0, code = -1; while ((count > 0) || (Ii[*Xx-32] != 0)) { if (count == 0) { count = (Ii[*Xx-32] < 0) ? -(Ii[*(Xx++)-32]) : 1; step = Ii[*(Xx++)-32]; } code += step; --count; if (cp < code) break; if (cp == code) return true; } return false; } inline bool isLl(int cp) { return isXx(cp, Ll); } inline bool isLu(int cp) { return isXx(cp, Lu); } ``` In the end, the compact version takes 1922 1216 bytes (including CR+LF end of line sequences). The original version only takes 2271 1578 bytes. To put this in context of the other solutions that only support the BMP, the equivalent compact version only takes 1451 1005 bytes (or 1800 1367 bytes for the original version). [Answer] ## Python 3, 1369 chars (not bytes) ``` a='abcdefghijklmnopqrstuvwxyzªµºßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿāăąćĉċčďđēĕėęěĝğġģĥħĩīĭįıijĵķĸĺļľŀłńņňʼnŋōŏőœŕŗřśŝşšţťŧũūŭůűųŵŷźżžſƀƃƅƈƌƍƒƕƙƚƛƞơƣƥƨƪƫƭưƴƶƹƺƽƾƿdžljnjǎǐǒǔǖǘǚǜǝǟǡǣǥǧǩǫǭǯǰdzǵǹǻǽǿȁȃȅȇȉȋȍȏȑȓȕȗșțȝȟȡȣȥȧȩȫȭȯȱȳȴȵȶȷȸȹȼȿɀɂɇɉɋɍɏɐɑɒɓɔɕɖɗɘəɚɛɜɝɞɟɠɡɢɣɤɥɦɧɨɩɪɫɬɭɮɯɰɱɲɳɴɵɶɷɸɹɺɻɼɽɾɿʀʁʂʃʄʅʆʇʈʉʊʋʌʍʎʏʐʑʒʓʕʖʗʘʙʚʛʜʝʞʟʠʡʢʣʤʥʦʧʨʩʪʫʬʭʮʯͱͳͷͻͼͽΐάέήίΰαβγδεζηθικλμνξοπρςστυφχψωϊϋόύώϐϑϕϖϗϙϛϝϟϡϣϥϧϩϫϭϯϰϱϲϳϵϸϻϼабвгдежзийклмнопрстуфхцчшщъыьэюяѐёђѓєѕіїјљњћќѝўџѡѣѥѧѩѫѭѯѱѳѵѷѹѻѽѿҁҋҍҏґғҕҗҙқҝҟҡңҥҧҩҫҭүұҳҵҷҹһҽҿӂӄӆӈӊӌӎӏӑӓӕӗәӛӝӟӡӣӥӧөӫӭӯӱӳӵӷӹӻӽӿԁԃԅԇԉԋԍԏԑԓԕԗԙԛԝԟԡԣԥԧաբգդեզէըթժիլխծկհձղճմյնշոչպջռսվտրցւփքօֆևᴀᴁᴂᴃᴄᴅᴆᴇᴈᴉᴊᴋᴌᴍᴎᴏᴐᴑᴒᴓᴔᴕᴖᴗᴘᴙᴚᴛᴜᴝᴞᴟᴠᴡᴢᴣᴤᴥᴦᴧᴨᴩᴪᴫᵢᵣᵤᵥᵦᵧᵨᵩᵪᵫᵬᵭᵮᵯᵰᵱᵲᵳᵴᵵᵶᵷᵹᵺᵻᵼᵽᵾᵿᶀᶁᶂᶃᶄᶅᶆᶇᶈᶉᶊᶋᶌᶍᶎᶏᶐᶑᶒᶓᶔᶕᶖᶗᶘᶙᶚḁḃḅḇḉḋḍḏḑḓḕḗḙḛḝḟḡḣḥḧḩḫḭḯḱḳḵḷḹḻḽḿṁṃṅṇṉṋṍṏṑṓṕṗṙṛṝṟṡṣṥṧṩṫṭṯṱṳṵṷṹṻṽṿẁẃẅẇẉẋẍẏẑẓẕẖẗẘẙẚẛẜẝẟạảấầẩẫậắằẳẵặẹẻẽếềểễệỉịọỏốồổỗộớờởỡợụủứừửữựỳỵỷỹỻỽỿἀἁἂἃἄἅἆἇἐἑἒἓἔἕἠἡἢἣἤἥἦἧἰἱἲἳἴἵἶἷὀὁὂὃὄὅὐὑὒὓὔὕὖὗὠὡὢὣὤὥὦὧὰάὲέὴήὶίὸόὺύὼώᾀᾁᾂᾃᾄᾅᾆᾇᾐᾑᾒᾓᾔᾕᾖᾗᾠᾡᾢᾣᾤᾥᾦᾧᾰᾱᾲᾳᾴᾶᾷιῂῃῄῆῇῐῑῒΐῖῗῠῡῢΰῤῥῦῧῲῳῴῶῷℊℎℏℓℯℴℹℼℽⅆⅇⅈⅉⅎↄⰰⰱⰲⰳⰴⰵⰶⰷⰸⰹⰺⰻⰼⰽⰾⰿⱀⱁⱂⱃⱄⱅⱆⱇⱈⱉⱊⱋⱌⱍⱎⱏⱐⱑⱒⱓⱔⱕⱖⱗⱘⱙⱚⱛⱜⱝⱞⱡⱥⱦⱨⱪⱬⱱⱳⱴⱶⱷⱸⱹⱺⱻⱼⲁⲃⲅⲇⲉⲋⲍⲏⲑⲓⲕⲗⲙⲛⲝⲟⲡⲣⲥⲧⲩⲫⲭⲯⲱⲳⲵⲷⲹⲻⲽⲿⳁⳃⳅⳇⳉⳋⳍⳏⳑⳓⳕⳗⳙⳛⳝⳟⳡⳣⳤⳬⳮⴀⴁⴂⴃⴄⴅⴆⴇⴈⴉⴊⴋⴌⴍⴎⴏⴐⴑⴒⴓⴔⴕⴖⴗⴘⴙⴚⴛⴜⴝⴞⴟⴠⴡⴢⴣⴤⴥꙁꙃꙅꙇꙉꙋꙍꙏꙑꙓꙕꙗꙙꙛꙝꙟꙡꙣꙥꙧꙩꙫꙭꚁꚃꚅꚇꚉꚋꚍꚏꚑꚓꚕꚗꜣꜥꜧꜩꜫꜭꜯꜰꜱꜳꜵꜷꜹꜻꜽꜿꝁꝃꝅꝇꝉꝋꝍꝏꝑꝓꝕꝗꝙꝛꝝꝟꝡꝣꝥꝧꝩꝫꝭꝯꝱꝲꝳꝴꝵꝶꝷꝸꝺꝼꝿꞁꞃꞅꞇꞌꞎꞑꞡꞣꞥꞧꞩꟺfffiflffifflſtstﬓﬔﬕﬖﬗabcdefghijklmnopqrstuvwxyz' def f(x): if x in a: return 'lowercase' if x in a.upper()+'ℂℇℋℍİℑℐℒℕℙℛℚℝℜẞℤΩℨÅKℭℬℱℰℳℿℾⅅℌϓϒϔϴ': return 'uppercase' return 'neither' ``` Almost as small as the other answer (uses the same approach but using literals instead of numbers) but no effort at all. Your browser may not render the chars properly and it is UTF-8 Edit: Making uppercase characters and adding those which didn't correspond to any lowercase saved a ton of chars [Answer] ## PowerShell, 2101 ``` filter x{if(97..122+170,181,186+223..246+248..255+311..312+(0..26|%{$_*2+257})+ 328..329+(0..6|%{$_*2+314})+(0..22|%{$_*2+331})+382..384+378,380,387,389+ 396..397+392,402+409..411+405,414,417,419,421,426,427,424,429,432,441,442+ 445..447+436,438,454,457,476,477+(0..7|%{$_*2+460})+495,496+(0..7|%{$_*2+479})+ 499,501+563..569+(0..28|%{$_*2+505})+575,576,572,578+591..659+661..687+ 891..893+(0..3|%{$_*2+583})+940..974+976,977,912+981..983+1007..1011+ (0..10|%{$_*2+985})+1013,1016,1019,1020+1072..1119+(0..16|%{$_*2+1121})+ (0..26|%{$_*2+1163})+1230,1231+(0..5|%{$_*2+1218})+1377..1415+7424..7467+ 7522..7578+(0..33|%{$_*2+1233})+7829..7835+(0..73|%{$_*2+7681})+7936..7943+ 7952..7957+7968..7975+7984..7991+8000..8005+8016..8023+8032..8039+ 8048..8061+8064..8071+8080..8087+8096..8103+8112..8116+8118,8119+ (0..44|%{$_*2+7841})+8130..8135+8144..8147+8150..8151+8160..8167+8178..8180+ 8182,8183,8126,8305,8319+8462..8463+8458,8467,8495,8500,8508,8509+8518..8521+ 8505,8526,8580+11312..11358+11365,11366,11361,11368,11370,11372,11382,11383, 11380+11491,11492+11520..11557+64256..64262+64275..64279+65345..65370+ (0..48|%{$_*2+11393})-ne7544-ne8133-eq$_){1}elseif(65..90+192..214+216..222+ (0..27|%{$_*2+256})+(0..7|%{$_*2+313})+376,377+(0..22|%{$_*2+330})+385..386+ 379,381+390..395+398..408+412..416+388,422,423,418,420,425,428+430..435+439, 440,437,444,452,455,458,497,500+(0..7|%{$_*2+461})+(0..8|%{$_*2+478})+ 502..504+570..574+(0..28|%{$_*2+506})+579..582+577,584,586,588,590,902,908+ 904..906+910..939+978..980+(0..11|%{$_*2+984})+1012,1015,1017,1018+1021..1071+ (0..16|%{$_*2+1120})+1216,1217+(0..26|%{$_*2+1162})+(0..5|%{$_*2+1219})+ 1329..1366+4256..4293+(0..33|%{$_*2+1232})+(0..74|%{$_*2+7680})+7944..7951+ 7960..7965+7976..7983+7992..7999+8008..8013+(0..44|%{$_*2+7840})+8040..8047+ 8120..8123+8136..8139+8152..8155+8168..8172+8184..8187+(0..3|%{$_*2+8025})+ 8450,8455,8469+8459..8461+8464..8466+8473..8477+8490..8493+8496..8499+8510, 8511,8484,8486,8488,8517+11264..11310+8579,11360+11362..11364+11367,11369, 11371,11381+65313..65338+(0..49|%{$_*2+11392})-notmatch'^(392|40[25]|414|432|572|912|930)$'-eq$_){2}else{0}} ``` Notes: * Returns 1 for lower-case, 2 for upper-case and 0 for neither. * Works only for BMP code points (as the `char` type in .NET represents a single UTF-16 code unit). This uses a few distinct ways of compressing the code points for the two sets: * adjacent code points are conflated in a range (`97..122`) * code points that are two apart are conflated in a small pipeline (`0..22|%{$_*2+331}`) * Ranges with only one missing value are done via `7522..7578-ne7544`, effectively removing that single element. This may not be done with all such rages by now. I did the first two steps automatically, the third one and minor optimizations (`0..1|%{2*$_+11370}` is useless) were done by hand. Some tests: ``` PS> [char]'a'|x 1 PS> [char]'A'|x 2 PS> [char]'1'|x 0 PS> [char]'α'|x 1 PS> [char]'Д'|x 2 ``` [Answer] ## Python 2: 811 characters (after minification) ``` def D(s): k = 0 for i in map(ord, s.decode('base64').decode('utf8')): for j in range(i // 2): yield k k ^= i % 2 k ^= 1 - i % 2 U = list(D('woI0w4ouAw5CbwQfBF0ECQYEBwQDBgQIAwQDBgYEAwQLBAUEBQQDBgcEBgMOAwQDBAMEHwQjBAMEBQZ1DgQDBAQFCBHJggcGAx4FBgcEAyIDEkYDBAYGLwoDBAUEBGZgQxJtBBkEwqccTOGakkzhqbTEqxLDgxIQEAwUEBAQEAwWDxAQwpAIGAgYCBgKFgjIjAMIAwYGBAYEAwYKDA0IBAgUBAoDegPhk7heYgUGBA0GBAMEAxTDh++Kuj8GFyYvxJYbBnsUCQQRCAPqvKo0xoo=')) L = list(D('w4I0XgMUAwgDSDADEG8EHwRdBAkGBAcEAwYECAMEAwYGBAMECwQFBAUEAwYHBAQEBgwDBAMEIQQjBAQHBnUOBAMEBAUIEcKKAzbGggcGAwYGJAM2RgMEBgYvCgUEAwQEZmBFEmsEGQTCqXpO4ruwWGwsA0TDjMSpEsODEhAMFBAQEBAMFBAQEBAcBBAQEBAQEAoDBAwDBgYDBBAIBAQQEBQGAwTDsgMaA8SUAwYEBgM2AwgDCAMEBBAICANqA+GVll4EAwYEDQgFBAMOCMOFBDZM74i2PwYXJi/ElhkGfxAJBBMIA+qbpg4YCuChkjTFig==')) f = lambda x: U[x] and 'upper' or L[x] and 'lower' or 'neither' ``` This supports the base multi-lingual plane only (as for the other answers). You could make it a bit shorter by omitting the encoding/decoding steps (and just putting Unicode strings into the program source), but then I think you really ought to count the length in bytes rather than characters. ]
[Question] [ A [redox reaction](https://chem.libretexts.org/Bookshelves/Analytical_Chemistry/Supplemental_Modules_(Analytical_Chemistry)/Electrochemistry/Redox_Chemistry/Oxidation-Reduction_Reactions#:%7E:text=An%20oxidation%2Dreduction%20(redox),gaining%20or%20losing%20an%20electron.) is a chemical reaction in which elements transfer electrons. One element loses electrons, while another gains electrons. *Oxidation* is the process where an element loses electrons, and *reduction* is the process where an element gains electrons. Since electrons have a negative charge, the oxidation number of an atom/ion changes during redox. Quick refresher: oxidation number is the one in the top-right corner of a chemical symbol (default 0), number of moles is the number to the left of the symbol (default 1), and the number of atoms is in the bottom right (again, default 1). The total atoms of an element in a symbol is the product of the moles and the atoms. The number of atoms of an atom/ion does not affect its charge. A [*half-reaction*](https://chem.libretexts.org/Bookshelves/Analytical_Chemistry/Supplemental_Modules_(Analytical_Chemistry)/Electrochemistry/Redox_Chemistry/Half-Reactions#:%7E:text=A%20half%20reaction%20is%20either,involved%20in%20the%20redox%20reaction.) shows either the oxidation or reduction portion of a redox reaction, including the electrons gained or lost. A reduction half-reaction shows an atom or an ion *gaining* one or more electrons while its oxidation number *decreases*. Example: Na+1 + 1e- → Na0 An oxidation half-reaction shows an atom or an ion *losing* one or more electrons while its oxidation number *increases*. Example: Na0 → Na+1 + 1e- For the purposes of this challenge, you will only need to deal with redox reactions containing exactly two elements. Every redox reaction has one half-reaction for the oxidation and one for the reduction. Here's how to write them: | Step | Example | | --- | --- | | 0. Start with a redox reaction. | Zn + Br2 → Zn2+ + Br- | | 1. Break it into two partial half-reactions. | Zn0 → Zn2+ Br20 → Br- | | 2. Balance the number of atoms on each side of the reactions, if necessary. | Zn0 → Zn2+ Br**2**0 → **2**Br- | | 3. Add electrons (e-) to balance the charge on each side of the reactions. | Zn0 → Zn2+ + **2e-** Br20 + **e-** → 2Br- | | 4. Balance the number of electrons gained and lost by changing the coefficients (LCM of electrons from each) | Zn0 → Zn2+ + 2e- **2**Br20 + **2**e- → **4**Br- | | 5. Determine which reaction is the reduction, and which is the oxidation. | Zn0 → Zn2+ + 2e- **(Oxidation)** 2Br20 + 2e- → 4Br- **(Reduction)** | Your task is, given a redox reaction, output its oxidation half-reaction and its reduction half-reaction. Input and output format is flexible; For example, you could take chemical symbols as a tuple of `[name: string, moles: number = 1, atoms: number = 1, oxidation: number = 0]`, and a list of these for each side of the equation. Your output should indicate somehow which reaction is for the reduction and which is for the oxidation, e.g. by putting the oxidation first and reduction second. ## Test cases Cr + Fe2+ → Cr3+ + Fe Oxidation: 2Cr0 → 2Cr3+ + 6e- Reduction: 3Fe2+ + 6e- → 3Fe0 Pb + Ag+ → Pb2+ + Ag Oxidation: Pb0 → Pb2+ + 2e- Reduction: 2Ag+ + 2e- → 2Ag0 Fe3+ + Al → Fe2+ + Al3+ Oxidation: Al0 → Al3+ + 3e- Reduction: 3Fe3+ + 3e- → 3Fe2+ Zn + Br2 → Zn2+ + Br- Oxidization: Zn0 → Zn2+ + 2e- Reduction: 2Br20 + 2e- → 4Br- [Answer] # [Mathematica v13.0+](https://blog.wolfram.com/2021/12/13/new-in-13-molecules-biomolecular-sequences/) ~~310~~ 300 Bytes Yeah, there's *almost* a built-in function for that... ``` Module[{b=Sort/@ReactionBalance[#][[1]]},k=Keys@b;v=Values@b;r=Keys@k;p=Keys@v;n=#["NetCharge"]#&/@#2/.#1&;c=n[k,r]-n[v,p];e=Superscript["e","-"];Table[If[c[[i]]>0,{"Reduction:",r[[i]](r[[i]]/.k)+c[[i]]e->p[[i]](p[[i]]/.v)},{"Oxidation:",r[[i]](r[[i]]/.k)->-c[[i]]e+p[[i]](p[[i]]/.v)}],{i,Tr[1^r]}]]& ``` **E:** -8 bytes by introducing sub-function `n`, -2 bytes by replacing `Length[r]` with `Tr[1^r]` **Explanation** New in v13.0, Mathematica features built-in functions to parse, balance, and otherwise analyze chemical reactions along with entities for elements. The four test reactions can be entered as simple strings: ``` test1 = "Cr + Fe^2+ -> Cr^3+ + Fe"; test2 = "Pb + Ag^+ -> Pb^2+ + Ag"; test3 = "Fe^3+ + Al -> Fe^2+ + Al^3+"; test4 = "Zn + Br2 -> Zn^2+ + Br^-"; ``` Applying the function `Sort/@ReactionBalance[#][[1]]&` does most of the heavy stoichiometric lifting (which we store to `b` for "balanced reaction") and yields the following formatted output: [![balanced reactions](https://i.stack.imgur.com/AA2FK.png)](https://i.stack.imgur.com/AA2FK.png) The remainder of my bodges are grappling with this custom datatype, while lamenting that there isn't a built in function for determining the half-reactions nor Lewis acids/bases. We store the elements & charge states for the reactants (`k=Keys@b;` and `r=Keys@k;`) and products (`v=Values@b;` and `p=Keys@v;`). We next do some kludges to determine the charge gained or lost by each element: `n=#["NetCharge"]#&/@#2/.#1&;c=n[k,r]-n[v,p];`, where we have used the `"NetCharge"` property to determine an element's ionic state (e.g., "Fe" vs "Fe^2+"). We store the nicely formatted string `e=SuperScript["e","-"];` for electrons, because we definitely aren't making par on this hole of code golf. (N.B., Mathematica does have an entity for electrons, `Entity["Particle","Electron"]`, but it doesn't play well with our later equations nor the `ChemicalReaction` data type.) Finally, we congeal all information into a horrific function to display the appropriately balanced half-reactions: ``` Table[ If[c[[i]]>0, {"Reduction:",r[[i]](r[[i]]/.k)+c[[i]]e->p[[i]](p[[i]]/.v)}, {"Oxidation:",r[[i]](r[[i]]/.k)->-c[[i]]e+p[[i]](p[[i]]/.v)} ], {i,Length[r]}] ``` This outputs an array (list of lists) of the half-reactions, with the first entry being the string "Oxidation:" or "Reduction:", as shown for the four test cases: [![half reactions](https://i.stack.imgur.com/5K45b.png)](https://i.stack.imgur.com/5K45b.png) This code could certainly be golfed down below 300 bytes (to perhaps ~250ish) with standard Mathematica tricks (e.g., ~~`Tr[1^r]` instead of `Length[r]`~~, ~~remove redundancies for `c`~~, try to remove redundant logic within the `Table[...If[...`, and so forth), but it all gets rather ugly. Similarly, we could forsake Mathematica's custom `ChemicalReaction` wrapper and operate on our own specified input and output formats, but that's not as fun (for me). As a final note, my function works fine so long as all reagents and products are single elements, but falters against more complex reactions, e.g., `"(Cr(N2H4CO)6)4(Cr(CN)6)3+KMnO4+H2SO4 -> K2Cr2O7+MnSO4+CO2+KNO3+K2SO4+H2O"`, even though `ReactionBalance` can parse and balance it: [![messy redox reaction](https://i.stack.imgur.com/0X17V.png)](https://i.stack.imgur.com/0X17V.png) [Answer] # [Python](https://www.python.org), 293 bytes ``` def f(a,b,c,d):a[1]*=c[2];c[1]*=a[2];b[1]*=d[2];d[1]*=b[2];i,j=abs(a[3]*a[1]-c[3]*c[1]),abs(b[3]*b[1]-d[3]*d[1]);n=math.lcm(i,j);a[1],c[1],b[1],d[1]=a[1]*n//i,c[1]*n//i,b[1]*n//j,d[1]*n//j;r,o=[[a,c],[b,d]][::1-2*(a[3]<c[3])];return[[o[0]],[o[1],e:=["e",n,1,-1]]],[[r[0],e],[r[1]]] import math ``` [Attempt This Online!](https://ato.pxeger.com/run?1=hVXNbtNAEBYSl_gpVkYodti0jgOkOHWlthJHQD2yXUX-2TQuztqsbbVVlCsPwJVLL_BOcOQ5OLCz63Wdlgqlar-Zb36-mVml336UN_Wq4Lc__2S8bOoqJJb82KfCxhP58SiW1lumLV9ZhpvucBBJMeR-iPu5xxfamijLcP4Od5drqunax_njKgw37XI_8n70iVLpt5bh_B43weOJSrbo96Zejg9-PXmesiVaOhGOcYJTN4jIhI7ChPh0nigYAYwVTAGmCsYAM3wZRnHlRGRKR5A4TgBBnouBiMGE3HEKCFLdOQ_XUb3ay5O1Iwu4c0jEkIMhEkNQqFTw_f1MERrFLbpUIQrNBS5CQiKcyH3EOKWUBMFk7I-UpENQ49K5YHUjOCEF8aiMK6ALC0Jiy-1yvRPwEyF5zCQSBDxWti4LUSNQ227r6TVsa13kLGlytigjUTGnXmX8wg2swTN0upIeFPEU5UXxqSlRnlV1ZQ2qJl5UicjKukIhIu8KzrD6ZZ83vnfg2y2YGvDSgFcGvDZgZsCBAW9sCi1KJh5t4nknuokEpsnMNJnJJkgj02VmusxMl5nqUuYNFNeeY9sarDPe85zYFqzhTC0clXLx9U23LmugD4GW9ibjtd4bvAiULZExjiaI5RVDw-F2o30e3W56-yPa61OKCqHCdiYn8Ox0CNzexCjdXZspPfJ0Gy2_Rxx6XX85iwXn1mMsSiFFM-EU11ka1VnBMRIsbRKA-vrvDWMNZNAiX1UYARAr2FDxgA3vPaTWLSd2dYxOJKN1VDq7sV1hl6pQXXlR1VLkhcxZ2p2YAG3awlv0-8tXtBmiF2i4d1lk3DFFtuZu7TxwqlQPAEDrEA_YR8W1PIi7y783bUvoabva_RE6OcGOaFO8HaetI0cYqBM599fRu1PnqVgZ2ufcduWNl_KNsM-NSkEZ_MB_haC3114FEOaMTLgLPf__Oowy-yy6QkVTq_o2Rv8KvtOGEeMpINCpv4Bub_Xfvw) I suspect this could be golfed much much further, but I can't be bothered trying to right now. Takes 4 inputs, the two reactants and the two products, in the format described in the question. Outputs two lists in the order oxidation, reduction. Each output list is a half-equation in the form `[[<REACTANTS>],[<PRODUCTS>]]`. The link above includes some pretty print to make it easy to read and check. More readable version: ``` def f(a,b,c,d): # Correct number of molecules on each side of the equation a[1]*=c[2] c[1]*=a[2] b[1]*=d[2] d[1]*=b[2] # Find the charge difference of each half equation i=abs(a[3]*a[1]*a[2]-c[3]*c[1]*c[2]) j=abs(b[3]*b[1]*b[2]-d[3]*d[1]*d[2]) # Find the LCM of the charges # This gives the required number of electrons num_electrons = math.lcm(i, j) # Balance equations so both sides have equal electrons a[1]=a[1]*num_electrons//i c[1]=c[1]*num_electrons//i b[1]=b[1]*num_electrons//j d[1]=d[1]*num_electrons//j # Work out which side is oxidation and which is reduction reduction,oxidation=[[a,c],[b,d]][::1-2*(a[3]<c[3])] # The electron molecule/s electrons = ["e", num_electrons, 1, -1] # The two half equations oxidation_output = [[oxidation[0]],[oxidation[1],electrons]] reduction_output = [[reduction[0],electrons],[reduction[1]]] return oxidation_output, reduction_output ``` ]
[Question] [ # Introduction A circle-tangent polynomial is a polynomial of degree \$N\ge3\$ or above that is tangent to the unit circle from inside at all of its N-1 intersection points. The two tails that exits the circle are considered tangent at their intersection points from inside as well. You may consider such polynomials are wrapped inside the unit circle except for the two tails. The first several circle-tangent polynomials are shown here. ![enter image description here](https://i.stack.imgur.com/qcLhH.png) ![enter image description here](https://i.stack.imgur.com/JcecC.png) The mirror images of a circle-tangent polynomial along x- or y- axis are also circle-tangent polynomials. # Challenge Write a full program or function that, given a whole number input \$N\ge3\$, outputs a circle-tangent polynomial. You may either output the whole polynomial or only its coefficient in a reasonable order. Since such coefficients can be irrational, floating point inaccuracy within reasonable range is allowed. The algorithm you used should be theoretically able to calculate with any valid input provided, although in reality the program could timeout. Since this is a code-golf challenge, the shortest code of each language wins. # Example input/output Both exact forms and approximate forms are shown for reference. The polynomials here are shown with positive leading terms, but mirrored counterparts around the axes are acceptable. The approximate forms are shown with 6 decimal places, but the calculation should be as accurate as possible. ``` Input -> Output 3 -> 8√3/9 x^3 - √3 x 1.539601 x^3 - 1.732051 x 4 -> 27/8 x^4 - 9/2 x^2 + 1 3.375 x^4 - 4.5 x^2 + 1 5 -> 2048√15/1125 x^5 - 128√15/45 x^3 + √15 x 7.050551 x^5 - 11.016486 x^3 + 3.872983 x 6 -> 3125/216 x^6 - 625/24 x^4 + 25/2 x^2 - 1 14.467593 x^6 - 26.041667 x^4 + 12.5 x^2 - 1 7 -> 1492992√35/300125 x^7 - 62208√35/6125 x^5 + 216√35/35 x^3 - √35 x 29.429937 x^7 - 60.086121 x^5 + 36.510664 x^3 - 5.916080 x ``` # Restrictions NO HARDCODING POLYNOMIALS. NO USE OF DEFAULT LOOPHOLES. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 84 bytes -18 bytes thanks to @att. Now returns a polynomial in `Quantifier`LocalVariable$1`. ``` p/.#&@@Solve@ForAll[x,t#2#####&@@(x-b/@2~Range~#)==x^2+(p=Sum[a@i*x^i,{i,0,#}])p-1]& ``` [Try it online!](https://tio.run/##FcrRCsIgFIDhVxGEsdWx1erWMIiuo12KAwtXB3TKsBBie3Vb/@33Ox1fxumID517wnOoN7QQovX2Y8TFjydrZYJIG/pvkTKxey2a@aaHp5lpxXnqmnUZePt2UgtcpQ7hi7AFOqkqsJ0q8tnL64hDlEjYkfQSlQKyPGQP5DCp/AM "Wolfram Language (Mathematica) – Try It Online") This is the first time that I write `#####` in a Mathematica program. The two intersections that enters and exits the circle have multiplicity 3, and other intersections have multiplicity 2. Let the polynomial be \$p=\sum\_{i=0}^{N} a\_i x^i\$, and the \$x\$-coordinate of the intersections be \$x\_1,\dots,x\_{N-1}\$, where \$x\_1\$ and \$x\_2\$ has multiplicity 3. Then we must have \$x^2+(\sum\_{i=0}^{N} a\_i x^i)^2-1 = t(x-x\_1)(x-x\_2)\prod\_{i=1}^{N-1}(x-x\_i)^2\$ for some \$t\$ and for all \$x\$. Comparing the coefficients of \$x\$, we have \$2N+1\$ equations and \$2N+1\$ unknowns (\$a\_0,\dots,a\_N,x\_1,\dots,x\_{N-1},t\$). We can solve this with the built-in function `Solve`. [Answer] # [Maxima](http://maxima.sourceforge.net/), 227 bytes Port of [@alephalpha's Mathematica code](https://codegolf.stackexchange.com/a/248603/110802) in Maxima. This is the first time that I write a Maxima program. --- Golfed version. [Try it online!](https://tio.run/##RVDRboMwDPyZPdjMSCXbE1N/pAiklAbJwiRRCFP29dS0avdinU9n39mLLbzYfWYRsCL4s0/gsT1fJYwzxHbdFrAd91UZmJhO5JGSsxK8/LU5bY4uqrmuGSZOWtcgvw4WOzthbcfgpglcidbfoAzmE@Jg6gbrXEGpS9f0@ARGQUzhto0ZHgT3OBh1bMirHqkQ4/n0iGAqDWFjdLrz7XSEfAV8k@VJNgfZ5R51T0T82GNin/9nj5PJ0xd9oz7gDg) ``` f(n):=block(p:sum(a[i]*x^i,i,0,n),realonly:true,Z:subst(first(solve(makelist(coeff(expand(x^2+(p^2-1)-t*(x-x[1])*(x-x[2])*product((x-x[i])^2,i,1,n-1)),x,i)=0,i,0,2*n),append(makelist(a[i],i,0,n),makelist(x[i],i,1,n),[t]))),p))$ ``` Ungolfed version. [Try it online!](https://tio.run/##ZZJBT4QwFITv/Ip38NBizQp6YrNnPejFPW7YpItFmy1tpQ9T/fPYFmExJiS0neF9kykd97Lj43iWShGuFN1mLdG02p2Uac4kA7AVuKEj/CDr3B8lg/DcMtCUBVF8DByl0U@P@wr8sYRrIDa8bqD4o79EPewBMCc@yP5Q1HRelmGZRNub16FB8nsua3osE7AIwH9DKxDecv1KVimCacUM9uDf5PAgEPBdQGNE28pGCo0OTJvOZj@EUeAmYwdo4Fv0BvLNiugq6PhZKOmQpFELmoEPQSnsYjdTQ2WuJ34vuDJafVWA/SBYCrQXiFK/wXPqP9JsL1rRJzM4o4bEm/DztoqrT7FAHQNurQgNLKniNa2u6BLXz0IxCQes6VLPfjg5lDigSI20sne4UEHqGG@KwmMHLtpJcpHZFUZamtGrLMtsH764RIr/U2AyuGNwT@l2HH8A) ``` kill(all); f(n):=block( p: sum(a[i]*x^i, i, 0, n), equationLHS: x^2 + (p^2 - 1), equationRHS: t*(x - x[1])*(x - x[2])* product((x - x[i])^2, i, 1, n - 1), equation: expand(equationLHS - equationRHS), /* Get the coefficients of the equation and set them to zero */ equations: makelist(coeff(equation, x, i) = 0, i, 0, 2*n), realonly: true, /* Setting Maxima to prefer real solutions */ solution: solve(equations, append(makelist(a[i], i, 0, n), makelist(x[i], i, 1, n), [t])), /* Substitute the first solution into p */ ans: subst(first(solution), p) )$ print(makelist(f(n), n, 3, 4)); ``` ]
[Question] [ What general tips do you have for golfing in Lexurgy? I'm looking for ideas which can be applied to code-golf problems and which are also at least somewhat specific to Lexurgy (e.g. "remove comments" is not an answer). Please post one tip per answer. Lexurgy is a tool created by Graham Hill/`def-gthill` meant for conlangers (people who create constructed languages) to apply sound changes to their lexicon. As a result, Lexurgy is highly geared towards rule-based string operations. Its feature set includes capturing, character classes, and much more as detailed in the documentation below. The documentation for Lexurgy is [here](https://www.meamoria.com/lexurgy/html/sc-tutorial.html), and a cheatsheet is [here](https://www.meamoria.com/lexurgy/html/sc-cheat-sheet.html). You can access Lexurgy [here](https://www.lexurgy.com/sc). [Answer] ### Reducing Whitespace Lexurgy has specific rules about where whitespace can be removed. Consider the following rule (taken from my submission to [Covfefify a string](https://codegolf.stackexchange.com/a/241306/77309)): ``` part-1: @consonant * => @consonant ; / $ @consonant* @vowel* _ // {$ _, $ @consonant _} ``` Lexurgy parses the rules as such, with `<>` separating individual elements: ``` <part-1>: <@consonant *> => <@consonant ;> / <$ @consonant* @vowel* _> // <{<$ _>, <$ @consonant _>}> ``` You cannot remove any whitespace within the `<>` or else it will yield a parsing error. As a result, with all extraneous whitespace removed, the rule turns into: ``` part-1: @consonant *=>@consonant ;/$ @consonant* @vowel* _//{$ _,$ @consonant _} ``` If both sides have only 1 possible string on each side, then you can combine them: ``` # single string a: s t r=>o t h b: # -1 byte per space str=>oth # combinable strings c: s t r *=>* o t h d: # -1 byte per space str *=>* oth # two or more strings e: str ing=>oth er f: # -1 byte per string string=>other ``` [Answer] ### Caveats about Lexurgy * Lexurgy treats whitespace in the input as word separators, so whitespace must be replaced by some other character. Individual inputs are separated by newlines, and those cannot be escaped in the input box. * Escaping certain characters is done with `\`, i.e. `\! => !`. * Lexurgy is designed for working on characters from a set of characters; use `[]` for matching any single character. [Answer] ### Use class variables within class declarations Lexurgy allows you to define arbitrary "classes" of characters which can be accessed by `@classname`. Classes must have at least 1 character within them. Consider the following classes: ``` # 75 bytes Class v {a,e,i,o,u} Class c {p,t,k,b,d,g} Class l {a,e,i,o,u,p,t,k,b,d,g} # 59 bytes (-16 bytes) Class v {a,e,i,o,u} Class c {p,t,k,b,d,g} Class l {@v,@c} ``` A class is minimum 11 bytes long (`Class n {c}` to account for the single character needed for a class), and each additional character is +2 bytes. Consider these two minimum classes, and wanting to make a class `c` that is the union of `a` and `b`: ``` Class a {a} Class b {b} Class c {a,b} # +13 bytes Class c {@a,@b} # +15 bytes ``` For minimal classes it's better to use the explicit declaration instead of using class variables. The break-even point is at three characters for 2 classes: ``` Class a {a,e} Class b {b} Class c {a,b,e} # +15 bytes Class c {@a,@b} # +15 bytes ``` Let there be \$c \ge 2\$ classes. The total number of characters \$n\$ in classes will cause the byte count to break even (i.e. using class variables is just as good as explicitly declaring the union) at \$2n=3c \Rightarrow n=\frac{3}{2}c\$. **Therefore, it is better to use variables when \$n \ge \frac{3}{2}c\$, and explicit declarations when \$n \le \frac{3}{2}c\$**. ([Desmos link to my calculations](https://www.desmos.com/calculator/whb7ajr2up)) [Answer] ### Programs with no input Programs with no input are possible in Lexurgy, with a rule like: ``` # +7 bytes a: *=>c ``` It takes an empty string and outputs a character for you to further mutate as needed. You can put an entire string on the right-hand side as well. This must be the first rule for anything useful to happen. However, if the program is given input, it will apply the rule to each input and every possible match in the input strings. [Answer] ### Use classes as variables holding strings You can place entire, arbitrary strings into class definitions, provided they are properly escaped: ``` Class s {Hello\,\ world\!} ``` Then, use it like any other class: ``` # 38 bytes a: []=>Hello\,\world\!Hello\,\world\! # 41 bytes Class s {Hello\,\ world\!} a: []=>@s @s ``` The above example gains a 3 bytes, but if you use the string multiple times you get even more savings: ``` # 53 bytes a: []=>Hello\,\world\!Hello\,\world\!Hello\,\world\! # 44 bytes Class s {Hello\,\ world\!} a: []=>@s @s @s ``` [Answer] ### The "Find/Marker/Delete" Pattern A common pattern that I've found, which I've named the "Find/Marker/Delete" pattern, shows up often whenever the output is unrelated to the input except for some value that cannot be done using a simple replacement. For example, consider this code that will output `true` or `false` if the word ends with `e`: ``` a: *=>|true/e _ $ else: *=>|false/_ $ b propagate: []=>*/_ | c: |=>* ``` This code has three parts: ``` # part a: find and place the marker. (here it's a |) a: *=>|true/e _ $ else: *=>|false/e _ $ # part b: delete everything before/after the marker. (here it's everything before) b propagate: []=>*/_ | # part c: delete the marker c: |=>* ``` This pattern is the only real way you can have an output that is not some simple replacement of the input. The minimal version for 2 outputs is as such (68 bytes): ``` a: *=>|a/e _ $ else: *=>|b/_ $ b propagate: []=>*/_ | c: |=>* ``` ]
[Question] [ In as few bytes as possible in t-sql, return 100 rows containing the phrase 'Have a great Christmas' 92 (I think) to beat :D ``` CREATE TABLE #(m char(99)) GO INSERT # SELECT'Have a great Christmas' GO 100 SELECT * FROM # ``` Previous best effort was: ``` WITH t(m,r)AS(SELECT'Have a great Christmas',1 UNION ALL SELECT m,r+1 FROM t WHERE r<100)SELECT m FROM t; ``` [Answer] # SQL Server (tested on 2016) - 82 78 bytes ``` SELECT TOP 100*FROM STRING_SPLIT(REPLICATE('Have a great Christmas!',100),'!') ``` ## SQL Server (tested on 2016) - 88 87 bytes (Old Solution) ``` WITH N(a)AS(SELECT'Have a great Christmas'UNION ALL SELECT*FROM N)SELECT TOP 100*FROM N ``` Of course, on a sql instance with existing objects, you can come up with some... hackier solutions. For example, 58 bytes that are pretty darn likely to work: ``` SELECT TOP 100'Have a great Christmas'FROM sys.all_objects ``` [Answer] # SQL Server 2016, ~~54~~ 53 bytes *Edit: -1 byte thanks to [@Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen).* ``` select top 100'Have a great Christmas'from spt_values ``` Works in my instance of SQL Server 2016. `spt_values` may be replaced with any system view/table of at least 100 rows. Inspired by this [tips answer](https://codegolf.stackexchange.com/a/172557/55372). ]
[Question] [ # Introduction This challenge is about producing a code to count the frequency of bigrams in a text. A bigram is two consecutive letters in a text. For instance 'aabbcd' contains the bigrams aa, ab, bb, bc, cd once each. Counting bigram frequencies is super useful in cryptography. In a brute force algorithm, this code may be called many times and as a result, must be optimised to run quickly. # Challenge * Challenge is in Python 3 and NumPy can be used. * The input will be a string of text (no spaces or punctuation). The output will be a NumPy array that is 26x26 or a list of lists that would be equivalent to the NumPy array. The first letter of the bigram is the row index and the second letter is the column index. The values in the array represent the frequency of that particular bigram. * The fastest code wins. I will measure the time it takes for the code to run 10,000 times on my computer (2015 Aspire F15 Intel i3 2.0GHz 4GB RAM). # Input This is the input that I will test the code on ``` 'WERENOSTRANGERSTOLOVEYOUKNOWTHERULESANDSODOIAFULLCOMMITMENTSWHATIMTHINKINGOFYOUWOULDNTGETTHISFROMANYOTHERGUYIJUSTWANNATELLYOUHOWIMFEELINGGOTTAMAKEYOUUNDERSTANDNEVERGONNAGIVEYOUUPNEVERGONNALETYOUDOWNNEVERGONNARUNAROUNDANDDESERTYOUNEVERGONNAMAKEYOUCRYNEVERGONNASAYGOODBYENEVERGONNATELLALIEANDHURTYOUWEVEKNOWNEACHOTHERFORSOLONGYOURHEARTSBEENACHINGBUTYOURETOOSHYTOSAYITINSIDEWEBOTHKNOWWHATSBEENGOINGONWEKNOWTHEGAMEANDWEREGONNAPLAYITANDIFYOUASKMEHOWIMFEELINGDONTTELLMEYOURETOOBLINDTOSEENEVERGONNAGIVEYOUUPNEVERGONNALETYOUDOWNNEVERGONNARUNAROUNDANDDESERTYOUNEVERGONNAMAKEYOUCRYNEVERGONNASAYGOODBYENEVERGONNATELLALIEANDHURTYOUNEVERGONNAGIVEYOUUPNEVERGONNALETYOUDOWNNEVERGONNARUNAROUNDANDDESERTYOUNEVERGONNAMAKEYOUCRYNEVERGONNASAYGOODBYENEVERGONNATELLALIEANDHURTYOUNEVERGONNAGIVENEVERGONNAGIVEGIVEYOUUPWEVEKNOWNEACHOTHERFORSOLONGYOURHEARTSBEENACHINGBUTYOURETOOSHYTOSAYITINSIDEWEBOTHKNOWWHATSBEENGOINGONWEKNOWTHEGAMEANDWEREGONNAPLAYITIJUSTWANNATELLYOUHOWIMFEELINGGOTTAMAKEYOUUNDERSTANDNEVERGONNAGIVEYOUUPNEVERGONNALETYOUDOWNNEVERGONNARUNAROUNDANDDESERTYOUNEVERGONNAMAKEYOUCRYNEVERGONNASAYGOODBYENEVERGONNATELLALIEANDHURTYOUNEVERGONNAGIVEYOUUPNEVERGONNALETYOUDOWNNEVERGONNARUNAROUNDANDDESERTYOUNEVERGONNAMAKEYOUCRYNEVERGONNASAYGOODBYENEVERGONNATELLALIEANDHURTYOUNEVERGONNAGIVEYOUUPNEVERGONNALETYOUDOWNNEVERGONNARUNAROUNDANDDESERTYOUNEVERGONNAMAKEYOUCRYNEVERGONNASAYGOODBYE' ``` # Output: This is the expected output ``` [[ 0. 0. 4. 0. 0. 1. 8. 0. 0. 0. 8. 11. 10. 21. 0. 2. 0. 14. 7. 10. 0. 0. 0. 0. 10. 0.] [ 0. 0. 0. 0. 4. 0. 0. 0. 0. 0. 0. 1. 0. 0. 2. 0. 0. 0. 0. 0. 2. 0. 0. 0. 6. 0.] [ 0. 0. 0. 0. 0. 0. 0. 4. 0. 0. 0. 0. 0. 0. 1. 0. 0. 6. 0. 0. 0. 0. 0. 0. 0. 0.] [ 6. 6. 0. 6. 10. 0. 0. 5. 1. 0. 0. 0. 0. 3. 8. 0. 0. 0. 1. 1. 0. 0.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. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.] [ 1. 0. 0. 0. 6. 2. 38. 2. 0. 0. 0. 0. 0. 0. 7. 0. 0. 0. 5. 13. 7. 0. 0. 0. 6. 0.] [ 9. 4. 0. 0. 7. 1. 0. 2. 2. 0. 1. 0. 0. 0. 3. 0. 0. 0. 0. 6. 0. 0. 1. 0. 0. 0.] [ 5. 0. 0. 0. 8. 0. 1. 10. 4. 0. 0. 0. 1. 0. 7. 0. 0. 1. 5. 4. 0. 0. 2. 0. 19. 0.] [ 1. 0. 6. 6. 0. 0. 0. 2. 0. 0. 1. 3. 0. 24. 0. 7. 0. 10. 2. 2. 9. 0. 2. 0. 1. 0.] [ 0. 0. 0. 0. 49. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.] [ 2. 0. 0. 0. 9. 0. 0. 3. 3. 0. 0. 0. 0. 8. 1. 0. 0. 0. 0. 3. 0. 0. 2. 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. 6. 0. 6. 0. 5. 0. 0. 0. 0. 6. 43. 0. 0. 0. 0. 2. 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.]] ``` [Answer] # [Python 3](https://docs.python.org/3/) + numpy (0.359 seconds) ``` def f(IN): a = np.array([IN.encode()],"S").view(np.uint8)-ord('A') c = np.bincount(np.ravel_multi_index((a[:-1],a[1:]),(26,26)),None,26*26) return c.reshape(26,26) ``` [Try it online!](https://tio.run/##5VTRattAEHz3V4i8WCqOISmEYujD2VpLV592w90pQhgTVFshglgWipzWX@/uqW6c/oFLBQLd7M7O3By65tA97@rPx2rb7NrOq/fb5uAVr17dDAYSva/eMAMNSMZqgRFoY0nRA@SULpAyG4NOFRiBoaGQpJinSs0oSaRNAK3JYmFlYmOJC4kRzZmWUapCtBFYhs1cUyIwJzcoSnP5LTU2E4jCglLcHVMmkzmAYnpE1opELJx4iqHzwroID0wlpkSy95XenyEFlpGQMjxjOuWXeACTQzCgXcu5fBKY6fyMGZFHROE0hzPmDAolgafEaT8j45oLBUHM4n5Hc9KG48KIqzoGoa2ZAiCXeTvT1JE0WCIT55ZYRFqJRoaQwZT5bpYLsOdE5ALEDE6xRyJx0u5wejv3ytEZkS5kYRYJfMwuJLTOcQJ/NKcMh6wKcDkJXqqTv1fv3i7gwP/pH@Z/dTIcHDflk/fkSwwmA4@fgi/auhkXbVsc/KXEcVmvd5vSD1ajK3MVjN@q8ofPDfuq7r4E17t24w/FMOi569/c7xVT9nXn2trirXx53O5fuuqxqjflT98vlpPrm9WoWN5MVsHIv70b3d4FwQh3dclfn3jRD2vLbt/W3nrclq/PRVOeGgfHpmVpv7ccHH8B "Python 3 – Try It Online") **UPDATE** better array construction (first line in function) thanks @tsh! **(0.332 seconds)** ``` a = np.frombuffer(IN.encode(),"u1")-ord('A') ``` **/UPDATE** [Answer] # Python (133 chars) (16.1 seconds) ``` import numpy as np i=input() o=np.zeros((26,26)) for b in[(ord(i[j])-65,ord(i[j+1])-65)for j in range(len(i)-1)]:o[b]+=1 print(o) ``` This code runs in O(n) time, where n is the length of the string. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~180µs on PC, 1000µs on TIO ``` res=Normal@SparseArray[ Normal@Counts[ Partition[ Flatten[Position[ToUpperCase /@ Alphabet[], #] & /@ Characters@data], 2, 1]]] ``` [Try it online!](https://tio.run/##rVVNa9tAEL3rVywp9BQo7bUEvJZGq62lHbMfFsL2YZsKbPAXknror3dnFWEllKQJ9sWgNzNv3ryZxXvfbeq977aP/vzLd/7hrgQNCo3VXAnQxmKOC6jQzRSWNgPtcjBcJQYTlDx1eR5jUUhbgLKmzLiVhc3kKlIzqQSmVFiiyxNlBVgKmFRjwVWFgUq4Sv5wxpZcKW4hzyk7w1IWKUBO5QJXkbW84LMgwKkk6KHeChZUjFQkZK/NzUcoB0tIgqUaMb2KHP0iUVB5AgZ0SBoThhaxrkbM8EogJtMKRoz0kEyeSyCezPUsJUWDOQp4nPVzpagN2aYERXUGXFszBVAUpqGmjopIjwaLaLLKIjWSViojEyhhSgyBLVjZVwkMRqoShgUIXoTmYU3BHxI1zwMBYTLYzc2sgOcuJqhsUF2ECfuuU4IT6guXyYjn3V6@5WTgea@X/zr53OdbqAk8t1Aj6J4X8PLqLvo@tH7y5@kArlz/KhoO4LL@/zykV57RKvrgQ3rF7gvPlXbT3m@g5sJz9fL793WDU@x53lZz9/3c1O2DOjZ7v5uYk2/amjeN/7OMGGMDHB9/H7q2Rxib@6bbdtvjYfhm6c53XX1Yzo/tE26P7nSqm9i3NfsyYXx32vifdbdc37NPa/Y5YEMpY/HGN/6xq5t2Ev4IKOXbPfu6Xq/P82Z76CYk7vwX "Wolfram Language (Mathematica) – Try It Online") [![enter image description here](https://i.stack.imgur.com/71amw.jpg)](https://i.stack.imgur.com/71amw.jpg) Tested for now just on Mathematica 12 on Windows 7 Lenovo laptop, 4x1.5Ghz 4Gb Sure Mathematica 13 on more powerful PC takes tens of µs [Answer] # Rust, 304.1µs ### `src/main.rs` ``` // extern crate ndarray; use ndarray::Array2; use std::collections::HashMap; use std::time::Instant; fn main() { let start = Instant::now(); let result = convert_string("WERENOSTRANGERSTOLOVEYOUKNOWTHERULESANDSODOIAFULLCOMMITMENTSWHATIMTHINKINGOFYOUWOULDNTGETTHISFROMANYOTHERGUYIJUSTWANNATELLYOUHOWIMFEELINGGOTTAMAKEYOUUNDERSTANDNEVERGONNAGIVEYOUUPNEVERGONNALETYOUDOWNNEVERGONNARUNAROUNDANDDESERTYOUNEVERGONNAMAKEYOUCRYNEVERGONNASAYGOODBYENEVERGONNATELLALIEANDHURTYOUWEVEKNOWNEACHOTHERFORSOLONGYOURHEARTSBEENACHINGBUTYOURETOOSHYTOSAYITINSIDEWEBOTHKNOWWHATSBEENGOINGONWEKNOWTHEGAMEANDWEREGONNAPLAYITANDIFYOUASKMEHOWIMFEELINGDONTTELLMEYOURETOOBLINDTOSEENEVERGONNAGIVEYOUUPNEVERGONNALETYOUDOWNNEVERGONNARUNAROUNDANDDESERTYOUNEVERGONNAMAKEYOUCRYNEVERGONNASAYGOODBYENEVERGONNATELLALIEANDHURTYOUNEVERGONNAGIVEYOUUPNEVERGONNALETYOUDOWNNEVERGONNARUNAROUNDANDDESERTYOUNEVERGONNAMAKEYOUCRYNEVERGONNASAYGOODBYENEVERGONNATELLALIEANDHURTYOUNEVERGONNAGIVENEVERGONNAGIVEGIVEYOUUPWEVEKNOWNEACHOTHERFORSOLONGYOURHEARTSBEENACHINGBUTYOURETOOSHYTOSAYITINSIDEWEBOTHKNOWWHATSBEENGOINGONWEKNOWTHEGAMEANDWEREGONNAPLAYITIJUSTWANNATELLYOUHOWIMFEELINGGOTTAMAKEYOUUNDERSTANDNEVERGONNAGIVEYOUUPNEVERGONNALETYOUDOWNNEVERGONNARUNAROUNDANDDESERTYOUNEVERGONNAMAKEYOUCRYNEVERGONNASAYGOODBYENEVERGONNATELLALIEANDHURTYOUNEVERGONNAGIVEYOUUPNEVERGONNALETYOUDOWNNEVERGONNARUNAROUNDANDDESERTYOUNEVERGONNAMAKEYOUCRYNEVERGONNASAYGOODBYENEVERGONNATELLALIEANDHURTYOUNEVERGONNAGIVEYOUUPNEVERGONNALETYOUDOWNNEVERGONNARUNAROUNDANDDESERTYOUNEVERGONNAMAKEYOUCRYNEVERGONNASAYGOODBYE"); let duration = start.elapsed(); println!("Time elapsed in convert_string() is: {:?}", duration); println!("["); for row in result.genrows() { print!("["); let last_index = row.len() - 1; for (index, item) in row.iter().enumerate() { if index == last_index { print!("{:3}", item); } else { print!("{:3},", item); } } println!("]"); } println!("]"); } fn convert_string(input: &str) -> Array2<i32> { let mut transition_counts = HashMap::new(); let mut prev_char = None; for c in input.chars() { let current_char = c as i32 - 'A' as i32; if let Some(prev) = prev_char { *transition_counts.entry((prev, current_char)).or_insert(0) += 1; } prev_char = Some(current_char); } let mut result = Array2::zeros((26, 26)); for (&(i, j), &count) in transition_counts.iter() { // println!("{:?}",count); result[(i as usize, j as usize)] = count; } result } ``` ### `Cargo.toml` ``` [package] name = "rust_hello" version = "0.1.0" edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] ndarray = "0.15" ``` ### Build and running ``` # win10 environment $ cargo build --release $ target\release\rust_hello.exe Time elapsed in convert_string() is: 304.1µs [ [ 0, 0, 4, 0, 0, 1, 8, 0, 0, 0, 8, 11, 10, 21, 0, 2, 0, 14, 7, 10, 0, 0, 0, 0, 10, 0] [ 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 1, 0, 0, 2, 0, 0, 0, 0, 0, 2, 0, 0, 0, 6, 0] [ 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 1, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0, 0] [ 6, 6, 0, 6, 10, 0, 0, 5, 1, 0, 0, 0, 0, 3, 8, 0, 0, 0, 1, 1, 0, 0, 2, 0, 0, 0] [ 11, 2, 0, 0, 8, 0, 5, 1, 0, 0, 4, 11, 0, 13, 0, 0, 0, 53, 7, 10, 0, 39, 2, 0, 17, 0] [ 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 1, 0, 0, 1, 0, 0, 0, 2, 0] [ 2, 2, 0, 1, 2, 0, 2, 0, 9, 0, 0, 0, 0, 0, 52, 0, 0, 0, 0, 0, 1, 0, 0, 0, 2, 0] [ 3, 0, 0, 0, 8, 0, 0, 0, 4, 0, 2, 0, 0, 0, 5, 0, 0, 0, 0, 0, 5, 0, 0, 0, 2, 0] [ 1, 0, 0, 2, 5, 1, 0, 0, 0, 2, 0, 0, 4, 12, 0, 0, 0, 0, 1, 5,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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] [ 2, 0, 0, 0, 9, 0, 0, 3, 3, 0, 0, 0, 0, 8, 1, 0, 0, 0, 0, 3, 0, 0, 2, 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, 6, 0, 6, 0, 5, 0, 0, 0, 0, 6, 43, 0, 0, 0, 0, 2, 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] ] ``` ]
[Question] [ What general tips do you have for golfing in [Scala 3](https://dotty.epfl.ch/)? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to Scala 3 (e.g. "remove comments" is not an answer). Please post one tip per answer. Also see [Tips for golfing in Scala](https://codegolf.stackexchange.com/questions/3885/tips-for-golfing-in-scala) [Answer] # Use [parameter untupling](https://dotty.epfl.ch/docs/reference/other-new-features/parameter-untupling.html) Parameter untupling allows you to write functions accepting a single tuple as input as if they were functions accepting 2 parameters. Basically, you can replace these ``` list.map{case(a,b)=>a+b} //and list.map{case(a,b)=>Seq(a,b)} //or list.map(t=>t._1+t._2) //and list.map(t=>Seq(t._1,t._2)) ``` with this, which is both shorter and more beautiful. ``` list.map(_+_) //and list.map(Seq(_,_)) ``` [Answer] # Optional braces In match expressions, at least, you can save a byte by using indentation-based syntax. ``` a match case b=>c case d=>e ``` is 27 bytes, while the below code is 28. ``` a match{case b=>c case d=>e} ``` As a side note, `match` also gets special treatment when it comes to chaining. The following Scala 2 code: ``` ("foo"match{case x=>x})match{case x=>x} ``` can now be written without the parentheses: ``` "foo"match{case x=>x}match{case x=>x} ``` [Answer] # Use @main and toplevel functions If you need to make a full program, use the `@main` annotation on a toplevel main method. ``` @main def m={code} ``` It's a lot shorter than these 2 approaches: ``` object M extends App{code} object M{def main(a:Array[String])={code}} ``` [Answer] # Leave out `new` with [universal apply methods](https://dotty.epfl.ch/docs/reference/other-new-features/creator-applications.html) You can call constructors without using `new` (like Kotlin), treating all classes as if they have `apply` methods in their companions. This saves 4 bytes every time you instantiate something, since `new Foo()` becomes just `Foo()`. This also applies to givens (although you rarely need them for code golf): ``` given foo as Foo=new Foo() //bad given foo as Foo=Foo() //better given foo as Foo //great ``` [Answer] # Numeric Literals Edit: As @stewSquared pointed out, this only works in experimental releases now You can now write a [number literal](https://dotty.epfl.ch/docs/reference/changed-features/numeric-literals.html) for any user-defined type with a given/implicit instance of the `FromDigits` trait, such as `BigInt` and `BigDecimal`. In Scala 2, to pass the number 9,999,999,999,999,999 to a function accepting `BigInt`s, you would have to use `BigInt("9999999999999999")`, but now you can just directly say `9999999999999999` without using the apply method or constructor explicitly. You can also use underscores, scientific notation, hex, etc., just like any normal number literal, as long as the `FromDigits` instance for that type supports that notation, of course. Both `BigInt` and `BigDecimal` are okay with underscores, but only `BigInt` allows hex, and only `BigDecimal` allows scientific notation (with decimals). [Answer] # New Control Syntax In most cases, the new control syntax doesn't shorten code (and is actually more verbose), it comes in handy in for comprehensions. If your expression or pattern ends or starts with a parentheses or double quote, you can save a byte or two: ``` for((x,y,z)<-Seq((1,2,3),(3,4,5));y<-"foo")yield y+x //Old-style syntax for(x,y,z)<-Seq((1,2,3),(3,4,5));y<-"foo"yield y+x //New control syntax ``` It's not as useful as some other things, like parameter untupling, but I often find myself using for comprehensions for function calls like `f(foo)` or `Seq(1,2)`, which end in parentheses. See it run in [Scastie](https://scastie.scala-lang.org/E00ZMRqzTpiwQG04sfwu4A). [Answer] # Use match types for recursive functions that pattern match Making a typealias with a match type is sometimes shorter than using a proper function. For example, take this implementation of the KI calculus (not an actual thing). The type doesn't need `:Any`, so you save 7 bytes in all (`type` is 1 byte more than `def`). ``` //A normal function def r(t:Any):Any=t match{case(('K',x),y)=>r(x)case('I',x)=>r(x)case t=>t} //With match types type R[T]=T match{case(('K',x),y)=>R[x]case('I',x)=>R[x]case _=>T} ``` Admittedly, in this particular example, you could use auto-tupling, `->`, pattern-matching function literals, etc. to make the def shorter, but this is just one case. When you're not dealing with tuples, or the return type is more complex than just `Any`, or you have multiple parameters, this tip becomes more useful. # Use type constructors for two-argument functions When you define a type with two type parameters, you can treat it like an infix operator. Not so for methods. Suppose you have the following two definitions ``` def>(a:Int,b:Int)=... type +[A,B]=... ``` When you invoke `>`, you can call it with `>(a,b)`, whereas for `+`, you can call it like `A+B`. You can use any other operator you want if you want a specific precedence. ]
[Question] [ This challenge is inspired by the same task I read some time ago in CACM. There are many ways to sort stuff. Most attempt to sort in as few operations as possible (= as fast as possible). However, it is also possible to consider how few resources you might require to sort stuff, which seems more fitting for a codegolf challenge. You have a stack of cards, numbered from `1` to `N` (or `0` to `N-1` or `a` to `zzz` if you prefer). You do not know `N`. All you have available are two additional stacks, where one of them has capacity for just a single card. At any point, you see just the top of those stacks and you have no memory what was there even a single step before. Your task is to write a function (or whatever) that would take top of those 3 stacks as input in some convenient form and return operation that has to be performed - eg `2,3` meaning card has to move from stack 2 to stack 3. Please note that one stack has capacity for a single card. Input given when stack is empty is arbitrary. Initial state of sorting is one stack with all the cards in arbitrary mixed order and two empty stacks, one of the two with capacity for a single card (and the other is unlimited). After executing your function (and performing the operation returned) finitely many times on arbitrarily mixed initial cards, cards have to be guaranteed to be sorted on any of the stacks. Saving previous state or checking non-top numbers in any way is prohibited. As are all other loopholes. [Answer] # JavaScript (ES6), 23 bytes Uses 1-indexed cards and stacks. The initial stack is the 1st one. The single-card stack is the 3rd one. Expects \$0\$ for an empty stack. Returns a 2-digit number, where the 1st digit is the source stack and the 2nd digit is the destination stack. ``` (a,b,c)=>c?b>c?21:32:13 ``` [Try it online!](https://tio.run/##bVHLboJAFN3zFacuZCaORKSPRION38CSskAYhQYZwiCmrW77Af3E/gidC5po0sW9yT3n5Nwzd97jNtZJnVfNtFSp7LZ@x2KxEQn3V8nrxtTcXXjzhet1jdQNfKzhr/BlAfqTJqeQ5a7JlgYIzByuBcKIKlpaBktUqVUhnULtmK2buG5sgYD33DHLC8keAkervWSafPXFDr5P/uOxQWQr6w/GSoGck6YkMscELue8TwKEuk4EUt1ElMFxnC2jHoSzKHIqVTGO0wkzgQF1/0Xndyg3G2x7eAWQb01Q2oIp3Oia0uhSOooPj7KSxYW6BgOarFZHjPKyjYs8xV61crTsuXPfg5AsetfqoDN2s6UPwwfx7SFJYMLh9/vH9AllGI46eN7f/JAkUuu30jb82bLoF1kIT2Au4CLiV@TFjD34KPAsSPBk2O4P "JavaScript (Node.js) – Try It Online") ### Commented ``` ( // input: a, // a = top card in the primary stack b, // b = top card in the secondary stack c // c = card in the temporary stack ) => // c ? // if there's already a card in the temporary stack: b > c ? // if there's a card in the secondary stack and it's // greater than the temporary card: 21 // move from secondary to primary : // else: 32 // move from temporary to secondary : // else: 13 // move from primary to temporary ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~9~~ 8 bytes ``` ṖM⁸aḢ;‘$ ``` [Try it online!](https://tio.run/##y0rNyan8///hzmm@jxp3JD7cscj6UcMMlf8GD3d3P9q47nC7NZDh8HDnqoc75huc6j601PpR05pHjTsPLQOKVR9aemztsUlcOlDVKg93rnWAsg2P7D/WdXTSw50zgBqyHjXMUdC1U3jUMPfhzpaHO2cfbuc63P5wV8choFm7DXUMdAyPbTq0////6OhYHRAy1zHUMdIx0THTMdYxjY0FAA "Jelly – Try It Online") A monadic link taking a list of three integers representing the top of the three stacks, or zero for an empty stack. The three stacks are `[single card, destination, source]`. Returns a pair of integers indicating which stack to move from and to. In keeping with Jelly’s indexing of lists, the third stack can be referred to either as `3` or `0`. Inspiration taken from [@Arnauld’s JavaScript answer](https://codegolf.stackexchange.com/a/197250/42248) so be sure to upvote that one! ## Explanation ``` Ṗ | Remove last list item M | Indices of maximum ⁸a | Original argument and with this Ḣ | Head ;‘$ | Concatenate to itself plus 1 ``` ]
[Question] [ I was doing some investigation into trig functions using compound angles recently, and noticed that the results are really long and tedious to write: $$ \cos(A+B) = \cos A \cos B - \sin A \sin B \\ \cos(A-B) = \cos A \cos B + \sin A \sin B \\ \sin(A+B) = \sin A \cos B + \sin B \cos A \\ \sin(A-B) = \sin A \cos B - \sin B \cos A \\ $$ $$ \tan(A+B) = \frac{\tan A + \tan B}{1 - \tan A \tan B} $$ $$ \tan(A-B) = \frac{\tan A - \tan B}{1 + \tan A \tan B} $$ Realising this, I devised a shorter, golfier way, of writing such expressions: ``` <direction><operator>[functions](variables) ``` Where `direction` is either `«` or `»` and `operator` is in the string `+-*/` --- Also, when there is more variables than functions, the variables are, in a sense, left shifted through the functions, with unused variables simply being concatenated to the expression: ``` »-[f,g](x,y,z) ``` Turns into: $$ f(x)g(y)z - f(y)g(z)x - f(z)g(x)y $$ *Note that the variables `x`, `y` and `z` are left shifting through the functions* --- Note that when there is only one function given, it is applied as if the expression was an algebraic expansion. For example: ``` «+[cos](a,b) ``` Turns into $$ cos(a) + cos(b) $$ --- For an expression like `«+[f, g, h](foo, bar, baz)`, each function in the function list (`f, g, h`) is applied to every variable, as if the expression was being algebraically expanded: ``` f(foo)f(bar)f(baz) g(foo)g(bar)g(baz) h(foo)h(bar)h(baz) ``` These expressions are then concatenated with the provided operator (when the operator is `*`, the expressions are simply concatenated without any symbols): ``` f(foo)f(bar)f(baz) + g(foo)g(bar)g(baz) + h(foo)h(bar)h(baz) ``` --- For an expression like `»+[f, g, h](foo, bar, baz)`, each function in the function list (`f, g, h`) is applied to the variables in sequence, as if the variables were "shifting" through the functions: ``` f(foo)g(bar)h(baz) f(bar)g(baz)h(foo) f(baz)g(foo)h(bar) ``` These expressions are once again concatenated using the above method: ``` f(foo)g(bar)h(baz) + f(bar)g(baz)h(foo) + f(baz)g(foo)h(bar) ``` ## Some Clarifications When the direction is `»` and there are more variables than functions , the following method is applied: ``` FOR j = 0 TO length of functions FOR i = 0 TO length of variables IF i >= length of functions - 1 THEN Result += variables[i] ELSE Result += Functions[i] + "(" + variables[i] + ")" NEXT i Left shift variables Result += operator NEXT j ``` Given the expression `»-[f,g](x,y,z)`, this would turn into: ``` f(x)g(y)z - f(y)g(z)x - f(z)g(x)y ``` Empty function lists should return an empty expression, as should empty variable lists. When there are more functions than variables and the direction is `»`, simply ignore the functions in the functions list whose index is greater than the length of the variables list. For example, given `»+[f,g,h](x,y)`: ``` f(x)g(y) + f(y)g(x) ``` ## The Challenge Given a shorthanded string as described above, output the expanded expression ## Test Cases ``` Input -> Output «+[cos,sin](a,b) -> cos(a)cos(b) + sin(a)sin(b) »+[cos,sin](a,b) -> cos(a)sin(b) + cos(b)sin(a) «[f](x,y,z,n) -> f(x)f(y)f(z)f(n) «+[f](x,y,z,n) -> f(x) + f(y) + f(z) + f(n) «+[f,g]() -> »*[f,g]() -> »-[f,g](a,b) -> f(a)g(b) - f(b)g(a) »[g,f](a,b) -> g(a)f(b)g(b)f(a) «+[tan](a,b) -> tan(a) + tan(b) »+[](a,b) -> »-[f,g](x,y,z) -> f(x)g(y)z - f(y)g(z)x - f(z)g(x)y «/[f,g](x,y,z) -> f(x)f(y)f(z) / g(x)g(y)g(z) «[]() -> »[]() -> »+[x,y](foo,bar,baz) -> x(foo)y(bar)baz + x(bar)y(baz)foo + x(baz)y(foo)bar »+[f,g](x) -> f(x) + g(x) «+[f,g](x) -> f(x) + g(x) »+[f,g,h](x,y) -> f(x)g(y) + f(y)g(x) ``` Let it be known that: * The direction will *always* be given * The operator is *optional* * The `[]` denoting the functions will always be present, but will not always contain functions * The `()` denoting the variables will always be present, but will not always contain variables * Functions can be outputted in any order just as long as the expressions are in order (`cosAsinB - sinAsinB` can be written as `sinBcosA - sinBsinA` but not as `sinAsinB - cosAsinB`) * Variable names can be of any length * The `«` and `»` can be taken as `<` and `>` if wanted (`«` and `»` are preferred however) Therefore, if no functions/variables are present, then an empty output is required. Whitespacing within the answer doesn't matter (i.e. newlines/extra spaces don't invalidate outputs). Input can also be taken as: ``` [direction, operator, [functions], [variables]] ``` In which case, `direction` will be a string, `operator` will be either an empty string or an operator, `functions` will be a (sometimes empty) list of strings, as will variables. ## Score This is code golf, so fewest bytes wins. Standard loopholes are forbidden. ## Leaderboards Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language. To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template: ``` # Language Name, N bytes ``` where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance: ``` # Ruby, <s>104</s> <s>101</s> 96 bytes ``` If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header: ``` # Perl, 43 + 2 (-p flag) = 45 bytes ``` You can also make the language name a link which will then show up in the leaderboard snippet: ``` # [><>](http://esolangs.org/wiki/Fish), 121 bytes ``` ``` var QUESTION_ID=194719; var OVERRIDE_USER=8478; var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;function answersUrl(d){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+d+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(d,e){return"https://api.stackexchange.com/2.2/answers/"+e.join(";")+"/comments?page="+d+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(d){answers.push.apply(answers,d.items),answers_hash=[],answer_ids=[],d.items.forEach(function(e){e.comments=[];var f=+e.share_link.match(/\d+/);answer_ids.push(f),answers_hash[f]=e}),d.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(d){d.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),d.has_more?getComments():more_answers?getAnswers():process()}})}getAnswers();var SCORE_REG=function(){var d=String.raw`h\d`,e=String.raw`\-?\d+\.?\d*`,f=String.raw`[^\n<>]*`,g=String.raw`<s>${f}</s>|<strike>${f}</strike>|<del>${f}</del>`,h=String.raw`[^\n\d<>]*`,j=String.raw`<[^\n<>]+>`;return new RegExp(String.raw`<${d}>`+String.raw`\s*([^\n,]*[^\s,]),.*?`+String.raw`(${e})`+String.raw`(?=`+String.raw`${h}`+String.raw`(?:(?:${g}|${j})${h})*`+String.raw`</${d}>`+String.raw`)`)}(),OVERRIDE_REG=/^Override\s*header:\s*/i;function getAuthorName(d){return d.owner.display_name}function process(){var d=[];answers.forEach(function(n){var o=n.body;n.comments.forEach(function(q){OVERRIDE_REG.test(q.body)&&(o="<h1>"+q.body.replace(OVERRIDE_REG,"")+"</h1>")});var p=o.match(SCORE_REG);p&&d.push({user:getAuthorName(n),size:+p[2],language:p[1],link:n.share_link})}),d.sort(function(n,o){var p=n.size,q=o.size;return p-q});var e={},f=1,g=null,h=1;d.forEach(function(n){n.size!=g&&(h=f),g=n.size,++f;var o=jQuery("#answer-template").html();o=o.replace("{{PLACE}}",h+".").replace("{{NAME}}",n.user).replace("{{LANGUAGE}}",n.language).replace("{{SIZE}}",n.size).replace("{{LINK}}",n.link),o=jQuery(o),jQuery("#answers").append(o);var p=n.language;p=jQuery("<i>"+n.language+"</i>").text().toLowerCase(),e[p]=e[p]||{lang:n.language,user:n.user,size:n.size,link:n.link,uniq:p}});var j=[];for(var k in e)e.hasOwnProperty(k)&&j.push(e[k]);j.sort(function(n,o){return n.uniq>o.uniq?1:n.uniq<o.uniq?-1:0});for(var l=0;l<j.length;++l){var m=jQuery("#language-template").html(),k=j[l];m=m.replace("{{LANGUAGE}}",k.lang).replace("{{NAME}}",k.user).replace("{{SIZE}}",k.size).replace("{{LINK}}",k.link),m=jQuery(m),jQuery("#languages").append(m)}} ``` ``` body{text-align:left!important}#answer-list{padding:10px;float:left}#language-list{padding:10px;float:left}table thead{font-weight:700}table td{padding:5px} ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="https://cdn.sstatic.net/Sites/codegolf/primary.css?v=f52df912b654"> <div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td><a href="{{LINK}}">{{SIZE}}</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td><a href="{{LINK}}">{{SIZE}}</a></td></tr></tbody> </table> ``` [Answer] # JavaScript (ES6), ~~174~~ 171 bytes ``` (d,o,f,v,g=(f,V=v)=>f?V.map(v=>f+`(${v})`):V)=>f+f&&v+v?(d<'»'?f[1]?f.map(f=>g(f).join``):g(f[0]):v.map((_,i)=>v.map((_,j)=>g(f[j],[v[i++%v.length]])).join``)).join(o):'' ``` [Try it online!](https://tio.run/##nZJdboMwDMffewoUbSUeKd1eq1Fu0ReEVmgbBuqSalQRMO1EO0LfejHmJFtXVdCPITmxZfuX8HeKRCXl4j3fbEdCLlctD1q6ZJJxplgWUM5mgYJgysOZ/5ZsqELXm9O7D/UJc5jMdMrjw6HyVEiXz@5@54Y8eopDbsp5MM0oB7@QuZhjPQbRYwwTZbL0heUIOAQFmPKoiFmkotzz7pW/Xols@xrHcIBYh0qYuG67kKKU65W/lthIyf6LMId4uERkIUvCSJkLEuswwSAlyHGc8djBJE1Aryk4noNVGOo1hcEpc3cT00KQaeGWPOi8JxpCuGVVyKrRGjRxYHJaAac1WoMmekD2chdBeCnNMltjt0tERjJDNZijD4mEdCv18P/W0UnrscA/rRzVzLTAI3RTdJOegVlxMwTwPpZutpAUeO@UrBTbRHRiDAiT2I6CaufsC@pG3KzL34yP55vhcBsjTI1@A5XxG/QrqLt/bnwd@fcJOlo0e5A@4Myz7pr85R@9qrX9Bg "JavaScript (Node.js) – Try It Online") ### Commented ``` ( d, // d = direction o, // o = operator f, // f[] = list of functions v, // v[] = list of variables g = (f, V = v) => // g = helper function taking (f, V[]) f ? // if f is defined: V.map(v => // for each variable v in V[]: f + `(${v})` // return f, followed by '(v)' ) // : // else: V // just return V[] as-is ) => // f + f && v + v ? // if both f[] and v[] are non-empty: ( d < '»' ? // if the direction is '«': f[1] ? // if there are at least 2 functions: f.map(f => // for each function f_i in f[]: g(f).join`` // return 'f_i(v_0)f_i(v_1)...' ) // end of map() : // else: g(f[0]) // return [ 'f_0(v_0)', 'f_0(v_1)', ... ] : // else (the direction is '»'): v.map((_, i) => // for each variable at position i: v.map((_, j) => // for each variable at position j: g( // return [ 'f_j(v_k)' ] f[j], // where k = i mod v.length [v[i++ % v.length]] // and increment i ) // ).join`` // end of inner map(); join the list ) // end of outer map() ).join(o) // join the final list with the operator : // else: '' // just return an empty string ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 63 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` UÇ`θiVεY€…(ÿ)«}ëDg©DIgα+>∍Œ®ùεζεðK'(ýyðå≠i')«]Dg≠iJ}¸˜Xý³gIg*Ā× ``` Four loose inputs in the order `operator, direction, [variables], [functions]`. [Try it online](https://tio.run/##yy9OTMpM/f8/9HB7wrkdmWHntkY@alrzqGGZxuH9modW1x5e7ZJ@aKWLZ/q5jdp2jzp6j046tO7wznNbz207t/XwBm91jcN7Kw9vOLz0UeeCTHWghliXdBDTq/bQjtNzIg7vPbQ53TNd60jD4en//2tzHdrNFa1UUaGko1RZqRQLZKcBmcn5xUqxAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpSbKWgZF@pw6XkX1oC5IJ5LqfbghL@hx5uTzi3IzPs3NbIR01rHjUs0zi8X/PQ6trDq13SD610ObQeKJt@bqO23aOO3qOTDq07vPPcVrBg8blt57Ye3uCtrnF4b@XhDYeXPupckKkO0goELukgnlftoR2n50Qc3gvUYHR4RTrEMK0jDYen/9c5tM3@0Jb/0dFK2ko6SodWK@lEKyUCWUlKsUBWcn4xkF2cmacUG6ujAFWzG78auDEVQFYlEFcBcR5YaRqyMcSqgQjqKKVDJbRgbkCX0MXiOGR5LNLpQBamoxDyJYl4fI5uK8Iv6DbrY/EvNtdBvYvqXLgAwglp@fkgRyQWgUmIWRCT0VVWYNiDHPZY5ZD8gpDXUcpAD8UKsBqwZxC@ASWG2NhYAA). **Explanation:** ``` U # Pop and store the 1st (implicit) input `operator` in variable `X` Ç # Convert the 2nd (implicit) input `direction` to a list of codepoint ` # Push this codepoint to the stack θ # Only leave its last digit i # If this digit is 1 (so the direction is "«"): V # Pop and store the 3rd (implicit) input `variables` in variable `Y` ε } # Map over the 4th (implicit) input `functions`: Y # Push the `variable`-list from variable `Y` €…(ÿ) # Surround each variable with parenthesis « # And append it to the current `function` we're mapping ë # Else (so the direction is "»" instead): D # Duplicate the 3rd (implicit) input `variables` g # Pop and push the length to get the amount of `variables` © # Store it in variable `®` (without popping) D # Duplicate this length I # Push the fourth input `functions` g # Pop and take its length as well α # Take the absolute difference between the two amounts + # And add it to the duplicated amount of `variables` > # And increase it by 1 ∍ # Then extend the duplicated `variables` list to that length Œ # Get all sublists of this list ®ù # Only leave the sublists of a length equal to variable `®` ε # Map each remaining sublist to: ζ # Create pairs with the 4th (implicit) input `functions`, # with a default space as filler character if the lengths differ ε # Map each pair: ðK # Remove the spaces '(ý '# Join the pair with a ")" delimiter yðå≠i # If the current pair did NOT contain a space: ')« '# Append a ")" ] # Close all open if-statements and maps D # Duplicate the resulting list g≠i } # Pop and if its length is NOT 1: J # Join the inner-most list together to a string ¸ # Then wrap it into a list (in case it wasn't a list yet) ˜ # And deep flatten the list Xý # Join it by the operator we stores in variable `X` ³g # Get the length of the 3rd input-list `variables` Ig # And the length of the 4th input-list `functions` * # Multiply them with each other Ā # Truthify it (0 remains 0; everything else becomes 1) × # And repeat the string that many times # (so it becomes an empty string if either list was empty, # or remains unchanged otherwise) # (after which this is output implicitly as result) ``` [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 177 bytes ``` (d,o,f,v)=>string.Join(o=="*"?"":o,d<61?f.Select(l=>v.Aggregate("",(a,b)=>a+l+$"({b})")):v.Select((x,y)=>string.Concat(v.Select((i,o)=>o>=f.Count?i:f[(y+o)%f.Count]+$"({i})")))) ``` [Try it online!](https://tio.run/##fZJPb5wwEMXvfIqp1YpxmKUlhxx2MaiqVClVpBy2Ug6IgxfMxhLCEXjRplE@@9b8SXdDpB4Qmvfm/cyMKbpV0enTz0NTxMWjbKmzrW72dHunOxtPRbKo5nclTliSoYp6LpJJDH8Z3aARgl2xlLG1oTK@idIq3KpaFRZrkfTh9/2@VXtpFTJGKGnn4jKog88MX3avnHG@7t8CeKTnM/2HaQpp8exqMs41iaicd2hsqtdVhs@B4V9mJR@xesRyftp4vdElWNVZnKAgObx4AL1sodQtCJDZt3wzK@ZpFKIchAA/8yEFxmA9SuFvsx0RyId2OXSG28Nu4uIQFUN3CpFLXPM3ZuWWbbVpukUgIlfeNqU63lfo5z6HFUQ83D7V2qJP/giYGe7RclerJeMCgA4QwHsoH6GLpsUp4cOjahUeQSRwhE/DCNyNOvwC06APrbbqTjcKK3QbI7ckOg9F52/jfAPeqzcum8VBVpiOOt3kw6XSH3cjm9lLshwvy6v/tK7eeZfOvwPIyg9u/PVjzjv9BQ "C# (Visual C# Interactive Compiler) – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), ~~179~~ ~~190~~ 194 bytes ``` lambda d,o,F,V,S='%s(%s)':(o*(o>'*')).join([(''.join(S%(u,v)for v in V)for u in F if V),(''.join(map(lambda u,v:v and u and S%(u,v)or v or'',F,(V+V)[i:i+len(V)]))for i in range(len(V)))][d>'<']) ``` [Try it online!](https://tio.run/##lVTBbsIwDD23X5ELckLDNu1YAZdJ/ABSL10PgbaQCRLUFDT4@c4JHZTRQqdKrp28vOc4cXbHcq3Ve5VPPquN2C5SQVKu@YxHfD6BgaEDwyCkekj1FIbA2MuXlorGFODszQd0zw8s1wU5EKlI5Ny9dWdE5hjzC3YrdrQWwTXhgQiVItTamsax6AIAM6BRELFYhjLYZIpGLGGOWlrqQqhVRs/jjCVxOoUxJKwqM1N@CJMZMiGx73kUhzmBAE0MS21sYKSCxMbCRgtcxh1y2ht55XSz3zY8WnOyRt0yOsIceiCDf0If48a9Kd@4@9rWobtyi2/Uhx2zXUSPq92cRbNsT8vhR3@FW1kdaGW9/MnxQSme3oXu@ftsmhW@UXvtA20p32997vbXWfVG5rWEk8u1djsQxfl3ar96zfyShxfiCrhL294Ph7WHAGuEY0ehlzY1H4F8L/F92@v1U2Q7/tLZoe/hs5KGZFdIVZI00AHENr/6kZmxABLaGIhwgJERaua0JkSFbGOymsOvfgA "Python 2 – Try It Online") 11 bytes lost to fixing a bug. A function that takes a direction, an operator, a list of functions, and a list of variables. For direction, uses `<,>` instead of `«,»` because utf-x reasons. This assumes that if the direction is `>`, and there are more functions than variables, that we ignore the excess function(s); e.g., `>*[f,g,h],[c,d]) => f(c)g(d)*f(d)g(c)` ]
[Question] [ There's a little-known secret in Banjo-Kazooie that you can interleave the three Cheato codes on the Treasure Trove Cove Sandcastle floor and it will still recognize all of them. So you could, for instance, enter `BLUREEGOLDDFFEEGEAATHTHEEGSRSRS`, activating `BLUEEGGS`, `REDFEATHERS`, and `GOLDFEATHERS` all at once. # Challenge Your task is to take a list of cheat codes and a code entry and determine which of the codes are activated. A code entry is valid if and only if some substring of the entry can spell out a subset of the cheat codes by assigning letters one at a time to exactly one word in order until all codes are exactly filled in. For example, applying this to the above code entry: ``` BLUREEGOLDDFFEEGEAATHTHEEGSRSRS BLU_E________E_G_________GS____ ___R_E___D_F__E__A_TH__E___RS__ ______GOL_D_F___E_A__TH_E____RS ``` ## Other Assumptions * Both cheats and entries will contain only uppercase letters A-Z. * Each code in the input list will appear only once. * If two cheat codes share a prefix or a suffix, their shared letters must still appear twice to be counted, thus `REDGOLDFEATHERS` would, for the purposes of this challenge, only return `GOLDFEATHERS`. * Each code entry can only contain one matching substring. * If it is ambigous how a code-matching substring could be chosen, choose the one that starts the earliest and is the longest match for that particular starting point. * The order of matched codes returned does not matter. * If it is ambiguous which code could be used, prefer cheat codes that appear earlier in the code list. * A substring *does not* match if some of the letters inside it cannot be assigned to a cheat code. For instance `BLUEXEGGS` does not match any cheat codes. * If no codes are matched, you may return an empty list or any falsy value. *Note that this may not necessarily be consistent with the nuances of the game`s implementation* # Example Test Cases ``` Codes: BLUEEGGS Entry: BLUEEGGS Result: BLUEEGGS ``` ``` Codes: BLUEEGGS REDFEATHERS GOLDFEATHERS Entry: BANJOGOLDBLUREEDFEATHEERGGSSKAZOOIE Result: BLUEEGGS REDFEATHERS ``` ``` Codes: BLUEEGGS REDFEATHERS GOLDFEATHERS Entry: KAZOOIEBLUREEGOLDDFFEEGEAATHTHEEGSRSRSBANJO Result: BLUEEGGS REDFEATHERS GOLDFEATHERS ``` ``` Codes: BLUEEGGS REDFEATHERS GOLDFEATHERS Entry: BANJOKAZOOIE Result: <falsy> ``` ``` Codes: CAT DOG Entry: CCADOGATT Result: DOG (The substring may not contain the same code twice) ``` ``` Codes: COG ATE CAT DOG Entry: CDCOAGTE Result: DOG CAT (Match the earliest and longest substring) ``` ``` Codes: ACE BDF ABC DEF Entry: ABCDEF Result: ACE BDF (Prefer matching codes earlier in the list) ``` # Rules/Scoring Standard procedure for code golf applies. I/O can use any convenient format. Fewest bytes wins. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 25 bytes ``` hsS&t⊇.g;Sz{∋ʰ}ᵐhᵍ{tᵐc}ᵐp ``` [Try some of the faster test cases online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRuX/2obcOjpuaaRx3LldISc4pT9ZRqH@7qrH24dcL/jOJgtZJHXe166dbBVdWPOrpPbQCJZzzc2ltdAmQkg3gF//9HK0QrOfmEurq6uwcr6SCxY2N1gFLOzo4u/u6OISEgOWdHIKUE5MMkXZz9Hd1DXMFyQFEdJUcQB0WdQiwA "Brachylog – Try It Online") Extremely slow brute force, that I haven't verified on the longer test cases yet. It wouldn't surprise me if a clever implementation of a smarter algorithm turns out considerably shorter. Takes input as a list `[entry,codes]` through the input variable and outputs through the output variable [if it succeeds](https://tio.run/##SypKTM6ozMlPN/r/P6M4WK3kUVe7Xrp1cFX1o47uUxtqH26dkPFwa291CZCRDOIV/P8frRQYqKQTreTkE@rq6u4erKSjFOTq4ubqGOLhGgTiufv7ILixsf@jAA). Seems to comply [fully](https://tio.run/##SypKTM6ozMlPN/r/P6M4WK3kUVe7Xrp1cFX1o47uUxtqH26dkPFwa291CZCRDOIV/P8freTo5Ozi6qakA2Q5uyrpKDm5ADlAQSATJB4b@z8KAA) with the spec to the extent to which I've tested it at all. The exact nature of the brute force is that for every substring of the entry (until there's a match), it tries every subset of the codes until it's possible to assign one code to each letter of the substring such that the letters assigned to each code taken in order form that code. The worst case complexity, where the worst case is failure, is something vaguely along the lines of \$O(x^22^yy^x)\$ with \$x\$ the length of the entry and \$y\$ the number of codes. [Answer] # [Python 2](https://docs.python.org/2/), ~~419~~ 416 bytes ``` def f(a,s): V=[] for u,c in((u,c)for z in product(*[g(c,s)for c in a])for u,c in zip(S(z),S(a))):A=set(sum(u,[]));L=sum(map(len,u));V+=A and(len(A)==L>max(A)-min(A))*[(min(A),-L,c)] return V and sorted(V)[0][2] S=lambda A:A and[u+[A[0]]for u in S(A[1:])]+S(A[1:])or[[]] def g(c,s,i=0): r=[[]]*(c=='') while c and c[0]in s[i:]:i=s.find(c[0],i)+1;r+=[u+[i-1]for u in g(c[1:],s,i)] return r from itertools import* ``` [Try it online!](https://tio.run/##pZNLj9owEMfv@RQj7QEbsmh3e2PlSgYCfdBSkS2HWjmY4CxW85LtqMt@eToT9tVDL61y8Dw8v//MWGmP4dDUN6fT3hRQMB17PolgK1QWQdE46OIcbM0Ynpz8R/Sgdc2@ywMbqnuWYwUl6BrojL8WwaNtWcoeeZwyzTmfSOFNYL6rkKYyzm9XgpxKt6w0ddxhZDsSEnS9pwCTXIjV@0o/oHVZWQrwoWJnK75cYUvYpTOhczVsqQx844LZsy1XV5m6yaJUlLra7TXISc9V3UhJzGV9m9RkyqS6nmQ8Gz1bjVMqyyJaSD9ebMUVLcUJig9ZLsRgwCP4dbClwblJN0cmwryyk2xihR8XFoegaGz56PrWjQRJ28vrV2WEkx4JvJnDRYVrKrDBuNA0pQdbtTjU8NQ6Wwd8IjWYrZeDGAbyLqHjLpF0zDGY4TnDsCSHwwWgDdaDP9BaHISDruGcjmHXBVQBH7QLHox2pTUuiv4mg9w/ZOaztVxiimS@6JAfkG6eMD70Symb@p5s3@18QOz9W7qc9djpfNGLTGc9PVn0dHTJJPY3ZwpsvSIJREDe7M1Lu7RGki2tD2/h09X3JFkuU2JukvkikXcfkk3vLterV5@0pvLrp/Vn@WO9/nieptClPwIzVRuOPZn/F5qiWLRJni8nGyxPXxSj6AL@Df@EOMMpO18s0Egk3iGdZbrBr2@iHyzon7g6vWvw5d8B/kZdMH48HkfR6Tc "Python 2 – Try It Online") After some trivial spaces being removed, still pretty long! The function `S` returns the power set of a collection. The function `g(c,s)` return a list whose elements are a list of indexes of a potential embedding of the code `c` in the entry string `s`. The function `f(a,s)` then looks at all possible combinations of embeddings of some or all of the codewords in s, selecting those which end up being a continuous sub-string of `s` (the bit about `A` and `L` first ensures that the particular choice of embeddings are pairwise disjoint, and then that there are no gaps). By nature of the use of `product` and the action of `S`, the unsorted results will "prefer cheat codes that appear earlier"; we then further sort by first the starting index of such a substring, and then by length in case of a tie; so that in case of a tie for both starting index and length, the original ordering will prevail as I think was demanded. If no embeddings are found, the empty list is returned. I'm guessing the `g` can be golfed a bit more, at the expense of a much longer running time... ]
[Question] [ > > **ALERT: IN CASE YOU DOUBT, NO PUN ON "QUINE" IS INTENDED** > > > In regulated horse-racing for gambling, bets called *Quinella bets* [exist and in which a person bet on the first two places of a race.](https://en.wiktionary.org/wiki/quinella) In racecourses, usually there is a display which shows the odds of a specific combination as below: [![enter image description here](https://i.stack.imgur.com/iQUEI.png)](https://i.stack.imgur.com/iQUEI.png) (This picture is a cropped picture from Hong Kong Jockey Club. QIN stands for Quinella) ## Challenge Write a program or function, receiving either lines of strings or an array, print or return an ASCII Quinella table with the following format: ``` QUINELLA | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+----- | 8\1 | 162 | 7.2 | 11 | 109 | 4.5 | 6.0 | 11 | 999 | 11 | | | | | 1 -----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+----- 9 | 37 | 9\2 | 11 | 999 | 41 | 350 | 75 | 24 | 999 | 31 | | | | | 2 -----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+----- 10 | 8.2 | 84 |10\3 | 75 | 999 | 85 | 48 | 8.1 | 138 | 191 | | | | | 3 -----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+----- 11 | | | |11\4 | 45 | 6.4 | 999 | 287 | 473 | 60 | | | | | 4 -----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+----- 12 | | | | |12\5 | 15 | 8.9 | 40 | 175 | 378 | | | | | 5 -----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+----- 13 | | | | | |13\6 | 26 | 999 | 15 | 860 | | | | | 6 -----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+----- 14 | | | | | | |14\7 | 727 | 100 | 37 | | | | | 7 -----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+----- | 8 | 9 | 10 | 11 | 12 | 13 | | 8 | 9 | 10 | 11 | 12 | 13 | 14 | ``` In this challenge, the numbers in the middle are calculated from the input by a specific algorithm, which will be explained later. # Specification **Input**: Your program or function must receive one of the two formats as below: * **Lines of Strings**: The first line will be `<number of horses> <number of bets>`, following by `<number of bets>` lines of `<horse 1> <horse 2> <amount of bet>`. Example: ``` 10 100 1 2 100 3 4 500 5 6 100 7 8 2000 9 10 10 (... 95 more lines) ``` * **Array**: An array or tuple, with 3 elements, `[<number of horses>, <number of bets>, <bets>]`, where `<bets>` is a 2d array consisting of `<number of bets>` elements, each element consists of 3 elements, `[<horse 1>, <horse 2>, <amount of bet>]`. *As a special rule for functions, passing the tuple as 3 arguments is allowed.* Example: ``` [10, 100, [ [1, 2, 100], [3, 4, 500], [5, 6, 100], [7, 8, 2000], [9, 10, 10], ... 95 more elements ]] ``` * You may assume all inputs are valid. * You may assume `1 <= <horse 1> < <horse 2> <= <number of horses>` in both cases. * You may assume `9 <= <number of horses> <= 14` in both cases. **Processing**: The odds for each quinella pair `<horse 1>, <horse 2>` (unordered, i.e. `1,2` and `2,1` are considered identical) is calculated as follows: ``` Odds = <Total bet amount of all pairs> / <Total bet amount of the pair> / 2 Maximum Odds: 999, Minimum Odds: 1.1 ``` In case you doubt, **the odds will be 999** if `<Total bet amount of the pair> == 0`. The result should be rounded to the nearest 0.1 if `Odds < 9.95` (in this case, the `.0` must be retained if necessary), and to the nearest integer if `Odds >= 9.95`. **Output**: Replace each ***bold-and-italic number pair*** with the corresponding odds calculated in the previous step. Leave the cell blank if any of the number in the pair is larger than `<number of horses>`. ``` QUINELLA | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+----- | 8\1 | ***1,2*** | ***1,3*** | ***1,4*** | ***1,5*** | ***1,6*** | ***1,7*** | ***1,8*** | ***1,9*** |***1,10*** |***1,11*** |***1,12*** |***1,13*** |***1,14*** | 1 -----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+----- 9 | ***8,9*** | 9\2 | ***2,3*** | ***2,4*** | ***2,5*** | ***2,6*** | ***2,7*** | ***2,8*** | ***2,9*** |***2,10*** |***2,11*** |***2,12*** |***2,13*** |***2,14*** | 2 -----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+----- 10 |***8,10*** |***9,10*** |10\3 | ***3,4*** | ***3,5*** | ***3,6*** | ***3,7*** | ***3,8*** | ***3,9*** |***3,10*** |***3,11*** |***3,12*** |***3,13*** |***3,14*** | 3 -----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+----- 11 |***8,11*** |***9,11*** |***10,11***|11\4 | ***4,5*** | ***4,6*** | ***4,7*** | ***4,8*** | ***4,9*** |***4,10*** |***4,11*** |***4,12*** |***4,13*** |***4,14*** | 4 -----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+----- 12 |***8,12*** |***9,12*** |***10,12***|***11,12***|12\5 | ***5,6*** | ***5,7*** | ***5,8*** | ***5,9*** |***5,10*** |***5,11*** |***5,12*** |***5,13*** |***5,14*** | 5 -----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+----- 13 |***8,13*** |***9,13*** |***10,13***|***11,13***|***12,13***|13\6 | ***6,7*** | ***6,8*** | ***6,9*** |***6,10*** |***6,11*** |***6,12*** |***6,13*** |***6,14*** | 6 -----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+----- 14 |***8,14*** |***9,14*** |***10,14***|***11,14***|***12,14***|***13,14***|14\7 | ***7,8*** | ***7,9*** |***7,10*** |***7,11*** |***7,12*** |***7,13*** |***7,14*** | 7 -----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+----- | 8 | 9 | 10 | 11 | 12 | 13 | | 8 | 9 | 10 | 11 | 12 | 13 | 14 | ``` * Each cell is 5 characters wide. * You must center the odds, and if you cannot balance the margins, make left margin 1 character less wider than right margin. ## Test Cases [Here is a TIO driver which generates random test cases. No hard-coded test cases will be provided.](https://tio.run/##rZRvb6NGEMbf8ylGvIKYEHb5Z87xVW11p6a6Jjq198pY8l6MEyIHOCBXrOB@9fSZxUns3KXqi7M0axie/c3s7OzeqK@quazzqj0uymX28FXV1G6qjKZkNm2dF1cmnZzQr9dl2WTPrrImU9W12pikGsqL6q6lVVnfqlYTirvbz1l9sfqtrJusAesP1V67tSqW5a1l0xFFNKKEem9isLzOLst6@T1d4gkohec9aRVUs/nEQDSL3zu8exP8nT5i8DIa2XRvEH@vvkN9kR4CAO/Ql/8rnRj093W@zsgCfUpfbJpVmD7n1H50LCyVlFvdNdfWzHXdIZDblHVrWblDNzZN31JOx3hySNLREVkvucJjlk09eXN7YmwN47IsmnKduevyyjLPePfekIlP@YqsYfeft19Xcn/CYZrOY9kxnVuAdrtSrkjZBh3M7NybMi8WtNBZZGt01EHEoaNsOoz3@58X5@6QTL7aWLNX4juk5g5quF6jDjYi6HZpy1atf8lalPt@69AVl@Uv9nHbOFQuddvdb3VDHeTOy36cPZt1Mw/0bibmc95m65UvPWpso9rdTPLG7YUbTXfO7X6kKYmhdw8X9dzCT9oNtB3v4wSPp9NvJmx2E3TTY1mQ70U/QWuc7GXNJNMxMW52SSNbvRk89S0lSWLvKHjkb0@7xd5TEq54FOCRBVxKVMMBkSuEV7ct3@ddttxNSdwk5DBb7kDOcpk31Vrxwhb08ewcaZCE@bAAFsIiWAwbw5IenQwTMOgEdCLojZ7GaSp64UiYDwtgISyCxbAxLIFhMgZWCpYK1goOJAyGjyGiJE1lL4GRwEhgJDASGAmMhEIyRjJGMkYyRg4YaXB@YxYkOpiXpn7vA@QD5APkA@QD5APks8RnkM8gn0H@APINXuSYvyU6YU@PIk2DPgAqACoAKgAqACpgVMCagFEBo4IBFRhcqzG7E71sT49DCWSahn0IWAhYCFgIWMiwkGEhi0KGhQMsNLjoY/YkunyeHodS6koIP02jPgIuAi4CLmJcxLiIcRGrogEXGbx/Y35JeGBcoHGBxmHUBRFBmsZ9DGAMYMzAmIExA2MGxgMwNl7tlP9socXkxY2YFhd37dOluP9p17IuxrxdGAv3VlVWx1dwt/P1g2/DPuufjZsXy6y7WFk4bTb9RCbxobP0YRmOngn/G9rYbqWW74qlFdr2cE32i@HBQhw@rsf8G5lunVWZai0R8kWz0F4DUrjX6jKzTBwlXPWE803mx09n5@8@fPjZxIX48PAv "JavaScript (Node.js) – Try It Online") ## Winning Criteria Shortest code in each language wins as per the rules of code-golf challenges. No standard loopholes allowed. [Answer] # JavaScript (ES8), 321 bytes Takes input as `(number_of_horses)(bets)`. The number of bets [is not taken](https://codegolf.meta.stackexchange.com/a/12442/58563). ``` n=>b=>' QUINELLA '+(y=e='',g=(x,y)=>b.map(([X,Y,b])=>k+=X-x|Y-y?0:b,k=-(x>n|y>n))|k,F=x=>y>16?e:`|+ `[x?y&1:2]+(Y=y/2,s=y&1?'-----':(x%15|Y%8?x?Y>7?x>7?x:x<7?x+7:e:x-Y?y?x<15?~g(x>Y?Y:x+7,x>Y?x:Y+7)?(k=.5/k*g())<999?k.toFixed(k<9.95):999:e:Y:x:x+7+'\\'+x:y-2?Y+7:e:e)+e).padStart(s[2]?4:3).padEnd(5)+F(++x<16?x:!++y))(2) ``` [Try it online!](https://tio.run/##XVdda1tHEH33r3AfUt3be@XszM5@CcuXPiRQCIVSChG2IU6smFSpHGJTrsDkr7uzuzMbNQZbq/2amTNnzqz/vvn35uHD109fHpf7@9vt88f183598X59sTj946/ffn/15s2vp6eLoTust@vFYrxbd/N46HnH2T83X7ru8u24Gd9f88RuWL9dzk@b5WEyq/fjbr3s5ov90@Fi3/dPu/H1el5fHC7AT9vVu6fh5N3lPB1@hhVeD91mfXiJ48Oav0@LZf5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aVjRoAgHENag2ZuixPm@aDTbUC4RV72AnoK2HauAoViAGGqzEcZk@SHXmACl3WWeolYQFwSJBKWoAkdJSCySwGctaO@J6BrFQQu@OsD7KuqFODLk4ympENX0sMfO6YniSkFA8sMnNNlO5S4UcmSWlgBzMOxBaVW@NABMWileqUU6wFbq1HQgRWr3oNOdAEWmvNCmSK45kokcdaxkM1WCU0mw02LC5KSEqzjEip3WbCVlpViClgIxia42nbwqqeX14JRSqNgm3Ra11tJxWcQKW42tEbKYycscVamcqiuiMFYZDhX0MgraMPW9AvZ7tVLRQeEmtukAre8nTXEgrR4r3S2XozSeHE9LQJAr@bycIWmNUKPxDYyGeXUqp8g23lolP2lf4bdqTW120kZQVYCGOUSsWsA7fDPphZS5gkKUOvNWnl1ehMLb@rjJwbYUewPCYzKtPnxQuY5We9EP75HMo@NGWgrAh5ZIlG4oqUN9NGcBPG5q5WUKTlMdWomAMUl0lZR8schfOlJ/1hdsr2hSlFRgsVGM6lsEmoZDbTv6TNBGBWSbhRA0404LTvUS5ZWj79xQnu51rSpzZbxvefOktcygtnTJ@yu/XKSxZGlJP3Qn830AoO@0ql22Jr0uk/zTUC7xTSj1SApRgHeM2XXfP/8H "JavaScript (Node.js) – Try It Online") ## How? ### Main part ``` n => b => // n = number of horses; b[] = bet array ' QUINELLA ' + ( // append header y = e = '', // e is the empty string; start with y = '', coerced to 0 F = x => // F = main recursive function, taking x y > 16 ? // if y is greater than 16: e // return an empty string and stop recursion : // else: `|+\n`[x ? y & 1 : 2] // append a linefeed if we are at the beginning of a row + ( // or either '|' or '+' depending on the parity of y Y = y / 2, // define Y = y / 2 s = // define s: y & 1 ? // if y is odd: '-----' // s = 5 hyphens : // else: [cell content] // s is set to the content of the cell ) // .padStart(s[2] ? 4 : 3) // prepend leading spaces .padEnd(5) + // append trailing spaces F(++x < 16 ? x : !++y) // append the result of a recursive call )(2) // initial call to F() with x = 2 ``` ### Cell content The cell content is computed with [a huge cascade of ternary operators](https://tio.run/##hVRti9tG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uE6pB/NS4QPGX6PHhHOynpQ@VpJ6WRJFV@8qoTaIU2m7aPqJDTrofhm4CUSBOxpKYRR0mfOJj6rigevwI), which is neither easy nor very interesting to detail here. One key part in there is the formatting of a bet: ``` ~g( // invoke g(): x > Y ? Y : x + 7, // first horse x > Y ? x : Y + 7 // second horse ) ? // if g() didn't return -1: (k = .5 / k * g()) // compute amount_of_all_pairs / amount_of_this_pair / 2 < 999 ? // if the result is less than 999: k.toFixed(k < 9.95) // output it with the proper number of decimal places : // else: 999 // force result to 999 : // else: e // output an empty cell ``` ### Bet amount processing The helper function \$g\$ computes the total bet amount for a given pair of horses, or the total bet amount of all pairs when invoked with no argument. If at least one of the horses is not valid, it returns \$-1\$ instead. ``` g = (x, y) => // x = 1st horse, y = 2nd horse b.map(([X, Y, b]) => // for each bet of amount b on horses (X, Y): k += // update k: X - x | Y - y ? // if (x, y) is not matching (X, Y): 0 // add 0 to k : // else: b, // add b to k k = -(x > n | y > n) // start with k = 0 if both x and y are valid horses // otherwise, start with k = -1 ) | k // end of map(); return k ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~500~~ ~~448~~ 444 bytes ``` R=range(1,15) h,_,b=input() Q=eval(`[['']*16]*9`) Q[8][1:6]=R[7:13];Q[8][8:16]=R[7:] for i in R: if i<8:Q[i][i]=`7+i`+'\\'+`i`;Q[i][::15]=[['',7+i][i>1],i] for j in R:v=sum(v*((A,B)==(i,j))for A,B,v in b);x=min(999,0**v*999or.5*sum(zip(*b)[2])/v);X,Y=i<j<=h and[i,j-7,j,i-7][i>7::2]or(0,0);Q[X][Y]=x<10and round(x,1)or int(x+.5) Q[0]=[' QUINELLA ']+R[1:]+[''] for l in Q:print('-----+'*15+'-----\n')*(l<[' '])+'|'.join(map('{:^5}'.format,l)) ``` [Try it online!](https://tio.run/##XVbbbuM2EH3PV@hNkq2kHN6pRAW2QB8KLAokQIFdKGrtYHcbBYkduImR3r495fAijmv4gRQ5tzNnjvT858v9fsff32@Gw3b3@9cGOlD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Mn8jpoAdDMyhuFA5E7MERLVR6AKHCcqAcnjj3PSZXKFlIushoqZqQ/kcy2iAbY7CTEW8SU5yZn3RCLikWqwf/fKkDLTZ0VZCwVoYzlvLzTzMIYHBWmTkokDeemDK5QnIxO1gh860pSuswWOmtaxoBRUAU9EszSI6ZKY4QjCFiClIkSuwjO8gLNnwGxUEGGSylZqvEybohr4GRjoHy6QPJBVTfhpohOZ/b5pXJQGE7bDvpESwVRqzK0LH17JIF0lmJLpoNryjeR5w3VjpFXnBQn0rUoT9ioMgwkf6BD7jR5E@eM8YMAVEFFK0bKdEVrOf3G0US1LaeKwItKgSuYOvK1wE@ozASZb/DCNk3/AQ "Python 2 – Try It Online") [Answer] # [Clean](https://github.com/Ourous/curated-clean-linux), ~~498~~ ... 483 bbytes [Doesn't take](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/12442#12442) the number of bets. ``` import StdEnv,Text q="" j=join $h a=replaceSubString" 0"" "(" QUINELLA"+(j("\n"+j"+"(repeatn 16"-----")+"\n")[j"|"[q<+cjustify 5[c\\c<-: ?h a u v]\\v<-[0..15]]\\u<-[0..8]])%(9,9^9)) ?h a u v|u<1=q<+v rem 15|v>14=q<+u rem 8|u>7|v>7=q<+v=q<+(v+7)*sign(v rem 7) |u==v=u+7<+"\\"<+v|v<1|u>1=q<+u+7=q #p=sort[k+if(u>=v)7 0\\k<-[u,v]] #r=sum[z\\(x,y,z)<-a|[x,y]==p] |r>0.0#r=sum(map thd3 a)/r/2E0 |r<9.95=snd(sort[(abs(e-r),e<+".0")\\e<-[1.1,1.2..1E1]]!!0)%(0,2)=q<+toInt r |p!!1<h="999"=q ``` [Try it online!](https://tio.run/##ZVrbbhzHEX0Ov2K1dgBuOKK7@t4G10GA6MGAESRR8kQywJqiLMoiJfEWy@C3R@numalzOMsHYnZ3pru6rqdOzcWHy93N1@uPbx4@XK6ud1c3X6@uP328vV@9vn/z6uZx@Nflb/cHn7fr9cH77fuPVzcH375b7ba3l58@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OH7WCcXHI@6xsKz8Xmw1AeTCf1OsGgCIqVUURam6LO9E/OYfAR6OyYDxhoLM0W4j9f5M/BNJ4y9LBN80PGFICkkhMr51/9dvP2w@@Xu68sff/r61y83u@uri/HD3z/s7t9@vL3@@vLn/wM "Clean – Try It Online") Explained: ``` q = "" // define `q` as the empty string j = join // define `j` as the join function $ h a // function $ of horses `h` and array `a` = replaceSubString // replace all " 0" // zeroes with spaces before them " " // with two spaces ( // (in the string) " QUINELLA" + // " QUINELLA" prepended to ( // (the string created by) j // joining arg2 with arg1 ( // (the separator string) "\n" + // newline prepended to j "+" // joining arg2 with plusses (repeatn 16 // a list with 16 of "-----") // string with 5 dashes + "\n" // prepended to a newline ) [ // (a list made out of) j "|" // joining arg2 with vertical pipes [ // (a list made out of) q <+ // stringifying cjustify 5 [ // center-aligning a list of c // character `c` \\ c <-: // for every `c` in the string ? h a u v // (the thing that goes in the cell) ] \\ v <- [0..15] // for every `v` from 0 to 15 ] \\ u <- [0..8] // for every `u` from 0 to 8 ] ) % (9, 9^9) // drop 9 elements off the front ) ? h a u v // function ? of `h` `a` `u` and `v` | u < 1 // if `u` is zero = q <+ v rem 15 // stringify `v` modulo 15 | v > 14 // if `v` is 15 = q <+ u rem 8 // stringify `u` modulo 8 | u > 7 // if `u` is 8 | v > 7 // if `v` is more than 7 = q <+ v // stringify `v` = q <+ // otherwise stringify (v+7) * // `v` plus 7 unless sign(v rem 7) // `v` is 7 or zero | u == v // if `u` equals `v` = u + 7 <+ // stringify `u` plus 7 and append "\\" <+ v // a slash and the stringification of v | v < 1 // if `v` is zero | u > 1 // if `u` is more than 1 = q <+ u + 7 // stringify `u` + 7 = q // empty string # p = // define `p` as sort // the sorted [ // (list of horse numbers) k + // k plus if(u >= v) 7 // if u >= v, 7 0 // else zero \\ k <- [u, v] // for every `k` in u and v ] # r = // define `r` as sum // the sum of [ // (the bets on those horses) z // the bet `z` \\ (x, y, z) <- a // for every subarray | [x, y] == p // where the horse pair matches `p` ] | r > 0.0 // if `r` is greater than zero # r = // redefine `r` as sum // the sum of (map thd3 a) // every bet / r // divided by the previous `r` / 2E0 // divided by two | r < 9.95 // if r is less than 9.95 = snd // the second element of ( // (the tuple with the closest matching odd) sort // sort the [ // (list of potential odds) ( // (tuple with) abs(e - r) // the difference between `r` and the odd `e` , e <+ ".0" // and the stringification of `e` ) // for every `e` in the list of odds \\ e <- [1.1, 1.2..1E1] ] !! 0 // the first element ) % (0, 2) // "round" the number = q <+ toInt r // otherwise stringify and round `r` | p!!1 < h // if the bet was actually zero = "999" // the odds are 999 = q // otherwise there isn't a horse ``` ]
[Question] [ # Description OEIS sequence [A096004](https://oeis.org/A096004) gives the > > Number of convex triangular polyominoes [[polyiamonds](https://en.wikipedia.org/wiki/Polyiamond)] containing n cells. > > > It begins: ``` 1, 1, 1, 2, 1, 2, 2, 3, 2, 2, 2, 3, 2, 3, 3, 5 ``` For example, a(8)=3 with the following three convex polyiamonds: ``` Input: 8 Output: *---*---*---*---* / \ / \ / \ / \ / *---*---*---*---* *---*---* / \ / \ / *---*---* / \ / \ / *---*---* *---* / \ / \ *---*---* / \ / \ / \ *---*---*---* ``` --- # Requirements The goal of this challenge is to write a program that takes in an integer *n* (in any reasonable format) and outputs ASCII art of all convex polyiamonds with *n* cells (in any orientation), with each polyiamond separated by two newlines. Your program must be able to handle up to a(30) in under 60 seconds. --- # Scoring This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge, so fewest bytes wins. [Answer] # [Ruby](https://www.ruby-lang.org/), 202 bytes ``` ->n{(r=[*0..n]).product(r,r,r).map{|i|p,b,c,d=i;b>c||c>d||b+c+d>p||p*p-b*b-c*c-d*d!=n||0.upto(p-d<<1){|j|s=" "*j+"*---\\ / "[j%2*4,4]*p*2;(k=b*4-j)>0&&s[0,k]=" "*k;puts s[0,[p*4+1-j,p*4+1-c*4+j].min]}}} ``` [Try it online!](https://tio.run/##JYvdioMwEEZfxQorOmayadc7TV4kzcUmoWCkdvDnojg@u213@eAcOPBNq38eN32gGbdy0haUlKOrJE2PuIalnMR7lbz/0sY9k/AiiKj71pvAHExk9nWooyFmAkIPHgMEjBBPemRWcqXlURLGrjtXGyeedZ7lkOocEPF6zb6z3KavCzSicUBwactBe2gwVUYVxWyVGNzfZWhpXebsUyxBU58xiX@HN5OT9350@74fN/uj3PEC "Ruby – Try It Online") Uses formula per the OEIS sequence: search for solutions where `n = p**2 - b**2 -c**2 - d**2`. `n =`the number of triangular tiles `p =`the side length of a large equilateral triangle (pointing downwards) `b,c,d =`the side length of three smaller equilateral triangles, which are removed from the corners of the large equilateral triangle to get the required shape. Some additional conditions (per OEIS) are needed to avoid duplicates: `b<=c<=d` and `b+c+d<=p` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 89 bytes ``` NθF⊕θF⊕ιF⊕κF⊕λ¿∧¬‹ι⁺⁺κλμ⁼⁻×ιιθΣE⟦κλμ⟧×νν«⸿G↙⊕⊗μ↘⊕⊗⁻ι⁺κμ→⊕×⁴κ↗⊕⊗⁻ι⁺κλ↖⊕⊗λ“⌈∨¿ZH↖↖⸿T u≡9”D⎚ ``` [Try it online!](https://tio.run/##lU@xTsMwEJ3brzhlulS2ujAgmBBhqNRWEdCJMKSp01qxz4kTgxDi24OdgITUdMCSz0/v3ju/K065LUyu@n5Fteu2Tu@FxSa@nZfGAq6osEIL6sTBkzGckXKKrKZI5UlZAt7RAbemw7VoW5QMUuVaHErFQMUMdBz7@tC4XLW4keQ7z1KLQSx9p/H3yWnc5DW@BI@3vDIYNcSA4uHA53yWWkkdRpmN/EKz1KiPoyG8Scw7rUXZMfgbMDFur/yrw/eD5lEeTxdEY67f@NWYOvgmPGOyKwbVoNjV/5mrfubu6suJVVBEsIQsy2jBOc/IQ1hmxPmCD7snTtcYwL0SuQ3oq@@ve/6mvgE "Charcoal – Try It Online") Link is to verbose version of code. Thanks to @LevelRiverSt for explaining the OEIS formula. Explanation: ``` Nθ ``` Input `n`. (Using the OEIS formula names rather than the Charcol names here.) ``` F⊕θF⊕ιF⊕κF⊕λ ``` Loop `p` from `0` to `n`, `d` from `0` to `p`, `c` from `0` to `d` and `b` from `0` to `c` inclusive. This satisfies the condition `b<=c<=d<=p`. ``` ¿∧¬‹ι⁺⁺κλμ⁼⁻×ιιθΣE⟦κλμ⟧×νν« ``` Check the other two conditions: `b+c+d<=p` and `n=p*p-b*b-c*c-d*d`. Sadly the power function doesn't vectorise yet otherwise that would save 2 bytes. ``` ⸿ ``` Leave a blank line between polyiamonds. ``` G↙⊕⊗μ↘⊕⊗⁻ι⁺κμ→⊕×⁴κ↗⊕⊗⁻ι⁺κλ↖⊕⊗λ“⌈∨¿ZH↖↖⸿T u≡9” ``` Draw the polyiamond. Five of the sides are calculated, and the sixth is inferred and the polygon filled using the compressed string `/ \` `*---` `\ /` `--*-`, which results in the desired pattern. (The pattern doesn't start with `*---` because the blank line causes the pattern to be offset.) ``` D⎚ ``` Output and clear the canvas ready for the next polyiamond. This is quicker than positioning the cursor. ]
[Question] [ Inspired by [this comment](https://codegolf.stackexchange.com/questions/149585/coffee-machine-machine#comment365526_149585). # Input The number of seconds on the timer. # Output Here's our basic microwave: ``` _____________________________________________________________ | | ___________ | | | | [display] | | | ___________________________________ | |___________| | | | | | | | | | | | | | | | 1 | 2 | 3 | | | | | | |___|___|___| | | | | | | | | | | | | | | | 4 | 5 | 6 | | | | | | |___|___|___| | | | | | | | | | | | | | | | 7 | 8 | 9 | | | | | | |___|___|___| | | | | | | | | | | | | | | 0 | Start | | | | | | |___|_______| | | | | | ___________ | | |___________________________________| | | | | | | | | | | | |___________| | |_____________________________________________|_______________| ``` You should replace `[display]` with: * The time left to cook in the format `minutes:seconds` if there is any time left. * The system time in `hours:minutes` if the time left is 0. # Rules * The display can be aligned in either direction, but the vertical bars need to align with the ones above them. * You may assume that the input will never be negative and never exceed 59,999,999. * No leading zeroes before a cook time. Remove the minutes and the colon for inputs less than 60. * Use 12-hour time UTC with no leading zeroes for the system time. * Trailing whitespace is allowed. * Since this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest answer in bytes wins. # Display test cases You should, of course, print the entire microwave along with the display, and it should work for any input within the boundaries, but here are some test cases for the display: ``` Input Display 100 1:40 59 59 60 1:00 120 2:00 59999999 999999:59 1 1 0 [show system time] UTC Time Display 00:00 12:00 01:00 1:00 13:04 1:04 ``` [Answer] # JavaScript (ES6), ~~345~~ 342 bytes *Saved 2 bytes thanks to @StephenLeppik* ``` n=>[...'lmnopqsuvwxyz{}~'].reduce((s,c)=>(x=s.split(c)).join(x.pop()),` p{{yyvu{ xvs${(n&&n<60?n+'':(k=n||new Date/6e4|0,k/60%(n?k:12)|0||(n?0:12))+':'+('0'+k%60).slice(-2)).padEnd(9)}xoup__uuxx{~zzn1s2s3wn4s5s6wn7s8s9wuuq 0sStartmy_~ { oxp__zxllx{|x |p{_|{y_|qox}}}uzs}uuuuu {yyy__z|u y___s|wm|y~zzv |}}}}xu sx q~|p{{{ox znzq m qy|ylx}|xv`) ``` ### Test cases ``` let f = n=>[...'lmnopqsuvwxyz{}~'].reduce((s,c)=>(x=s.split(c)).join(x.pop()),` p{{yyvu{ xvs${(n&&n<60?n+'':(k=n||new Date/6e4|0,k/60%(n?k:12)|0||(n?0:12))+':'+('0'+k%60).slice(-2)).padEnd(9)}xoup__uuxx{~zzn1s2s3wn4s5s6wn7s8s9wuuq 0sStartmy_~ { oxp__zxllx{|x |p{_|{y_|qox}}}uzs}uuuuu {yyy__z|u y___s|wm|y~zzv |}}}}xu sx q~|p{{{ox znzq m qy|ylx}|xv`) O.innerText = [100, 59, 60, 120, 59999999, 1, 0].map(f).join('\n'); ``` ``` <pre id=O></pre> ``` [Answer] # [SOGL V0.12](https://github.com/dzaima/SOGLOnline), ~~151~~ 150 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) ``` ╔*:@ΚG┐∙+;┐Κ+Γ╬5□ ‽uS9w'+*;5wι+}:'+÷;'+%lH⁵!+‽ 0Κ}⁴‽ι}⁰ :∑ā;'!3ž"∑⅓/«juΒ v←>k─z“M»─4n{_□}4Δ№{' ;3*I:A26□'$a22□}'(7«■ _čž'&'¹"<Ξ‘⁾žL∫L%F3‰4*'℮+f3÷⁽3*ž ``` [Try it Here!](https://dzaima.github.io/SOGLOnline/?code=JXUyNTU0KiUzQUAldTAzOUFHJXUyNTEwJXUyMjE5KyUzQiV1MjUxMCV1MDM5QSsldTAzOTMldTI1NkM1JXUyNUExJTBBJXUyMDNEdVM5dyUyNysqJTNCNXcldTAzQjkrJTdEJTNBJTI3KyVGNyUzQiUyNyslMjVsSCV1MjA3NSUyMSsldTIwM0QlMjAwJXUwMzlBJTdEJXUyMDc0JXUyMDNEJXUwM0I5JTdEJXUyMDcwJTIwJTNBJXUyMjExJXUwMTAxJTNCJTI3JTIxMyV1MDE3RSUyMiV1MjIxMSV1MjE1My8lQUJqdSV1MDM5MiUwOXYldTIxOTAlM0VrJXUyNTAweiV1MjAxQ00lQkIldTI1MDA0biU3Ql8ldTI1QTElN0Q0JXUwMzk0JXUyMTE2JTdCJTI3JTIwJTNCMypJJTNBQTI2JXUyNUExJTI3JTI0YTIyJXUyNUExJTdEJTI3JTI4NyVBQiV1MjVBMCUyMCUyMF8ldTAxMEQldTAxN0UlMjclMjYlMjclQjklMjIlM0MldTAzOUUldTIwMTgldTIwN0UldTAxN0VMJXUyMjJCTCUyNUYzJXUyMDMwNColMjcldTIxMkUrZjMlRjcldTIwN0QzKiV1MDE3RQ__,inputs=NTk5OTk5OTk_,v=0.12) Explanation: ``` □ a function which draws a rectangle uses of the stack [xPos, yPos, height-1, (width+1)/2] the width everywhere luckily is an odd number ╔* repeat "_" width times : create a duplicate of that @Κ prepend a space to it G get the height on top of the stack ┐∙ repeat "|" vertically that many times + add that below the " ___..." ; get the other copy of the underscores ┐Κ prepend "|" to it + and add that below the rest Γ palindromize horizontally with 1 overlap ╬5 place that at the coords [xPos; yPos], without overwriting spaces system time ‽ } if the input isn't 0 uS push date & time stuff — [year, month, day, hour, minute, second, milliscond, weekday, hours in 12-hour time, am(= 0)/pm(= 1)] 9w get the 9th element — hours in 12-hour time '+* multiply by 60 ; get the array on top again 5w get the 5th item — minutes ι pop the array + add the minutes to hours*60 time formatting : duplicate the time (result of above or input) '+÷ divide by 60 ; get the other time copy '+% mod by 60 l get the length of the minutes H decrease it — truthy if the minutes are a single digit ⁵! negate the hours — truthy if the hours aren't 0 + add those — acts like OR — truthy if minutes are a single digit or hours aren't 0 ‽ } if not that 0Κ prepend 0 to the minutes ⁴ get a copy of the hours ‽ } if equal to 0 ι pop the hours ⁰ wrap the stack in an array :∑ join with ":" ā; push an empty array below the time — the main canvas '! push 51 3 push 3 ž at [51; 3] in the canvas insert the time main microwave body "...“ push 196046633463872206014875356167606 M»─ base 50 decode — [1,1,19,31,6,4,13,18,1,1,19,23,49,2,1,6,49,17,2,6] 4n group 4 items — [1,1,19,31],[6,4,13,18],[1,1,19,23],[49,2,1,6],[49,17,2,6] { } for each group _ put the arrays contents on the stack □ execute the rectangle making function boxes for the numbers 4Δ push [1,2,3,4] № reverse — [4,3,2,1] { } for each ' ; push 49 below the current number — X pos 3* multiply the current number by 3 I and increment it — Y pos :A save a copy of that on variable A (for the next rectangle) 26□ create a rectangle at [49; cnum*3+1] with width 11 and height 3 '$ push 53 — X pos a push A — Y pos 22□ create a rectangle at [53; cnum*3+1] with width 3 and height 3 '(7«■ _ push 57, 14 and " _" č chop the string into chars (aka make it vertical) ž insert that at [57; 14] in the canvas '&'¹"..‘ push 55, 15, "start" ⁾ uppercase the first letter of "start" ž insert that at [55; 15] in the canvas number inserting L∫ for each in 1..10, pushing counter L% push counter % 10 — the drawn digit F3‰ push (counter-1)%3 + 1 4* multiply that by 4 '℮+ and add 47 — X position f3÷ floor divide the 0-based counter by 3 ⁽ increment by 2 3* multiply by 3 ž insert it in the main canvas ``` [Answer] # Python 3, 319 bytes Hide a `%9s` into compressed string, then use `time.strftime` to get time, `%-I` to strip the leading zero. ``` import lzma,base64,time lambda a:lzma.decompress(base64.b85decode('T>t=p0RR90|NsC0{{Rpd^C|@(1X`TL^f`u<KIrh0p%HYiiZbvoDPNw6<V^!O(Lz{boq`zUBx6K?Tsnl5A-wX&%GXCq@<%4wDjJcoz5VNNSc<>}9i|2|i)oHsC6Kg`@30<`nrg{=G5%W0xn9J;m-hJXY%|G!|Limu^8')).decode()%[time.strftime('%-I:%M',time.gmtime()),a,'%d:%02d'%(a/60,a%60)][a and~(a<60)] ``` [Try it online!](https://tio.run/##VVBbU4JAGH33V@jDxu4M0nqBEUOzdMZr1JgZ5sSwCOg2chEwDai/TqE1Q9/TuT1853gf4cZ1amlKbc/1w@I2sgmrk8AU6mxIbbNgtbbE1g1SJM3M4wxz5dqebwYBPMc4vcFnomFCZtYOWx6eTkWcyEEXx/HUM9Ru0oEVRZtNVEvbS@Ohv8EeGCwofdHf3d6DfBCkuVq6h5Mo1t2dFj3dHoXx9SxwtvxN@aBcgL7S3XUkUD/03kYrN@Lnsvy4ktqfIk2qCUXuIOgK47XWqWFJc/x13Orz4BkfHXF0ZZc3I2UBkn4pmVB7rzYYhLjfbxFYZg25IPStDEAGlIdNcMecinNr@yQixBKWAUYT4KrBAEguBcwSIGD0uvwZxTG@IJEylno@dUJoQYxQ4Q9X8jhv8GKOCHlHqP2LnQ@h9Bs "Python 3 – Try It Online") [Answer] # PHP, 416 bytes ``` if(is_numeric($a=$argv[1])&&$a&&-1<$s=$a%60){$m=(int)($a==$s?'':$a/60);$s=$m||$s>9?substr("0$s",-2,2):$s;$e=$m?"$m:$s":"$s";}elseif(!$a){$e=date("g:i");}else{$e=date("g:i",strtotime($a));}$e=str_pad($e,9);eval(gzinflate(base64_decode('S03OyFdQUIqnBPBy1SiQAoCqkXQD+aQbUKOgkgqiYDqJcCVMJ5IQwgBi7K+BWa2AhMkywBCIjYDYmEwDQE6H4QHyggkQmwKx2dD1gjkQWwCx5QB7QYF8LxgAcXBJYlEJZV4gOy9gz8fIWQwXQAoDhJlkFQSUGoBRHhDheiQt6HwlawA='))); ``` More readable: ``` if(is_numeric($a=$argv[1])&&$a&&-1<$s=$a%60){ $m=(int)($a==$s?'':$a/60); $s=$m||$s>9?substr("0$s",-2,2):$s; $e=$m?"$m:$s":"$s"; }elseif(!$a){ $e=date("g:i"); }else{ $e=date("g:i",strtotime($a)); } $e=str_pad($e,9); eval(gzinflate(base64_decode('S03OyFdQUIqnBPBy1SiQAoCqkXQD+aQbUKOgkgqiYDqJcCVMJ5IQwgBi7K+BWa2AhMkywBCIjYDYmEwDQE6H4QHyggkQmwKx2dD1gjkQWwCx5QB7QYF8LxgAcXBJYlEJZV4gOy9gz8fIWQwXQAoDhJlkFQSUGoBRHhDheiQt6HwlawA='))); ``` $e is placed within the zipped microwave which also includes the echo like this (the double space after the echo is to get a more optimal b64 encoded string, it saves a byte here): ``` echo base64_encode(gzdeflate('echo "_____________________________________________________________ | | ___________ | | | | $e | | ``` [Answer] ## Batch, 833 bytes ``` @echo off set t=%time% set/ah=(%t:~,2%+11)%%12+1,s=%1+0,s+=s/60*40 if %s%==0 set s=%h%%t:~3,2% set s= %s% set s=%s:~-4,2%:%s:~-2% set s=%s: := % set u=_______ set p= set "v=| | for %%l in (" %u%%u%%u%%u%%u%%u%%u%%u%_____" "|%p%%p%%p%%p% | %u%____ |" "|%p%%p%%p%%p% | | %s% | |" "| %u%%u%%u%%u%%u% | |%u%____| |") do echo %%~l call:c 1 2 3 call:c 4 5 6 call:c 7 8 9 for %%l in ("%v%%p%%p%%p% %v%| |%p:~4%| |" "%v%%p%%p%%p% %v%| 0 | Start | |" "%v%%p%%p%%p% %v%|___|%u%| |" "%v%%p%%p%%p% %v% %u%____ |" "| |%u%%u%%u%%u%%u%%v%|%p%| |" "|%p%%p%%p%%p% | |%p%| |" "|%p%%p%%p%%p% | |%u%____| |" "|%u%%u%%u%%u%%u%%u%___|%u%%u%_|") do echo %%~l exit/b :c for %%l in ("%v%%p%%p%%p% %v%| | | | |" "%v%%p%%p%%p% %v%| %1 | %2 | %3 | |" "%v%%p%%p%%p% %v%|___|___|___| |") do echo %%~l ``` [Answer] # [Python 2](https://docs.python.org/2/), 481 bytes ``` from datetime import* def f(t,r=range): d=datetime.utcnow();g=[[' ']*63 for _ in" "*21] for i in r(1,62): for j in[0,-1]+[3,-4]*(5<i<41)+[1,3,6,9,12,15,16,19]*(48<i<60):g[j][i]="_" for i in r(1,21): for j in[0,-1,46]+[5,41]*(3<i<18)+[48,60]*(1<i<20)*(i!=16)+[52]*(3<i<16)+[56]*(3<i<13):g[i][j]="|" for i in r(10):g[i/3*3+5][i%3*4+50]=`-~i%10` g[14][54:59]="Start";g[2][49:60]=(t and(`t/60`+":")*(t>59)+`t%60`.zfill(2)or`d.hour`+":"+`d.minute`.zfill(2)).center(11);return g ``` [Try it online!](https://tio.run/##jY7ditswFISv46dQBWElW/FasiRiZ92X6KUQ67D@WYWNFITC0lL66umxIZRue7GXZ2bOzHf5nl6DF7fbFMMZDcc0JncekTtfQkx5NowTmkhisYtHP4@0zTZDd0@V1/Tiwzuhh7kz5gE92FzXaAoRPSPnMcK54DbbLIIDAUXCmRZLx6qdQDMV23FbmJrtpM2JenJPktPCcFYzzRrGBeOKcc14A7bcg68r2s7mZI2zHX7GH/oF/7efSQ0TikkOHTVU8D1MyD3TFQgcBFHRnLgvHddgKHGPrZe@X/Wy6yxMd/jnh92VyT3WeV0oINvWuSxUZbt@98ttedVnm9lwaY2SrWrg/1s6xoQPsxHWyKYFkI4kdPQD6dOjrvoCtxiQ0lfV0KJPW5DKH5N7eyOChtgP5Wu4xjVVwHF2/prGPwlavow@jcDF6SGO6Ro9mm8LbwzvC/FEABhdovMJYVyegvMELJqtUvZXklefzwLtZ6P6/6233w "Python 2 – Try It Online") [Answer] # C#, 701 bytes [Try it Online!](https://tio.run/##jVJdS8MwFH3PrwhlsITW0s5NYbVTUXxSEDfwYYzStVmXsaXSZIq0@e3zttlwOqcGbnN77rnfSeRJkhdss5ZcZHj4LhVbBShZxlLilxJJFSue4Necp/gh5oJQVKK7tUguuFCOVAV4DfAMABziDYlpOCjBghehF3ynTUOSgF2wN2wQAup4UvqO5xjZaY2uxwvbngy8y3bU7rdx20loYPwwC60Kw2k@f5wtsbKcWchsK4qiaicAHhSZhfNwwOyWhcu5Br9ybvvbu6ObOEHB1LoQrSugTMmZTzWqQOn2qIZcoPkAQco9FNzrrm9jxUZ8xYhH3es0HbIkF6mEobmjfGgmYq1WfSkt6j7G6RPP5or4XhMBmV4h5GmvDm@agl9cp6sJJdPbdo0AkpG6unKmfzZ2fzOeHxjxzgiIB9pQxYXaIduZRmauptqmvFMzlyZE9HnwMVL1ZXdH@v4PZy9Ztb@NekP1bQV6E6CbXMh8ydzngit2zwUj9WMmfsejNEAa6c0H) ``` (a)=>{int j=0;Func<int,string>b=(c)=>new string(new[]{1,0,1,0,1,1,0,1,0,0,1,1}[j++]>0?'_':' ',c);string e="| | | | |",f=e+"___|___|___| |";Func<int,string>g=h=>e+$" {h} | {h+1} | {h+2} | |";return$@" {b(61)} |{b(45)}| {b(11)} | |{b(45)}| | {new DateTime(0).AddSeconds(a).ToString("mm:ss").PadRight(10)}| | | {b(35)} | |{b( 11)}| | {e} | | | | {g(1)} {f} {e} | | | | {g(4)} {f} {e} | | | | {g(7)} {f} {e} | | | {e} 0 | Start | | {e}___|_______| | | |{b( 35)}| | ___________ | | |{b( 35)}| | | | | | {b(35)} | | | | | {b(35)} | |___________| | |{b(45)}|{b(15)}|";} ``` ]
[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/147919/edit). Closed 6 years ago. [Improve this question](/posts/147919/edit) Given an *n*-dimensional array filled with numbers, output which *p*-dimensional array has the largest sum. # Input * An *n*-dimensional array of numbers, or your language's equivalent. You can assume this is a rectangular array, or not. * *n*, the number of dimensions in the array. (doesn't need to be called `n`) * *p*, the number of dimensions in the arrays you are adding up. (doesn't need to be called `p`) # Output The respective indices of the *p*-dimensional array with the largest sum. You may have undefined behavior in the case of a tie. The dimensions of the array that you find should be the last *p* dimensions of the original array. # Test Cases Input: ``` [[[4,2], [6,8]], [[0,0], [500,327]]], 3, 2 ``` Output: ``` 1 ``` Input: ``` [[1,2], [4,3]], 2, 0 ``` Since *p*=0, you're just finding the largest number in the array, which in this case is 4. The coordinates are: ``` 1 0 ``` Input: ``` [[1,2], [4,-1]], 2, 1 ``` You might see the 1 and 4 in the same column, and that that would have the largest sum of 5. However, because those share the second index, not the first, they are ignored. Both of the rows in this array add to 3, resulting in a tie, so you can return whatever you want here. --- Input: ``` [[1,2], [3,4]], 2, 2 ``` Since *p*=*n*, there are no indices of the array with the largest sum, so the output would be empty. # Additional Rules * [Standard loopholes](https://codegolf.meta.stackexchange.com/q/1061/75524) are forbidden. * Output can be in any reasonable format. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins. [Answer] ## [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 36 bytes ``` #~Position~Max@#&@Total[#,{-#2,-1}]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7X7kuIL84syQzP6/ON7HCQVnNISS/JDEnWlmnWlfZSEfXsDZW7X9AUWZeiYKDlkKagoODg0I1l4JCNRCY6CgY1eooVJvpKFjUghjVBjoKBiCGqQGQZWxkXgsSBqqBaDCEqgfqMwZJGGCRAFoIZBmiyxjrKJhAzOKq/Q8A "Wolfram Language (Mathematica) – Try It Online") Returns an array containing all the indices where the maximum value can be found. So for normal inputs that's a singleton array, containing the list of indices to it. If there's a tie, you'll get all the lists of indices for where that value shows up. The function doesn't actually read the `n` parameter, because it isn't needed, but you could pass it in as a third argument if you like (it would just be ignored anyway). One catch here is that for some reason the dimension specification `{0,-1}` for `Total` never sums anything. I don't really understand why, but luckily that's just what we need for this challenge. [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 21 bytes ``` (⍴⊤⊃∘⍒∘,)+/,⍤⎕⊢⎕ ``` First input is the array, second is `p`. [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkGXFyPOtoV0v5rPOrd8qhryaOu5kcdMx71TgKSOpra@jqPepcA1T7qWgQk/wOV/k/jMlYAQpDy3s1G5lxAE9CFDDGFjDCFjEFCRgpACBRSMAEyzBQsFAyA0NTAQMEYpgkibwTUaqhgAjEaImQI1GGiYMxlAAA) **How?** `+/,⍤⎕` - apply sum over sub arrays of rank `p` `⊃∘⍒∘,` - flatten, grade down and take first `⍴⊤` - encode in the mixed base derived by the shape of the previous result [Answer] # [Python 3](https://docs.python.org/3/) + [numpy](http://numpy.org), 92 bytes ``` lambda a,n,p:unravel_index(argmax(sum(a,(*-arange(n-p,n),))),a.shape[p:]) from numpy import* ``` [Try it online!](https://tio.run/##XY/RioMwEEWfm6@Yx6SMJRrbXQS/JA3LlGormDGkWvTrbez2ZXdeLpxzGbhhGe8Dm7Wtz2tP/nIlIGQM1cSRnk3/0/G1mSXFm6dZPiYvCeU@o0h8ayRnAVmhUgrp8LhTaGyonBJtHDzw5MMCnQ9DHPdrDzVYsbPpSiwc2hN@uxRWo05x1BpN8eUSAoOQCu9u/q6WaDZeIOh/PMs/Iv8jDJYfvj1yQrRD/N0FHUNfiV2IHY@yTcMiLZLU5pRaXw "Python 3 – Try It Online") Quite a bit longer than I would have hoped. Errors out on cases with no solution. [Answer] # [Python 3](https://docs.python.org/3/), 138 bytes There is probably a better way of doing this ``` lambda x,n,p:f(x,n,p)[:0:-1] f=lambda x,n,p:n>p and max([*f(l,n-1,p),i]for i,l in enumerate(x))or[sum(f(l,n-1,p)[0]for l in x)if n else x] ``` [Try it online!](https://tio.run/##XY/BasMwEETP8VfsUSobkC23KQb3R1RRlETCAls2lgLK1ztrtRDSvQzMvF1ml3sa5iC3of/eRjOdrwYyBlw6x4py1YnuWOvK9S9x@FrAhCtMJjP15tiI4VgTjl67eQWPI/gANtwmu5pkWeZ8XlW8TezJKlHYQmbuHdDCGC1kvSUb08/FRBuhB1UdFE2LjUb1gZ@aRAkUJO9CoGxOmiyQCAQUti5oi3L3GwTxz6eHfoP6JZDY/vn7IfqZ2hk842Vv@KzUVYdl9SGxgZWU8@0B "Python 3 – Try It Online") ]
[Question] [ I need this down to as few characters as possible. I would use Test-NetConnection but I need PSv2 compatability. Any help would be appreciated. ``` $socket = new-object Net.Sockets.TcpClient $socket.Connect("192.168.5.5",445) $socket.Connected ``` As a note I have tried this but it doesn't work ``` (new-object Net.Sockets.TcpClient).Connect("192.168.5.5",445).Connected ``` [Answer] ### PowerShell v2+, 63 bytes You can use a [different constructor](https://msdn.microsoft.com/en-us/library/115ytk56(v=vs.80).aspx) to create the object and connect in one go. ``` (new-object Net.Sockets.TcpClient('192.168.5.5',445)).Connected ``` I've verified this works in v2 on my Windows 8.1 machine. That constructor is supported by .NET 2.0, so this should be v2 compatible. [Answer] AFAIK, there's no default alias for `New-Object`, and no type accelerator for `Net.Sockets.TcpClient`, so they can't be any shorter. You can merge the constructor and connect code into one line: ``` (New-Object Net.Sockets.TcpClient -A 192.168.5.5,445) ``` But if it can't connect, it now throws an exception, which you can't silence with -ErrorAction. So handling that ends up being 70 characters, only 8 shorter than your original after shrinking the variable name: ``` !!$(try{(new-object net.sockets.tcpclient -A 192.168.5.5,445)}catch{}) ``` `!!` forcing the result to a bool. ]
[Question] [ This is similar to prime factorization, where you find the smallest prime factors of a number (i.e. 8 = 2 x 2 x 2). But this time, you are to return an array/list of the smallest composite factors of any given positive integer `n`. If `n` is prime, simply return an empty list. **Examples:** * Prime: ``` n = 2 Result: [] ``` * Composite and Positive: ``` n = 4 Result: [4] n = 32 Result: [4, 8] n = 64 Result: [4, 4, 4] n = 96 Result: [4, 4, 6] ``` **Rules:** * The product of the factors in the list must equal the input * [Standard loopholes](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are banned * An array/list must be returned or printed (i.e. `[4]`) * Your program must be able to return the same results for the same numbers seen in the examples above * The factors in the array/list can be strings so `[4]` and `["4"]` are both equally valid * A prime number is any positive integer whose only possible factors are itself and 1. 4 returns `[4]` but is not prime since 2 is also a factor. * A composite number for this challenge any positive integer that has 3 or more factors (including 1) like 4, whose factors are 1, 2, and 4. **Clarifications:** * Given a number such as 108, there are some possibilities such as `[9, 12]` or `[4, 27]`. The first integer is to be the smallest composite integer possible (excluding 1 unless mandatory) thus the array returned should be `[4, 27]` since 4 < 9. * All factors after the first factor need to be as small as possible as well. Take the example of 96. Instead of simply `[4, 24]`, 24 can still be factored down to 4 and 6 thus the solution is `[4, 4, 6]`. **Winning Criteria:** Shortest code wins since this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes ``` »0Æf×Ṫ$-¦×2/ ``` [Try it online!](https://tio.run/nexus/jelly#@39ot8HhtrTD0x/uXKWie2jZ4elG@v8Ptz9qWuP@/7@uoY6CgY6CkY6CiY6CGRBbmukoGBpYAAA "Jelly – TIO Nexus") ### How it works ``` »0Æf×Ṫ$-¦×2/ Main link. Argument: n »0 Take the maximum of n and 0. Jelly's prime factorization does weird things for negative numbers. Æf Take the prime factorization of the maximum. ¦ Conditional application: ×Ṫ$ Pop the last element of the array and and multiply all elements of the remaining array with it. - Replace the element at index -1 with the corresponding element in the result. This effectively multiplies the last two elements of the array. ×2/ Multiply the factors in non-overlapping pairs. If the last element does not have a partner, leave it unmodified. ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 8 bytes ``` Òā¨ÉÅ¡P¦ ``` [Try it online!](https://tio.run/##ARwA4/9vc2FiaWX//8OSxIHCqMOJw4XCoVDCpv//MTA4 "05AB1E – Try It Online") Explanation: ``` # implicit input (example: 72) Ò # prime factorization ([2, 2, 2, 3, 3]) ā # indices ([1, 2, 3, 4, 5]) ¨ # drop the last element ([1, 2, 3, 4]) É # is odd ([1, 0, 1, 0]) Å¡ # split on 1s ([[], [2, 2], [2, 3, 3]]) P # product ([1, 4, 18]) ¦ # drop the first element ([4, 18]) # implicit output ``` Note that this correctly returns `[]` for prime inputs. [Answer] # Haskell 150 Pretty basic answer but: ``` r n=p n$n-1 p 1 _=[] p n 1=[n] p n m |n`mod`m==0=p(n`div`m)(m-1)++r m |1>0=p n$m-1 i[x,y,z]=[x*y*z] i(x:y:z)=x*y:i z i _=[] c n |n>0=i.r$n |1>0=[] ``` Works very straightforwardly: find all the prime factors of the input (the `p` function) in a way that produces them sorted ascending, and multiply them by twos (with the exception of multiplying three together if there are an odd number, to handle cases like `32` that prime factor into `[2,2,2,2,2]`. Example usage `c 2880 = [4, 4, 4, 45]`. *Bonus fun* As a massively ineffecient prime generator: `primes = filter (> 1) . zipWith (-) [2..] $ map (product . c) [1..]`. [Answer] # JavaScript ES6 112 ``` c=n=>{with(a=[]){for(i=k=1;i++<n;)for(;1^n%i;n/=i)push(++k%2?pop()*i:i);k%2||push(pop()*pop());return k<3?[]:a}} test=k=>{console.log("n = "+k);console.log(c(k))}; test(-1); test(0); test(2); test(4); test(64); test(96); test(32); ``` [Answer] # [Haskell](https://www.haskell.org/), ~~106 104~~ 101 bytes ``` c x=2/=sum[1|0<-mod x<$>[1..x]] (x:r)%n|c x,mod n x<1,d<-div n x,c d=x:g d|1<3=r%n e%n=e g n=[4..n]%n ``` [Try it online!](https://tio.run/nexus/haskell#LY4xb4MwEIV3/4onVCRQwIWmQxXhSFWX7h0pA8JOsApny5iEgf9OTdrl9N37nnSnR2ucx4ch78zA360ddNd6fVPIc5BSUkkYgtcGF@NQPZ1hrHKtD8u9110PPUHT0M17UxOsU0NgmAs@2@lHDQPeeMHGNjgBO/sv7xKvJo@yKFLGHlgEFUV/vNd2SCgvUxwOmHpzD2mgCPk5jP8suYIeheiboq3DIl6exTSPdbkWVT4aiSW8W5ecL03DkuXk0pjW0Mt2R8GWmaxyqW/7knWQYjldIdeyOgoXE1MxCcXCFVG/ck5NTNv2Cw "Haskell – TIO Nexus") **Less golfed and explanation:** ``` c x = 2 /= sum[1|0<-map(mod x)[1..x]] -- counts number of divisors of x and returns true for all non-primes g n = f [4..n] n -- call f with a list of factor candidates and n f [] n = [] -- if there are no factor candidates, return the empty list f (x:r) n -- for the factor candidate x ... | c x, -- check if x is composite (d,m) <- divMod n x, -- set d = n div x and m = n mod x m < 1, -- n is divided by x if m = 0 c d -- check that d is composite or 1 = x : f (x:r) d -- if all those checks are true append x to the list and determine the composites for d | otherwise = f r n -- otherwise check the next candidate ``` [Answer] # Javascript (ES6), 94 bytes ``` n=>{for(a=[],d=2,l=q=0;n>1;)n%d?d++:(n/=d,q&&(a[l++]=q*d),q=q?0:d);q&&l&&(a[l-1]*=q);return a} ``` Ungolfed: ``` n=>{ //function declaration for( a=[], //the list d=2, //current factor l= //next index of the list q=0; //stored factor n>1; //while n>1 ) n%d? //if the factor is not a factor of current n d++ //go to next factor :( //else n/=d, //remove the factor q&& //if a factor is stored, (a[l++]=q*d), //add multiple of the saved factor and current factor q=q?0:d //store factor if it doesn't exist ); //end else //implicit for loop close q&& //if there is remaining factor l&& //if the input is not a prime (a[l-1]*=q); //place the factor in the last element in the list return a //return the list } //end function ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 83 bytes ``` my&f=->\n {my \p=min grep {n%%$_&!is-prime $_|n/$_},2..^n;Inf>p??flat p,f n/p!![n]} ``` Note: uses the `is-prime` builtin [Try it online!](https://tio.run/##K0gtyjH7/z@3Ui3NVtcuJk@hOrdSIabANjczTyG9KLVAoTpPVVUlXk0xs1i3oCgzN1VBJb4mT18lvlbHSE8vLs/aMy/NrsDePi0nsUShQCdNIU@/QFExOi@29r81V3FipUKahpkmjGVsBGeamcCZlggFhgYWmtb/AQ "Perl 6 – Try It Online") ]
[Question] [ Today (March 15) is the [Ides of March](https://en.wikipedia.org/wiki/Ides_of_March), best known for being the date that Julius Caesar was assassinated. What's “Ides”? Well, the ancient Romans didn't simply number the days of month from 1 to 31 like we do. Instead, they had a more complex system of counting backwards to the [Kalends, Nones, or Ides](http://www.polysyllabic.com/?q=calhistory/earlier/roman/kalends). ## Challenge Write, in as few bytes as possible, a program that will display the current date (on the Gregorian calendar, in the local timezone) using the abbreviated Roman-style convention described below. Your program should work until at least the end of 2037. ## Roman dates ### Months of the year These should look familiar to you: Ianuarius, Februarius, Martius, Aprilis, Maius, Iunius, Iulius (Quintilis), Augustus (Sextilis), September, October, November, December. Your program is to abbreviate all months to three letters, using the classical Latin alphabet (all caps, with J=I and U=V). That is, `IAN`, `FEB`, `MAR`, `APR`, `MAI`, `IVN`, `IVL`, `AVG`, `SEP`, `OCT`, `NOV`, `DEC`. ### Special dates of the month * **Kalendis**, or the **Kalends** (abbr. `KAL`) is the first day of each month. * **Idibus**, or the **Ides** (abbr. `ID`) is the **15th** day of March, May, July, or October; but the **13th** day of the other eight months. * **Nonas**, or the **Nones** (abbr. `NON`) is 8 days before the Ides (5th or 7th of the month) ### Other days of the month Other days of the month are numbered by counting **backwards** and **inclusively** to the next reference date (Kalends, Ides, or Nones). Notation is `AD` (abbreviation for **ante diem**, no relation to [Jesus of Nazareth](https://en.wikipedia.org/wiki/Anno_Domini)) followed by the appropriate **Roman numeral**. **Exception**: Write `PR` (for **pridie**) instead of `AD II` for the day before Kalends, Nones, or Ides. ### The leap day In leap years, [*two* days](https://maas.museum/observations/2008/02/28/leap-day-makes-it-a-bisextile-year/) (February 24 and 25 in modern reckoning) are given the date `AD VI KAL MAR`. (You do not need to distinguish the two days in your program.) February 14-23 are `AD XVI KAL MAR` through `AD VII KAL MAR` as in non-leap years. Feb 26 = `AD V KAL MAR`, Feb 27 = `AD IV KAL MAR`, Feb 28 = `AD III KAL MAR`, and Feb 29 = `PR KAL MAR`, offset by one from the corresponding dates in non-leap years. ## Example In March, the output of your program should be: * On March 1: `KAL MAR` * On March 2: `AD VI NON MAR` * On March 3: `AD V NON MAR` * On March 4: `AD IV NON MAR` * On March 5: `AD III NON MAR` * On March 6: `PR NON MAR` * On March 7: `NON MAR` * On March 8: `AD VIII ID MAR` * ... * On March 13: `AD III ID MAR` * On March 14: `PR ID MAR` * On March 15: `ID MAR` * On March 16: `AD XVII KAL APR` * ... * On March 30: `AD III KAL APR` * On March 31: `PR KAL APR` [Answer] # Tcl/Tk, 675 bytes Well, I suppose I could crunch it more, but this is it for now... ``` set a {y m d} rename proc p p r {n {s ""}} {foreach {v d} {10 X 5 V 1 I} {while {$n>=$v} {set s $s$d;incr n -$v}};string map {VIIII IX IIII IV} $s} p y y {expr !($y%100?$y%4:$y%400)} p i $a {expr {($m in {3 5 7 10})?15:13}} p n $a {expr [i $y $m $d]-8} p k $a {expr $m==2?29+($d>24&&[y $y]):$m<8?31+$m%2:32-$m%2} p N {} {clock f [clock se] -f {%Y %N %e}} p M m {lindex {IAN FEB MAR APR MAI IVN IVL AVG SEP OCT NOV DEC IAN} $m-1} p d $a {foreach f {n i k} n {NON ID KAL} mo {0 0 1} {if {$d<=[$f $y $m $d]} break} string map {{AD I } {} {AD II } {PR }} "AD [r [expr [$f $y $m $d]+1-$d]] $n [M [expr $m+$mo]]"} p p $a {if {$d==1} {puts "KAL [M $m]"} {puts [d $y $m $d]}} p {*}[N] ``` **How it works** The first thing is to collect today's date as a list: year, month, day. Everything works over that. The first of the month is a simple special case; we handle that separately. All remaining cases work like this: 1. Find the future reference day's date in (5,7,13,15,days-in-month) 2. Get the abbreviation corresponding to that reference (`NON`, `ID`, `KAL`) 3. For Kalends we increment the month by one 4. Assemble the date string as: "AD <days-in-roman-numerals> <abbreviated-reference-day> <abbreviated-month-name>" 5. Apply a text replace to correct `AD I` and `AD II`. The first step is done with a function lookup table for each of the Nones, Ides, and Kalends. Nones and Ides are straight-forward subtraction and lookup, respectively. Computing the **Kalends** is only a little more complicated (notice the trick with leap-February's day number.): * February → 28 days + (it's a leap year AND day > 24) * January..July → 30 days + (it's January, March, May or July) * August..December → 31 days - (it's September or November) The days is a simple difference: (reference\_day - todays\_day + 1) Computing the **leap year** is done with a somewhat unusual arrangement of the standard formula so that it could be crunched better (removing braces and parentheses from the `expr` command). Converting decimal to **Roman numerals** is a simple table-driven approach, stripped to use only ones, fives, and tens since we don't need to print the year in Roman numerals (domain is [1,39]). Almost everything else is application of lookup tables. **A note on Tcl and reducing bytes** The first two lines of the script eat bytes by simply being shorter than spelling out `proc f {y m d}` for all instances. Single-letter proc names and variables, of course: ``` r := decimal→roman(n) i := ides(y,m,d) M := month-abbreviation(month) y := is-leap(year) n := nones(y,m,d) d := date→roman(y,m,d) [d ≠ 1] N := today → (y,m,d) k := kalends(y,m,d) p := date→roman(y,m,d) [∀d] ``` **Testing for dates other than today** Change the very last line from `p {*}[N]` to ``` p {*}$argv ``` and run the program with the date desired: ``` % tclsh roman.tcl 2016 2 25 AD VI KAL MAR ``` Enjoy! [Answer] (I will not give myself the checkmark, even though I have the shortest submission so far.) # Python 3: 390 bytes ``` import time y,m,d=time.localtime()[:3] d-=(y%4==0)*(m==2)*(d>24) i=13+2*(m in (3,5,7,10)) n=i-8 k=29+(0,3,0,3,2,3,2,3,3,2,3,2,3)[m] a,R={1:(0,'KAL'),d>1:(n-d,'NON'),d>n:(i-d,'ID'),d>i:(k-d,'KAL')}[1] a+=1 A={1:'',2:'PR '}.get(a,'AD '+a//10*'X'+('','I','II','III','IV','V','VI','VII','VIII','IX')[a%10]+' ') if d>i:m=m%12+1 M='IFMAMIIASONDAEAPAVVVECOENBRRINLGPTVC'[m-1::12] print(A+R+' '+M) ``` # Explanation ``` y,m,d=time.localtime()[:3] ``` Gets the current date: `y`=year, `m`=month, and `d`=day. To test the program with dates other than the current date, simply replace this line with something else. ``` d-=(y%4==0)*(m==2)*(d>24) ``` If this is February 25-29 of a leap year, subtract 1 from the date. From this point on, we can treat February as if it's a non-leap year. Note that, because the challenge rules don't require correct behavior in the year 2100, I used the simple 4-year Julian leap-year rule instead of the Gregorian 400-year cycle. ``` i=13+2*(m in (3,5,7,10)) ``` Ides of the current month. ``` n=i-8 ``` Nones of the current month. ``` k=29+(0,3,0,3,2,3,2,3,3,2,3,2,3)[m] ``` One more than the number of days in the current month, equivalent to the Kalends of the *next* month. ``` a,R={1:(0,'KAL'),d>1:(n-d,'NON'),d>n:(i-d,'ID'),d>i:(k-d,'KAL')}[1] ``` `a` is the number of days until the next reference date and `R` is its abbreviation. This expression takes advantage of the fact that if the same key is specified multiple times in the same `dict` literal, only the last one counts. ``` a+=1 ``` Adjustment for inclusive counting. ``` A={1:'',2:'PR '}.get(a,'AD '+a//10*'X'+('','I','II','III','IV','V','VI','VII','VIII','IX')[a%10]+' ') ``` Stringify the count `a` to the next reference date. * If 1, use no prefix * If 2, use the prefix `PR` * If 3 or higher, use the prefix `AD` + Roman numeral + space There's probably a shorter way to do the Roman numerals, but I'm too lazy to find it. ``` if d>i:m=m%12+1 ``` If after the Ides, increment the month for display. ``` M='IFMAMIIASONDAEAPAVVVECOENBRRINLGPTVC'[m-1::12] ``` Get the month name. ``` print(A+R+' '+M) ``` Finally, print the date. ]
[Question] [ **This question already has answers here**: [Is it Christmas?](/questions/4106/is-it-christmas) (38 answers) Closed 8 years ago. The community reviewed whether to reopen this question 6 months ago and left it closed: > > Original close reason(s) were not resolved > > > ## Task Constantly having to check on television, or the time on your computer to see if its 2016 is a tedious task. Being programmers, we should be able to automate this task. Write a program that will output `2016` when the system time hits Friday, January 01, 2016 00:00:00. or rather `1451624400000` ms since midnight January 1, 1970. ## Input There will be no input to your program. ## Output Your program will output `2016` to STDOUT or the equivalent when the system time hits `1451624400000`. The maximum allowed delay is 1 second or `1000` ms. If your program is started after `1451624400000`, it should not output anything (an empty string is fine) and terminate normally. ## Rules * Your code must be a full program, not just a function. * You can assume your program will be started after midnight January 1, 1970. * Your program should be able to detect 2016 within a second of it occurring. * Your program should terminate after outputting `2016`. * If your program is started after midnight January 1, 2016, it should not produce any output, or an empty string, and should terminate normally. ## Scoring To keep with the trend of shortcomings in 2015, this is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge. The shortest code in bytes wins. [Answer] # Pyth, ~~20~~ 17 bytes ``` WnJ2016.d3=hZ)IZJ ``` This is rather simple. * `J2016`: assign `J = 2016` * `.d3`: gets current year * `WnJ2016.d3`: while current year is not 2016 * `=hZ`: increment `Z`, which starts at 0 * `)`: end the loop * `IZJ`: print `J` (2016) if `Z` is not zero, i.e. the loop was run at least once [Answer] ## Mathematica, ~~53~~ 49 bytes ``` a:=UnixTime[]<1451606400;If[a,While@a;Print@2016] ``` ~~Not entirely sure if it works. Will have to wait for another 9 hours...~~ ]
[Question] [ On occasion I get a little blue and need a little music to cheer me up, but clicking the start button and finding my media player takes *sooooooo* long. I want a faster way to play a song. **The challenge:** Write a program that: * Choose a song from my home directory *(so you don’t mix-up program sound files with music)* *(this includes sub folders of the home directory)*. * This song should be a random choice from all the media in my home folder. This doesn't need to be a perfect random, but I don't want to hear the same song multiple times. *(unless that's my only song ;)* * To make it simple you should only look for files ending in `.mp3`. * In the event that you find no music in my home dir, you should print `Sorry Joe, no Jams!` to stdout or closest equivalent *(btw my name isn't Joe ;)* * The layout of my home folder will contain no infinite loops * You should use system to play the song instead of using built in media playing APIs in your language *(i.e. I want the song to play in the default player for my system)*. * I should be able to place this file anywhere on my computer *(e.g. my desktop or start folder)* * Your answer should work on windows, multi-platform is a *(un-scored)* bonus This is code golf so the shortest program in bytes wins!! [Answer] ### PowerShell, 59 52 bytes ``` ii(ls -r./*.mp4|random);(,"Sorry Joe, no Jams!")[$?] ``` -7 byte golf improvements, thanks to Jaykul: * Use `ii` (`Invoke-Item`) instead of `saps` * No need to use `Get-` in `Get-noun` commandlet names, it will be searched by default. * No space needed after `-r` --- Previously at 59 bytes ``` saps(ls -R ~/*.mp3|Get-Random);(,"Sorry Joe, no Jams!")[$?] ``` It will throw an error if there are no files, but it will print the message too. Explanation: * `saps` is an alias for Start-Process * `ls` is an alias for Get-ChildItem * `~` maps to the home directory, and `-R` is -Recurse * Get-Random selects a random item from the pipeline. * After trying to launch it, it uses the previous command exit value as an index into a two-item array which either does nothing, or returns the apology message. [Answer] # [Dyalog APL](http://goo.gl/9KrKoM), ~~78~~ ~~75~~ 73 ``` {0::'Sorry Joe, no Jams!'⋄⎕SH⍵,{⍵⊃⍨?≢⍵}⎕SH∊'dir/b '⍵'*.mp3'}'%HOMEPATH%\' ``` **Explanation**: `{`...`}` unnamed function, wherein `⍵` represents whatever is to the right of the `}` APL statements (separated by `⋄`) are executed leftmost first, but each statement is evaluated from right to left (no precedence rules), so each function gets whatever is to its right as argument `0::` sets a trap for all errors to return the string instead `∊'dir/b '⍵'*.mp3'` makes the three strings into a single string `⎕SH` passes its argument to *cmd.exe* `?≢⍵` random 1 ≤ integer ≤ count (or 0 < float < 1 if count is 0) `⍵⊃⍨` pick that element (floats are invalid indices, so an error is triggered here if count was 0) `⍵,` prepends the home dir `⎕SH` passes its argument to *cmd.exe* [Answer] # Python 2, 178 bytes ``` import glob,os,random try:os.startfile(random.choice([y for x in os.walk(os.getenv('HOMEPATH'))for y in glob.glob(os.path.join(x[0],'*.mp3'))])) except:print"Sorry Joe, no Jams!" ``` Works on Windows, as per the spec. [Answer] # Linux shell utilities, 74 Ok, so this one's not going to work on windows, but in case you decide to use a real OS (😉), here's what you could do in Linux: ``` find ~ -name \*.mp3|shuf|(read l&&xdg-open "$l"||echo Sorry Joe, no Jams!) ``` ]
[Question] [ ## Introduction Pi is ``` 3.1415926535897932384626433832795028841971693993751058209749445923078164062862089... ``` Let's treat each digit as an instruction as to how to get to the next digit. * The first digit is 3. * Counting three digits after the first digit, we arrive at 1. * One digit after this 1 is a 5. * Five digits after that is 3. * Three digits later is 9. The digits included in this sequence are in bold: **3**.14**15**9265**3**58**9**79323846**2**6**4**33... If a digit is 0, the next digit is 10 later. ## Challenge Given a positive integer `n` less than 1000, find out how many of the first `n` digits of pi, including the initial 3, are in the sequence. Furthermore, your code's characters must have a "pi-based frequency". Choose any character; your program must use exactly three of that character. Choose another character, use exactly one of it. Choose another character, use it four times. You may continue for as long as you wish, but each character chosen must be different. For example, the following snippet complies with the frequency rules (but produces the wrong output): ``` print "r\"rriiiittttnttttppppp" # Uses 3 quotation marks, 1 space, 4 r's, 1 \, 5 i's, 9 t's, 2 n's, and 6 p's. ``` For the purposes of "pi-based frequency", treat the digit 0 as 10. You may write a function or a full program. You may not use any built-in constants, trigonometry functions, or complex number functions to find pi. Shortest code in characters wins. The tiebreaker is the most votes. ## Examples ``` Input Output ------------- 1 1 2 1 3 1 4 2 5 3 28 8 77 17 123 28 328 73 625 122 999 189 ``` [Answer] ## Mathematica, 253 bytes ``` f=(For[i=0;j=1,j<=#,j+=Mod[RealDigits[9801/Sqrt@8/Sum[(4j)!(1103+26390j)/(j!)^4/396^(4j),{j,0,125}],10,999][[1,j]]-1,10]+1;++i];"99iiiitS===oooo8862^^^^^^\uusRRRRRRqqqqqqqqMMMMmlllllllgggggggFFFeeeeeeeeDDDDDDaaaaa55555555<<{{\{{{{{{}}}}}}}}--@@@@@@";i)& ``` Ungolfed: ``` f = ( For[i = 0; j = 1, j <= #, j += Mod[ RealDigits[ 9801/Sqrt@8/ Sum[(4 j)! (1103 + 26390 j)/(j!)^4/396^(4 j), {j, 0, 125}], 10, 999][[1, j]] - 1, 10] + 1; ++i]; "99iiiitS===oooo8862^^^^^^uusRRRRRRqqqqqqqqMMMMmlllllllgggggggFFFeeeeeeeeDDDDDDaaaaa55555555<<{{{{{{{{}}}}}}}}--@@@@@@"; i ) & ``` Usage is `f[999]`. A whopping 122 bytes are used to pad the code with a useless string to get the right character frequencies. I'll try to improve that tomorrow. The character frequencies should match the digits of pi in this order: ``` 3#/&(,![)4+9j0it"S=;]ro862^usRqM1mlgFfeDda5<{}-@ ``` I confirmed that there is *some* correct order with the following snippet: ``` Sort[Last /@ Tally[Characters@ "f=(For[i=0;j=1,j<=#,j+=Mod[RealDigits[9801/Sqrt@8/Sum[(4j)!(\ 1103+26390j)/(j!)^4/396^(4j),{j,0,125}],10,999][[1,j]]-1,10]+1;++i];\"\ 99iiiitS===oooo8862^^^^^^\ uusRRRRRRqqqqqqqqMMMMmlllllllgggggggFFFeeeeeeeeDDDDDDaaaaa55555555<<{{\ {{{{{{}}}}}}}}--@@@@@@\";i)&"]] == Sort[RealDigits[Pi, 10, 48][[1]] /. 0 -> 10] ``` I'm computing pi with [Ramanujan's series](http://en.wikipedia.org/wiki/Approximations_of_%CF%80#20th_century). It converges to 1000 digits in 125 terms. Due to golfing reasons, I recompute the 999 necessary digits for every single digit of the subsequence, but it still completes within a second for `n = 999` on my machine. [Answer] # C++, 550 428 ``` #include<iostream> long a[3505],b,c=3505,d,e,f=10000,g,h,i,j,k,l,x,z;int main(){int P[1000];int M[4];for(;(b=c-=14)>0;){for(;--b>0;){d*=b;if(h==0)d+=2000*f;else d+=a[b]*f;g=b+b-1;a[b]=d%g;d/=g;}h=e+d/f;i=h;for(j=0;j<4;j++){M[j]=i%10;i/=10;}for(j=3;j>=0;j--){P[z]=M[j];z++;};d=e=d%f;}std::cin>>k;j=0;while(j<k){x=P[j];(x==0)?x=10:x;j+=x;l++;}std::cout<<l;}//{{{:+-2220000%,ddhhhhiiiiiiijjnorrt, # # # ,MQQQRRRSSSSSSSSTTTTTTTTT:}}} ``` I'm not 100% confident that my code has a π-based frequence. I will check tomorrow. If it works, there is a direct correspondance between the frequencies of the following characters and the 60 first digits of π. ``` zdj(mxakcb)1[*uPes>0M34t;l]g+=n%wo-,hQ{}Rr<f/Si :sT#2 3.141592653589793238462643383279502884197169399375105820974944 ``` The craziest part is the computation of π. It is done thanks to an implementation of [a fascinating spigot algorithm](http://www.cecm.sfu.ca/%7Ejborwein/Expbook/Manuscript/Related%20files/spigot.pdf): ![enter image description here](https://i.stack.imgur.com/IdgK0.png) > > **Edit:** you can generate *n* digits of π with this 288 characters-long program: :) > > > ``` #include<iostream> #include<vector> using namespace std;long b,c,d,e,f=10000,g,h,l;int main(){cout<<"? ";cin>>l;cout<<": ";l=(l/4+1)*14;c=l;vector<long> a;a.resize(l);for(;(b=c-=14)>0;){for(;--b>0;){d*=b;if(h==0)d+=2000*f;else d+=a[b]*f;g=b+b-1;a[b]=d%g;d/=g;}h=e+d/f;cout<<h;d=e=d%f;}} ``` ]
[Question] [ In [this problem on Puzzling.SE](https://puzzling.stackexchange.com/questions/274/choosing-units-for-drug-testing/297?noredirect=1#297), I ask a question about determining the amounts of drug to use in a clinical test to minimize total drug usage and fulfill the requirements of the testing procedure. The problem is as follows, for those of you who currently don't have access to the private beta: > > A medical researcher is trying to test the effect of a certain drug on mice. He is supposed to collect data for all doses from 1 to `2N` units, but only has the data collection resources for `N` tests. He has decided to only test dose amounts that are not multiples or factors of each other (for example, if he decided to use a dose of 15 units for a specific test, that would preclude tests for 1, 3, 5, 30, 45, etc. units). Moreover, because the drug is relatively expensive, he wants to use as little of the drug as he can manage to run these tests. > > > How can he arrange the dosage amounts so that he ends up using all `N` test packages, **and the total units of dosage used in the tests are as low as possible**? > > > The original problem states `N = 25`. Your task is to build a program than can answer this question for *any* number of tests up to `N = 2500`. Your program will take a number `N` from 1 to 2500 as input, and return a set of `N` integers between `1` and `2N` inclusive such that none of the `N` numbers are multiples of each other, each number from `1` to `2N` is a factor or multiple of at least one of the numbers in the set, and the sum of all the numbers in the set is as low as you can manage. Your program must return a valid result for each value of `N` to be valid. Your program will be scored by the sum of all the returned numbers for each scenario from `N = 1` to `N = 2500`. In the event of a tie, the shorter solution will win. [Answer] ## Javascript 5,955,958,211 I'm not sure if it is the optimal solution. I used a brute-force method. ``` function f(n) { var o=[]; for(var i=n;i--;) o.push(2*n-i); //init array from n+1 to 2*n for(i=n;i>0;i--) { //bruteforce on number from n to 1 var index=0; var nbFactor=0; for(j=0;j<n;j++) { if((o[j]/i)%1==0) { index=j; nbFactor++; } } if(nbFactor==1) { //if there is only 1 factor, replace it by the new number o[index]=i; } } return o.sort(function(a,b){return a-b;}); } ``` Golfed (130) : ``` function f(n){o=[];for(i=n;i++<2*n;)o.push(i);for(i=n;i;i--){for(d=c=j=0;j<n;j++)if((o[j]/i)%1==0)d=j,c++;if(c==1)o[d]=i}return o} ``` Here is the result found by my algorithm for `25` : > > [8, 12, 14, 17, 18, 19, 20, 21, 22, 23, 25, 26, 27, 29, 30, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49] > > > Little piece of code to compute the score (takes approx. 200 seconds on Chrome) : ``` var result=0; var t = Date.now(); for(var j=1;j<2501;j++) { result += f(j).reduce(function(r,e){return r+e;}); } console.log("Score : " + result + "\nCompute time : " + ((Date.now()-t)/1000) + " seconds"); ``` [Answer] # JavaScript - 5,955,958,211 A tiny bit of pre-processing to generate the factors of 1 ... 5000 ``` var factors = []; for( var i = 1; i <= 5000; i++ ) { factors[i] = []; for( var j = 1; j <= i; j++ ) { if ( i % j == 0 ) factors[i].push(j); } } ``` The main function: ``` function find_min_doses( N, DEBUG ) { var output = []; var factorCount = []; for( var i = 1; i <= 2*N; i++ ) { factorCount[i]=0; for( var j = 0; j < factors[i].length; j++ ) { factorCount[factors[i][j]]++; } } var changed = false; do { if ( DEBUG && changed ) { console.log( output.sort( function(a,b){ return a-b; } ).toString() + " = " + output.reduce( function(p,c){ return p+c; } ) ); } changed = false; var count = 0; for( var i = 1; i <= 2*N; i++ ) { if ( factorCount[i] == 1 ) { if ( count < N ) { output[count++] = i; } else { for( var j = 0; j < factors[i].length; j++ ) factorCount[factors[i][j]]--; } } } for( var i = 0; i < N; i++ ) { var o = output[i]; var f = factors[o]; for( var j = 0; j < f.length; j++ ) { var v = f[j]; if ( factorCount[v] == 2 ) { output[i]=v; for( var k = 0; k < f.length; k++ ) { factorCount[f[k]]--; } changed = true; break; } } } } while( changed ); return output.reduce( function(p,c){ return p+c; } ); } ``` A test harness: ``` var total = 0; var time = new Date(); for ( var i = 1; i <= 2500; i++ ) { total += find_min_doses( i ); } console.log( "Score: " + total + "\nTime: " + ((new Date()-time)/1000) + " seconds." ); ``` **Output (Chrome)** ``` Score: 5955958211 Time: 1.438 seconds. ``` **Output (FireFox)** ``` Score: 5955958211 Time: 66.107 seconds. ``` [Answer] # Prolog - 5,955,958,211 (?) Its far too slow to run all 2500 test cases but it will find the optimal solution(s) in every case. **Golfed - 370 Characters** ``` a([]). a([_]). a([H,N|T]):-H<N,a([N|T]). s([],0). s([H|T],S):-s(T,X),S is X+H. e(_,[]). e(V,[H|T]):-H mod V>0,e(V,T). d([]). d([H|T]):-e(H,T),d(T). b(N,L):-T is 2*N,between(1,T,L). l([H|T],M):-l(T,H,M). l([],M,M). l([H|T],C,M):-X is min(H,C),l(T,X,M). m(R,M):-findall(T,s(R,T),L),l(L,M). f(N):-length(R,N),maplist(b(N),R),a(R),d(R),m(R,M),s(R,M),write(R),nl,write(M),nl. ``` **Ungolfed** ``` ensure_sorted([]). % Ensures that the values of ensure_sorted([_]). % a list are in ascending order. ensure_sorted([Head,Next|Tail]):- Head<Next, ensure_sorted([Next|Tail]). sum([Head|Tail],Total):- % Calculate the sum of sum(Tail,Temp), % a list Total is Temp+Head. ensure_not_divisor(_,[]). % Ensure that the value ensure_not_divisor(Val,[Head|Tail]):- % is not a divisor of Head mod Val > 0, % any numbers of the list. ensure_not_divisor(Val,Tail). ensure_no_divisors([]). ensure_no_divisors([Head|Tail]):- % For each value of the list ensure_not_divisor(Head,Tail), % ensure that it is not a divisor ensure_no_divisors(Tail). % of the succeeding values. btwn(N,List):- % Restrict the values to be Temp is 2*N, % between 1 and 2N between(1,Temp,List). list_min([Head|Tail],Min):- % Find the minimum value of list_min(Tail,Head,Min). % the list. list_min([],Min,Min). list_min([Head|Tail],Current_Min,Min):- Temp is min(Head,Current_Min), list_min(Tail,Temp,Min). min_sum(R,Min):- % For all the valid answers findall(Temp,sum(R,Temp),List), % find the minimum sum. list_min(List,Min). func(N):- length(R,N), % A list of N unknown values maplist(btwn(N),R), % Restrict each value to integers 1..2N ensure_sorted(R), % Ensure the list is sorted. ensure_no_divisors(R), % Ensure that each value is not a divisor of a higher value. min_sum(R,Min), % Find the minimum sum of all answers sum(R,Min), % Restrict the answer to have the minimum sum. write(R),nl, % Output the doses (and a newline). write(Min),nl. % Output the score (and a newline). ``` [Answer] # Python – 7,818,751,250 As a last-place reference answer, consider the following: ``` def f(n): return range(n+1, n*2+1) ``` For any `N`, choosing unit sizes from `N+1` to `2N` will ensure that no number is a multiple or factor of any other, simply by virtue of the fact that they're too close together. The smallest nontrivial multiple of `N+1` is `2N+2`, and the largest nontrivial factor of `2N` is `N`, and no nontrivial multiple or factor of any number will fall between those two. However, there will always be solutions that do much better than this – simply replacing `2N-2` with `N-1` already will always yield a better solution. ]
[Question] [ Your challenge is to write a program that takes input from *stdin*, creates a set of `1` to `n`colors and outputs them on *stdout*, formatted as a 6-digit-hex value with a prefixed #. * The starting color should have following values (in a hsv colorspace) (pesudocode) + `h=rand(), s=0.5, v=0.95`. * Every subsequent color should have its *hue* value increased by + `1/Φ` * After every 5th color, the *saturation* and *value* for the forthcoming colors should be + *saturation* - increased by `0.1` + *value* - decreased by `0.2` *e.g.* ``` Color # h s v 1 0.5 0.5 0.95 2 0.118... 0.5 0.95 11 0.680... 0.7 0.55 ``` **Input** Your program shall receive an Integer `n`as input *(stdin)*, which defines the number of colors, to be generated. *Where `0 < n < 16`* **Output** * On each call, the *hues*' start value should be different from the last call *(Don't just take the same random start number on every call)* * Output should be on stdout with one color per line. * The array shall contain `n` different hex codes. * The hex codes should be prefixed with a "#" and be padded with a "0", such that you always get a 7 character string like "#FFFFFF" **Additional Rules** * The use of built in functions/tools/etc for the following conversions is forbidden + HSV->RGB + RGB->HEX representation of RGBa function which specifically converts rgb to hex, generic tools like `sprintf` are ok. + HSV->HEX representation of RGBjust to make sure... **Scoring** The size of your code in bytes. **Test Cases**(result of rand() in parantheses) ``` 3 (0.35389856481924653) -> #79f388 #f3798e #79b1f3 8 (0.763850917108357) -> #c079f3 #79f39d #f37979 #4c6ec0 #90c04c #c04cb1 #4cc0ac #c08b4c 15 (0.10794945224188268) -> #f3c879 #a479f3 #79f381 #f37995 #79b8f3 #aac04c #b44cc0 #4cc092 #c0704c #4f4cc0 #448c2a #8c2a61 #2a7e8c #8c7e2a #612a8c ``` *for a visualization of the codes, you can paste your output [here](http://jsfiddle.net/SCnd6/)* *I will change the accepted Answer, as soon as new appear* [Answer] ## Python 184 bytes ``` from random import* h,s,v=random()*6,.5,243.2 for i in range(input()): h+=3.708;print'#'+'%02x'*3%((v,v-v*s*abs(1-h%2),v-v*s)*3)[5**int(h)/3%3::int(h)%2+1][:3] if i%5/4:s+=.1;v-=51.2 ``` The HSV ⇒ RGB conversion is taken directly from [wikipedia](http://en.wikipedia.org/wiki/HSL_and_HSV#From_HSV). A few implementation notes. * `h` is defined as its proper value times *6*, which simplifies region determination. * `v` is defined as its proper value times *256*, which propagates through to all three RGB values. * *6/Φ* (approximately *~3.708*) is used instead of *1/Φ*, in agreement with the scaling of `h`. Similarly, the decrement value for `v` is also scaled by *256*. * The bit of magic `((v,v-v*s*abs(1-h%2),v-v*s)*3)[5**int(h)/3%3::int(h)%2+1][:3]` is logically equivalent to `c=v*s;m=v-c;x=c-c*abs(1-h%2)+m;c+=m;[(c,x,m),(x,c,m),(m,c,x),(m,x,c),(x,m,c),(c,m,x)][int(h)%6]` Sample usage: ``` $ echo 3 | python color-set.py #f37994 #79b8f3 #dbf379 $ echo 8 | python color-set.py #d2f379 #f079f3 #79f3cc #f3a979 #8579f3 #62c04c #c04c84 #4ca6c0 $ echo 15 | python color-set.py #7984f3 #a8f379 #f379cb #79eff3 #f3d379 #804cc0 #4cc05e #c04c5c #4c7dc0 #9fc04c #8b2a8c #2a8c6f #8c522a #352a8c #3b8c2a ``` A visualization of the values for *n = 15*: ![enter image description here](https://i.stack.imgur.com/3pJ20.png) and the [corresponding html](http://codepad.org/9IJy6Jt4). [Answer] As I saw by other People, i start with my own solution # Javascript, ~~418~~433 ``` a=prompt();x=0.6180339887;r=[];m=Math.random;p=[m(),0.5,0.95];function h(c,g,d){k=~~(6*c);b=6*c-k;c=d*(1-g);l=d*(1-b*g);g=d*(1-(1-b)*g);f=e=b=255;1>k?(b=d,e=g,f=c):2>k?(b=l,e=d,f=c):3>k?(b=c,e=d,f=g):4>k?(b=c,e=l,f=d):5>k?(b=g,e=c,f=d):(b=d,e=c,f=l);return"#"+[b,e,f].map(function(c){return 16>(c=0|256*c)?0:""+c.toString(16)}).join("")}for(;a--;)r.push(h.apply(h,p)),p[0]+=x,p[0]%=1,!(a%5)&&(p[1]+=0.1,p[2]-=0.2);console.log(r.join("\n")) ``` *Damn, i did something wrong in the previous versioon when inlining the function, i shouldn't write the code golfed from beginning* Sample Output ![enter image description here](https://i.stack.imgur.com/ksEOD.png) ``` #79f3a0 #f37d79 #7999f3 #bcf379 #f379e0 #4cc0b0 #c08e4c #6d4cc0 #4ec04c #c04c6f #2a648c #818c2a #7b2a8c #2a8c5e #8c412a ``` ]
[Question] [ Write the shortest program possible which outputs a table of Normal distribution values ``` phi(z) = Integral[t from -infty to z of e^(-t^2/2) /sqrt(2 pi) dt] ``` for `z` from 0.00 to 3.99, giving values accurate to 4 decimal places. The canonical format for such a table appears to be: ``` 0.00 0.01 0.02 0.03 0.04 0.05 0.06 0.07 0.08 0.09 0.0 0.5000 0.5040 0.5080 0.5120 0.5160 0.5199 0.5239 0.5279 0.5319 0.5359 0.1 0.5398 0.5438 0.5478 0.5517 0.5557 0.5596 0.5636 0.5675 0.5714 0.5753 0.2 0.5793 0.5832 0.5871 0.5910 0.5948 0.5987 0.6026 0.6064 0.6103 0.6141 0.3 0.6179 0.6217 0.6255 0.6293 0.6331 0.6368 0.6406 0.6443 0.6480 0.6517 0.4 0.6554 0.6591 0.6628 0.6664 0.6700 0.6736 0.6772 0.6808 0.6844 0.6879 0.5 0.6915 0.6950 0.6985 0.7019 0.7054 0.7088 0.7123 0.7157 0.7190 0.7224 0.6 0.7257 0.7291 0.7324 0.7357 0.7389 0.7422 0.7454 0.7486 0.7517 0.7549 0.7 0.7580 0.7611 0.7642 0.7673 0.7704 0.7734 0.7764 0.7794 0.7823 0.7852 0.8 0.7881 0.7910 0.7939 0.7967 0.7995 0.8023 0.8051 0.8078 0.8106 0.8133 0.9 0.8159 0.8186 0.8212 0.8238 0.8264 0.8289 0.8315 0.8340 0.8365 0.8389 1.0 0.8413 0.8438 0.8461 0.8485 0.8508 0.8531 0.8554 0.8577 0.8599 0.8621 1.1 0.8643 0.8665 0.8686 0.8708 0.8729 0.8749 0.8770 0.8790 0.8810 0.8830 1.2 0.8849 0.8869 0.8888 0.8907 0.8925 0.8944 0.8962 0.8980 0.8997 0.9015 1.3 0.9032 0.9049 0.9066 0.9082 0.9099 0.9115 0.9131 0.9147 0.9162 0.9177 1.4 0.9192 0.9207 0.9222 0.9236 0.9251 0.9265 0.9279 0.9292 0.9306 0.9319 1.5 0.9332 0.9345 0.9357 0.9370 0.9382 0.9394 0.9406 0.9418 0.9429 0.9441 1.6 0.9452 0.9463 0.9474 0.9484 0.9495 0.9505 0.9515 0.9525 0.9535 0.9545 1.7 0.9554 0.9564 0.9573 0.9582 0.9591 0.9599 0.9608 0.9616 0.9625 0.9633 1.8 0.9641 0.9649 0.9656 0.9664 0.9671 0.9678 0.9686 0.9693 0.9699 0.9706 1.9 0.9713 0.9719 0.9726 0.9732 0.9738 0.9744 0.9750 0.9756 0.9761 0.9767 2.0 0.9772 0.9778 0.9783 0.9788 0.9793 0.9798 0.9803 0.9808 0.9812 0.9817 2.1 0.9821 0.9826 0.9830 0.9834 0.9838 0.9842 0.9846 0.9850 0.9854 0.9857 2.2 0.9861 0.9864 0.9868 0.9871 0.9875 0.9878 0.9881 0.9884 0.9887 0.9890 2.3 0.9893 0.9896 0.9898 0.9901 0.9904 0.9906 0.9909 0.9911 0.9913 0.9916 2.4 0.9918 0.9920 0.9922 0.9925 0.9927 0.9929 0.9931 0.9932 0.9934 0.9936 2.5 0.9938 0.9940 0.9941 0.9943 0.9945 0.9946 0.9948 0.9949 0.9951 0.9952 2.6 0.9953 0.9955 0.9956 0.9957 0.9959 0.9960 0.9961 0.9962 0.9963 0.9964 2.7 0.9965 0.9966 0.9967 0.9968 0.9969 0.9970 0.9971 0.9972 0.9973 0.9974 2.8 0.9974 0.9975 0.9976 0.9977 0.9977 0.9978 0.9979 0.9979 0.9980 0.9981 2.9 0.9981 0.9982 0.9982 0.9983 0.9984 0.9984 0.9985 0.9985 0.9986 0.9986 3.0 0.9987 0.9987 0.9987 0.9988 0.9988 0.9989 0.9989 0.9989 0.9990 0.9990 3.1 0.9990 0.9991 0.9991 0.9991 0.9992 0.9992 0.9992 0.9992 0.9993 0.9993 3.2 0.9993 0.9993 0.9994 0.9994 0.9994 0.9994 0.9994 0.9995 0.9995 0.9995 3.3 0.9995 0.9995 0.9995 0.9996 0.9996 0.9996 0.9996 0.9996 0.9996 0.9997 3.4 0.9997 0.9997 0.9997 0.9997 0.9997 0.9997 0.9997 0.9997 0.9997 0.9998 3.5 0.9998 0.9998 0.9998 0.9998 0.9998 0.9998 0.9998 0.9998 0.9998 0.9998 3.6 0.9998 0.9998 0.9999 0.9999 0.9999 0.9999 0.9999 0.9999 0.9999 0.9999 3.7 0.9999 0.9999 0.9999 0.9999 0.9999 0.9999 0.9999 0.9999 0.9999 0.9999 3.8 0.9999 0.9999 0.9999 0.9999 0.9999 0.9999 0.9999 0.9999 0.9999 0.9999 3.9 1.0000 1.0000 1.0000 1.0000 1.0000 1.0000 1.0000 1.0000 1.0000 1.0000 ``` [Answer] # Mathematica 132 136 127 If `Erfc` is acceptable, here's my attempt, accurate to 6 places: ``` t=Table;TableForm[Partition[t[0.5 Erfc[-x/Sqrt[2]],{x,0,3.99,.01}],10], TableHeadings->{t[k,{k,0,3.9,.1}],t[k,{k,0,.09,.01}]}] ``` ![enter image description here](https://i.stack.imgur.com/ITHKw.png) [Answer] ## GolfScript (124 chars) ``` 10:&,~]' 0.0'*40,{n\:I&/'.'I&%&,{' '\I&*+&8?:^*100/:x^54,-2%{:i*x.{*^/}:$~$i).)*/^\-}/$3989423$15000500+`5<(49-'.'@}%}/ ``` Note: the only whitespace in there are two tab characters. MarkDown is turning them into triple-spaces. The interesting part (i.e. the calculation) is done in `x.8` fixpoint using [identity 26.2.10 of *Abramowitz and Stegun (1972)*](http://people.math.sfu.ca/~cbm/aands/page_932.htm). The program runs in under 2 seconds on my machine. [Answer] ## Perl - ~~137~~ 133 bytes ``` print"\t0.0$_"for 0..9;for($f=2.506628;$i++<80;$f*=-++$i){printf' %.1f',$x,s;;+\$x**$i/$i/$f;;printf"\t%.4f",eval,$x+=.01for(.5.$_)x10} ``` (both \t should be replaced with a literal tab character.) Uses a Taylor Series expansion[1], adding one term per row, which seems to be good enough. The script produces the output exactly as expected, ~~although each row does have a trailing whitespace~~. Runs in about 60ms on my lappy. Edit as per comment by Peter Taylor. [1] <http://mathworld.wolfram.com/NormalDistributionFunction.html> (formula 10) [Answer] ## c -- 372 Just for interest this is an implementation of Peter's Monte Carlo suggestion from the comments ``` #include "stdio.h" #include "stdlib.h" #include "math.h" #define P printf #define F(c,n) for(c=0;c<n;++c) long c=9e9,i,j,k;double a[400],b=.01,t; double B(){return sqrt(-2*log(drand48()))*cos(2*M_PI*drand48());}main() {srand48(time(0));F(i,c){t=B();F(k,400)a[k] += t<b*k;}P("%4c",' ');F(j,10) P("%4.2f ",b*j);F(i,40){P("\n%3.1f ",10*i*b);F(j,10) P("%6.4f ",a[10*i+j]/c);}} ``` Lots of repetitive code. A very straight forward implementation, ungolfed it looks like ``` #include "stdio.h" #include "stdlib.h" #include "math.h" long c=9e9, i, j, k; /* demands longs longer than 32 bits */ double a[400], bw=.01, t; double B/*oxMuller*/(){ /* normal distribution, centered on 0, std dev 1 */ return sqrt(-2*log(drand48())) * cos(2*M_PI*drand48()); } main(){ srand48(time(0)); for(i=0; i<c; ++i) { /* compute the probabilities by MC integration */ t=B/*oxMuller*/(); for(k=0; k<400; ++k) a[k] += t<bw*k; } /* Print the table */ printf("%4c",' '); for(j=0; j<10; ++j) printf("%4.2f ",bw*j); for(i=0; i<40; ++i) { printf("\n%3.1f ",10*i*bw); for(j=0; j<10; ++j) printf("%6.4f ",a[10*i+j]/c); } printf("\n"); /* make the end pretty */ } ``` It is slow, about 60 seconds to do 100,000,000 throws with absolutely all the optimization bells and whistles turned on (`-m64 -Ofast`) on my 2.2 GHz Core 2 Duo laptop. Worse, it needs circa 50 times that many to provide real confidence that you have the right value in each and every bin. As written I'm asking for even more. That seems too long to me, but I suspect that I underestimate how much work `drand48` is doing (and I have sacrificed about a factor of 2 in the random number generation at the alter of small code). It also demands that long is a bit bigger than 32 bits (thus the `-m64` above). [Answer] # k This is based on the Zelen and Severo algorithm [here](https://en.wikipedia.org/wiki/Normal_distribution#Numerical_approximations_for_the_normal_CDF). 162 characters. Can improve the character count significantly by reducing precision. ``` +`q`p!(q;{abs(x>0)-(exp[-.5*x*x]%sqrt 2*acos -1)*t*.31938153+t*-.356563782+t*1.781477937+t*-1.821255978+1.330274429*t:1%1+.2316419*abs x}(q:0.1*!391)+\:0.01*!100) ``` Runs in about 15ms on a Pentium E2160. ]
[Question] [ The [Roman numeral](https://en.wikipedia.org/wiki/Roman_numerals) for 499 is usually given as `CDXCIX` which breaks down as `CD + XC + IX` = 400 + 90 + 9 where numerals like `CD` and `IX` are written using subtractive notation. Some programming languages have a `roman()` function that extends this subtractive notation through various *relaxation levels*. From Google Sheets [documentation](https://support.google.com/docs/answer/3094153): * **0** indicates strict precedence rules, where *I* may only precede *V* and *X*, *X* may only precede *L* and *C*, and *C* may only precede *D* and *M*. Therefore `ROMAN(499,0)` is *CDXCIX*. * **1** indicates a relaxation where *V* may precede *L* and *C* and *L* may precede *D* and *M*. Therefore `ROMAN(499,1)` is *LDVLIV*. * **2** indicates a further relaxation where *I* may precede *L* and *C*, and *X* may precede *D* and *M*. Therefore `ROMAN(499,2)` is *XDIX*. * **3** indicates a further relaxation where *V* may precede *D* and *M*. Therefore `ROMAN(499,3)` is *VDIV*. * **4** indicates a further relaxation where *I* may precede *D* and *M*. Therefore `ROMAN(499,4)` is *ID*. Write a function that takes a `number` and a relaxation `level` as input and outputs or returns a Roman numeral. **Input**: `number`, an integer between 1 and 3999 inclusive, and `level`, an integer between 0 and 4 inclusive. Input format is flexible and you may also use delimited strings and the like. Inputs can be passed as parameters or read from any source. **Output**: a Roman numeral. When `level` is 0, the output must conform to the [standard form](https://en.wikipedia.org/wiki/Roman_numerals#Standard_form). In other levels, the output must observe the list above and give the shortest allowed form that implements the subtractive notation shown in a given level. If your language has a built-in for Roman numerals, you are free to use it to generate the standard form, but you must use your own code to manage other levels. Output format is flexible as long as it can be read as illustrated in these test cases: ``` 1, 0 -> I 1, 4 -> I 499, 0 -> CDXCIX 499, 4 -> ID 1999, 0 -> MCMXCIX 1999, 1 -> MLMVLIV 1999, 2 -> MXMIX 1999, 3 -> MVMIV 1999, 4 -> MIM 2024, 0 -> MMXXIV 48, 1 -> VLIII 993, 2 -> XMIII 1996, 3 -> MVMI 1998, 4 -> MVMIII 3999, 2 -> MMMXMIX 3999, 4 -> MMMIM ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). The winning criteria is shortest code by language, as long as the output meets the criteria above. [Default loopholes](https://codegolf.meta.stackexchange.com/q/1061/119296) forbidden. (this question spent a week in the [Sandbox](https://codegolf.meta.stackexchange.com/a/26239/119296) with no negative or positive votes) [Answer] # Google Sheets, 364 bytes ``` =let(ø,tocol(,1),r,roman(A2),a,vstack({"C(D|M)XC","L$1XL";"C(D|M)L","L$1";"X(L|C)IX","V$1IV";"X(L|C)V","V$1"},if(B1<2,ø,{"V(L|C)IV","I$1";"L(D|M)XL","X$1";"L(D|M)VL","X$1V";"L(D|M)IL","X$1IX"}),if(B1<3,ø,{"X(D|M)V","V$1";"X(D|M)IX","V$1IV"}),if(B1<4,ø,{"V(D|M)IV","I$1"})),if(B1,reduce(r,sequence(rows(a)),lambda(r,i,regexreplace(r,index(a,i,1),index(a,i,2)))),r)) ``` Put the number in cell `A2`, the level in cell `B1`, and the formula in cell `B2`. [Try it.](https://docs.google.com/spreadsheets/d/1VU4a7d-dJQdmJiZmIma2xQAcvilK6jQX4KmtEc7Cfwk/edit) After posting the challenge, I started wondering whether the transformation could be done with regexes. It turns out that just 11 replaces are required to cover all levels in the number range 1...3999. A smaller number of regexes would probably suffice in languages where `replace()` can take a function argument. The formula builds an array of regexes and replacement strings that accumulate by level. The array is applied to the standard form using `reduce()`. ![Relaxing Romans.png](https://i.imgur.com/u5a0SfX.png) Ungolfed: ``` =let( regexReplaceAll_, lambda(text, regexes, replacements, reduce(text, sequence(rows(regexes)), lambda(acc, i, regexreplace(acc, chooserows(regexes, i), chooserows(replacements, i)) )) ), nullRow, tocol(æ, 2), map(B1:F1, lambda(level, let( regexes, vstack( { "C(D|M)XC", "L$1XL"; "C(D|M)L", "L$1"; "X(L|C)IX", "V$1IV"; "X(L|C)V", "V$1" }, if(level < 2, nullRow, { "V(L|C)IV", "I$1"; "L(D|M)XL", "X$1"; "L(D|M)VL", "X$1V"; "L(D|M)IL", "X$1IX" } ), if(level < 3, nullRow, { "X(D|M)V", "V$1"; "X(D|M)IX", "V$1IV" } ), if(level < 4, nullRow, { "V(D|M)IV", "I$1" } ) ), map(A2:A, lambda(number, let( standardForm, roman(number), if(level, regexReplaceAll_(standardForm, choosecols(regexes, 1), choosecols(regexes, 2)), standardForm ) ))) ))) ) ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 79 bytes ``` NθNηF⁷«≦⁻⁶ι≔⊗÷⊖ι²ζF⮌⊞OE⊕⌊⟦ζη⟧⟦⁻ζκι⟧⟦ι⟧«≔↨Eκ×Xχ÷λ²⊕×⁴﹪λ²±¹εW¬‹θε«Fκ§IVXLCDMμ≧⁻εθ ``` [Try it online!](https://tio.run/##TVBNa8JAED2bX7F4moUtVJEW6ck2l0BiRUopiIdoRrOY7Mb90GLxt6ez0VZhGfbNx3tvZl3mZq3zqm0T1Xg39fUKDez5S3SPS8IbbRg8c/YT9bK8mVgrtyrFjYNMKm8FexJMUlvvUoFY@1WFBSTKxfIgC4QY1wZrVI6ykgs25BROYaSjnuMBjUWYeVu@N2hypw2QEjHc5khL1r6GxUmwchkIFp08EN4RksuQosg7o39mXnMiDlw7wT5kjRZm@kh7DR4Fuxmsrp7uBS/dI8EyXfhKX3tC1xS3uUMYhD@GLXrHUlbIYKodpGgt7EPhauSy446zmZHKwcQlqsBv6CefX@lbnPUFq3lHcjvuXG7L/@uiYPuufo7ondt2NB5Hw/bhUP0C "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Greedy algorithm. ``` NθNη ``` Input the number and the relaxation. ``` F⁷«≦⁻⁶ι ``` Iterate over the indices of Roman numerals in the string `IVXLCDM` in reverse order. ``` ≔⊗÷⊖ι²ζ ``` Calculate the index of the Roman numeral that precedes it at a relaxation of `0`. ``` F⮌⊞OE⊕⌊⟦ζη⟧⟦⁻ζκι⟧⟦ι⟧« ``` Create pairs of indices for up to the given relaxation level, plus also consider the Roman numeral index on its own, and loop over these lists in reverse order, so that the highest value is considered first. ``` ≔↨Eκ×Xχ÷λ²⊕×⁴﹪λ²±¹ε ``` Calculate the decimal value of the list, which is obtained by converting each element of the list to decimal and then taking the list as base `-1`. (The newer version of Charcoal on ATO can vectorise this calculation for a saving of `2` bytes.) ``` W¬‹θε« ``` While the current value does not exceed the input, ... ``` Fκ§IVXLCDMμ ``` ... convert the list to a string and output it, and... ``` ≧⁻εθ ``` ... subtract the value from the input. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 68 bytes ``` IḢ_ḂṪµƝ>⁴;Ṫ>ḢƊ3Ƥ;_ṪṠ‘Ʋ4ƤḌ=⁵ƲṆ5,2ṁṖPƲ€N<ƝT$¦SƊ}Ẹ? 1ḃ7Ç⁼ɗ1#ḃ7ị“IVXLCDM ``` * [Try it online!](https://tio.run/##AYsAdP9qZWxsef//SeG4ol/huILhuarCtcadPuKBtDvhuao@4biixoozxqQ7X@G5quG5oOKAmMayNMak4biMPeKBtcay4bmGNSwy4bmB4bmWUMay4oKsTjzGnVQkwqZTxop94bq4Pwox4biDN8OH4oG8yZcxI@G4gzfhu4vigJxJVlhMQ0RN////Mzk5Of81 "Jelly – Try It Online") * [Test suite](https://tio.run/##TY7NSsNAFIX38xQBXUZsmvgTonFhNwMdEZQhrrrqRvoCLoQkgoXoSkEFDYiWilJcBAszrbhI6ICPcedF4k2N2M3lfOeew73H3V7vpCwpiKcOiBjkWz5WqZ@/eyh9dFViq4HXQQL5qMM7lTlqAOJyW0djlYE8XzObICOQN/sq0/Fob0ulh8v58EAlpzARO8QCcbZR9HX0@X1rLVUA0wsdPlAetHdbrNRhSkDe5684dCSKPtKXhwFjxTdw6RUvqwSmH7NrkM//Nr42u@IqwZP4VSMfosAr8eioLC3TaFQxSlA5v8px3T/dIpZbUbMiFjAa1IY9NzijvDbmeUYZcTZNw6qAtymlxHXtuo5tZEyvL9SJvdBm2P8B) A full program taking the Arabic number as the first argument and the 1-indexed relaxation level as the second argument. Prints the Roman numeral to STDOUT. Full explanation to follow, but overall strategy is: 1. Starting at 1, find the first integer that satisfies the following: 1. Convert to bijective base 7 2. Check if any of the following are true: * A smaller integer precedes a larger one, and the gap is too big per the relaxation rules; this is determined by taking the difference between consecutive digits, subtracting one if the second digit was odd, and then comparing to the relaxation level * We have a pattern `a, b, c` where `a < c`; examples would be `1, 1, 7` or `1, 3, 5`. * We have a pattern `a, b, c, b` where `a < b` and `c < b`, for example `1,7,1,7` 3. If none of those were true, index the digit list into `1,5,10,50,100,500,1000`, negate smaller digits that precede larger ones, and sum. 4. Compare to the desired Arabic number 2. If different, proceed to the next integer and run through the steps above 3. If we’ve reached our target, bijective convert to base 7 and index into `"IVXLCDM"` ## Explanation (outdated) ``` IḢ_ḂṪµƝ>⁴;Ṫ>ḢƊ3ƤṆ5,2ṁṖPƲ€N<ƝT$¦SƊ}Ẹ? # ‎⁡Helper link: test whether a Roman numeral (expressed as digits from 1 to 7) is valid, and if so, convert to Arabic µƝ # ‎⁢Following as a monad for each neighbouring pair of digits: I # ‎⁣- Increments (differences) Ḣ # ‎⁤- Head (effectively just remove the one and only increment from its list) _Ḃ # ‎⁢⁡- Subtract the original pair mod 2 Ṫ # ‎⁢⁢- Tail; this will effectively be (b - a) - (b % 2) >⁴ # ‎⁢⁣Greater then the relaxation level ; Ɗ3Ƥ # ‎⁢⁤Concatenate to the following, run as a monad over each overlapping infix length 3: Ṫ>Ḣ # ‎⁣⁡- Tail greater than head Ẹ? # ‎⁣⁢If any are non-zero: Ṇ # ‎⁣⁣- Not (will yield zero) Ɗ} # ‎⁣⁤Else: following applied as a monad to the link’s original argument (the digit list) Ʋ€ # ‎⁤⁡- For each digit: 5,2ṁ # ‎⁤⁢ - Mould [5,2] into that length (so 5 becomes [5,2,5,2,5] Ṗ # ‎⁤⁣ - Remove last (so 5 would now be [5,2,5,2] P # ‎⁤⁤ - Product (so 5 would now be 100) N<ƝT$¦ # ‎⁢⁡⁡- Negate those where a smaller digit precedes a larger S # ‎⁢⁡⁢- Sum ‎⁢⁡⁣ 1ḃ7Ç⁼ɗ1#ḃ7ị“ # ‎⁢⁡⁤Main link 1 ɗ1# # ‎⁢⁢⁡Starting at 1, find the first positive integer which satisfies the following, called as a monad with the main link’s left argument as its right: ḃ7 # ‎⁢⁢⁢- Convert to bijective base 7 Ç # ‎⁢⁢⁣- Call helper link ⁼ # ‎⁢⁢⁤- Equal to (main link’s left argument) ḃ7 # ‎⁢⁣⁡Convert to bijective base 7 ị“IVXLCDM # ‎⁢⁣⁢Index into "IVXLCDM" (last closing quote is implicit) and then implicitly print 💎 ``` Created with the help of [Luminespire](https://vyxal.github.io/Luminespire). ]
[Question] [ Classic Tetris was often a difficult game to play. One problem was that you could only work with the Tetris piece you were given, so if you had an awkward board, it would sometimes be difficult to find a suitable location to put your piece. Another problem was that you could only look one piece ahead, so it was difficult to prepare your board for upcoming pieces. These problems together made the classic game quite frustrating to play. Official Tetris solves these problems with the hold slot and next queue. The next queue allowed a player to look ahead 5 pieces, instead of 1. However, if a player was still unsatisfied with the piece they currently had, they could "hold" the piece in the hold slot and instead use the next piece in the queue. For example, take the board below. [![Tetris board (I wanted to make a unicode version of it but the line spacing made it difficult to read, so here's an image instead)](https://i.stack.imgur.com/ceJTfm.png)](https://i.stack.imgur.com/ceJTfm.png) It would be hard to place the square piece on the board, so the player could "hold" the piece and use the jagged 'Z' piece instead: [![Hold Z piece](https://i.stack.imgur.com/gSY12m.png)](https://i.stack.imgur.com/gSY12m.png) Once you "hold" a piece, however, the game doesn't allow you to keep "holding", or switching the pieces again and again until you've used the new piece. For instance, in the example above, you wouldn't be able to switch back to the square piece until you've used the jagged 'Z' piece. If you want to try this mechanic out yourself, go to [JSTris](https://jstris.jezevec10.com/) or [tetr.io](https://tetr.io) and play around with it. # Challenge: The pieces will be labelled J, L, S, Z, O, I, or T. Given the next queue, the current piece, and the hold piece (assume it exists for now), generate all possible orders you can place 6 of the pieces in. For example, if the next queue was `[Z,S,L,J,I]`, the current piece was O, and the held piece was T, 3 possible orders would be the following: ``` 1. O, Z, S, L, J, I (no hold used at all) 2. T, Z, S, L, J, I ^ hold O here 3. O, Z, T, L, J, S ^ hold S here ^ hold I here, S was in hold slot so put S here ``` [Answer] # [Python 3](https://docs.python.org/3/), 70 bytes ``` f=lambda x,y=[]:x[1:]and f(x[1:],y+x[:1])+f(x[:1]+x[2:],y+[x[1]])or[y] ``` [Try it online!](https://tio.run/##Hcm/CoAgEAfgV2lTycXahB6gCBpq6rjBCCkok2jwnt6uhg9@fyI92xXqnH1zuHNZXZE0NYA2gbHowlp4@UdNZQJrUJXfwIFr9c/AP6K6biDM8d7DI70EMQgtJjazkfWsY61ApfIL "Python 3 – Try It Online") # [Python 3](https://docs.python.org/3/), 66 bytes by tsh ``` f=lambda a,o='':a[1:]and f(a[1:],o+a[0])+f(a[0]+a[2:],o+a[1])or[o] ``` [Try it online!](https://tio.run/##K6gsycjPM/7/P802JzE3KSVRIVEn31Zd3Sox2tAqNjEvRSFNA8zUyddOjDaI1dQG8Q1igRwjqKBhrGZ@UXR@7P@Cosy8Eo00DXX/kOAoHy9PdU3N/wA "Python 3 – Try It Online") I'm not sure if I understood correctly, [Answer] # JavaScript (ES6), 49 bytes Expects `(queue, held_piece)`, where the first item in the queue is the current piece. ``` f=([c,...a],h,o="")=>c?f(a,h,o+c)+[,f(a,c,o+h)]:o ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/zVYjOllHT08vMVYnQyffVklJ09Yu2T5NIxHE1U7W1I7WAXGSgZwMzVir/P/J@XnF@Tmpejn56RppGtHq/uo66lFAHAzEPkDsBcSe6rE6Cuoh6pqa/wE "JavaScript (Node.js) – Try It Online") [Answer] # [Curry (PAKCS)](https://www.informatik.uni-kiel.de/%7Epakcs/), 39 bytes ``` f(c:q)h=h:f q c f(c:q)h=c:f q h f""h="" ``` [Try it online!](https://tio.run/##Sy4tKqrULUjMTi7@/z9NI9mqUDPDNsMqTaFQIZkLxk8G8zO40pSUMmyVlP7nJmbmKdgqpCko@UcF@3h5Kimoh6j/BwA "Curry (PAKCS) – Try It Online") Takes the queue (starting from the current piece) as a string and piece in hold as a char. Basically, the code just describes what can happen during a move. Due to non-deterministic behavior, Curry just walks through all the possibilities, which is exactly what we need here. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~32~~ 29 bytes ``` ⊞υSFS≔ΣEυ⟦⭆κ⁺μ×ι¬ν⁺ικ⟧υEυ⮌✂ι¹ ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70iOSOxKDk_MWfBgqWlJWm6FjfnB5QWZ2iU6ih45hWUlgSXFGXmpWtoalpzpeUXKWigCio4FhdnpudpBJfmavgmFoB0RUMkQbxsHYWAnNJijVwdhZDM3NRijUwdBb_8Eo08TSCAygGFsjVjQdxSoBUBQK0lMJOCUstSi4pTNYJzMpNTQQoNQfqslxQnJRdDHbs8Wkm3LEcpdkUIl39UsI-XJ0QYAA) Link is to verbose version of code. Takes the hold piece as the first input and the current piece and next queue as a single string as the second input. Explanation: ``` ⊞υS ``` Start with the hold piece and no played pieces. ``` FS ``` Loop over the queue. ``` ≔ΣEυ⟦⭆κ⁺μ×ι¬ν⁺ικ⟧υEυ ``` For each position, create two positions, one playing the current piece and one holding it and playing the hold piece. Note that the piece is played at the start of the string, so the played pieces are currently in reverse order. ``` ⮌✂ι¹ ``` Print the played pieces of the positions in the correct order. [Answer] # [Python 3](https://docs.python.org/3/), 69 bytes ``` f=lambda x,y,*a:a and[p+j for p,q in[x+y,y+x]for j in f(q,*a)]or[x,y] ``` [Try it online!](https://tio.run/##JYu7CoAgFEB/5W7lY2sL@oAiaKgpcbghklFq0qBfb0brefj07M42OevuxGtTCJEnTrFFQKuEZwdoF8DzG4wVkSWeWJQfOgoAXd8lJtIFUT6ZP2F@QatlWudx6CvS@mDsUxuSXw "Python 3 – Try It Online") Input 7 chars, output str. [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 30 bytes ``` +%`(.),(.) $2$1,$'¶$`$1$2, ., ``` [Try it online!](https://tio.run/##K0otycxL/P9fWzVBQ09TB4i5VIxUDHVU1A9tU0lQMVQx0uHS0@H6/z9Exz8q2MfLEwA "Retina 0.8.2 – Try It Online") Takes the hold piece as the first input and the current piece and next queue as a single string as the second input, separated by a comma. Explanation: ``` (.),(.) $2$1,$'¶$`$1$2, ``` Match the hold piece and the current piece and create two new positions, one by playing the current piece and one by playing the hold piece. ``` +%` ``` Repeat the above separately on each position until queue is empty. ``` ., ``` Delete the hold piece and separator from each result. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 19 bytes ``` W;Ɱ2ṗ6¤œ-ị@¥\€œ-Ɲ€Y ``` [Try it online!](https://tio.run/##y0rNyan8/z/c@tHGdUYPd043O7Tk6GTdh7u7HQ4tjXnUtAbIOTYXSEf@//8/xD84ysfLEwA "Jelly – Try It Online") A full program that takes a string as its argument (held, current, five next) and prints the 64 possibilities to STDOUT. ## Explanation ``` W | Wrap in a list ;Ɱ | Concatenate to each of: 2ṗ6¤ | - 2 Cartesian power 6 (i.e. all lists length 6 of 1s and 2s) ¥\€ | For each of these, reduce using the following, collecting up intermediate results: œ-ị@ | - Set difference between the current set of pieces and the one found at the index of the right argument (either the first or second) œ-Ɲ€ | Set difference of neighbours for each of these outputs Y | Join with new lines ``` [Answer] # [Scala](https://www.scala-lang.org/), 127 bytes A port of [@l4m2's Python answer](https://codegolf.stackexchange.com/a/268831/110802) in Scala. 127 bytes, it can be golfed more. --- Golfed version. [Attempt This Online!](https://ato.pxeger.com/run?1=NY6xTsMwEIb3PMVtsUWZWNAVV0KZQAGGwkIUIRPs2sg1le2iRlHFg7BkgY0H4m3wpcXD95_P_u_-z-_YSSfPxp-351fVJbiR1sPwtU369Pz3I_UbBXVTtaK2MWUtXpQG3VQXWBkZWrZDep31k4hb63iuqG7FDtYydWboZFRgED1iEgvNSLPhxHBE1Mwcr57Pp59PYkG7WM_n-_8YALR2naMxGVYR4TIE2TfLFKxftRzhwdsEAoYC8nmXDoKKW0ctzaZp5V05g_Ke8EhYEmrCNeGq5HzybvLE5Dw7-Km3L44xxvGgfw) ``` type L[C]=List[C] def f[C<:Char](x:L[C],y:L[C]=Nil):L[L[C]]=x match{case h::n::t=>f(n::t,y:+h):::f(h::t,y:+n);case _=>List(y);} ``` Ungolfed version. [Attempt This Online!](https://ato.pxeger.com/run?1=TVDBSgMxEMVrv-LdNsH25EUCFcST0qJQvViKjNtsN5JGyaayi_RLvPSiH-XXmEm2dC8vzHuZN2_m-7cpydLF4fCzC9Xk8u_s4f31TZcBczIOXyNgrStUolWYmSYsb2ryqzG6YYlpKoSUPXuSWGuxpVDWyQwoqdGoNa2hFJxuA7-BjMX0Ks4ZMnEM1Hn6LCOnonxsHMjcIU_WL-yT4nTM7kf9Ctu4jyC_aRSuvaduuQjeuM0qZn5yJsScOd8nWXjd7CxTlUhOxX0xRvHI8MywYJgx3DHcFjIH-IiOwTqR-_P4fT5sf9_jnf8B) ``` object Main { def f(x: List[Char], y: List[Char] = List()): List[List[Char]] = x match { case head :: next :: tail => f(next :: tail, y :+ head) ::: f(head :: tail, y :+ next) case _ => List(y) } def main(args: Array[String]): Unit = { val result = f(List('O', 'T', 'Z', 'S', 'L', 'J', 'I')) println(result) } } ``` [Answer] # [APL(Dyalog Unicode)](https://dyalog.com), ~~33,32,31,29,~~26 bytes [SBCS](https://github.com/abrudz/SBCS) ``` (,⍳6⍴2){1↓¯1∘⌽@(⍸1,⍺)⊢⍵}¨⊂ ``` [Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=e9Q31dP/UdsEAwA&c=09B51LvZ7FHvFiPNasNHbZMPrTd81DHjUc9eB41HvTsMgbK7NB91LXrUu7X20IpHXU0A&f=S1MP8Y8K9vHyVAcA&i=AwA&r=tryapl&l=apl-dyalog-extended&m=train&n=f) A tacit function which takes a string on the right in the order of held piece, current piece, queue. ## Old Explanation (essentially the same) ``` (⍳64){1↓¯1∘⌽@(⍸~(7⍴2)⊤⍺)⊢⍵}¨⊂­⁡​‎‎⁡⁠⁢⁤⁡‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁢⁢‏⁠‎⁡⁠⁢⁣⁣‏⁠‎⁡⁠⁢⁣⁤‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁡‏⁠‎⁡⁠⁢‏⁠‎⁡⁠⁣‏⁠‎⁡⁠⁤‏⁠‎⁡⁠⁢⁡‏⁠‎⁡⁠⁢⁢⁣‏‏​⁡⁠⁡‌⁤​‎⁠‎⁡⁠⁢⁡⁢‏⁠‎⁡⁠⁢⁡⁣‏⁠‎⁡⁠⁢⁡⁤‏⁠‏​⁡⁠⁡‌⁢⁡​‎‎⁡⁠⁢⁡⁡‏⁠‎⁡⁠⁢⁡⁢‏⁠‎⁡⁠⁢⁡⁣‏⁠‎⁡⁠⁢⁡⁤‏⁠‎⁡⁠⁢⁢⁡‏⁠‎⁡⁠⁢⁢⁢‏‏​⁡⁠⁡‌⁢⁢​‎‎⁡⁠⁤⁤‏‏​⁡⁠⁡‌⁢⁣​‎‎⁡⁠⁤⁣‏‏​⁡⁠⁡‌⁢⁤​‎‎⁡⁠⁤⁢‏⁠‎⁡⁠⁤⁣‏⁠‎⁡⁠⁤⁤‏⁠‎⁡⁠⁢⁡⁡‏⁠‎⁡⁠⁢⁡⁢‏⁠‎⁡⁠⁢⁡⁣‏⁠‎⁡⁠⁢⁡⁤‏⁠‎⁡⁠⁢⁢⁡‏⁠‎⁡⁠⁢⁢⁢‏⁠‎⁡⁠⁢⁢⁣‏⁠‎⁡⁠⁢⁢⁤‏‏​⁡⁠⁡‌⁣⁡​‎‎⁡⁠⁤⁡‏⁠‎⁡⁠⁢⁣⁡‏⁠‎⁡⁠⁢⁣⁢‏‏​⁡⁠⁡‌⁣⁢​‎‎⁡⁠⁣⁡‏⁠‎⁡⁠⁣⁢‏⁠‎⁡⁠⁣⁣‏⁠‎⁡⁠⁣⁤‏‏​⁡⁠⁡‌⁣⁣​‎‎⁡⁠⁢⁣‏⁠‎⁡⁠⁢⁤‏‏​⁡⁠⁡‌­ ⊂ # ‎⁡put the input in an array # ‎⁡ so the 'each' doesn't apply to it { }¨ # ‎⁢apply this dfn for each... (⍳64) ⍺ # ‎⁣ number between 0 and 63 7⍴2 # ‎⁤2 2 2 2 2 2 2 so we can... (7⍴2)⊤ # convert 7 binary digits ~ # ‎⁢⁢bitwise not ⍸ # ‎⁢⁣indices of 1s (⍸~(7⍴2)⊤⍺) # ‎⁢⁤all combinations of 0-6 that have a 0 @ ⊢⍵ # ‎⁣⁡at those indices of the input... ¯1∘⌽ # ‎⁣⁢ shift the letters left by 1 1↓ # ‎⁣⁣then drop the first letter 💎 ``` Created with the help of [Luminespire](https://vyxal.github.io/Luminespire). This works without recursion because we can take the composition of swaps (holding a piece) and get $$(0~d)(0~c)(0~b)(0~a) = (0~a~b~c~d)$$ in permutation notation. So we take all possible selections of places to hold, add a 0 to each, and permute the input using `¯1∘⌽@`, rotating the selected indices by 1. [Answer] # x86-64 machine code, 23 bytes ``` B6 40 56 88 F2 A8 AA AC D0 EA 73 FA A4 75 F9 5E FE C6 71 EE 88 17 C3 ``` [Try it online!](https://tio.run/##VZJRT9swFIWffX/FJVMlpw1VgQpNdEVCexpimjR4QCs8pLaTuHJtK3YhHeKvL7tJ2mm8OPK5n885kS1OSyHaNg9b5Pgz4TAtjVvnBgsoroBt3QvKKsPLOdTKqzyS5nehwjrow9RkRACbrvdR4ay5@QzhVUdRERmiC2tgxkn6WNVEr5VQ3aCq@4NnwDZW4HCg9@v4jf2N/2jKc36I04R2URvrcGgzVFjVUj9TCwOsVhHSBNMFvDgtseCiymsc1yrsTMxQOBsiDlogCD6Rp9lJhV9ClNpNq@sPUq1t2WmgbcRtri1P4Q1YbzB4rs5m53MKH3tcHqQFsIIfE5OHH7/u726/JZTGXittFPKxT4Exj5MlekqIBU9G4ckmGfqOOmpP9nsuKm0V1ZbqqnfoejSUNMtwT1vp8O2I42h2/kge@yXnOxt0aZXsf3WcFumqmUye08U7Hirs8YRMmq8X/wciH2nsrjGkfZuGhu9t@0cUJi9De7q9nNNCT2VJvDJ/AQ "C (gcc) – Try It Online") Following the standard calling convention for Unix-like systems (from the System V AMD64 ABI), this takes: * in RDI, an address at which to place the result, as multiple null-terminated byte strings run together, terminated with an empty string; * in RSI, the address of the input, as a null-terminated byte string. In assembly: ``` f: mov dh, 64 # Set DH to 64. # (This value will run from 64 to 127. The bottom six bits indicate # when to switch the hold piece in, covering all possibilities. # The top two bits are always 01.) repeat: push rsi # Save the value of RSI onto the stack. mov dl, dh # Set DL to the value of DH. .byte 0xA8 # Absorbs the next instruction into "test al, 0xAA". switch: stosb # Write AL to the output string, advancing the pointer. lodsb # Read from the input string into AL, advancing the pointer. nextpiece: # (AL will store the currently held piece.) shr dl, 1 # Shift DL right by 1 bit. The bit shifted out goes into CF. jnc switch # Jump if CF=0. movsb # Add a byte from the input string to the output string, # advancing both pointers. jnz nextpiece # Jump if the last calculated value (DL) is nonzero. pop rsi # Restore the value of RSI from the stack. inc dh # Add 1 to DH. jno repeat # Jump back, except when DH overflows from 127 to -128. mov [rdi], dl # Add a null byte from DL to the output string. ret # Return. ``` ]
[Question] [ Your task is to convert non-empty strings - between strings using the 26 letters, and programs, which are strings of bytes, where each byte has 256 possible values. You should use the same codepage your answer is written in for the possible values of bytes. You need to do the following to do the conversion: * Convert the letters to numbers `1-26`. * Treat it as a base 26 [bijective numeration](https://en.wikipedia.org/wiki/Bijective_numeration) number to convert it to a positive integer. * Convert it to base 256 using `1-256`, again using bijective numeration. * Turn it to bytes, where `i` turns to the byte with value `i-1`. For example, for the string `hello`, you start with converting it to `[8, 5, 12, 12, 15]`, then you evaluate \$15 + 12\cdot26 + 12\cdot26^2 + 5\cdot26^3 + 8\cdot26^4 = 3752127\$. Then you convert \$3752127 = 191 + 64\cdot256 + 57\cdot256^2\$, so the answer is `[56, 63, 190]`. **However**, you dislike gibberish. You want your code to be a concatenation of English words. You can't do that directly in your code, so instead you'll do that in its base26 representation. ## Rules * Your code, when converted to base 26 using bijective numeration, has to be a concatenation of English words from [this wordlist](https://github.com/first20hours/google-10000-english/blob/d0736d492489198e4f9d650c7ab4143bc14c1e9e/google-10000-english-no-swears.txt), with 1 or 2 letter words removed, except for `a, i, of, to, in, is, on, by, it, or, be, at, as, an, we, us, if, my, do, no, he, up, so, pm, am, me, go, ok, hi`. * You can choose whether you want your input to have lowercase or uppercase letters, but it has to be consistent. * Your input has to be a string, an array of characters or an array of bytes - you can't take an array of numbers from `1` to `26`, for example. * Your output has to be a string, an array of characters, an array of bytes, or an array of numbers from `0` to `255`. * [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are disallowed. * If your language uses a base which isn't 256 then use that base, as long as it isn't a power of 26. If it is that language can't compete. ## Test cases ``` input string -> array of bytes hi -> [216] iw -> [0, 0] sr -> [0, 255] cat -> [7, 25] crxq -> [255, 0] cshl -> [255, 255] cshm -> [0, 0, 0] hello -> [56, 63, 190] helloworld -> [39, 138, 176, 111, 2, 107] apple -> [10, 110, 12] loremipsumdolorsitamet -> [81, 108, 15, 236, 169, 234, 61, 72, 24, 166, 102, 147, 49] ``` ## Scoring Your score is the length of your program, encoded in base 26. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in each language wins. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), score 23 The bijective base \$26\$ program as words: ``` yrs seo dts i am a be in cpu sap ``` The Jelly code: ``` ÑÞ²¶O_96ḅ26ḃ⁹’ ``` **[Try it online!](https://tio.run/##y0rNyan8///wxMPzDm06tM0/3tLs4Y5WIyDR/Khx56OGmf///1fKACrKVwIA "Jelly – Try It Online")** Raw bytes as integers \$[1,256]\$: ``` [17, 21, 131, 128, 80, 96, 58, 55, 213, 51, 55, 232, 138, 254] ``` Converted from base \$256\$: ``` 346505452333233856289746614520574 ``` Converted to bijective base 26: ``` [25, 18, 19, 19, 5, 15, 4, 20, 19, 9, 1, 13, 1, 2, 5, 9, 14, 3, 16, 21, 19, 1, 16] ``` As characters, and then with spaces added to show the dictionary words used: ``` yrsseodtsiamabeincpusap yrs seo dts i am a be in cpu sap ``` See [this process](https://tio.run/##y0rNyan8/z/T4VHTmsMzvB7ubFF4uKP1UeNOCKvZyAzM2N19eEYiiBVtomOuY2igY2ioY2isY2iiY2imY2ihY2QYe3Tyw53TvP///690eOLheYc2HdrmH29pBjQMaMSOZqCJjxpmKgEA) starting with the Jelly code. ### How? The first part, up to the `¶` is filler to ensure we get a valid intermediate string, the `¶` is equivalent to a newline and separates Links, and execution of Jelly programs start at the final Link. Since the final Link (`O_96ḅ26ḃ⁹’`) is not calling the previous one (`ÑÞ²`) and the full program parses without error, the final Link is called with an input of the input string as a list of characters: ``` O_96ḅ26ḃ⁹’ - Link: list of characters O - ordinals _96 - subtract 96 from each ḅ26 - convert from base 26 ḃ⁹ - convert to bijective base 256 ’ - decrement each ``` --- I also tried these suffixes (some will only work with upper case input): ``` ¶O%32ḅ26ḃ⁹’ ¶O%48ḅ26ḃ⁹’ ¶O%64ḅ26ḃ⁹’ ¶O_64ḅ26ḃ⁹’ ¶Oạ64ḅ26ḃ⁹’ ¶Oạ96ḅ26ḃ⁹’ ``` There are many more that could be tried (like using unused code-page entires like `q` to create a new Link, or making a single Link that has some sort of no-op at the start etc.), so there may be terser out there. ]
[Question] [ I have a coding problem that goes like this: > > Given a positive integer \$N\$, return a list of all possible pairs of positive integers \$(x,y)\$ such that $$\frac1x+\frac1y=\frac1N$$ > > > I already solved the problem using Python, but I was wondering how I can code golf it. The following is my attempt at golfing (I try to follow some tips on the tips page): 108 bytes ``` exec("f=lambda N:[b for i in range(1,N+1)if N*N%i==0"+"for b in[%s,%s[::-1]]][:-1]"%(("[N+i,N+N*N//i]",)*2)) ``` [Try it online!](https://tio.run/##TYtBCgIhFED3nUIEQUdjxoYiBK/gBcSFltaHcsSZRZ3enF2r9xbvle/2XPJ8LbW1@Ik3ipN@@Xe4e2SUDSgtFQGCjKrPj0ilMFwySMgMhoDWE@Z4T0JPLFkFWa1SR@mcszswoRRbw6Fv/RhHcFiw4cTYoVTIG030/OfzZWKstR8 "Python 3.8 (pre-release) – Try It Online") Ungolfed code for better readability ``` def f(N): l=[] for i in range(1,N+1): if N*N%i==0: a=[N+i,N+N*N//i] l.extend([a,a[::-1]]) return l[:-1] ``` [Try it online!](https://tio.run/##PclBCsMgEIXhvaeYTcFp0iYSGorgFbyAuBCi7YAYEQvt6W2E0t17358/9bmn5Z5La5sPELhGySAqYxmEvQABJSguPTwXox5Er0AB9FmfSKm5X3DK6IGOfOg0ke0Wr/5dfdq4caMzUl6Etcig@PoqCaLpwFgulCoP/Ib42/i3ZZ0RW/sC "Python 3.8 (pre-release) – Try It Online") [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 60 bytes ``` f=lambda N:[[N+i,N+N*N//i]for i in range(1,N*N+1)if 1>N*N%i] ``` [Try it online!](https://tio.run/##K6gsycjPM7YoKPr/P802JzE3KSVRwc8qOtpPO1PHT9tPy09fPzM2Lb9IIVMhM0@hKDEvPVXDUAcorm2omZmmYGgHZKpmxv4vKMrMK9FI0zDV1OSCsY3NDDQ1/wMA "Python 3.8 (pre-release) – Try It Online") No need for reversing: We just generate every fraction for which the first denominator is a divisor of N squared. [Answer] As AnttiP has pointed out, this can be shorter with a change of approach and full rewrite. Let's look at some simpler manipulations of your original code though just for the sake of it though: Here was my first attempt at eliminating the `exec` hack: ### 85 bytes ``` lambda N:[b for i in range(1,N+1)if N*N%i==0for b in[A:=[N+i,N+N*N//i],A[::-1]]][:-1] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3Q3MSc5NSEhX8rKKTFNLyixQyFTLzFIoS89JTNQx1_LQNNTPTFPy0_FQzbW0NQPJJQPloRyvbaD_tTKA8UEpfPzNWxzHaykrXMDY2NhpEQQzfWVCUmVeikaZhqqnJBWMbmxloakLkFyyA0AA) Unfortunately, as you may notice, it doesn't work, because `:=` is not allowed in `for` comprehension iterable expression. There's another place we can put it in though: the `if` clause just before it: ### 91 bytes ``` lambda N:[b for i in range(1,N+1)if(A:=[N+i,N+N*N//i])and N*N%i==0for b in[A,A[::-1]]][:-1] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3o3MSc5NSEhX8rKKTFNLyixQyFTLzFIoS89JTNQx1_LQNNTPTNBytbKP9tDOBXD8tP339zFjNxLwUBSBbNdPW1gCkKwmoK9pRxzHaykrXMDY2NhpEQazYWVCUmVeikaZhqqnJBWMbmxloakLkFyyA0AA) This can be shortened a bit by combining the comparison `==0`: ### 89 bytes ``` lambda N:[b for i in range(1,N+1)if 0in(A:=[N+i,N+N*N//i],N*N%i)for b in[A,A[::-1]]][:-1] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3I3MSc5NSEhX8rKKTFNLyixQyFTLzFIoS89JTNQx1_LQNNTPTFAwy8zQcrWyj_bQzgUJ-Wn76-pmxOkBaNVMTpCcJqCfaUccx2spK1zA2NjYaREEs2FlQlJlXopGmYaqpyQVjG5sZaGpC5BcsgNAA) The `[:-1]` at the end is just to remove the final duplicated result of `(x, x)`, but we can remove this just by switching to a set comprehension (and using a tuple instead of a list, because it's hashable): ### 84 bytes ``` lambda N:{b for i in range(1,N+1)if 0in(A:=(N+i,N+N*N//i),N*N%i)for b in[A,A[::-1]]} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3Q3ISc5NSEhX8rKqTFNLyixQyFTLzFIoS89JTNQx1_LQNNTPTFAwy8zQcrWw1_LQzgUJ-Wn76-pmaOkBaNVMTpCcJqCfaUccx2spK1zA2thZi9s6Cosy8Eo00DVNNTS4Y29jMQFMTIr9gAYQGAA) The output is no longer in order, so hopefully that doesn't matter here. I'm working on going further than this... stay tuned ]
[Question] [ Given a map from arrays of integers of same size to single integers, determine if there is a set of indices such that the output is equal to the maximum of the elements at those indices for every corresponding pair. You can take the input as a map if your language support, arrays of pairs, separated 2D array of input and its output, or other reasonable format. Shortest code wins. ## Test cases ``` input => output input => output -> truthy/falsey [1,2,3] => 2 [2,1,3] => 2 [3,2,1] => 3 -> true (maximum of pos 1 and pos 2) [1,2,3] => 2 [2,3,1] => 2 [3,3,2] => 2 -> false (Whatever positions chosen, 3 must at least appeared in output) [1,2,3] => 2 -> true (maximum of pos 2, or maximum of pos 1 and 2) [1,2,3] => 0 -> false (no way maximum of some of 1, 2 and 3 result in 0) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes ``` ZŒPZ€Ṁ€€i ``` [Try it online!](https://tio.run/##y0rNyan8/z/q6KSAqEdNax7ubACSQJT5//BypaOTHu6cAeRE/v8fHW2oY6RjHKsTbaRjCKaNgXzD2FgdBWQpY6AQSAoogiyFzPwPVAZWrgBmGIEZIMIgFgA "Jelly – Try It Online") Outputs `0` for falsey, non-zero for truthy -3 bytes thanks to [hyper-neutrino](https://codegolf.stackexchange.com/users/68942/hyper-neutrino)! ## How it works ``` ZŒPZ€Ṁ€€i - Main link. Takes a list of inputs I on the left and outputs O on the right Z - Transpose I ŒP - Powerset of the columns Z€ - Transpose each € - Over each column powerset: Ṁ€ - Get the maximum of each column i - Index of O in this list of lists, or 0 if not found ``` [Answer] # JavaScript (ES6), 70 bytes Returns `false` for valid, or `true` for invalid. ``` a=>a.some(b=([a,m])=>a.every((v,i)=>v-m|b[i],a.map((v,i)=>b[i]|=v>m))) ``` [Try it online!](https://tio.run/##jY9BDoIwFET3XoQ2KUSo27r0BO6@XRQsiqGUUGxCwt1ra4BoIsTd/DeZzvQhrDBFV7V93OirdCVzgh1FYrSSKGcIBFEcByKt7AaELKn8aWM15lBxIhIl2pkGMjJ7VBhjV@jG6Fomtb6hCM7ds78PPMK7T14iAEhJRignGScAGUkXTT1PuT853kr9drmPBufLii4NnERt/tlBQ/e0gwax0jStXNbP2quN1NS133QPq397v@pe "JavaScript (Node.js) – Try It Online") [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 28 bytes ``` Times@@Max/@(Sign[#-#2])& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7PyQzN7XYwcE3sULfQSM4Mz0vWllX2Sj2fX@7ptr/gKLMvBKggF2ag4NyrFpdcHJiXl01V3V1taGOkY5xrQ6XgkK1kY4hjGkMFDWsBbGBoiAFQCa6YmOgCqhioHKEYiMUxRBhTCEDTCGT2lqu2v8A "Wolfram Language (Mathematica) – Try It Online") Input `[inputs, outputs]`. Returns `0` for truthy, and nonzero (`1` or `-1`) otherwise. ``` Sign[#-#2] categorize indices for each i/o (-1 <, 0 =, 1 >) Max/@( ) take max for each index across i/o s Times@@ 0 present (solutions exist)? ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 7 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` øæʒø€àQ ``` Port of [*@cairdCoinheringaahing*'s Jelly answer](https://codegolf.stackexchange.com/a/235348/52210), so make sure to upvote him! Outputs an empty list `[]` as falsey, and a non-empty list (containing one or multiple matrices of integers) as truthy. [Try it online](https://tio.run/##yy9OTMpM/f//8I7Dy05NOrzjUdOawwsC//@PjjbUMdIxjtWJNtIxBNPGQL5hbCwXUAAkAQA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9WmRDqYq@kkJiXoqBkHwFkPWqbBGT9P7zj8LJTkw7veNS05vCCiMD/tS726UcalNISc4pTKxVKikpLMiqVlIsPr1BS0Di8X1NJ5380EBjqGOkYx@pEG@kYgmljIN8wNlZHASgCkgGyFFCUGQOlQcqACuHKjFCVgYUxhQxiY2MB). **Explanation:** ``` ø # Zip/transpose the (implicit) first input-matrix, swapping rows/columns æ # Get the powerset of these columns ʒ # Filter this list of matrices by: ø # Zip/transpose the current matrix, swapping rows/columns € # For each inner list: à # Pop and leave the maximum Q # Check if this list is equal to the (implicit) second input-list # (after which the filtered list of matrices is output implicitly as result) ``` ]
[Question] [ **Challenge**: Given an expressions made of additions and multiplications, output an expression that is a sum of products. The output must be equivalent to the input modulo the law of distribution. For example, \$1 + ((2 + 5\times 6) \times(3+4))\$ becomes \$1 + 2 \times 3 + 2 \times 4 + 5\times6\times3 + 5 \times 6 \times 4 \$. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). This task is useful in automatic theorem proving, since the conversion to *[disjunctive normal forms](http://mathworld.wolfram.com/DisjunctiveNormalForm.html)* is exactly the same task. (Oops, that gives away a Mathematica builtin!) **Clarifications**: * You can assume the numbers are whatever you want, integers, floats, or even just strings of symbols, as long as it's convenient. * You can use the law of distribution, commutativity and associativity of addition and multiplication. But you cannot use any other property of addition or multiplication. So e.g. \$3 \times (1 + 3) \to 3 + 3 \times 3\$ is not acceptable. * This means that answers are not unique, the test cases are just a reference. * Parentheses are optional, you won't need them anyway. * You can assume any reasonable input form. **Test cases**: ``` 2 -> 2 (Corner case, you can ignore this.) 1+3 -> 1+3 1+(3*4) -> 1+3*4 1+3*4 -> 1+3*4 (1+3)*4 -> 1*4+3*4 (1+2+3)*(4+5+6) -> 1*4+2*4+3*4+1*5+2*5+3*5+1*6+2*6+3*6 (1+2*(3+4))*((5+6)*7)+8 -> 1*5*7+1*6*7+2*3*5*7+2*3*6*7+2*4*5*7+2*4*6*7+8 ``` [Answer] # [Haskell](https://www.haskell.org/), 139 bytes ``` data M=I Int|M:*M|M:+M deriving(Show,Read) f(x:*y)|z:+w<-f y=f(x:*z):+f(x:*w)|z:+w<-f x=f(z:*y):+f(w:*y) f(x:+y)=f x:+f y f x=x show.f.read ``` [Try it online!](https://tio.run/##RY3NCsIwEITvfYqleEgaLai3YB4gh1z0CQLpT7CmkhbTlL573BTBy84w3yzT6@nZDENKRs8alJAg3bwpXik8TIFpvP1Y15FHP4bjvdGGFi1ZeBXptnIWbqcWotiTlXK2m/BHC6I1lzMK2ezfLFKBEEOIRW4tRScmXKjb2uNGemnrxNtbNx@6UsIFeAVEwvWnZ@AMMKa0TF8 "Haskell – Try It Online") ## IO Format Here our IO format uses the functions `:+` for addition and `:*` for multiplication. We also require that numbers themselves are prefixed with `I` , and that all parentheses be explicit. So for example ``` 2 * (3 * (1 + 2)) ``` is ``` I 2 :* (I 3 :* (I 1 :+ I 2)) ``` We uses this format because we are parsing into a native haskell data type defined on the first line. If I could operate on the data type directly the code would be a lot shorter: # [Haskell](https://www.haskell.org/), 107 bytes ``` data M=I Int|M:*M|M:+M f(x:*y)|z:+w<-f y=f(x:*z):+f(x:*w)|z:+w<-f x=f(z:*y):+f(w:*y) f(x:+y)=f x:+f y f x=x ``` [Try it online!](https://tio.run/##RY7BDsIgEETvfMUm9lBKelBvRG5eSOTkFxBLW2KlpkUptX47QqPxsjuZN5udVo5X1XXhVW7gJE3zkI2Cs5Wmkl1v1FEN@qlNA5vyHSppJQjGgRu7CFqIOIhAdT7RwuNlpsQdyho8W50ZU7IK90dTRHMKJ@SSWK@JxyzCaIJHKTWF6vdYmzG2ucRSbe9AIHST2rD7oI3N6ozDDmgBOYf9d2@BEog2xuED "Haskell – Try It Online") Since this gets rid of all the parsing bits and just includes the manipulations. [Answer] # [Python 3](https://docs.python.org/3/), 157 bytes ``` lambda e:"+".join(eval(re.sub("\d","A('\g<0>')",e))) import re class A(list):__mul__=lambda s,x:A(i+"*"+j for i in s for j in x);__add__=lambda s,x:A([*s]+x) ``` ## How it works : We define a new object named `A` with the wanted properties for addition and multiplication. * each digit is stored as a list of string * an expression like `1+2` is converted into `['1', '2']` * an expression like `1*2` is converted into `['1*2']` * the sum is equivalent to the python list addition * the product is a double iteration over the 2 lists Then we let python do the multiplication over addition priority * `re.sub("\d","A('\g<0>')",e)` we convert all the digits in our expression into instances of this object * `"+".join(eval(...))` we evaluate and formate the result [Try it online!](https://tio.run/##XY7bTsMwDIavyVNEvpmdVBO05aBCkfoc6xR1NIVU6UFJhsrTl6UMLrjy58@y/c9f4WMas7Ur69U2w6ltuC5Awr6fzIj6s7Ho9N6fTwh1CwlUuKvfX25fdwSJJiJmhnlygTvN3mzjPa/QGh@oUGo4W6XK61GfLEWFRoIA2fNuctxwM3K/YR9xoWelmrb9v3MQ/igXWoP2wfPywCCFhMGdzLYiUvEDEjOR03Uk8gh4IfrDNDaYy3v5QL9KYCZzumiMVjySfIIjYzFUiKG2pwW7mZ0ZA3YYiNZv "Python 3 – Try It Online") [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 118 bytes ``` {`\(([\d*]+)\) $1 \(([\d*]+)\+([^()]+\))(\*([\d*]+|\([^()]+\))) $1$3+($2$3 ([\d*]+\*)\(([\d*]+)\+([^()]+\)) $1$2+$1($3 ``` [Try it online!](https://tio.run/##bYy9DgIxDIP3PkcGO5nalJ93uRwCCQYWBsQG717a4yQYGCLbX@LcL4/r7dTa8xjAFGedjcEkOf1kw3QAZwsSoSt@xZeOgrhBinha96H8/2LcFpMM8dZKyuZ94Fo5vNaELvxoGQ7VNrblkhVulZ1hIN3R9m8 "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: ``` {` ``` Perform all possible reductions. ``` \(([\d*]+)\) $1 ``` `(a*b*...)` becomes `a*b*...`. ``` \(([\d*]+)\+([^()]+\))(\*([\d*]+|\([^()]+\))) $1$3+($2$3 ``` `(a*b*...+c*d*...+...)*f*g*...` becomes `a*b*...*f*g*...+(c*d*...+...)*f*g*`, where `f*g*...` could instead be `(f*g*...+h*i*...+...)`. ``` ([\d*]+\*)\(([\d*]+)\+([^()]+\)) $1$2+$1($3 ``` `a*b*...*(c*d*...+e*f*...+...)` becomes `a*b*...*c*d*...+a*b*...(e*f*...+...)`. ]
[Question] [ [Gelatin](https://codegolf.stackexchange.com/questions/224491/interpret-gelatin) is a worse version of [Jelly](https://github.com/DennisMitchell/jelly). It is a tacit programming language that always takes a single integer argument and that has 7 (or maybe 16) commands. ## Gelatin Gelatin programs will always match the following regex: ``` ^[+_DSa\d~]*$ ``` i.e. they will only contain `+_DSa0123456789~` characters. The commands in Gelatin are: * Digits return their value (`0` is \$0\$, `1` is \$1\$ etc.) Digits are stand alone, so `10` represents \$1\$ and \$0\$, not \$10\$ * `a` returns the argument passed to the Gelatin program * `D` takes a left argument and returns it minus one (decremented) * `S` takes a left argument and returns it's square * `+` takes a left and a right argument and returns their sum * `_` takes a left and a right argument and returns their difference (subtract the right from the left) * `~` is a special command. It is always preceded by either `+` or `_` and it indicates that the preceding command uses the same argument for both the left and the right. Each command - aside from `~` - in Gelatin has a fixed *arity*, which is the number of arguments it takes. Digits and `a` have an arity of \$0\$ (termed *nilads*), `D` and `S` have an arity of \$1\$ (termed *monads*, [no relation](https://en.wikipedia.org/wiki/Monad_(functional_programming))) and `+` and `_` have an arity of \$2\$ (termed *dyads*) If `+` or `_` is followed by a `~`, however, they become *monads*. This affects how the program is parsed. Tacit languages try to avoid referring to their arguments as much as possible. Instead, they compose the functions in their code so that, when run, the correct output is produced. How the functions are composed depends on their arity. Each program has a "flow-through" value, `v` and an argument `ω`. `v` is initially equal to `ω`. We match the start of the program against one of the following arity patterns (earliest first), update `v` and remove the matched pattern from the start. This continues until the program is empty: * **2, 1**: This is a dyad `d`, followed by a monad `M`. First, we apply the monad to `ω`, yielding `M(ω)`. We then update `v` to be equal to `d(v, M(ω))`. * **2, 0**: This is a dyad `d`, followed by a nilad `N`. We simply update `v` to be `d(v, N)` * **0, 2**: The reverse of the previous pattern, `v` becomes `d(N, v)` * **2**: The first arity is a dyad `d`, and it's not followed by either a monad or a nilad as it would've been matched by the first 2. Therefore, we set `v` to be `d(v, ω)` * **1**: The first arity is a monad `M`. We simply set `v` to be `M(v)` For example, consider the program `+S+~_2_` with an argument `5`. The arities of this are `[2, 1, 1, 2, 0, 2]` (note that `+~` is one arity, `1`). We start with `v = ω = 5`: * The first 2 arities match pattern **2, 1** (`+S`), so we calculate `S(ω) = S(5) = 25`, then calculate `v = v + S(ω) = 5 + 25 = 30` * The next arity matches pattern **1** (`+~`). `+~` means we add the argument to itself, so we double it. Therefore, we apply the monad to `v`, updating it to `v = v + v = 30 + 30 = 60` * The next arity pattern is **2, 0** (`_2`), which just subtracts 2, updating `v` to `v = v - 2 = 60 - 2 = 58` * Finally, the last arity pattern is **2** (`_`), meaning we update `v` to be `v = v - ω = 58 - 5 = 53`. * There are now no more arity patterns to match, so we end the program At the end of the program, Gelatin outputs the value of `v` and terminates. In a more general sense, `+S+~_2_` is a function that, with an argument \$\omega\$, calculates \$2(\omega + \omega^2) - 2 - \omega = 2\omega^2 + \omega - 2\$. However, `S+~+_2` is one byte shorter, which is our goal in this challenge. --- Given an integer \$n\$ and a target integer \$m\$, you should output a valid Gelatin program that takes \$n\$ as input and outputs \$m\$. A valid Gelatin program is one where the arities always follow the five patterns above (so not `S1S`, or `123`, etc.), and one that matches the described regex above. However, this is not a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge. Instead, your program will be scored on how short the generated Gelatin programs are for a set of 20 randomly generated inputs where \$-9999 \le n \le 9999\$. The shortest combined length wins. I will be testing the submissions in order to get a final score. If your program times out on TIO for \$|n-m| > 500\$, please provide testing instructions. If, for whatever reason, you program fails to produce a correct output for any of the scoring cases, I cannot score your program and it is disqualified. This includes time and memory limitations, so please make your metagolfers somewhat efficient. The MD5 hash of the list of inputs, in the form of a list of newline separated lines like `n m`, is ``` 91e5dd2ab754ce0d96590f8f161e675b ``` You can use the following test cases to test your answer. They have no bearing on your final score. You are under no obligation to golf your generating code. [This](https://tio.run/##y0rNyan8/9/G4OHu7keN@7TjT062dnjUtObQVscUywoHS@uT0/W54g@3u/1/uGPToZ3H2sOAkoeX63M93L3lcDuQHflwZwuQ7ebz/7@CgoK5AggYcSko6FqAmeZcID5cVMEQxNJFEjUEMQ1ALGMDLgVdEzDTzAwkagpSamgKFDWyBCu1AIoamYBEjY25gFywbbpApokhiGlqaMSla2hgCNJlAFRrDNZmZAqywsIMZKy5AQA "Jelly – Try It Online") is a very naïve attempt, that simply adds or subtracts \$9\$ until it's within \$9\$ of the target, where it adds/subtracts the remaining gap. It scores 292 on the test cases, and 3494 on the scoring cases. You should aim to beat this at the very least. ## Test cases ``` n m 7 2 -8 7 2 2 1 -7 2 1 0 30 -40 66 5 -15 -29 18 24 -33 187 -3 417 512 -101 -108 329 251 86 670 ``` [Answer] # [Python 3](https://docs.python.org/3/), score 135 ``` DYAD_MONAD = 0 DYAD_NILAD = 1 NILAD_DYAD = 2 DYAD = 3 MONAD = 4 nilads = { **{str(i): (lambda i: lambda argument: i)(i) for i in range(10)}, "a": lambda argument: argument } monads = { "D": lambda x: x - 1, "S": lambda x: x * x, "+~": lambda x: x + x, "_~": lambda x: 0 } dyads = { "+": lambda x, y: x + y, "_": lambda x, y: x - y } commands = { DYAD_MONAD: { d + m: (lambda D, M: lambda a, x: D(x, M(a)))(D, M) for d, D in dyads.items() for m, M in monads.items()}, DYAD_NILAD: { d + n: (lambda D, N: lambda a, x: D(x, N(a)))(D, N) for d, D in dyads.items() for n, N in nilads.items()}, NILAD_DYAD: { n + d: (lambda D, N: lambda a, x: D(N(a), x))(D, N) for d, D in dyads.items() for n, N in nilads.items()}, DYAD: { d: (lambda D: lambda a, x: D(x, a))(D) for d, D in dyads.items()}, MONAD: { m: (lambda M: lambda a, x: M(x))(M) for m, M in monads.items()} } import heapq def f(n, m): # STATE VECTOR # # [current gelatin program length, current value, current gelatin program, last group type] def update(argument, pq, seen, state_vector, arity_config): length, value, program, last_type = state_vector for key, f in commands[arity_config].items(): newval = f(argument, value) if abs(newval) > 20*abs(n)+abs(m) < abs(newval-n*n): continue if newval in seen: continue seen.add(newval) heapq.heappush(pq, (length + len(key), newval, program + key, arity_config)) initial = (0, n, "", -1) # initially, the program is empty (so has length 0), the value is n, and there was no last group; -1 suffices to avoid breaking the check pq = [initial] # priority queue. we'll use heapq to keep the shortest program at the front so it's *guaranteed* to be an optimal solution seen = set() while True: length, value, program, last_type = sv = heapq.heappop(pq) # get the current shortest program; ties are ordered by value so this has no guarantee to be optimal in speed # print(length, value, program, last_type) # ^ DEBUGGING OUTPUT if value == m: return program if last_type != DYAD: # to prevent issues with 2 | 1 becoming 2,1 and 2 | 0,2 becoming 2,0 | 2, we will not allow 1 ... or 0 2 ... following a dyad update(n, pq, seen, sv, MONAD) update(n, pq, seen, sv, NILAD_DYAD) update(n, pq, seen, sv, DYAD_MONAD) update(n, pq, seen, sv, DYAD_NILAD) update(n, pq, seen, sv, DYAD) score = 0 while True: try: n, m = map(int, input().split()) output = f(n, m) print(output) score += len(output) except: print("FINAL SCORE:", score) break ``` [Try it online!](https://tio.run/##pVZtb@JGEP7M/oop@XA2MciGvJVrKqVHGkW6kOpCKlWnFG3wAqvgXWe9hqDr9a@nM2uMTZq7VOoXvJ63Z@aZ2THp2s616j0/D/44G4yvrodnAziFkLnX4eVH9xoxdxqTEF@7bHPosdLhgDElFzzO8PyFNVqtL5k1nvT74C14ch9zkH3YnLiZ5YlQtg/SRxOYagMSpALD1Ux4Ueh/DVijyZuveJQn9pWxRKstYHNQWT/14QnaEFGQmxfiFjyReP/vF/L9Qj7elYcEE68rlP2aOoB14bl2nv/WtGFN/hOdJFyVISqa@/TaiDFAUrE0COCqKjugJAYeBrzyuO/7Hql91iDG4gAGRJpLryOtSDKv4DJBI9IU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I2nSIWAi9kLUPQjg6Yod48Q9Zu/sjRCesewDtXo9FJ8f4ZAfRMRxGGCAK0TUKT1gPzbqHETs5gqPj8B8 "Python 3 – Try It Online") Basically a rip-off of hyper-neutrino's initial answer, but with a branch cut based on the magnitude of current value: ``` if abs(newval) > 20*abs(n)+abs(m) < abs(newval-n*n): continue ``` First, let's list all the possible one-step operations for Gelatin (no-ops and duplicate operations are ignored): ``` input = x, current = v 2 1: +a +D +S ++~ _a _D _S _+~ v+x v+x-1 v+x^2 v+2x v-x v-x+1 v-x^2 v-2x 2 0: +1 .. +9 _1 .. _9 0 2: 0_ .. 9_ 1 : D S +~ _~ v-1 v^2 2v 0 ``` Now, there are very limited number of operations that can reduce the magnitude of the current number. Assuming `x` is positive, there are `v-d` (where `1<=d<=9`), `v-x`, `v-2x`, and `v-x^2`. Squaring tends to overshoot the numbers significantly, and if it can't get close to the target number by using a small number of these steps, there is no reason to consider that branch. I initially thought that `v-x^2` is useless and it's fine to prune anything that goes over `some_const*abs(n)`, but soon found that `v-x^2` is useful in some special cases like `100 1881` where it can be solved in 5 bytes only by going through a number close to `n^2`: `9+S_S`. If allowing single use of `_S` turns out to be insufficient, I can always extend the condition like ``` if all(abs(newval - n*n*i) > (20-2*i)*abs(n)+abs(m) for i in range(5)): continue ``` at the cost of increased running time and memory usage. I think it won't `MemoryError` for any reasonable constant instead of 5 in `range(5)`. [Answer] # [Python 3](https://docs.python.org/3/), score 238 In order to run without running out of memory, I had to make it somewhat suboptimal :( there's probably a better heuristic for this. ``` DYAD_MONAD = 0 DYAD_NILAD = 1 NILAD_DYAD = 2 DYAD = 3 MONAD = 4 nilads = { **{str(i): (lambda i: lambda argument: i)(i) for i in range(10)}, "a": lambda argument: argument } monads = { "D": lambda x: x - 1, "S": lambda x: x * x, "+~": lambda x: x + x, "_~": lambda x: 0 } dyads = { "+": lambda x, y: x + y, "_": lambda x, y: x - y } commands = { DYAD_MONAD: { d + m: (lambda D, M: lambda a, x: D(x, M(a)))(D, M) for d, D in dyads.items() for m, M in monads.items()}, DYAD_NILAD: { d + n: (lambda D, N: lambda a, x: D(x, N(a)))(D, N) for d, D in dyads.items() for n, N in nilads.items()}, NILAD_DYAD: { n + d: (lambda D, N: lambda a, x: D(N(a), x))(D, N) for d, D in dyads.items() for n, N in nilads.items()}, DYAD: { d: (lambda D: lambda a, x: D(x, a))(D) for d, D in dyads.items()}, MONAD: { m: (lambda M: lambda a, x: M(x))(M) for m, M in monads.items()} } def heuristic(diff, length): return (diff * length ** 3) import heapq # STATE VECTOR # # [heuristic value, current value, desired, current gelatin program, last group type] def update(argument, pq, seen, state_vector, arity_config): _, value, desired, program, last_type = state_vector for key, f in commands[arity_config].items(): newval = f(argument, value) if newval in seen: continue seen.add(newval) heapq.heappush(pq, (heuristic(abs(newval - desired), len(program + key)), newval, desired, program + key, arity_config)) def f(n, m): initial = (heuristic(abs(n - m), 0), n, m, "", -1) # initially, the program is empty (so has length 0), the value is n, and there was no last group; -1 suffices to avoid breaking the check pq = [initial] # priority queue. we'll use heapq to keep the shortest program at the front so it's *guaranteed* to be an optimal solution seen = set() while True: _, value, desired, program, last_type = sv = heapq.heappop(pq) # get the current shortest program; ties are ordered by value so this has no guarantee to be optimal in speed # print(_, value, desired, program, last_type) # ^ DEBUGGING OUTPUT if value == m: return program if last_type != DYAD: # to prevent issues with 2 | 1 becoming 2,1 and 2 | 0,2 becoming 2,0 | 2, we will not allow 1 ... or 0 2 ... following a dyad update(n, pq, seen, sv, MONAD) update(n, pq, seen, sv, NILAD_DYAD) update(n, pq, seen, sv, DYAD_MONAD) update(n, pq, seen, sv, DYAD_NILAD) update(n, pq, seen, sv, DYAD) score = 0 while True: try: n, m = map(int, input().split()) output = f(n, m) print(output) score += len(output) except: print("FINAL SCORE:", score) break ``` [Try it online!](https://tio.run/##rVbdb@I4EH/3XzFHHzZpA0qgX8eqD72lV1Xa0tOWnnSqesglDlhN4tR2oNHe7r/eHTsJCbSr5eF4AGc@f/Ob8YSs0AuRDl5fR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vLy6vxJdzcTf66m7QvTwnm7AzX4lrc2l5VyLZHw8xvZ9Xi3jOgM8mWhgSuVI5FrzhOXB/@gwDLwRtvJqbvBXbgjNj3@m2Fj6K@h0OCjjgmqdCAgy1W6N7r9ZA@8NHNHCNh5MaL2oW/AbvabunGWlt65VvA3cm0eSk29j@zbf5S7Ghrg@9mi1tCzYRk9u8i2Z5fLYvWosS9gGYJzRxudiRPsxwHv6eymONvk0/kGjV2o9rdQzZnqlQ30jL/wZndeW0le5mxTA@33Dt/Xo3PP8Ptp5svF0NcUta9iWYXB3l9PcE/uN1TOCF9PATQNYeA@DDwSffQh@NjcoSb54h0@79DcEr6h9AdDEhweoK/5DA4gaMAAwQ@ugb@KRmgWf8oIKfHcHzi/wA "Python 3 – Try It Online") ]
[Question] [ This is a relatively simple question. I'm trying to golf a Snake game I've written, and I'm trying to work out if there's a way to golf the following conditional assignments which control x and y coordinates of the snake ensuring a wrap around of the play area: ``` if (P<0) { P = T-1; } if (P>T-1) { P = 0; } if (Q<0) { Q = T-1; } if (Q>T-1) { Q = 0; } ``` Is there a simpler way of expressing these, regardless of the value of T? [Answer] Try the following, it ensures `x` to be inside `[0, n]` (say `n = 5`), only when `x > -n` and `x < 2n`. ``` x = (5 + x) % 5 ``` Thanks to [ovs](https://codegolf.stackexchange.com/users/64121/ovs)! [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/V@WmKNgqxCta6SjoGuoo2CgowBkGesomOoomOsoWMT@T87PKy5RSKsAqgJiOwUNUwVthQpNBVUFUy6IZiCpl5tYoJFWoQlWnZ@TqpeTn64BFNf8DwA "JavaScript (Node.js) – Try It Online") --- As mentioned by [xash](https://codegolf.stackexchange.com/users/95594/xash) in the comments, if you want to make it work for any `x`, then do ``` x = ((x % 5) + 5) % 5 ``` [Try it online!](https://tio.run/##JYzNCoMwHMPve4pcBi37V9RN3GV7keGh@DE2Oisq0rfvUj3kRxJIvnazSzt/ptWMvuvjZh0eeJnyJjBFTtRUmYKAke4qqASs74IiKW9i68dlxRC4pZ5QKuCMSuOSQHc6jsnsZyc1BL1vvOsz59@KvY5/ "JavaScript (Node.js) – Try It Online") ]
[Question] [ # Objective Given an Arabic string consisting of ISO/IEC 8859-6 Arabic letters (U+0621–063A, 0640–064A), decode it to Arabic Presentation Forms-B (U+FE70–FEFF). # Behavior of Arabic letters ISO/IEC 8859-6 Arabic letters change their displayed form to letters in Arabic Presentation Forms-B, which are categorized to **isolated**, **initial**, **medial**, or **final** letters. * If a letter is the first letter or follows another letter in isolated or final form: + If it is also the last letter or it lacks an initial form, it is in **isolated** form. + Otherwise, it is in **initial** form. * Otherwise, if the letter is not the last letter, its medial form is available, and the next letter is not `ء`(U+0621), it is in **medial** form. * Otherwise, the letter is in **final** form. * `ـ` (U+0640) is a special case. It doesn't have a presentation form, and always will be mapped to itself. It will be assumed to appear only where a letter in medial form could appear. Note that Arabic letters are written right-to-left. # Mapping [![Arabic letters](https://i.stack.imgur.com/PoGjR.png)](https://i.stack.imgur.com/PoGjR.png) Note that we don't care about ligatures (U+FEF5–FEFC). # Rule If the string contains a letter not within U+0621–063A nor U+0640–064A, the challenge falls in *don't care* situation. # Example The following word: ``` الله (U+0627 U+0644 U+0644 U+0647) ``` is decoded to: ``` ﺍﻟﻠﻪ (U+FE8D U+FEDF U+FEE0 U+FEEA) ``` The following word: ``` تكبر (U+062A U+0643 U+0628 U+0631) ``` is decoded to: ``` تكبر (U+FE97 U+FEDC U+FE92 U+FEAE) ``` The following word: ``` سلـام (U+0633 U+0644 U+0640 U+0627 U+0645) ``` is decoded to: ``` ﺳﻠـﺎﻡ (U+FEB3 U+FEE0 U+0640 U+FE8E U+FEE1) ``` The following word: ``` شيء (U+0634 U+064A U+0621) ``` is decoded to: ``` ﺷﻲﺀ (U+FEB7 U+FEF2 U+FE80) ``` [Answer] # JavaScript (ES6), ~~231 ... 148~~ 146 bytes I/O format: list of code points ``` a=>a.map(t=(c,i)=>c%32?(g=A=>n^c%49?g([x=n%32<26,k*x,x&=454642>>n++*25%54%26,x].map(x=>x&&++k)):A[t=t>1^2*(a[i+1]>1569)]||A[t^=2])(n=k=0)+65151:c) ``` [Try it online!](https://tio.run/##bZBPS8MwGMbv/RShsDVZa1hrW9hmMsbw4ElheCodhKzbuj9paTMpOEFQEfwWnhRvoh@m@zQzXXcZmByS53neN7y/LNgdy3kWp/JMJJNoPyV7RijDa5ZCSSC3YkQob5w7fTgjA0LFmDfcTn8Gg4IIZV84vrVsFVbRJK7n@q5DqTDNluM1PLehsiI8PFUQWjSbprlEqDsIJJHUHjstyILYtENqe34HhdutSsbECREUZEnayPQ927O7HO0nm3UKCIAylqvIAjkChIJ7wBORJ6sIr5JZHQETGF1gqCNHvZM4wBjn9Sy8auaYK9ybJBZyICHCMhnJLBYzaPuVuE3TKBuyPFJRyiYjyTIJXQsYbQMhvFBt0ADq2gMPmhZoAOjlx@5Z7VfdOqiv3VP5WX4f1Y9KHlXFy1H/7t7Kd10LNTxNskvG5zCviSpQqF@JdCOBbh0oaut6I5WnrHpMPM2S9XDOsqGigIpt@h/hMa8Aq3X6I9XsaP8H "JavaScript (Node.js) – Try It Online") ``` a => // a[] = input array a.map(t = (c, i) => // for each code point c at position i in a[]: c % 32 ? // if c is not 0x0640: ( g = A => // g is a recursive function taking a list A[] n ^ c % 49 ? // if we haven't reached the correct character: g( // do a recursive call: [ // build a list describing the existence of: x = n % 32 < 26, // - isolated: if not in range 0x063B-0x0640 k * x, // - final: same as isolated, except for the // first entry which is undefined x &= // - initial: we use a lookup bit-mask 454642 >> n++ // with the following hash formula: * 25 % 54 % 26, // ((n * 25) mod 54) mod 26 x // - medial: same as initial ].map(x => x && ++k) // turn it into a list of indices ) // end of recursive call : // else: A[ // output the relevant entry from A[]: t = // update t: t > 1 ^ 2 * ( // (previous was initial or medial) XOR a[i + 1] > 1569 // 2 * (this is not the last letter ) // and the next letter is not 0x0621) ] || // if A[t] is not defined: A[t ^= 2] // use A[t ^ 2] instead )(n = k = 0) // initial call to g with n = k = 0 + 65151 // add 0xFE7F : // else: c // output c unchanged ) // end of map() ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~110~~ 107 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` 1ƵFLŽ$§R©+ε•7Ö›±ćY¨Γ∊%•ƵBвNåi1‚1ª]˜4ô®¸šIŽ6d-D₂›6*-èRćURviy2èDiyнsë0ëyθDΘIN>èŽ6dQ~i\y1è1ë0]Xs_i¦}н)IŽ6ηDŠkǝ ``` -3 bytes due to looser I/O rules. I/O as a list of code-point integers. [Try it online](https://tio.run/##yy9OTMpM/a/kmVdQWmKlgB0o2Xvacik5JpeUJuYoZIJUKiQWKyTnp6QW5GfmlRRbgZQcbrcNU/pveGyrm8/RvSqHlgcdWql9buujhkXmh6c9ath1aOOR9shDK85NftTRpQoUPbbV6cImv8NLMw0fNcwyPLQq9vQck8NbDq07tOPowsije81SdF0eNTUBNZpp6R5eEXSkPTSoLLPS6PAKl8zKC3uLD682OLy68twOl3MzIv3sDq8A6Qisy4ypNDy8whAoGRtRHJ95aFnthb2aINPObXc5uiD7@Nz/SnphcJ/kl5Zg8YqSPdCv/gipjMSixOSS1KJiK0RwHF6u8//GqpvNN1bc2AgA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9TxqXkmVdQWmKlgB0o2Vfacik5JpeUJuYoZIJUKiQWKyTnp6QW5GfmlRRbgZQcbrcNU/pveGyrm8/RvSqHlgcdWql9buujhkXmh6c9ath1aOOR9shDK85NftTRpQoUPbbV6cImv8NLMw0fNcwyPLQq9vQck8NbDq07tOPowsije81SdF0eNTUBNZpp6R5eEXSkPTSoLLPS6PAKl8zKC3uLD682OLy68twOl3MzIv3sDq8A6Qisy4ypNDy8whAoGRtRHJ95aFnthb2aINPObXc5uiD7@Nz/SnphcJ/kl5Zg8YqSPdCv/gipjMSixOSS1KJiK0RwHF6uw3Vom/3/G8tvtgBhO9eNVTebb6y4sZHrxmYgvwEo3sp1Y8vNrhsLuRCyC4HyNxugPKCijQA). **Explanation:** ``` 1 # Push a 1 (which we'll use later on) ``` We start by creating the lookup table: ``` ƵF # Push compressed integer 116 L # Pop and push a list in the range [1,116] Ž$§ # Push compressed integer 25156 R # Reverse it to 65152 © # Store this value in variable `®` (without popping) + # Add it to each value in the list, to make the range [65153,65268] ε # Map each value to: •7Ö›±ćY¨Γ∊%• # Push compressed integer 35731296019285847629599 ƵB # Push compressed integer 112 в # Convert the larger integer to base-112 as list: # [1,3,5,7,13,19,41,43,45,47,109,111] Nåi # If the map-index is in this list: 1‚1ª # Pair it with a 1, and add a second 1 to this list ]˜ # Close the map and if-statement, and flatten the list of values 4ô # Split it into parts of size 4 ®¸š # Prepend [65152] (from variable `®`) in front of this list ``` Which will now hold the following list: ``` [[65152],[65153,65154,1,1],[65155,65156,1,1],[65157,65158,1,1],[65159,65160,1,1],[65161,65162,65163,65164],[65165,65166,1,1],[65167,65168,65169,65170],[65171,65172,1,1],[65173,65174,65175,65176],[65177,65178,65179,65180],[65181,65182,65183,65184],[65185,65186,65187,65188],[65189,65190,65191,65192],[65193,65194,1,1],[65195,65196,1,1],[65197,65198,1,1],[65199,65200,1,1],[65201,65202,65203,65204],[65205,65206,65207,65208],[65209,65210,65211,65212],[65213,65214,65215,65216],[65217,65218,65219,65220],[65221,65222,65223,65224],[65225,65226,65227,65228],[65229,65230,65231,65232],[65233,65234,65235,65236],[65237,65238,65239,65240],[65241,65242,65243,65244],[65245,65246,65247,65248],[65249,65250,65251,65252],[65253,65254,65255,65256],[65257,65258,65259,65260],[65261,65262,1,1],[65263,65264,1,1],[65265,65266,65267,65268]] ``` Which corresponds to the following table: ``` ISO 8859-6 Isolated Final Initial Medial 1569[0621] 65152[FE80] 1570[0622] 65153[FE81] 65154[FE82] 1[n\a] 1[n\a] 1571[0623] 65155[FE83] 65156[FE84] 1[n\a] 1[n\a] 1572[0624] 65157[FE85] 65158[FE86] 1[n\a] 1[n\a] 1573[0625] 65159[FE87] 65160[FE88] 1[n\a] 1[n\a] 1574[0626] 65161[FE89] 65162[FE8A] 65163[FE8B] 65164[FE8C] 1575[0627] 65165[FE8D] 65166[FE8E] 1[n\a] 1[n\a] 1576[0628] 65167[FE8F] 65168[FE90] 65169[FE91] 65170[FE92] 1577[0629] 65171[FE93] 65172[FE94] 1[n\a] 1[n\a] 1578[062A] 65173[FE95] 65174[FE96] 65175[FE97] 65176[FE98] 1579[062B] 65177[FE99] 65178[FE9A] 65179[FE9B] 65180[FE9C] 1580[062C] 65181[FE9D] 65182[FE9E] 65183[FE9F] 65184[FEA0] 1581[062D] 65185[FEA1] 65186[FEA2] 65187[FEA3] 65188[FEA4] 1582[062E] 65189[FEA5] 65190[FEA6] 65191[FEA7] 65192[FEA8] 1583[062F] 65193[FEA9] 65194[FEAA] 1[n\a] 1[n\a] 1584[0630] 65195[FEAB] 65196[FEAC] 1[n\a] 1[n\a] 1585[0631] 65197[FEAD] 65198[FEAE] 1[n\a] 1[n\a] 1586[0632] 65199[FEAF] 65200[FEB0] 1[n\a] 1[n\a] 1587[0633] 65201[FEB1] 65202[FEB2] 65203[FEB3] 65204[FEB4] 1588[0634] 65205[FEB5] 65206[FEB6] 65207[FEB7] 65208[FEB8] 1589[0635] 65209[FEB9] 65210[FEBA] 65211[FEBB] 65212[FEBC] 1590[0636] 65213[FEBD] 65214[FEBE] 65215[FEBF] 65216[FEC0] 1591[0637] 65217[FEC1] 65218[FEC2] 65219[FEC3] 65220[FEC4] 1592[0638] 65221[FEC5] 65222[FEC6] 65223[FEC7] 65224[FEC8] 1593[0639] 65225[FEC9] 65226[FECA] 65227[FECB] 65228[FECC] 1594[063A] 65229[FECD] 65230[FECE] 65231[FECF] 65232[FED0] 1601[0641] 65233[FED1] 65234[FED2] 65235[FED3] 65236[FED4] 1602[0642] 65237[FED5] 65238[FED6] 65239[FED7] 65240[FED8] 1603[0643] 65241[FED9] 65242[FEDA] 65243[FEDB] 65244[FEDC] 1604[0644] 65245[FEDD] 65246[FEDE] 65247[FEDF] 65248[FEE0] 1605[0645] 65249[FEE1] 65250[FEE2] 65251[FEE3] 65252[FEE4] 1606[0646] 65253[FEE5] 65254[FEE6] 65255[FEE7] 65256[FEE8] 1607[0647] 65257[FEE9] 65258[FEEA] 65259[FEEB] 65260[FEEC] 1608[0648] 65261[FEED] 65262[FEEE] 1[n\a] 1[n\a] 1609[0649] 65263[FEEF] 65264[FEF0] 1[n\a] 1[n\a] 1610[064A] 65265[FEF1] 65266[FEF2] 65267[FEF3] 65268[FEF4] not in the list: 1600[0640] 1600[0640] ``` After that, we'll use the input to get a quartet from this list: ``` I # Push the input-list of codepoint integers Ž6d # Push compressed integer 1569 - # And subtract it from each integer in the list D # Duplicate this list ₂› # Check which are larger than 26 (1 if truthy; 0 if falsey) 6* # Multiply that by 6 (6 if truthy; 0 if falsey) - # And subtract that from the values in the list as well è # Then index it into our list of quartets ``` And now we apply the rules specified in the challenge description on these quartets of `[isolated, final, initial, medial]`. ``` R # Reverse the list ć # Extract the head; pop and push remainder-list and head separated U # Pop the head, and store it in variable `X` # (`X` now holds the last letter) R # Reverse the list back v # Loop `y` over each remaining quartet: i # If the top of the stack is 1 (it's an isolated or final form): # (which is always truthy for the first letter, since we pushed a 1 at the start) y2è # Get the initial form of `y` D # Duplicate it i # If it's 1, thus no initial form is available: yн # Push the isolated form of `y` instead s # And swap so the 1 is at the top for the next iteration ë # Else, thus an initial form is available: 0 # Push a 0 for the next iteration ë # Else (it's an initial or medial form instead): yθ # Get the medial form of `y` DΘ # Duplicate it, and 05AB1E-truthify it (1 if 1; else 0) I # Push the input-list of codepoints again N> # Use the loop-index+1 è # To index into this list for the next letter codepoint Ž6d # Push compressed integer 1569 Q # And check if this next codepoint is equal to it (1 if truthy; 0 if falsey) ~i # If either of the two checks is truthy: \ # Discard the duplicated medial form that's on the stack y1è # Get the final form of `y` 1 # And push a 1 for the next iteration ë # Else (it's a medial, and the next character is NOT `ء` (U+0621)): 0 # Push a 0 for the next iteration ] # Close the loop and all inner if-else statements X # Push the last letter from variable `X` s_i # If we ended with a 0 (thus an isolated or medial form) ¦ # Remove the first item from `X` }н # After the if-statement: pop and push the first item of `X` # (so the isolated form if we ended with an isolated or final form, # or the final form if we ended with an initial or medial form) ) # Wrap all values on the stack into a list I # Push the input-list of codepoints again Ž6η # Push compressed integer 1600 DŠ # Duplicate it, and triple swap (`®`,1600,1600 to 1600,`®`,1600) k # Get the index of 1600 inside the codepoints list (-1 if not present) ǝ # And insert the 1600 at that index in our created list # (which doesn't work on negative indices) # (after which this list of codepoint integers is output implicitly) ``` [See this 05AB1E tip of mine (sections *How to compress large integers?* and *How to compress integer lists?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `ƵF` is `116`; `Ž$§` is `25156`; `•7Ö›±ćY¨Γ∊%•` is `35731296019285847629599`; `ƵB` is `112`; `•7Ö›±ćY¨Γ∊%•ƵBв` is `[1,3,5,7,13,19,41,43,45,47,109,111]`; `Ž6d` is `1569`; or `Ž6η` is `1600`. ]
[Question] [ This is a simple game of getting rid of those damn numbers. You start with the numbers from 1 to 19, written in a grid of 9 by 3: ``` 1 2 3 4 5 6 7 8 9 1 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 ``` You may notice that the number 10 is missing, this because the number zero would be hard to get rid of later on. The two rules are: 1. If you find a pair of two numbers such that (a) they are equal OR (b) they add up to 10, you can eliminate both of them. What is a valid pair? Either, they directly follow each other (ignoring any eliminated numbers, potentially continuing in the next row, but not connecting the last with the first row) when going left-to-right through the rows, or they directly follow each other when going top-to-bottom through the columns (ignoring any eliminated numbers, not continuing in any following columns). Small example: ``` 2 9 1 2 3 4 5 6 ``` Here, we can remove the pair (9, 1) as the sum is ten: ``` 2 x x 2 3 4 5 6 ``` Now we can remove (2, 2) as they are adjacent: ``` x x x x 3 4 5 6 ``` Now, nothing else can be eliminated. 2. If nothing can be eliminated anymore, you will copy all remaining numbers to the bottom and continue. Example. Starting with: ``` 1 2 3 4 5 6 7 8 X X X 1 2 1 3 1 4 1 5 X X X 7 X 8 X X 1 X X X X X X X X X X X X X X X 2 X 4 5 X X 4 X 5 6 X 8 ``` we get: ``` 1 2 3 4 5 6 7 8 X X X 1 2 1 3 1 4 1 5 X X X 7 X 8 X X 1 X X X X X X X X X X X X X X X 2 X 4 5 X X 4 X 5 6 X 8 1 2 3 4 5 6 7 8 1 2 1 3 1 4 1 5 7 8 1 2 4 5 4 5 6 8 ``` You have **won** the game when all numbers are eliminated. The shortest solution in terms of moves (either an elimination or a "copy remainder") wins this challenge. If you can prove your solution to be the shortest possible (for example by doing exhaustive BFS), you get extra points. Tell us about your crazy optimizations you used to make this fit into memory! Showing us your code that you used to get to your solution is highly recommended. Further examples of valid pairs: * ``` 1 X 2 3 4 5 X 6 7 ``` Here, only (4,6) is a valid pair to eliminate, as they add up to ten and are directly adjacent in a column (ignoring all Xs in between). * ``` 1 X X X X X X X 9 ``` The only valid pair is (1, 9), as they are directly adjacent row-wise (ignoring the many eliminated numbers in between). [Answer] # 36 moves This Rust program finds a 36 move solution in half a second. There’s room to make the search faster, but this solution may already be optimal. ### Solution ``` 1 2 3 4 5 6 7 8 9 1 X X 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 1 2 3 4 5 6 7 8 9 1 . . 2 1 3 1 4 1 5 1 6 1 7 1 8 X X X 2 3 4 5 6 7 8 9 X . . 2 1 3 1 4 1 5 1 6 1 7 1 8 . . . 2 3 4 5 6 7 8 X . . . 2 1 3 1 4 X 5 1 6 1 7 1 8 . . . 2 3 4 5 6 7 X . . . . X 1 3 1 4 . 5 1 6 1 7 1 8 . . . 2 3 4 5 6 7 . . . . . . 1 3 1 4 . 5 1 6 1 7 1 8 . . 2 3 4 5 6 7 1 3 1 4 5 1 6 1 7 1 8 . 2 3 4 5 6 7 . . . . . . 1 3 1 4 . 5 1 6 1 7 1 X . . X 3 4 5 6 7 1 3 1 4 5 1 6 1 7 1 8 . 2 3 4 5 6 7 . . . . . . 1 3 1 4 . 5 1 X 1 7 1 . . . . 3 X 5 6 7 1 3 1 4 5 1 6 1 7 1 8 . 2 3 4 5 6 7 . . . . . . 1 3 1 4 . 5 X . X 7 1 . . . . 3 . 5 6 7 1 3 1 4 5 1 6 1 7 1 8 . 2 3 4 5 6 7 . . . . . . 1 3 1 4 . 5 . . . 7 1 . . . . 3 . 5 6 7 X 3 1 4 5 1 6 1 7 X 8 . 2 3 4 5 6 7 . . . . . . 1 3 1 4 . 5 . . . 7 1 . . . . 3 . 5 6 X . X 1 4 5 1 6 1 7 . 8 . 2 3 4 5 6 7 . . . . . . 1 3 1 4 . 5 . . . 7 1 . . . . 3 . 5 6 . . . 1 4 5 1 6 1 7 . 8 2 3 4 5 6 7 1 3 1 4 5 7 1 3 5 6 1 4 5 1 6 1 7 8 . 2 3 4 5 6 7 . . . . . . 1 3 1 4 . 5 . . . 7 1 . . . . 3 . 5 6 . . . 1 4 5 1 6 1 7 . X X 3 4 5 6 7 1 3 1 4 5 7 1 3 5 6 1 4 5 1 6 1 7 8 . 2 3 4 5 6 7 . . . . . . 1 3 1 4 . 5 . . . 7 1 . . . . 3 . 5 6 . . . 1 4 5 1 6 1 X . . . X 4 5 6 7 1 3 1 4 5 7 1 3 5 6 1 4 5 1 6 1 7 8 . 2 3 4 5 6 7 . . . . . . 1 3 1 4 . 5 . . . 7 1 . . . . 3 . 5 6 . . . 1 4 5 1 6 1 . . . . . 4 5 6 7 1 3 1 4 5 7 X 3 5 6 1 4 5 1 6 X 7 8 . 2 3 4 5 6 7 . . . . . . 1 3 1 4 . 5 . . . 7 1 . . . . 3 . 5 6 . . . 1 4 5 1 6 1 . . . . . 4 5 6 7 1 3 1 4 5 X . X 5 6 1 4 5 1 6 . 7 8 . 2 3 4 5 6 7 . . . . . . 1 3 1 4 . 5 . . . 7 1 . . . . 3 . 5 6 . . . 1 4 5 1 6 1 . . . . . 4 5 6 7 1 3 1 4 X . . . X 6 1 4 5 1 6 . 7 8 . 2 3 4 5 6 7 . . . . . . 1 3 1 4 . 5 . . . 7 1 . . . . 3 . 5 6 . . . 1 4 5 1 6 1 . . . . . 4 5 6 7 1 3 1 X . . . . . X 1 4 5 1 6 . 7 8 . 2 3 4 5 6 7 . . . . . . 1 3 1 4 . 5 . . . 7 1 . . . . 3 . 5 6 . . . 1 4 5 1 6 1 . . . . . 4 5 6 7 1 3 X . . . . . . . X 4 5 1 6 . 7 8 . 2 3 4 5 6 7 . . . . . . 1 3 1 4 . 5 . . . 7 1 . . . . 3 . 5 6 . . . 1 4 5 1 6 1 . . . . . X 5 6 7 1 3 . . . . . . . . . 4 5 1 X . 7 8 . 2 3 4 5 6 7 . . . . . . 1 3 1 4 . 5 . . . 7 X . . . . 3 . 5 6 . . . 1 4 5 1 6 1 . . . . . . 5 6 7 X 3 . . . . . . . . . 4 5 1 . . 7 8 . 2 3 4 5 6 7 . . . . . . 1 3 1 4 . 5 . . . X . . . . . X . 5 6 . . . 1 4 5 1 6 1 . . . . . . 5 6 7 . 3 . . . . . . . . . 4 5 1 . . 7 8 . 2 3 4 5 6 7 . . . . . . 1 3 1 4 . X . . . . . . . . . . . X 6 . . . 1 4 5 1 6 1 . . . . . . 5 6 7 . 3 . . . . . . . . . 4 5 1 . . 7 8 . 2 3 4 5 6 7 . . . . . . 1 3 1 X . . . . . . . . . . . . . . X . . . 1 4 5 1 6 1 . . . . . . 5 6 7 . 3 . . . . . . . . . 4 5 1 . . 7 8 . 2 3 4 5 6 7 . . . . . . 1 3 X . . . . . . . . . . . . . . . . . . . X 4 5 1 6 1 . . . . . . 5 6 7 . 3 . . . . . . . . . 4 5 1 . . 7 8 . 2 3 4 5 6 7 . . . . . . 1 3 . . . . . . . . . . . . . . . . . . . . . 4 5 1 6 1 . . . . . . 5 6 X . X . . . . . . . . . 4 5 1 . . 7 8 . 2 3 4 5 6 7 . . . . . . 1 3 . . . . . . . . . . . . . . . . . . . . . 4 5 1 6 1 . . . . . . 5 X . . . . . . . . . . . . X 5 1 . . 7 8 . 2 3 4 5 6 7 . . . . . . 1 3 . . . . . . . . . . . . . . . . . . . . . 4 5 1 6 1 . . . . . . X . . . . . . . . . . . . . . X 1 . . 7 8 . 2 3 4 5 6 7 . . . . . . X 3 . . . . . . . . . . . . . . . . . . . . . 4 5 1 6 X . . . . . . . . . . . . . . . . . . . . . . 1 . . 7 8 . 2 3 4 5 6 X . . . . . . . X . . . . . . . . . . . . . . . . . . . . . 4 5 1 6 . . . . . . . . . . . . . . . . . . . . . . . 1 . . 7 8 . 2 3 4 5 X . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . X 5 1 6 . . . . . . . . . . . . . . . . . . . . . . . 1 . . 7 8 . 2 3 4 X . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . X 1 6 . . . . . . . . . . . . . . . . . . . . . . . 1 . . 7 8 . 2 3 X . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 X . . . . . . . . . . . . . . . . . . . . . . . 1 . . 7 8 . 2 3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . X . . . . . . . . . . . . . . . . . . . . . . . . X . . 7 8 . 2 X . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . X 8 . X . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . X ``` ### Code ``` use std::collections::HashSet; fn start() -> Vec<i32> { (1..10).chain((1..10).flat_map(|i| vec![1, i])).collect() } fn display(solution: &[Option<(usize, usize)>]) { let mut grid = start(); for &step in solution { if let Some((i, j)) = step { grid[i] = 0; grid[j] = 0; } else { grid.extend(&grid.iter().copied().filter(|&n| n != 0).collect::<Vec<_>>()); } for (k, row) in (0..).step_by(9).zip(grid.chunks(9)) { for (l, &n) in (k..).zip(row) { if n != 0 { print!("{} ", n); } else if let Some((i, j)) = step { if l == i || l == j { print!("X "); } else { print!(". "); } } else { print!(". "); } } println!(); } println!(); } println!("{} moves", solution.len()); println!(); } fn search( grid: &mut Vec<i32>, solution: &mut Vec<Option<(usize, usize)>>, best: &mut usize, mut skips: usize, prune: &mut HashSet<(usize, usize)>, ) { let len = grid.len(); if solution.len() >= *best || len >= *best * 2 { return; } let mut pruned = vec![]; (|| { let mut stuck = true; let mut i = !0; let mut m = !0; for j in 0..len { let n = grid[j]; if n != 0 { if m == n || m + n == 10 { if !prune.contains(&(i, j)) { grid[i] = 0; grid[j] = 0; solution.push(Some((i, j))); search(grid, solution, best, skips, prune); solution.pop(); grid[i] = m; grid[j] = n; } if skips == 0 { return; } stuck = false; skips -= 1; prune.insert((i, j)); pruned.push((i, j)) } i = j; m = n; } } if i == !0 { *best = solution.len(); display(solution); return; } for k in 0..9 { i = !0; m = !0; for j in (k..len).step_by(9) { let n = grid[j]; if n != 0 { if m == n || m + n == 10 { if !prune.contains(&(i, j)) { grid[i] = 0; grid[j] = 0; solution.push(Some((i, j))); search(grid, solution, best, skips, prune); solution.pop(); grid[i] = m; grid[j] = n; } if skips == 0 { return; } stuck = false; skips -= 1; prune.insert((i, j)); pruned.push((i, j)) } i = j; m = n; } } } if stuck { grid.extend(&grid.iter().copied().filter(|&n| n != 0).collect::<Vec<_>>()); solution.push(None); search(grid, solution, best, skips, &mut HashSet::new()); solution.pop(); grid.truncate(len); } })(); for m in pruned { prune.remove(&m); } } fn main() { let mut grid = start(); let mut best = 200; for skips in 0.. { println!("skips = {}", skips); search( &mut grid, &mut vec![], &mut best, skips, &mut HashSet::new(), ); } } ``` ]
[Question] [ Given a range and a list thereof, while keeping the existing intervals in the list unchanged, split the additional range into sub-intervals and add them to the list, such that all the ranges in the final list are disjoint and contain all numbers present in the input ranges. The goal is to create an insertInterval(intervals, newInterval) function which returns a new interval list if there are any changes. **Pre-condition:** Interval range is sorted **smallest to larger** [[0, 1], [3, 5]]. **Examples:** Input and output: ``` assert.deepEqual( insertIntervalSec([[1,5],[10,15],[20,25]], [12,27]), [[1,5],[10,15],[15,20],[20,25],[25, 27]] ); assert.deepEqual( insertIntervalSec([[1,5],[10,15],[20,25]], [-3,0]), [[-3,0],[1,5],[10,15],[20,25]] ); assert.deepEqual( insertIntervalSec([[1,5],[10,15],[20,25]], [-3,3]), [[-3,1],[1,5],[10,15],[20,25]] ); assert.deepEqual( insertIntervalSec([[0,5],[10,15],[20,25]], [15,15]), [[0,5],[10,15],[20,25]] ); assert.deepEqual( insertIntervalSec([[0,5],[10,15],[20,25]], [20,21]), [[0,5],[10,15],[20,25]] ); assert.deepEqual( insertIntervalSec([[0,5],[10,15],[20,25]], [26,27]), [[0,5],[10,15],[20,25],[26, 27]] ); assert.deepEqual( insertIntervalSec([[0,5],[10,15],[20,25]], [25,27]), [[0,5],[10,15],[20,25],[25,27]] ); assert.deepEqual(insertIntervalSec([], [25,27]), [[25,27]]); assert.deepEqual(insertIntervalSec([[1,1]], [1,1]), [[1,1]]); assert.deepEqual(insertIntervalSec([[1,1]], [1,3]), [[1, 1], [1, 3]]); assert.deepEqual(insertIntervalSec([[2,2]], [1,3]), [[1, 2], [2, 2], [2, 3]]); ``` All programming languages are welcome. [Answer] # [Japt](https://github.com/ETHproductions/japt), 44 bytes ``` rò íU c ò@Vc øX ©X¥YÃke@V®ròÃc øXîgJõ0ÃcV n ``` [Try it online!](https://ethproductions.github.io/japt/?v=1.4.6&code=cvIK7VUgYyDyQFZjIPhYIKlYpVnDa2VAVq5y8sNjIPhYw65nSvUww2NWIG4=&input=WzEyLDI3XQpbWzEsNV0sWzEwLDE1XSxbMjAsMjVdXQotUQ==) Reworked it, at the cost of 1 byte. Now handles the `[[2,2]],[1,3]` test case [properly](https://ethproductions.github.io/japt/?v=1.4.6&code=cvIK7VUgYyDyQFZjIPhYIKlYpVnDa2VAVq5y8sNjIPhYw65nSvUww2NWIG4=&input=WzEsM10KW1syLDJdXQotUQ==). **Explanation**: ``` rò #Turn the second input into a range íU c #Duplicate each item in that range ò@ ©X¥Yà #Split in the middle of the duplicates that: Vc øX # Appear in the first input k #Remove the segments where: e@ øXà # Every item in the segment is in... V®ròÃc # A range from the first input ® à #For the remaining segments: gJõ0 # Get the first and last items cV #Add those pairs to the first input n #Sort the whole thing ``` **Worked Example**: Input: `[[2,2],[5,7]],[1,8]` Second input as a range: `[1,2,3,4,5,6,7,8]` Duplicate each item: `[1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8]` Numbers that appear in the first input: `[2,5,7]` After splitting: `[[1,1,2],[2,3,3,4,4,5],[5,6,6,7],[7,8,8]]` Numbers within the first input's *ranges*: `[2,5,6,7]` Segments using only those numbers:`[[5,6,6,7]]` Remaining segments after those are removed: `[[1,1,2],[2,3,3,4,4,5],[7,8,8]]` First and last item of each: `[[1,2],[2,5],[7,8]]` Merge with the first input: `[[1,2],[2,5],[7,8],[2,2],[5,7]]` Sort it: `[[1,2],[2,2],[2,5],[5,7],[7,8]]` Which matches the [actual output](https://ethproductions.github.io/japt/?v=1.4.6&code=cvIK7VUgYyDyQFZjIPhYIKlYpVnDa2VAVq5y8sNjIPhYw65nSvUww2NWIG4=&input=WzEsOF0KW1syLDJdLFs1LDddXQotUQ==) of the code [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~34~~ ~~33~~ 30 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ŸεI˜yåiðy)]˜#ʒI€Ÿ˜KgĀ}εнyθ‚}«ê ``` Created a port of [*@KamilDrakari*'s Japt answer](https://codegolf.stackexchange.com/a/178639/52210), in order to fix the new test case `[[2,2]], [1,3]` (which golfed 4 bytes at the same time). So make sure to upvote him as well! [Try it online](https://tio.run/##AU4Asf9vc2FiaWX//8W4zrVJy5x5w6Vpw7B5KV3LnCPKkknigqzFuMucS2fEgH3OtdC9ec644oCafcKrw6r//1sxLDhdCltbMiwyXSxbNSw3XV0) or [verify all test cases](https://tio.run/##yy9OTMpM/W9o4uZ5eEKovZJCYl6KgpK9pwuQ@ahtkgKQ/f/ojnNbI07PqTy8NPPwhkrN2trTc5RPTYp41LTm6I7Tc7zTjzTUntt6YW/luR2PGmbVHlp9eNV/nf/R0YY6prE60YYGOoYg2shAx8g0NpYr2tBIx8gcSOOS1zXWMcAvbQySNsBhuilIALc8iGGIT94M6jpc8qYQeSQm0KWGYKt1DFF4BJyJohfqKWDQIOkF8XSiTXXMIWIWsQA). **Explanation:** ``` Ÿ # Get the ranged list of the first (implicit) input # i.e. [1,8] → [1,2,3,4,5,6,7,8] ε # Map each number `y` to: I˜yåi # If the second input flattened contains the current map-number: # i.e. [[2,2],[5,7]] and `y`=2 → 1 (truthy) ðy # Push a space character, and value `y` again ) # Wrap `y`, space, `y` into a list ] # Close the if-statement and the map # i.e. [1,2,3,4,5,6,7,8] and [[2,2],[5,7]] # → [1,[2," ",2],3,4,[5," ",5],6,[7," ",7],8] ˜ # Flatten the list # i.e. [1,[2," ",2],3,4,[5," ",5],6,[7," ",7],8] # → [1,2," ",2,3,4,5," ",5,6,7," ",7,8] # # Split the list on spaces # i.e. [1,2," ",2,3,4,5," ",5,6,7," ",7,8] → [[1,2],[2,3,4,5],[5,6,7],[7,8]] ʒ } # Filter this list of lists by: I€Ÿ # Push the second input, and create a range of each pair # i.e. [[2,2],[5,7]] → [[2],[5,6,7]] ˜ # Flatten this list of lists # i.e. [[2],[5,6,7]] → [2,5,6,7] K # Remove these numbers from the current filter-list # i.e. [2,3,4,5] and [2,5,6,7] → [3,4] # i.e. [5,6,7] and [2,5,6,7] → [] g # Take the length of this list # i.e. [3,4] → 2 # i.e. [] → 0 Ā # And truthify it (0 remains 0; everything else becomes 1) # i.e. 2 → 1 (truthy) # i.e. 0 → 0 (falsey) # i.e. [[1,2],[2,3,4,5],[5,6,7],[7,8]] and [[2,2],[5,7]] # → [[1,2],[2,3,4,5],[7,8]] ε } # Map each inner list to: н # Take the first value # i.e. [2,3,4,5] → 2 yθ # And the last value # i.e. [2,3,4,5] → 5 ‚ # And pair them together # i.e. 2 and 5 → [2,5] # i.e. [[1,2],[2,3,4,5],[7,8]] → [[1,2],[2,5],[7,8]] « # Merge this list of pairs with the second (implicit) input # i.e. [[2,2],[5,7]] and [[1,2],[2,5],[7,8]] # → [[2,2],[5,7],[1,2],[2,5],[7,8]] ê # Sort the list of pairs, and remove any duplicated pairs at the same time # i.e. [[2,2],[5,7],[1,2],[2,5],[7,8]] # → [[1,2],[2,2],[2,5],[5,7],[7,8]] # (and output the result implicitly) ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~119~~ ~~118~~ 116 bytes ``` lambda l,A,B:sum([[[max(A,b),min(c[0],B)],c][max(A,b)>=min(c[0],B):]for(a,b),c in zip([[A,A]]+l,l+[[B,B]])],[])[:-1] ``` [Try it online!](https://tio.run/##pZLBisIwEIbvPsUcWxwhkxKFQoX2NeIcaqVYaGtxXdB9@e7EtSWuFWX39A/Jl49kJt3ltD@0ui@TTV/nzXaXQ40pZvHHZxNYa5v8HKS4DbGp2qCwijELGQseN9aJtxNzeTgGueMLqFr4qjqRpJgyz2us59ZmmDGLwXJo4wVx3x2r9gSlYIRG1kkhudQKtWFGII16FQIkCfxmyKBWIytpEPSKeTZ7aV1EqAapqx0zRb6nijwVvaNST95qZGFwqT9KXEH/liy9rk8xksvHbj@zmdc2h9zJvHO3kwPjj4SufUN58O2D0DQQjQD8TAiiO1B@2QOo3b3GEL7/Bg "Python 2 – Try It Online") --- If I/O can be flat lists (of even length): # [Python 2](https://docs.python.org/2/), 112 bytes ``` lambda l,A,B:sum([[a]+[max(A,a),min(B,b)]*(max(A,a)<min(B,b))+[b]for a,b in zip(*[iter([A]+l+[B])]*2)],[])[1:-1] ``` [Try it online!](https://tio.run/##nZHdasMwDIXv@xS6tBsV/ENWKMtF8hqeLhy2MEOShiyFbi@f2dRdvaxkbMhgo3M@IUvD@/R67NXcFE9za7v62UKLJVaHt1PHjLGUmc6eWYmWY@d6VmHNacuuucdrjmempuY4gsUaXA8fbmBb46aXkZmSsjYzFXlQcUJD3MjDTtI8jK6foGFGYo5SoMxRCVQ5IUiFas8BigISNRqCJxxQe9psVqrsNIpYJDxx6fgN1jdYrsHiZ/@h2UiLv4Dhlv8CH24TW6jotcWs7vD5Ch@0FE/8FyI6knHKMAX0X7msUN4R9ZfoQycGv/zvBhVD0/wJ "Python 2 – Try It Online") --- # [Python 3](https://docs.python.org/3/), 111 bytes ``` lambda l,A,B:sum([[a]+[max(A,a),min(B,b)]*(max(A,a)<min(B,b))+[b]for a,b in zip(*[iter([A,*l,B])]*2)],[])[1:-1] ``` [Try it online!](https://tio.run/##nZLRaoMwFIbv@xS5TOxfyElwhVIv9DWyXEQ2maBWnIN2L@8Sqqt1xbFxAgnn/79DzknaS/92avRQJM9D5er8xbEKKbLD@0fNjXF2a2p35imcQF02PEMubMSn3HHKia3JbXHqmEPOyoZ9li2PTNm/dtykiCpk1nNKWBgrDB12ZIe2K5ueF9wQYpAExVASKrZgpKD2grEkYTN1NARPWEztrdhsVsrsNORYJRyxdPxK6xtNq7T82UK474jLP5Fhp/@RT7exLVR4bTmwBwXilQJBu@NnwBWZLLOhUhgFfDvXp6RHqv5Wfei5w3@De4caw7uGLw "Python 3 – Try It Online") ]
[Question] [ Here you can see g-code parser, written in JavaScript to use in microcontroller (like espruino). But you can run it in browser, because it don't use any specific features. ``` function gcode(str){ //Removes comment, parses command name and args const [,f,args] = (str.match(/^([GM]\d+) ([^;]+)/) || [,"",""]); //A1.2 B43 C -> {A: 1.2, B: 42, C: 0} eval(f+"({"+args.replace(/(\w)([\d\.]*)/g,"$1: $2+0,")+"})"); } const G1 = console.log; gcode(prompt("crackme")); ``` When you pass `G1 X3 Y4.53 Z42` to `gcode()`, it runs `G1({X: 3, Y: 4.53, Z: 42})`. As you can see, it uses `eval`, protected by regexp. But despite of this, you can attack this function and cause remote code execution. Your goal is to run `alert("pwned")`. This is code golf, so shortest working input wins [![example](https://i.stack.imgur.com/I9thv.png)](https://i.stack.imgur.com/I9thv.png) [Answer] # 112 bytes ``` G1 $:(ƒ=(Τ,$=+[])=>Τ[$]?Τ[$]+ƒ(Τ,++$+'5'[+[]]*(Τ[$]==':')):'')[ƒ('constructor')](ƒ('alert("pwned")'))() ``` ``` function gcode(str){ //Removes comment, parses command name and args const [,f,args] = (str.match(/^([GM]\d+) ([^;]+)/) || [,"",""]); //A1.2 B43 C -> {A: 1.2, B: 42, C: 0} eval(f+"({"+args.replace(/(\w)([\d\.]*)/g,"$1: $2+0,")+"})"); } const G1 = console.log; payload = `G1 $:(ƒ=(Τ,$=+[])=>Τ[$]?Τ[$]+ƒ(Τ,++$+'5'[+[]]*(Τ[$]==':')):'')[ƒ('constructor')](ƒ('alert("pwned")'))()`; gcode(payload); ``` * Each `ƒ` (U+0192), `Τ` (U+03A4) cost 2 bytes, they are not as same as ASCII `f`, `T`. --- The `gcode` function will keep any `/\W/` characters as is. So, we just need to use these characters to write some logic here. The idea is basically based on how JSF\*\*k works. We construct the codes like this: ``` (()=>{})["constructor"]('alert("pwned")') ``` We need string literal `"constructor"` and `alert("pwned")`. But `gcode` convert `"constructor"` to `"c: +0,o: +0,n: +0,....r: +0"`. So we need to convert the string back. We use this function to do the convert: ``` ƒ=(Τ,$=+[])=>Τ[$]?Τ[$]+ƒ(Τ,++$+'5'[+[]]*(Τ[$]==':')):'' ``` `Τ` is the text inputed, $ is index. We first initialize `$` to 0 using `+[]`. Then we output the character at the index position, and check if next character is `":"`, if so we skip the following 5 characters. --- Thanks to l4m2, saves few bytes. ]
[Question] [ A number theory expression contains: ``` There exists at least one non-negative integer (written as E, existential quantifier) All non-negative integers (written as A, universal quantifier) + (addition) * (multiplication) = (equality) >, < (comparison operators) &(and), |(or), !(not) (, ) (for grouping) variable names(all lowercase letters and numbers, not necessary one char long) ``` However, it has some more limitations: * Arithmetic expressions should be syntactically valid. Here we only treat `+` as addition, not positive, so `+` and `*` should be surrounded by two number expressions * brackets should be well paired * `<` `=` `>` should be surrounded by two number expressions * `&` `|` `!` are fed with logical expressions * `E` and `A` are fed with a variable and an expression * For `E` and `A`, there should be a reasonable affected range. (\*) For (\*): We write `Ax Ey y>x & y=x`, `Ax Ey y>x & Ey y=x` as well as `Ax Ey y>x & Ax Ey y=x`, which mean `Ax (Ey ((y>x) & (y=x)))`, `Ax ((Ey (y>x)) & (Ey (y=x)))` and `(Ax (Ey (y>x))) & (Ax (Ey (y=x)))`; however we don't write `Ax Ey Ax x=y` or `Ax Ey x<y & Ex x>y`. That means there should be some way to add brackets, so everywhere any variable is at most defined for once, and anywhere that use the variable has it defined. ## Input You'll be given an expression with these chars (invalid chars won't appear), only split when necessary (two variable names together), split after each quantifier variable, or each symbols are separated. No invalid symbol. ## Output Check whether it's a **valid** number theory expression. Either true/false or multi/one are allowed. ## True samples (each symbol separated) ``` E a E b a < b E b A x b < x & A x b > x E b A x b < x & b > x A b b + b < ( b + b ) * b | E x x < b E x E y y < x & E x2 y = x2 E 1 A x x * 1 = x & E 2 2 * 2 = 2 + 2 & 2 > 1 & E x x + 1 = x * x * 2 E x E y y = y & y + y * y = y ``` ## False samples ``` E a E b a + b < c E a E b b * ( a > a ) + b A a A b ( a = b ) = b A x A y A z A y x < z E x E y y < x & E x y = x E E x x = x E x ( x < x E x = x ``` ## Undefined behavior samples ``` E C C = C AA x x = x Ex = x ``` Shortest code in bytes win Symbol definition: It's a resexpr ``` numexpr({s},∅) = s numexpr(a∪b,c∪d) = numexpr(a,c) + numexpr(b,d) numexpr(a∪b,c∪d) = numexpr(a,c) * numexpr(b,d) numexpr(a,c) = ( numexpr(a,c) ) boolexpr(a∪b,c∪d) = numexpr(a,c) = numexpr(b,d) boolexpr(a∪b,c∪d) = numexpr(a,c) < numexpr(b,d) boolexpr(a∪b,c∪d) = numexpr(a,c) > numexpr(b,d) boolexpr(a∪b,c∪d) = boolexpr(a,c) & boolexpr(b,d) boolexpr(a∪b,c∪d) = boolexpr(a,c) | boolexpr(b,d) boolexpr(a,c) = ! boolexpr(a,c) boolexpr(a,c) = ( boolexpr(a,c) ) boolexpr(a-{s},c∪{s}) = E s boolexpr(a,c) if s∉c boolexpr(a-{s},c∪{s}) = A s boolexpr(a,c) if s∉c resexpr = boolexpr(∅,a) a,b,c,d mean sets, s mean non-empty strings containing a-z0-9 ``` ## Notes * You don't need to check whether the expression is **true**, as it's usually impossible [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~318~~ ~~317~~ 319 bytesSBCS ``` ∨/{(4=⊃⍵)>≢⊃1⌽⍵}¨{1=≢⍵:⍵⋄⊃,/(⊂⍵)∇{⊃,/,(⍺⍺⍵↑⍺)∘.{c←⊃¨⍺⍵⋄w←⊃,/⊃¨u v←1↓¨⍺⍵ (⊂c)∊t←↓10 2⍴⎕A⍳'AOBAJACKANEADMLDJDGK':⊂(2,u)(1w 0)(3,v)(1u 0)(5(⊃u)⍬)(4w⍬)(6,u)(4,v)(7,v)(4,u)⊃⍨t⍳⊂c 6 4≡c:⊂4,u,¨v 9 1≡c:(2⊃v)↑⊂8,v 8 4≡c:(a∊3⊃⍵)↓⊂4(a~⍨⊃v)((3⊃⍵),a←⊃u) ⍬}⍺⍺⍵↓⍺}¨⍳¯1+≢⍵}{⌈/c←(⊃⍵)∊¨¯1⌽'()!',↓4 3⍴' &|=<>+* AE':8+⊃⍸c⋄1(⊂⍵)1}¨' '(≠⊆⊢)⍞ ``` [Try it online!](https://tio.run/##dVJNb9NAED3jX7Fc4nXjkDoxJURxpIVESC0fv8ExKpdKcKgTpyYc2spN3BqBIiROCHryAYlDiYSQuPinzB8pb9ZOCRIomdl5897Mjsf2Xx00nk/9g5cvrml@tg@XN2PpepSeULay@rS4ROjQxS/AWZHHjsepbNWF0fkpSLspKT1mNTrEOmFLyn7q/4qS9whAfbwTB5S8A1/kFXV@OikzdlOnQzEGdihZriUGtw5QnR6yMlk626JF2Xd6@0FRdmWqZw/Urnq4p54O1eDJ48Hu4NGe2UWNbNmhJZ2J2LZk2x4jDDm8i34noUXZV0u6E33ssNBlyT12LqB@@PwQF/Dtxo5wafEl4LZg7SIfG/eFo1OyBe3Y4odMjzv22OhUWulj5na1RczNtdJ/g7a6QMo1Z/vlCkLLwDizjb0tEcx4EVfFN6debn0W08W8yXuU697ztMghwBsypXXbtFHoijZ2ZIraa6/Xr28JNTS7nbou@BFg6876hTnobwpT0uIzpQmll9jMJ/4Qrm/tG0Ph@2IoRnz0xMjQqZFQIoLvwdequC@if5EbRIQ@U/xKArgF4OH4m/ZgNVgdtlVio9FolKJqFpB8QbCZHEEtEfdhFguYVAAKFBMeTot9SUQgprAjfUZod/SfOcsxS5Jh9AdG6MylN/CGkXoMvtX/DQ "APL (Dyalog Unicode) – Try It Online") -1 byte thanks to @Adám. +2 bytes because the code wrongly accepted `E ( a ) a = a`. Fixed by adding a "simple" flag to the Num node, which is 1 right after tokenization but becomes 0 after any kind of merging. `TQuant Num -> Quant` rule is accepted only if "simple" is 1. Full program. Takes a line of input (each symbol separated with a space) from stdin, and prints 1 if it can be parsed successfully, 0 otherwise. ### How it works: the grammar & parsing I manually dissected all the grammar rules into two-branch rules, e.g. the parenthesizing rule ``` "(" Num ")" -> Num ``` became two rules ``` "(" Num -> NumP NumP ")" -> Num ``` with `NumP` being a new node type. Also, I omitted the last part of the `Num` node, as it is always an empty set. ``` (Num ids,?) [+*] -> (NumR ids) (NumR ids) (Num ids2,?) -> (Num (ids+ids2),0) "(" (Num ids,?) -> (NumP ids) (NumP ids) ")" -> (Num ids,0) (Num ids,?) [=<>] -> (BoolN ids,[]) (BoolN ids,ids3) (Num ids2,?) -> (Bool (ids+ids2),ids3) (Bool ids,ids2) [&|] -> (BoolR ids,ids2) (BoolR ids,ids3) (Bool ids2,ids4) -> (Bool (ids+ids2),(ids3+ids4)) "!" (Bool ids,ids2) -> (Bool ids,ids2) "(" (Bool ids,ids2) -> (BoolP ids,ids2) (BoolP ids,ids2) ")" -> (Bool ids,ids2) [EA] (Num id,1) -> (Quant id) (Quant id) (Bool ids,ids2) -> (Bool (ids-id),(ids2+id)) if id not in ids2 ``` Using these rules, I could tackle the ambiguous parsing problem as follows: 1. Split the given list of tokens into two chunks. 2. Recursively get all possible parses for the two chunks. 3. Test all combinations of parses to gather all possible derived parses. 4. Repeat 1-3 for all possible splits, and gather all results. The algorithm is exponential in the number of tokens, so the two longest test cases are excluded from the tests. ### Original version with comments ``` ⍝ Constants to classify the grammar node type Num NumR NumP Bool BoolN BoolR BoolP Quant TQuant TParenL TParenR TNot TBool2 TCmp TNum2←⍳15 ⍝ Split given string by spaces, and convert to a list of grammar nodes tokenize←{ words←(' '∘≠⊆⊢)⍵ ⍝ split by spaces { class←(⊃⍵)∊¨'AE' '(' ')' '!' '&|' '=<>' '+*' ⌈/class: 8+⊃⍸class ⍝ Single-char tokens into respective nodes Num(⊂⍵)1 ⍝ An identifier is a Num node }¨words ⍝ wrap each word into tokens } ⍝ Takes two nodes, and gives a new node if valid, ⍬ otherwise match←{ class←⊃¨⍺⍵ Num TNum2≡class: ⊂NumR(2⊃⍺) NumR Num≡class: ⊂Num((2⊃⍺),2⊃⍵)0 TParenL Num≡class: ⊂NumP(2⊃⍵) NumP TParenR≡class: ⊂Num(2⊃⍺)0 Num TCmp≡class: ⊂BoolN(2⊃⍺)⍬ BoolN Num≡class: ⊂Bool((2⊃⍺),2⊃⍵)⍬ Bool TBool2≡class: ⊂BoolR(2⊃⍺)(3⊃⍺) BoolR Bool≡class: ⊂Bool((2⊃⍺),2⊃⍵)((3⊃⍺),3⊃⍵) TNot Bool≡class: ⊂Bool(2⊃⍵)(3⊃⍵) TParenL Bool≡class: ⊂BoolP(2⊃⍵)(3⊃⍵) BoolP TParenR≡class: ⊂Bool(2⊃⍺)(3⊃⍺) ⍝ Valid only if "simple" flag of Num node is 1 TQuant Num≡class: (3⊃⍵)↑⊂Quant(2⊃⍵) ⍝ Valid only if quantified variable is not already quantified Quant Bool≡class: (~(2⊃⍺)∊3⊃⍵)↑⊂Bool((2⊃⍵)~2⊃⍺)((3⊃⍵),2⊃⍺) ⍬ } ⍝ Given a list of tokens, returns an array of possible parses ⍝ Split in all possible ways and check for at least one split is valid parse←{ ⍝ Single token: no need to parse 1=≢⍵:⍵ splits←⍳¯1+≢⍵ ⍝ Concatenate parses based on all possible splits ⊃,/(⊂⍵)∇{ left←⍺⍺ ⍵↑⍺ right←⍺⍺ ⍵↓⍺ ⍝ Test all possible combinations of left/right parses ⊃,/,left ∘.match right }¨splits } ⍝ Test if one of the parses is Bool with no free variables test←{ ∨/{ Bool≠⊃⍵:0 0=≢2⊃⍵ }¨⍵ } ⍝ The solution is the chain of three functions defined above test∘parse∘tokenize ``` [Try it online!](https://tio.run/##jVbPaxtHFL7vX/Gig7VrybElt1BM5KC6pg2kqWOrhZLmMJJG1pLVrrK7tqQ0yaGBVBF1aCmFXAppevEhkEMJFB/9p@w/4n7vzf6QFAWKGGlm3o/vvW/evJEaehvdifKC46vk5R9H@9e/3fv6i3I7GLv@MQV@OZn9rX3V9vRR83YLCyjtfV@OlBeXrWT6814wGGg/tuw7JwNyu1H1pkP3Kuv3aWOXeO@QNx2rmFKmWWfVVItsbFR406luOVbJLtG8w1TroPBlplRySrkL1t1yFgNp3Ng1kXweBN4d2b53HzrFEmN7RUysMB@UqBm7zKwO/2uPC/eHhcBa3GCAzLLOG5@sBuHpdkXk4OBaiZbxcqMCSaj6iNrBckRzGzl1S/7u7TfvZ3RUa8bX3RPlx1jDSz5dCXo3z2gDKpJPHfk4Drk9qNIPfhC7vtBgWS3jSwBbByrU/m3ibMz8UAJs3QliYiZa7LluCG/tDYbp0bYQaF3qzcqqqBq5g6GnbzqWlJzUii11I8GZkzfHYygRI1NZJiKbM0VpXyVnf9Je4EcxdiOKA@p4Korc3oTivqbjUA0GKiQ/6GqKJ0MtIRSgH4EzGGnyWd5ZzpJvmqukKQkmz39Nzv6pfWpZHNHR0HNjOnZPtU9RHPI1bU8oGqqORh7K71In8E91GHPEijw3iinoLYQbWXHwQPvuIw3XP1pEoyDsRpjbZSon01fJi9fJ7Hkye@MkZ@@JGDUS1BwINmxHhhK2TGbPoOwk09nlebm5D0fszMG4hrH2GF84MnxX1stimfwy3RTrHfqsItb/ytLgHSEvT290@ghZgo3I9ZFQqKOh7sTIPs2EXYEk4P/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APL (Dyalog Unicode) – Try It Online") ]
[Question] [ ## Introduction For a given rational number `r`, find a pair of integers `p,q` so that `p/q=r` and the number of less used bits in `p` and `q` are minimized (details below). ## Challenge A positive rational number `r` can be expressed as the ratio of two positive integers, `r=p/q`. The representation is not unique. For each of these representations, both `p` and `q` can be expressed in its binary form and the number of `0`s and `1`s in the representation can be counted (not including leading zeros). We count the number of appearance of the less appeared digit for both `p` and `q` (denoted `g(p)` and `g(q)`) and finally define `f(p,q)=max(g(p),g(q))`. For example, the number `35` can be written as `35/1` or `175/5`, and we convert both the numerator and the denominator to binary. Then we can count ``` 35 -> 100011, 3 zeros, 3 ones. g(35)=min(3,3)=3 1 -> 1, 0 zero , 1 one. g(1)=min(1,0)=0 f(35,1)=max(g(35),g(1))=3. ``` And for `175/5` ``` 175 -> 10101111. 2 zeros, 6 ones. g(175)=min(2,6)=2 5 -> 101. 1 zero, 2 ones. g(5)=min(1,2)=1. f(175,5)=max(g(175),g(5))=2. ``` Therefore, if we want to minimize `f(p,q)` while keeping the rate of `p/q` constant, `p=175,q=5` is a better choice than `p=35,q=1`. An even better choice is `p=1015,q=29` since `f(1015,29)=1`. It is also easy to prove that there are no valid choice that makes `f(p,q)` equals `0`, so this the optimal choice. Your task is to write a full program or function that computes a choice of `(p,q)` for a given rational number `r` such that `f(p,q)` is minimized (sub-optimal solutions are OK but there are penalties), while keeping the program as short as possible. ## Test cases The outputs are not unique. ``` Input Output 63/1 63/1 0 17/9 119/63 1 35/1 1015/29 1 563/1 2815/5 2 ``` You may also wish to see whether you can get an answer without penalty(see below) for `595/1`. ## Scoring Your score will be composed of two parts: the code-length and the penalties. The code-length is measured in bytes. The penalties are calculated by running your program on all test cases in the given test set. For each `r` in the test set, if your program outputs `p,q`, you get a penalty of `max(f(p,q)-2,0)`. That is, you get no penalty (nor bounty) for any answer that gives a `f` value less than or equal to `2`. The final score is calculated by `final_penalty*codelength^(1/4)`, with lower score better. ## Test set The test set for calculating the penalty can be found in this [pastebin](https://pastebin.com/0rzNRt6F). Basically, it contains all rational numbers which when expressed in reduced fraction `p/q` has the property `128>p>q` (and of course, `(p,q)` coprime), along with all integers from `128` to `1023`(inclusive). The second column in the pastebin are the `f(p,q)` calculated by a naive method. The final line in the pastebin shows the total penalty of this naive method. It is `2343`. ## Specs * Input can be given in any reasonable form. For example, a rational if your program supports it, or a tuple or a list of the numerators and denominators in any order (and you should assume them to be coprime). Same flexiblility for output. * You need to output `p` and `q` in a reasonable form and also `f(p,q)` (To avoid 0-byte programs, thanks to @Lynn). * You should be able to score your own program (Thanks for the suggestion by @user202729). So in your answer, please specify all of the following: the final penalty, the code length in bytes, and the score. Only the score needs to be included in the title of your answer. [Answer] # Node.js, Score = 7873 This is both naive and rather long... * Code size = 129 bytes * Total penalty = 2336 * Score = round(1291/4 \* 2336) = 7873 Takes input as **[p, q]**. Returns **[p', q', f(p, q)]**. ``` f=(a,r=[k=6e3])=>k--?f(a,(i=Math.max(...a.map(n=>(g=n=>n?g(n>>1,n&1?++o:++z):o<z?o:z)(a=(p=a,n*k),o=z=0))))>r[2]?r:[p,a,i],k--):r ``` [Try it online!](https://tio.run/##Zc3BaoQwEAbge58ipzKpMXEM2ho6yRP0CcRD2Kq1bhPJLqX48jaXpbD9D8MwfMz/6b/95ZSW7VqG@D4ex0TgRaJ@pXbUAye7lqWb8g0WevPXD/nlf0BK6fOyQSALM@UZ3AzBWhThEV1RRFMUOzfxdXfR7Bw8wUZehKeVi0g7VTzHpr4eXDL9JrxYBpGbuEnHKYZLPI/yHGeYoG@1wIFzxpRirVbIcqqHO4TPorshxE61mjG8R7r5@4QVNqru/qPm1pdR/ZJRw1h9/AI) for the test cases or [compute the total penalty](https://tio.run/##Tb3fjnTJceR5r6foq0Vz2SLSPcL/cbdJzAPMExC86NFQGq1mSIHSLgZ6eW1l@s9OkQC/qK4T4ZmVEebhZnZOxv/zy//3y7/9w1//@V///e///Jf//qf//M9//PnHX376689/@Jef80/nj7/6@Xf/8vd///t//Prdj//883/95d//x2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9BXZH0fx0sP6b/0nPlLD9W@9IjlS4@3vfRk00uPXrz0fMHLn@8Jf0f@uz/@X3/3d//wlz//21/@559@8z//8k8//pff/PVP//3//Yc//fjjv/30wx9@@emH//bHX/3w8@9@@Lcffv3Df/3l3//Hb/7XL//7x3/8kSt/8D/@8Pc/@E8/vH71/v@v/vP/Bw) by processing the whole test set --- # Alternate version, Score = 8426 A modified version to reach a total penalty of 2330. But it's not worth it... * Code size = 171 bytes * Total penalty = 2330 * Score = round(1711/4 \* 2330) = 8426 Same I/O format as the main version. ``` f=(a,r=[k=5e3])=>k--?f(a,(i=Math.max(...a.map(n=>(g=n=>n?g(n>>1,n&1?++o:++z):o<z?o:z)(a=(p=a,n*([7007,7901,16239,32695,130527,261599][k]||k-5)),o=z=0))))>r[2]?r:[p,a,i]):r ``` [Try it online!](https://tio.run/##TZ3dkmy3caXv9RS8miBHR4ydCSB/NEMp/AB@AgYvaFv@GdmkQvJMOBR@d01X5bfQVIQOmr2BrOoCViLXWnsX/s@P/@/Hv/zjn//tT//5m59@/qc//O1v//zd1z9@@fN33//xu/OH9cM33/3uj7/5ze//@eN3X//bd3//43/@67f/8eN/ff3tt9/@@PHDn77@6bvfff0v3338@9Pv/@Xrn373O/vy0/@w3//61z//9te//us3v/35f//19z//9q/ffP3jd1//6bsfv/z0P7/@Pp8nv2Q/9sXCV39ZHn2@2HqO5xcPO90/fP/HH/77v//4m/PNN19@/u6v3z3ffPzvd3/@3n/4/Z9/@/2fvvz45d9@@Oa3f/7b33313Vff/@qrr773L/bDl@8X//rHv/v98/6yPv4975/P@/eH3@yPf@P9@/hyPv7N98/57pPvPvnuk1yNj3/r3afeV@v9@/qSH//2@/f9HtvvUf2@2lytj3/teXf6aNY0OU2/Gptr9o7w0axp9jRnmpgmp6lpNPx5tfMpfDRnmuSX79/Oh2Pz6Xw0a5o9zZkmpslpappm@EOrcO9A8znbfNAfzZmmucZFe1@debCZCJs5@GhymqILfe6Qd6@Zqo9mTXOmyWmaLvQxO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wk@EjwkeCjHh1/zVHQ4KPAR4GPAh8FPgp8FPgo8FHgo0xHSxMPfBT4KPBR4KPAR4GPAh8FPgp8lOsgZOKBjwIfBT4KfBT4KPBR4KPAR4GPWjolmHjgo8BHgY8CHwU@CnwU@CjwUeCjto59JR74KPBR4KPAR4GPAh8FPgp8FPioowNZiQc@CnwU@CjwUeCjwEeBjwIfBT4qdOAn8cBHgY8CHwU@CnwU@CjwUeCjwEelTr8kHvgoHb@uo8h10LVObdaxuTqAVgeS6jTNezajDhokHvgo8FHgo8BHgY8CHwU@CnyUvvP@0UlwnKkGPhp8NPho8NHgo8FHg48GHw0@2nRGG/HAR4OPBh8NPhp8NPho8NHgo8FHu87wIh74aPDR4KPBR4OPBh8NPhp8NPjopQOsiAc@Gnw0@Gjw0eCjwUeDjwYfDT566/gk4oGPBh8NPhp8NPho8NHgo8FHg48@OiuIeOCjwUeDjwYfDT4afDT4aPDR4KNDZ8kQD3w0@Gjw0eCjwUeDjwYfDT4afHTqmBbigY8GHw0@Gnw0@Gjw0eCjwUeDjy6dg6EzHIinMwJ15psOKNNxVjprSWfn6BgZnavR@gKyzxME9DX39zu379dL3@@1vd@Zer@N836J4/1WuPvVZvpepMfuF@grsr6P49FD@o@eM3/0UO2jRywfPd726MmmR49ePHq@4PH7PeGvyL/64X/96lf/@PNPf/n53//w7b///C9f/923f/7DP/3ff/zD11//5ctX3//45at/@OGbr7773Vd/@erXX/39j//5r9/@x4//9fU/f82V7/2Hr37zlX/56vnm9f9v/vb/AQ "JavaScript (Node.js) – Try It Online") It includes some hardcoded values for the highest multipliers. They were found by generating all bitmasks **m** with up to 32 bits and no more than 5 0's, keeping the values for which **m mod p = 0**, checking the score of **q \* m / p** and finally doing the same operation with the inverted bitmask of **m** of the same length (no more than 5 1's with all other bits set to 0). [Answer] # [Julia 0.6](http://julialang.org/), Score = 7702 ``` g(x,b=[bin(x)...])=min(sum(b.=='0'),sum(b.=='1')) f(a,b)=((r,i)=findmin(map(i->max(g(a*i),g(b*i)),1:10^5));[r,a*i,b*i]) ``` [Try it online!](https://tio.run/##PYvBCsIwEETv/kh2ZA3NQQ/K@iOlwi7SsGKKtBTy9zFePM28ecxrf7teWstU2WQ0X6gixjhBSu/bXsiiSBgC@A8pAIeZlA1CtLJDZl@ev0PRD/npXrRSJj06OJP1AKdrGh5n4Dau3AX3dUJrXw "Julia 0.6 – Try It Online") A naive and slow solution. Output of `f` is `[f(p,q),p',q']` * Length = 119 bytes * Penalty = 2332 * Score = round(119^.25\*2332) = 7702 To run this on the test set, I've downloaded the paste bucket as a `txt` file called `results.txt` and removed the last row. I used this code to evaulate the penalty using all cores of my machine: ``` all_res = open("results.txt","r") do f map(row->parse.(Int,split(split(row," ")[1], "/")), readlines(f)) end addprocs(7) @everywhere g(x,b=[bin(x)...])=min(sum(b.=='0'),sum(b.=='1')) @everywhere f(a,b)=((r,i)=findmin(map(i->max(g(a*i),g(b*i)),1:10^5));[r,a*i,b*i]) penalty = @parallel (+) for iter in all_res max(f(iter[1],iter[2])[1]-2,0) end ``` [Answer] # C++ (GCC), score = 11222 * Length: 538 (<-- less verbose than Java) * Penalty: 2330 ``` #import<bits/stdc++.h> using namespace std;uint32_t f(uint32_t x){int s=__builtin_popcount(x);return min(s,32-__builtin_clz(x)-s);}int i(vector<int>const&a,vector<int>const&b){int i=0,j=0;while(i<a.size()&j<b.size()){if(a[i]==b[j])return a[i];else++(a[i]<b[j]?i:j);}return 0;}int main(){vector<array<vector<int>,6>>T(1024);int p,q,a;for(a=1;a<1024;++a){for(unsigned m=1;m<500000;++m)for(p=f(a*m);p<6;++p)T[a][p].push_back(m);}while(cin>>p>>q){for(a=1;;++a){unsigned m=i(T[p][a],T[q][a]);if(m){cout<<p*m<<' '<<q*m<<' '<<a<<'\n';break;}}}} ``` Runs in 5 seconds on my machine. Input format: something like this ``` 2 1 3 1 3 2 4 1 4 3 5 1 5 2 ``` Output format: something like this ``` 2 1 1 3 1 1 3 2 1 4 1 1 4 3 1 5 1 1 5 2 1 ``` (`p', q', f(p', q')` on each line) --- Ungolfed code: ``` /* the program will not work without END_ANS and END_INPUT being correctly set but it can be easily calculated by a naive algorithm END_ANS must be greater than all of the answers,and END_INPUT must be greater than all of the inputs */ int constexpr END_ANS=6,//<-- according to the naive algorithm END_INPUT=1024,END_M=4194304; /* END_M is an parameter to the algorithm. As this gets larger, the algorithm takes more resource but the answer gets better. NOTE: (END_INPUT-1) * (END_M-1) must not overflow integer. */ static_assert((END_INPUT-1)*(long long)(END_M-1)<4294967296LL); #include<iostream> #include<vector> #include<array> #include<algorithm> uint32_t f(uint32_t x){ uint32_t len=32-__builtin_clz(x), sum=__builtin_popcount(x); return std::min(sum,len-sum); } /**Return a common value between two vectors,or 0 if not found. The input vectors must be sorted.*/ int intersect(std::vector<int>const&a,std::vector<int>const&b){ int i=0,j=0; while(i<a.size()&j<b.size()){ if(a[i]==b[j])return a[i]; else++(a[i]<b[j]?i:j); } return 0; } int main() { std::vector<std::array<std::vector<int>,END_ANS>>T(END_INPUT); //T[i][f1] = all values of m s.t. f(i*m) <= f1 for(int i=1;i<END_INPUT;++i){ for(unsigned m=1;m<END_M;++m) for(int fi=f(i*m);fi<END_ANS;++fi) T[i][fi].push_back(m); } // THIS PART IS USED FOR CALCULATING SCORE int score=0; int p,q;while(std::cin>>p>>q){ for(int ans=1;;++ans){ unsigned m=intersect(T[p][ans],T[q][ans]); if(m){ std::cout<<p*m<<' '<<q*m<<' '<<ans<<'\n'; // THIS PART IS USED FOR CALCULATING SCORE score+=std::max(ans-2,0); break; } } } // THIS PART IS USED FOR CALCULATING SCORE std::cerr<<score<<'\n'; } ``` --- Note: There are some hardcoded constants in the program (maximum input value, maximum `ans`, etc.) I assume it's allowed because otherwise most programs can work in 32-bit integer range anyway. For each `(p,q)` pair, the program tests all pairs `(p×m,q×m)` for all `m` in range `[1,MAX_M[` and find the optimal value, in a smart way. Because the result is the same for `MAX_M=500000` and `MAX_M=4194304` (the largest value such that all intermediate computations still fit in an `uint32_t` (unsigned 32-bit integer)), I just use `MAX_M=500000` so the program runs faster. Bash+Jelly script to calculate score: ``` jelly eun 'ỴḲṛ/VƊ€_2»0S' "'''$(cat result.txt)'''" # <- weird input format ``` --- tl;dr: Tested all values of `m` up to `4194304` (exclusive), best penalty so far = `2330`. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 7437 * Code size = 10 bytes * Total penalty = 4182 * Score = round(101/4 \* 4182) = 7437 Takes input as **[p, q]**, returns **[f(p, q), [p', q']]**. ``` BC,Bḅ1ZṀṂ, ``` [Try it online!](https://tio.run/##y0rNyan8/9/JWcfp4Y5Ww6iHOxse7mzS@f//f7SZoY6JQSwA "Jelly – Try It Online") ### How? This code simply computes **f(p, q)** without trying to apply any multiplier. ``` BC,Bḅ1ZṀṂ, - main link taking [p, q] --> e.g. [61, 40] B - convert to binary --> [[1,1,1,1,0,1], [1,0,1,0,0,0]] C - 1-complement --> [[0,0,0,0,1,0], [0,1,0,1,1,1]] B - convert to binary again --> [[1,1,1,1,0,1], [1,0,1,0,0,0]] , - pair --> [ [[0,0,0,0,1,0], [0,1,0,1,1,1]], [[1,1,1,1,0,1], [1,0,1,0,0,0]] ] ḅ1 - convert from unary base, --> [[1, 4], [5, 2]] which effectively sums the lists Z - zip, so that number of 0-bits and --> [[1, 5], [4, 2]] number of 1-bits are paired together ṀṂ - maximum of the minimum --> max(min(1, 5), min(4, 2)) = max(1, 2) = 2 , - pair with the input to comply with --> [2, [61, 40]] the expected output format ``` ]
[Question] [ There are *n* places set around a circular table. Alice is sat on one of them. At each place, there's a cake. Alice eats her cake, but it doesn't taste very nice. Then the Mad Hatter comes in. He gives Alice a list of *n*-1 numbers, each between 1 and *n*-1. For each item *i* in the list, Alice has to move around *i* places and eat the cake there if there is one. However, Alice will be able to choose whether to move clockwise or anticlockwise for each item in the list. She doesn't like the cakes, so she is trying not to eat them. Given an integer *n*, output all the possible lists the Mad Hatter could use to force Alice to eat all the cakes (represented as a tuple/list of tuples/lists of integers or some tuples/lists of integers separated by newlines). Note that it is possible for the Mad Hatter to force Alice to eat all the cakes if and only if *n* is a power of two, so you may assume that *n* is a power of two. Make your code as short as possible. You may also take in *x* such that 2^*x*=*n* if that helps. For example, you may take in 2 instead of 4, 3 instead of 8, etc. The order in which your program returns the possible lists does not matter. ### Test Cases ``` 1 -> [[]] 2 -> [[1]] 4 -> [[2, 1, 2], [2, 3, 2]] 8 -> [[4, 2, 4, 1, 4, 2, 4], [4, 2, 4, 1, 4, 6, 4], [4, 6, 4, 1, 4, 2, 4], [4, 6, 4, 1, 4, 6, 4], [4, 2, 4, 3, 4, 2, 4], [4, 2, 4, 5, 4, 2, 4], [4, 2, 4, 7, 4, 2, 4], [4, 2, 4, 3, 4, 6, 4], [4, 6, 4, 3, 4, 2, 4], [4, 2, 4, 5, 4, 6, 4], [4, 6, 4, 5, 4, 2, 4], [4, 2, 4, 7, 4, 6, 4], [4, 6, 4, 7, 4, 2, 4], [4, 6, 4, 3, 4, 6, 4], [4, 6, 4, 5, 4, 6, 4], [4, 6, 4, 7, 4, 6, 4]] ``` [Answer] # Perl, ~~78~~ ~~75~~ 72 bytes Includes `+1` for `n` ``` perl -nE '$"=",";say<@{[map"{@{[map$`*($_-.5)/@z,@z=1..$_&-$_]}}",/$/..$_-1]}\\ >' <<< 8 ``` Prints a space separated sequence of comma separated numbers (replace the final space by `\n` for a more readable output) Uses a string substitution inside a string substitution. [Answer] # Python 3, ~~235~~ ~~191~~ ~~177~~ ~~136~~ ~~134~~ ~~122~~ 119 bytes ``` lambda n:[*product(*[[*(i==n/2and range(1,n,2)or[[n/4,3*n/4],[n/2]][i%2])]for i in range(1,n)])] from itertools import* ``` [Try It Online](https://tio.run/##TctBCsIwEIXhfU8xGyETAsW0CxF6kphFtK0OtDNhjFBPH7sR3Tw@Hvz5XR7CXd1ggEtd0nodE/A52Kwyvm7F2BCsoWHg1iceQRPfJ3N07DyKhsBt7zq7b3S7fYyBDj5inEWBgPgX4P42s8oKVCYtIssTaM2ixdasxMVsxiM2X/d/PiHWDw) Thanks To Dennis for -31 bytes and ChasBrown for -14 bytes and Mr.XCoder for -1 byte. Numbers appear in the decimal form, eg:4.0. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 18 bytes ``` żN$Œp+\€%ṬȦ ’ṗ’çÐf ``` This is a brute-force solution that tests all **(n - 1)n - 1** potential solutions one by one. [Try it online!](https://tio.run/##y0rNyan8///oHj@Vo5MKtGMeNa1RfbhzzYllXI8aZj7cOR1IHl5@eELa////TQA "Jelly – Try It Online") ### Verification ``` $ time jelly eun 'żN$Œp+\€%ṬȦ¶’ṗ’çÐf' 8 [[4, 2, 4, 1, 4, 2, 4], [4, 2, 4, 1, 4, 6, 4], [4, 2, 4, 3, 4, 2, 4], [4, 2, 4, 3, 4, 6, 4], [4, 2, 4, 5, 4, 2, 4], [4, 2, 4, 5, 4, 6, 4], [4, 2, 4, 7, 4, 2, 4], [4, 2, 4, 7, 4, 6, 4], [4, 6, 4, 1, 4, 2, 4], [4, 6, 4, 1, 4, 6, 4], [4, 6, 4, 3, 4, 2, 4], [4, 6, 4, 3, 4, 6, 4], [4, 6, 4, 5, 4, 2, 4], [4, 6, 4, 5, 4, 6, 4], [4, 6, 4, 7, 4, 2, 4], [4, 6, 4, 7, 4, 6, 4]] real 85m33.780s user 85m35.903s sys 0m0.060s ``` ### How it works ``` ’ṗ’çÐf Main link. Argument: n (integer) ’ ’ Yield n-1. ṗ Cartesian power; yield all vector of length n-1 over [1, ..., n-1]. çÐf Filter; keep vectors v for which the helper link, called with left argument v and right argument n, returns a truthy value. żN$Œp+\€%ṬȦ Helper link. Left argument: v (vector). Right argument: n (integer) żN$ Zip v with -v, mapping [v(1), ... v(n-1)] to [[v(1), -v(1)], ..., [v(n-1), -v(n-1)]]. Œp Take the Cartesian product of all pairs. +\€ Take the cumulative sum of each resulting vector. % Take all cumulative sums modulo n. A valid solution results in a permutation of [1, ..., n-1]. Ṭ Untruth; map each resulting vector to a Boolean array with 1's at the specified indices, 0's elsewhere. Ȧ Test if the resulting array contains only non-zero integers. ``` [Answer] # [Python 2](https://docs.python.org/2/),~~130~~ ~~129~~ ~~127~~ ~~123~~ 121 bytes ``` f=lambda n:n>1and(lambda D:[l+[k]+r for l in D for r in D for k in range(1,n,2)])([[i*2for i in a]for a in f(n/2)])or[[]] ``` [Try it online!](https://tio.run/##RYtNDsIgEEbXeopZAiXRkrhpoqvegrDAtOikODSTbjw9ZhR19973sz63eyFXazrn@LhOEWigSx9pUs3HwefOL6FjSIUhAxKMb@Q/LoIc6Tar3pJ1OmjlPRonJUoZg2AUTIoOsijsfQj1N/n8j/akh/1uZaQN0OaZVFLOGNT6mzZvWl8 "Python 2 – Try It Online") Edited: Takes as input n (which must be a power of 2) as the number of seats at the Hatter's table. [Answer] # [Python 2](https://docs.python.org/2/), 81 bytes ``` f=lambda n,i=1,*l:i/n*[l]or sum([f(n,i+1,x,*l)for x in range(n)if x*i%n==n/2],[]) ``` [Try it online!](https://tio.run/##RY3BCsMgEETP@hVeSly7ECL0EvBLrAdLY7tgNsGkkH69tb30NDDvMbO@9@fCttbkcpxv96gYyQ1o8kg9G5/DUtT2mrVPupHzgEdjkFp7KGJVIj8mzUBJHYZO7Bz3NqAPUL8O/Z0LjFKws8aQFMW1OZBiLcR7u8wT6wLYXbnD8ov6AQ "Python 2 – Try It Online") --- # [Python 2](https://docs.python.org/2/), 92 bytes ``` f=lambda n,c=1:[x+[c*y]+z for y in range(1,n,2)for x in f(n/2,c*2)for z in f(n/2,c*2)]or[[]] ``` [Try it online!](https://tio.run/##Vc1BCsMgEAXQtZ7CXdQIJUI3AU9iXFgbWyEdw5BFzOVtbBelq4H3P3/Wsj0z6FqjWfzrdvcMVDDDaPfeBllcf7CYkRWWgKGHx8wHBUqLhnvDyOGiVZBfOv7JZbTWudqi9Ju4ipESMFrKRAmasy8oWTHBdn5fZuAoVDdBp/Bz6hs "Python 2 – Try It Online") [Answer] # [Clean](https://clean.cs.ru.nl), ~~194~~ ... 172 bytes Still in the progress of cutting more off. ``` import StdEnv ``` # ``` \n=let?_[]_=1>0;?l[i:j]m=all((\e= ?(updateAt e(1<0)l)j e&&l!!e)o\e=e-e/n*n)[m+i,n+m-i]in[k\\k<-iter(n-1)(\e=[[h:t]\\h<-[1..n],t<-e])[[]]| ?[q>1\\q<-[1..n]]k 0] ``` [Try it online!](https://tio.run/##bZJRa8IwFIWf56@4OhjJTF1rnQ7XKoNtMNibe0uCZBo1mqZq42Dgb1@XqGNSfLr3yznncuFmoqUwZZZPd1pCJpQpVbbOtxZGdvpivsqRFVtbu4YZpMBMqqUdjikfp9EgfBxqqvpLnqVCa4SYTGGIduupsPLJgkRREmKNlyBvbnS9LnHuHDKQd@bWYJo1FTHNLFBcGbpibJUEysotMkGE/ShKF33LGVskAY1aLcOJTQLJMaWc72FIN4OIsc2fyFcQcrellYUt3Ka0doUiAt6Mievbvo9O0PHQJhFpc@Jq7OpRePBCh7RJx4mH6gz/3D1xt6J3K7r3x5X8fYV7FY4r8y/lz/VL8871XmW/@EK@6vfMMa/tweQWkDBToIX/CvnOrncW0hTQkWGGQRn/xhigQ0dOLgxJcDwDx@4Q4tMHGq9CaWXm8OGFRi11P20NaOYnFS5y8Jc/k5kW86IM3t7L528jMjVxsCjjMMx@AQ "Clean – Try It Online") Lambda function which does a brute-force over every combination of indices up to length `n-1`. It still runs in about 5 seconds, because of compiler magic. ]
[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/145840/edit). Closed 6 years ago. [Improve this question](/posts/145840/edit) An [LTL Formula](https://en.wikipedia.org/wiki/Linear_temporal_logic) l is defined by the following grammar (where <x> describes the non-terminal symbol x): ``` <l> ::= <b> | F <l> | G <l> | X <l> | (<l> U <l>) | (<l> W <l>) | (<l> R <l>) | (<l> & <l>) | (<l> \| <l>) | !<l> <b> ::= BVar | True | False | (<i> < <i>) | (<i> <= <i>) | (<i> > <i>) | (<i> >= <i>) | (<i> = <i>) | (<i> != <i>) <i> ::= IVar | -128 | -127 | ... | 127 | (<i> + <i>) | (<i> - <i>) | (<i> * <i>) | (<i> / <i>) ``` (I escaped a pipe to denote boolean or. You should not print that backslash in your output) BVar and IVar represent variables of boolean and integral types respectively. Each must be one of four possible single character variable names, and there may by no overlap between BVar and IVar. For instance, you may choose a,b,c,d for BVar and w,x,y,z for IVar Note that all binary operators must have parentheses around them and that no other parentheses are allowed. Your task is to write a function that takes one input encoding the maximal nesting depth of an LTL formula and prints a random formula limited by that depth (but not necessarily exactly that depth). The distribution does not have to be uniformly random, but each possible formula has to have a non-zero chance of being generated. You may use ≤, ≥, and ≠ instead of <=, >=, and !=. You may add or remove whitespace as you see fit. Even no whitespace at all is allowed. Examples: ``` f(0) -> True f(0) -> d f(1) -> (a&b) f(1) -> Fd f(1) -> (x<y) f(3) -> (G(x!=y)|Fb) f(3) -> (x<(w+(y+z))) ``` Standard loopholes are forbidden. This is code-golf, so the shortest code in bytes wins. [Answer] ## [Perl 5](https://www.perl.org/), 251 bytes **249 bytes code + 2 for `-pa`.** ``` $d=I;sub a{map"($d$_$d)",@_}@I=(w..z,-128..127,a qw{+ - * /});@L=(@B=(a..d,True,False,a qw{< <= > >= = !=}),B,FL,GL,XL,"!".($d=L),a qw{U W R & |});$_=$L[rand@L];0while s/L|B|I/@{$&}[rand@{$&}]/e;$;=$_;s/[^()]//g;0while s/\)\(//g;$_=y/(//>"@F"?redo:$ ``` [Try it online!](https://tio.run/##nU1PS8MwHL37KX4rYSSaJm4gillq6KFSyEkUha2WSKIWaltbR9G2X321owfvHh483t/K1fnFOCIrY9HsX8B0H6byMLIoRZZ4VKWDiiVuGfuh/mp9xdhqfUkNfLbdGfhwCnwgQmmJVSixYczS@3rvaGTyxs2xDWwkBBBIkLCQA6EhjTS91fRJU2/hselLajJnH@AR7mAJ/TSKUon0tjaFVToR5@17ljtouO7DPuaqQ8thNo8s4U4gIVEqGr59xiTh/O2vsiM7fBSmxW8@scBTkXdTO1teo3HMiteTf@JQVl9ZWTSjX5n8Fw "Perl 5 – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), ~~298~~ ~~293~~ ~~283~~ 279 bytes ``` def f(n,t=1):s,*X=c([[(c(V[t>1]),)],[('%s',0),(c('FGX!')+'%s',1)]][t&1]+[(f"(%s{c('<U+≤W->R*≥&/=|+≠'[t::3])}%s)",*[2-(t&1)]*2)]);return n and s%tuple(f(n-1,x)for x in X)or c(V[t>1]) from random import* c=choice V=['True','False',*'abcd'],[*map(str,range(-128,128)),*'wxyz'] ``` [Try it online!](https://tio.run/##jY9NTsMwEIX3OYWplNrjOKJOF6BCuix7BCWS5UVwExqpdSLbES0/B@gtWMDFepEwYoHYIHUxevON5o3edPuwbu10GFZVTWpmRcglzLzgRW6YUsywpQpzqUGAForR2FMxAYFzurgpzigkPyMJWqswljpRrB6x2L/iwvV9cjx8PqTzW348fI3P8zfkD6rCbDbV8B57GAmuspShETTPQMOVq0LvLLGktCvi49B3m4phrlSKHdStIzvSWFIAdr/Rotq1W@LQgdJsu9YFHpncrNvGVNEyV/TO9RUVdFFuPCqn5aNZUfyHb8uO@eAEmp8qlsrsUmAB4M7zbv9C9dC5xgaCESYA0QkgT4Ppv3DxFzK8PXwD "Python 3 – Try It Online") [Answer] # Java 8, ~~456~~ ~~423~~ ~~419~~ ~~407~~ 403 bytes ``` n->{int r=R(9);return r>4?(r<8?"FGX!".charAt(r-5):"")+b(n):"("+b(n)+"UWR&|".charAt(r)+b(n)+")";};int R(int i){return i*=Math.random();}String b(int n){int r=R(9);return r>7?"abcd".charAt(r%4)+"":r>6?"True":r>5?"False":n>0?"("+i(n)+"<≤>≥=≠".charAt(r)+i(n)+")":b(n);}String i(int n){int r=R(n>0?256:261);return(r-=128)>131?"wxyz".charAt(r+2&3)+"":r>127?"("+i(--n)+"+-*/".charAt(r-128)+i(n)+")":r+"";} ``` -8 bytes thanks to *@ceilingcat*. [Try it online.](https://tio.run/##bZJLTsMwEIb3nGKwRGU3SmjSB9A0idjAii4KCCTEwk0CuDRO5bgUKDlAb8ECLtaLFDs1BCEkWx6//vk0/0zoE7XzWconyeMmntKigDPK@HIHgHGZijsapzDUW4BzKRi/hxirG@DEV4elmmoMgUMAG26HS30nghE@Ir5I5VxwEGEnwmJwGKGT0@td5MQPVBxLLOwu6SNErDHmKsCoCix0eTVqvNWviDkmyC99LT6q0jOyNPKsGZxR@eAIypM8w8QvDefYcP6LdBAhOo6TOs9eRyVBfRH2InQh5qkOuwqZTgsV87AVaURWsQzWq49wvfoM1qv336TMkPY18g8H@8uhxbxur@/13G8iVY3A9Q5J6LbdCC2eX15rXctrtA2b6x0YDNvWqSy7uf@roFqhhhDqj19uAGbz8ZTFUEgq1fKUswQy5THe8t3cAiVbg7XzkCknebqoNrgyGeAuF9uqBy0f2CBwW3q1LPNPtcZLIdPMyefSmSlROeU4c7ijWoUYibLqlnLzBQ) NOTE: Due to the rule "*The distribution does not have to be uniformly random*", I've been able to golf some parts by using modulo-4 on the input or random integer for the characters `"abcd"` or `"wxyz"`, and change `Math.random()*10` to `Math.random()*9` and change the ternary a bit. Personally I prefer to have the randomness equally divided for each method, which is **~~456~~ ~~441~~ 404 bytes** instead (and is explained below): ``` n->{int r=R(10);return r>4?(r<9?"FGX!".charAt(r-5):"")+b(n):"("+b(n)+"UWR&|".charAt(r)+b(n)+")";}int R(int i){return i*=Math.random();}String b(int n){int r=R(9);return r>7?"abcd".charAt(R(4))+"":r>6?"True":r>5?"False":n>0?"("+i(n)+"<≤>≥=≠".charAt(r)+i(n)+")":b(n);}String i(int n){int r=R(n>0?256:261);return(r-=128)>131?"wxyz".charAt(R(4))+"":r>127?"("+i(--n)+"+-*/".charAt(r-128)+i(n)+")":r+"";} ``` [Try it online.](https://tio.run/##bZLdTsIwFMfvfYpjL0zLssmQD2Fsizd6BReo0cR40X0gRdaRroCIewDewgt9MV4E2zGBGJM2Pf36n1/O/4zpnJrpNObj6HUbTmiWQY8yvjoBYFzGYkjDGPp6C3ArBeMvEGJ1A5w46jBXU40@cHBhy01vpe@EO8B2lTgiljPBQXh1H4tu20fXN4@nyApHVFxJLMwG6SBEjABzFWBUBAa6fxicfRxekfKYICd3tPqgyM/IqpRnFbdH5cgSlEdpgomTl6BBCbpnah8htXxEgzDa5xngOlFZUEd4TR/diVmsw4ZippNMxdyr@pqRFTDdzfrL26y/3c368xiVlagdzbwHYX9BtFit0ezUmvYvkiqHa9cuiWdf2D5avC3f/0Oza62SwjR1JsOsnB8VVAscGIT64@RbgOksmLAQMkmlWuYpiyBRJuMd3tMzULJzWFsPibKSx4tigwuXAYap2FXdrTrAuq5d1athlP9UbywzGSdWOpPWVInKCceJxS3VK6SUyIt2ybc/) **Explanation:** ``` n->{ // Method with integer parameter and String return-type int r=R(10); // Random integer [0,9] return r>4? // Is it [5,9]: (r<9? // Is it [5,8]: "FGX!".charAt(r-5) // Return a leading character : // Else (it's 9): "") // Return nothing +b(n) // + call to method `b(n)` : // Else (it's [0-4]): "(" // Return opening parenthesis +b(n) // + call to method `b(n)` +"UWR&|".charAt(r) // + middle character +b(n) // + another call to method `b(n)` +")"; // + closing parenthesis } // End of method int R(int i){ // Method `R(i)` with integer as both parameter and return-type return i*=Math.random(); // Return a random integer in the range [0,i) } // Else of method `R(i)` String b(int n){ // Method `b(n)` with integer parameter and String return-type int r=R(9); // Random integer [0,8] return r>7? // Is it 8: "abcd".charAt(R(4))+"" // Return random from "abcd" :r>6? // Else-if it's 7: "True" // Return literal "True" :r>5? // Else-if it's 6: "False" // Return literal "False" :n>0? // Else-if it's [0-5] AND the input is larger than 0: "(" // Return opening parenthesis +i(n) // + call to method `i(n)` +"<≤>≥=≠".charAt(r) // + middle character +i(n) // + another call to method `i(n)` +")" // + closing parenthesis : // Else (it's [0-5] and the input is 0): b(n); // Call itself again, hoping for random [6-8] } // End of method `b(n)` String i(int n){ // Method `i(n)` with integer parameter and String return-type int r=R(n>0?256:261);return(r-=128) // Random integer in range [-128,128] // OR [-128,132] if the input is larger than 0 >131? // If it is 132: "wxyz".charAt(R(4))+"" // Return random from "wxyz" :r>127? // Else-if it's [128,131]: "(" // Return opening parenthesis +i(--n) // + call to `i(n-1)` +"+-*/".charAt(r-128)// + middle character +i(n) // + another call to `i(n-1)` +")" // + closing parenthesis : // Else: r+""; // Return the random integer [-128,127] } // End of method `i(n)` ``` ]
[Question] [ ## Introduction This is the evolution of [this previous challenge](https://codegolf.stackexchange.com/q/84103/55329) which was about checking satisfieability of normal formulae in [conjunctive normal form (CNF)](https://en.wikipedia.org/wiki/Conjunctive_normal_form). However, this problem is [NP-complete](https://en.wikipedia.org/wiki/NP-completeness) and watching algorithms finish is just boring, so we're gonna simplify the problem! ## Specification ### Input **You may tune the following input specification to optimally match your language as long as you don't encode additional information.** Your input will be a list of implications. Each implication has a list of variables on the left and a single variable on the right. Variables may be represented using your favorite representation (integer, strings, whatever), for the sake of this specification, characters will be used. The list on the left side may be empty and there may not be a variable on the right. The variable on the right side will not appear on the left side of the same implication. Example input: ``` [A -> B; B -> A] [A,B,C -> D; B,C -> E; -> A; B -> ] ``` ### Output Your output will be a truthy or a falsy value. ### What to do? You need to determine whether the given formula is satisfieable and output truthy if it is satisfieable and falsy if not. `A,B -> C` means that if A and B need to hold then C needs to hold as well. `-> C` means that C always needs to hold (this is short-hand for `True -> C`). `A,B ->` means that if A and B need to hold, so does falsum and thus there is a contradiction, thus if you find such an implication where A and B hold, you can immediately output falsy (this is short-hand for `A,B -> False`). The list of implications all need to hold at the same time. Because this problem is also known as [HORNSAT](https://en.wikipedia.org/wiki/Horn-satisfiability), it is [P-complete](https://en.wikipedia.org/wiki/Horn-satisfiability) and to avoid trivial solutions to this, your solution **must run in polynomial time and you must provide reasoning why your solution does so**. ### Who wins? This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), thus the shortest solution in bytes wins! Standard rules apply. ## Examples ### with Explanation `[A,B -> C; C ->; -> A; A -> B]` A needs to hold, thus B needs to hold, thus C needs to hold and thus you found a contradiction. `[A,B -> D; C ->; -> A; A -> B]` A needs to hold, thus B needs to hold, thus D needs to hold, however C doesn't need to hold and thus this formula is satisfieable. ### without Explanation ``` [A -> B; B -> A] => 1 [A,B,C -> D; B,C -> E; -> A; B -> ] => 1 [A,B -> C; C ->; -> A; A -> B] => 0 [A,B -> D; C ->; -> A; A -> B] => 1 [P -> ; -> S ; P -> R; Q -> U; R -> X; S -> Q; P,U -> ; Q,U -> W] => 1 [-> P; Q -> ; T -> R; P -> S; S -> T; T,P -> Q ] => 0 ``` [Answer] # [Alice](https://github.com/m-ender/alice), 45 bytes ``` /;;?dhE..';F>@.>F*.?oK \'..zi;w!";-$"'!?n-$-/ ``` [Try it online!](https://tio.run/##S8zJTE79/1/f2to@JcNVT0/d2s3OQc/OTUvPPt@bK0ZdT68q07pcUclaV0VJXdE@T1dFV///f0ddOydrJ107a2ddO0drXTtnAA "Alice – Try It Online") Input is in the form `A->B;B->A` with no spaces. Output is `Jabberwocky` if the formula is satisfiable, and nothing otherwise. ### Explanation This follows a standard template for programs that run entirely in ordinal mode. Unwrapped, the program is: ``` ';.diEw.";->".!Fn.$o;.?zh;.!';F$@'>?*-?-K ';. Push a semicolon and duplicate it d Join these two semicolons into a single string and push it, without removing the originals This puts ";;" on top of the stack, with a ";" under it (and an irrelevant ";" under that) i Take input E Insert input between the only pair of characters in ";;" w Push return address (start main loop) . Duplicate current set of implications ";->" Push this string .! Copy to tape (to get it again later with fewer bytes) F Check whether this string is in current set of implications n Negate result: "Jabberwocky" if no match, "" if match .$o Output this string if nonempty (no unit clauses remain) ; Discard top of stack: if the previous command didn't output, this puts the implications back on the TOS If the previous command did output, this discards the implications and puts ";" on the TOS . Duplicate ?z Remove everything up to and including the first ";->" h; Take first character of remaining string: this is the literal in the first unit clause, or ";" if the clause is simply "->" (or if "Jabberwocky" was output earlier) .! Copy to tape, since we will need it later ';F Check whether this character contains (i.e., is) a semicolon $@ If so, terminate (Replace "A" in the next two lines with the actual value of the literal in this unit clause) '>?*- Remove all instances of ">A"; this destroys all clauses that imply A ?- Remove all instances of "A" K Return to start of main loop ``` Each command in the main loop takes polynomial time, and each iteration of the loop either terminates the program or destroys at least one clause. Hence, the entire program runs in polynomial time. [Answer] ## APL, 49 bytes ``` {×∧/∨/¨≢¨¨{(2⊃¨⍵/⍨0=≢¨⊃¨⍵)∘{x y←⍵⋄(x~⍺)y}¨⍵}⍣≡⊢⍵} ``` This function takes an array of implications, where each implication is a 2-element array, with the first element containing the variables before the arrow and the second containing the variable after the arrow if there is one. E.g. `[A,B,C -> D; B,C -> E; -> A; B -> ]` is represented as: ``` ('ABC' 'D')('BC' 'E')('' 'A')('B' '') ``` The elements need not be letters but could be anything as long as they can be compared. Explanation: * `{`...`}⍣≡⊢⍵`: run the following function on the input until a fixpoint is found + `(`...`)∘`: Find the current units: - `⊃¨⍵`: For each implication in the input, take the first element - `0=≢¨`: See which are empty - `⍵/⍨`: Select those implications - `2⊃¨`: Select the second element from each + `{`...`}¨⍵`: For each implication, given the units: - `x y←⍵`: unpack the implication into its first and second component - `(x~⍺)y`: remove the previous units from the first component and leave the second one alone * `≢¨¨`: find the length of each inner element. If the clause is unsatisfiable, there is at least one (0,0) element (i.e. `[] -> []`, True → False). * `∨/¨`: for each implication, find the GCD of the lengths of its parts. If unsatisfiable, this will be `0`. * `∧/`: find the LCM of all the GCDs. If unsatisfiable, this will be `0`. * `×`: return the sign, so a boolean value is returned (0 for unsatisfiable, 1 for satisfiable). Polynomiality proof: The main loop (`{`...`}⍣≡`) will run until there are no more reducible implications. Each step, all current known facts are removed from the left hand side of each implication. Because each implication can only have 0 or 1 variables on its right hand side, the size of the set of knowable facts is bounded by the amount of implications, meaning the loop will run at most `n` times. The main loop further contains a number of maps over the list of implications, meaning the total running time is `O(n^2)`. [Link to tests cases being run on tio.run](https://tio.run/##lVNLTsMwEN3nFN7ZFq3S9C@k3oILOKmFkCpI61S0isoGhNqiIDYINiwoC3IAuuky3GQuUsZ2TLNgQa0o88bj92bGHxGP6sO5GF2d16ORUOoi2kP2RhKpEhIJJZUnAwL3T4RREVJCI8oZ/gjVFo3QViAIKSd6wMMdkYESiWE1PNms0of/ojcdPfA82XJ8u4rR0PLIn8PwWwe@bP@mj1x@g2S1gtBU5OjtCr1zfPOdSvPd45vvVrL3Snp8IClttT/RYIxgqsEEwUwDhWBs1kxL0liDa0xh5HsV@X4pj/HYqWmbOPnYJdSqiQnFVt@K9Q@tevrKKCuIV8ZcAc7w9M1pImrZc0HUtluMqGN3C1HXNo6oZ2tE1LcJuDeZXpoLqcVTBtkOPxLA@hayLR80LVjsXTHp9wssP31Y5n6Rw2pT5EWeMr0M3WzrQ5Y3BmbeTXFYvqYzMkc2etgam91gDj5fmPACsg9YvcN6Y/LA4zMupGem4RgfjRye0ho78YmuoCy2yM0jUrxGfQxC9mXd/Q8). [Answer] # [Python 2](https://docs.python.org/2/), ~~312~~ ~~244~~, 243 bytes ``` from sympy import*;s=input() l=' ||,|&|;->|;1>>|[->|[1>>|->;|>>0;|->]|>>0]|;|)&(|->|>>|[|(|]|)|(|((|>>|)>>'.split('|') for i in zip(l[::2],l[1::2]):s=s.replace(*i) for i in range(65,91):y=chr(i);vars()[y]=Symbol(y) print satisfiable(eval(s))>0 ``` [Try it online!](https://tio.run/##dZDLasMwEEX3/oohi1gKTkgCLdTCgjy6j/OgBeOF4yqNQLaF5KR10b@7ku1CNt3onrlzZ5Akm/palcs2rz5YNBqN2ouqCtBNIRvghaxUPSE64qW81Qh7IvLBmMCMDZlSQxaUmsRC4mBKiaF0TiykDlJDDB4jWxoXM8ikBtsTIVdjSv2ZloLXyDc@9i6VAg68hB8ukUjCcJkGIlk4xaGO9EwxKbKcoQl/CKus/GTo@Sl4WeCwifKrQhyTe6Y0wkmTRoemOFcCNdiTipc16Kzm@sKzs2CI3TOBNMZ03tp3e19XLhgc1Y2FHgD7Zjm4P2n9ZAVTCmsCa6er1PesFayDjSu31u7plXTtIfaXcrwh4BJ//X7dY2D7b2DnsPMPVrpqTyB2eiKwd/pObM9qbPvBqc/HPbx1OyzshhkCx2FFt@owjB6tH3RObC/@Cw "Python 2 – Try It Online") **Some explications** The input is converted to the appropriate format of sympy module, then verifying satisfiability. **Is it time-polynomial?** I performed a set of experimental tests that shows that the algorithm is linear. Randomly, I took `N` implications, with `N in [1..1000]`, over a number of variables between 1 and 26. After that I do one thousand of satisfiability test for each `N`. Finally I plot the average in millisecond. [![experimental tests](https://i.stack.imgur.com/DAS8f.png)](https://i.stack.imgur.com/DAS8f.png) [Answer] # [JavaScript (Node.js)](https://nodejs.org), 69 bytes ``` f=x=>x.some(t=>t.a.every(v=>x[~v])&!x[~t.b]&&[x[~t.b]=1])?f(x):!x[~0] ``` [Try it online!](https://tio.run/##jU5dS8MwFH3fr4gvXQNZsO18aWhl3Xxf94FCyEM3U1HmKmspFZl/vd6bZCDopk/n3PPFfSnaot4ent@a0b561H1fJl2SdryuXrXfJGnDC65bfXj3W5DlZ6uodwXY8I3yPOlYEih6W/odjdG7Vr0YbKt9Xe0031VPfunLjyKWgWKbODwy5CHy4Kgo/T3KQhZhZOzi9rqxl@26nUsbGIxsMFI/uu6fP/rj//T7oZyQUUoyQTLEiRoOQGIZm@I5A9myO2FsFzulkE8FwcTJt3PfA7OzgTlSoy8BzLUQJEdcC7JAfBDgAebgs7XN55bcmw0gc9cRZOUmzNTSVVegM6Pk8PgX "JavaScript (Node.js) – Try It Online") Flow each `true` and check if `false` is true ]
[Question] [ This is very similar to [this challenge](https://codegolf.stackexchange.com/q/75151/42649), "Implode the Box". It was a pretty nice challenge and it didn't get many answers, so I'm going to post a similar challenge (strongly) inspired by it. ASCII Boxes look like this: ``` ++ +---+ +------+ +---+ +---+ ++ | | | | | | | | | | | | | | | | +-+ | | | | | | | | +-+ | | | | | | +---+ +---+ | | | | +--+ | | | | ++ | | | | | | || | | +------+ | | || +--+ | | || +---+ || || +-----+ || +------------+ | | ++ | | | | | | | | +------------+ +-----+ ``` Here are the same ASCII boxes, exploded: ``` -- - - - - - ++ +- -+ +- -+ +- -+ +- -+ ++ | | | | | | | | | | | | | | | | +-+ | | | | | | | | +-+ | | | | | | +- -+ +- -+ | | | | - +--+ - | | | | ++ | | | | | | || | | -- +- -+ | | | | +--+ - - - - | | | | - - -- - +- -+ | | - - - - - | | - - +- -+ || +- -+ | | ++ | | | | | | | | +- -+ +- -+ - - - - - - - - - - - -- ``` [Here](https://hastebin.com/ibopicoxij.txt) are the test cases in a more computer-friendly format. The challenge is to take an ASCII box as input and output the exploded box. A box is exploded according to the following rules: 1. `+` never changes, and neither do the `-` and `|` immediately neighboring them. 2. Starting from the corners and moving in, each `-` and `|` move outward one more space than the previous one. The result does not have to be symmetrical, so padding spaces are not needed. 1. [Standard loopholes apply.](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) 2. You can take input in any reasonable format, including LF/CR/CRLF separated lines, array of lines, array of array of characters, etc. 3. The only characters in the input string will be "+", "-", "|", " ", and "\n" (or whatever your newline is, if you choose this input format), and your output string should follow the same rules. 4. You may optionally have a single trailing newline at the end of the last line. 5. The smallest ASCII box you need to handle is the top-left example. Every ASCII box will have exactly 4 "+"s, exactly at its corners. 6. You can assume you will always get a single valid ASCII box as input. 7. The box must be left-aligned. 8. Each line may have trailing whitespace so long as the line (without the newline character) is not longer than the longest line with all trailing whitespace removed. That is, the padding whitespace to the right cannot stretch out farther than the center of the extrusion. [Answer] # [Retina](https://github.com/m-ender/retina), 136 bytes ``` m`^ # (¶#\|(.*))(?<=\1\1)(?=\1) ¶| $2 T`#`_`^(.|¶#)*$ }T`#`p +`^(.*?-)(-+)- $.1$* $2¶$1$.2$* - +`¶(.*?-)(-+)(-.*)$ ¶$1$.2$* $3¶$.1$* $2 ``` [Try it online!](https://tio.run/##hY0xCsMwEAT7e4VBV9xJnEB2m@BPpBSOXLhIkRBMSuVbeoA@ppzA4DLb7LLMsvv2ebzW1p5pAQNUi4mZvGWm@XKNIQYN6gy15GHAEW7JpHtayGdl2SJ8e/MG1zs7C5M4FkAf0CpfCwb0o2ZRpJaTIdEbhBPASfMxa81JlwN9VeW/fvA/ "Retina – Try It Online") Explanation: ``` m`^ # ``` Prefix a `#` to every line. ``` (¶#\|(.*))(?<=\1\1)(?=\1) ¶| $2 ``` Where there are three identical lines, i.e. in the middle of a box, expand the middle line of the three. (When there are more than tree identical lines, all except the first and last get expanded.) ``` T`#`_`^(.|¶#)*$ ``` If no lines were expanded, then delete the `#`s again. This causes the loop to exit. ``` }T`#`p ``` If at least one line was expanded, change the `#`s to spaces, and continue the loop. (I use `p` here because it's easier to see.) At the end of the loop, the sides of the box will have been completely exploded. ``` +`^(.*?-)(-+)- $.1$* $2¶$1$.2$* - ``` Repeatedly remove all but two of the top row of `-`s and put them on their own line preceding the rest of the original row. This explodes the top of the box. ``` +`¶(.*?-)(-+)(-.*)$ ¶$1$.2$* $3¶$.1$* $2 ``` Repeatedly remove all but two of the bottom row of `-`s and put them on their own line following the rest of the original row. This explodes the bottom of the box. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~56~~ 49 bytes ``` SχA⁰δW¬⁼χSA⁺¹δδ↓+P↗×-÷⁺¹Lχ²↙×|÷⁺¹δ²‖OO﹪Lχ²‖OO↓﹪δ² ``` [Try it online!](https://tio.run/##lY@9bsIwFIV3nsLKdFEcCRjphAQDUvhRaB8gsk1i6WKH2E6WvLtxiRVaoQ49y/3R@c61WV22TJfo/V41zl5sK1UFbP4x2xgjKwULSniY@lqiIHDUFnZ3V6IBRslPZB5EInNGZ2D5DY7wOTgsrLe6V5QkaRJWB4dWNuP@qylkVVtKPuVNGEiyhJKt7CQXU1IuVGXr8K6QuAqXfmXm4vqCh3eYT1AhriiYPXWixbKJBQ6aO9Qw3Xi6/zLHX0SGj17v0ywqnQ0kavhX@0rwWeczgw8 "Charcoal – Try It Online") Link is to verbose version of code. Explanation: The input box is measured; `χ` contains the first line of the box, while `δ` contains the number of rows of the box. The top left corner of the exploded box is then drawn: first the `+`, then the `-`s, then the `|`s. Finally the box is reflected horizontally and vertically; for boxes of odd sizes, a 1-character overlap is taken into account. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~80 79~~ 77 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` HĊḢ ċЀ⁾-|HµHĊS+=0Ḣ$©Ṭ€ḤH⁸ÇR¤¦;€⁸Ço1¤¦3Ḋ€¹®?z0ZUŒḄm0$⁸ḂḢ¤?€ŒḄm0$⁸ḂṪ¤?ị“-|+ ”Y ``` A full program that prints the result. **[Try it online!](https://tio.run/##y0rNyan8/9/jSNfDHYu4jnQfnvCoac2jxn26NR6HtgJFg7VtDYAyKodWPty5Bij1cMcSj0eNOw63Bx1acmiZNVgxkJdvCOIaP9zRBRQ5tPPQOvsqg6jQo5Me7mjJNVABKnm4owlozKEl9kB5NOGdq4DCD3d3P2qYo1ujrfCoYW7k////tXXhQJurRgEOaqjMQbYHAA)** ### How? ``` HĊḢ - Link 1: first item halved and rounded up: list H - halve (vectorises) Ċ - ceiling (vectorises) (i.e. round up) Ḣ - head ċЀ⁾-|HµHĊS+=0Ḣ$©Ṭ€ḤH⁸ÇR¤¦;€⁸Ço1¤¦3Ḋ€¹®?z0ZUŒḄm0$⁸ḂḢ¤?€ŒḄm0$⁸ḂṪ¤?ị“-|+ ”Y - Main link breaking the Main link down: ċЀ⁾-|Hµ - get the dimensions: list of characters ⁾-| - literal ['-', '|'] Ѐ - map with: ċ - count - yields a list [number of '-'s, number of '|'s] H - halve µ - start a new monadic link using that as it's argument, call it d HĊS+=0Ḣ$©Ṭ€ - build an appropriately sized binary "diagonal": e.g. [3,4] H - halve (vectorises) [1.5,2] Ċ - ceiling (vectorises) (rounds each halved dimension up) [2,2] S - sum 4 $ - last two links as a monad: =0 - equals zero? (vectorises) [0,0] Ḣ - head (first element) (i.e. "inputHasZeroDashes") 0 © - copy to register and yield + - addition 4 Ṭ€ - untruth for €ach [[1],[0,1],[0,0,1],[0,0,0,1]] ḤH⁸ÇR¤¦ - make 1s become 2s for those that will represent '|' rather than '-' Ḥ - double (vectorises) [[2],[0,2],[0,0,2],[0,0,0,2]] ¦ - sparse application... - ... at indexes: ¤ - nilad followed by link(s) as a nilad: ⁸ - chain's left argument, d [3,4] Ç - call last link (1) as a monad 2 R - range [1,2] - ...of: H - halve [[1],[0,1],[0,0,2],[0,0,0,2]] ;€⁸Ço1¤¦3 - place a 3 where the `+` should be 3 - literal 3 3 ¦ - sparse application... - ... at indexes: ¤ - nilad followed by link(s) as a nilad: ⁸ - chain's left argument, d [3,4] Ç - call last link (1) as a monad 2 1 - literal 1 1 o - logical or (when no '-' Ç returns 0, but we want 1) 2 - ...of: ;€ - concatenate for €ach (append the 3) [[1],[0,1,3],[0,0,2],[0,0,0,2]] Ḋ€¹®? - a further correction for zero width edge-case ? - if: ® - recal from register (inputHasZeroDashes) - ...then: Ḋ€ - dequeue €ach (all rows were made one longer, so adjust) - ...else: ¹ - identity (do nothing) [[1],[0,1,3],[0,0,2],[0,0,0,2]] z0ZU - pad with zeros and reflect each z0 - transpose with filler zero [[1,0,0,0],[0,1,0,0],[0,3,2,0],[0,0,0,2]] Z - transpose [[1,0,0,0],[0,1,3,0],[0,0,2,0],[0,0,0,2]] U - upend (reverse each) [[0,0,0,1],[0,3,1,0],[0,2,0,0],[2,0,0,0]] ŒḄm0$⁸ḂḢ¤?€ - perform reflections of row elements ?€ - if for €ach: ¤ - nilad followed by link(s) as a nilad: ⁸ - chain's left argument, d [3,4] Ḃ - modulo 2 (vectorises) [1,0] Ḣ - head (first element) 1 - ...then: ŒḄ - bounce [[0,0,0,1,0,0,0],[0,3,1,0,1,3,0],[0,2,0,0,0,2,0],[2,0,0,0,0,0,2]] - else: $ - last two links as a monad m0 - reflect ŒḄm0$⁸ḂṪ¤? - perform reflection of rows ? - if: ¤ - nilad followed by link(s) as a nilad: ⁸ - chain's left argument, d [3,4] Ḃ - modulo 2 (vectorises) [1,0] Ṫ - tail (last element) 0 - ...then: ŒḄ - bounce - else: $ - last two links as a monad m0 - reflect - [[0,0,0,1,0,0,0],[0,3,1,0,1,3,0],[0,2,0,0,0,2,0],[2,0,0,0,0,0,2], - [2,0,0,0,0,0,2],[0,2,0,0,0,2,0],[0,3,1,0,1,3,0],[0,0,0,1,0,0,0]] ị“-|+ ”Y - create the list of characters itself “-|+ ” - literal ['-', '|', '+', ' '] ị - index into [" - "," +- -+ "," | | ","| |", - "| |"," | | "," +- -+ "," - "] Y - join with newlines - " - \n +- -+ \n | | \n| |\n| |\n | | \n +- -+ \n - " - implicit print: >>> - >>> +- -+ >>> | | >>>| | >>>| | >>> | | >>> +- -+ >>> - ``` ]
[Question] [ What general tips do you have for [golfing in V](https://github.com/DJMcMayhem/V)? I'm looking for ideas which can be applied to code-golf problems and which are also at least somewhat specific to V (e.g. "remove comments" is not an answer). Since V is heavily based on vim, most of the [tips for golfing vim](https://codegolf.stackexchange.com/q/71030/31716) would apply too. But there are some features in V that don't really apply to vim. Please post one tip per answer. [Answer] Take advantage of implicit endings! In V, every single command will be implicitly finished if you don't actually finish out the command. For example, if the program ends in insert mode, the `<esc>` will be filled in automatically. Usually, this doesn't make any difference. However, if you have a count before the `i`, you have to actually hit `<esc>` at the end for the text to be inserted multiple times. So you can do `2i2i` for a quine, whereas in vim you would need `2i2i<esc>`, which is no longer a quine. This also applies to ex commands, and psuedo ex-commands such as compressed regexes. So where vim needs ``` :foo<cr> ``` V can do ``` :foo ``` if it's at the end of the program. But here is where it gets really cool: The implicit ending applies several layers deep. For example, consider this command: ``` òçfoo/óa ``` This translates to: ``` ò " Recursively: çfoo/ " On every line matching 'foo' óa " Remove the first 'a' ``` Without implicit endings, the `ó` needs a `<cr>`, the `ç` needs a `<cr>`, and the `ò` needs another `ò`. But none of these are needed with implicit endings! The interpreter will fill in the needed `ò`, the recursive command will fill in the `<cr>` that `ç` needs, and the `ç` command will fill in the `<cr>` that `ó` needs. This saves us 3 bytes. [Answer] Carefully choose how you take input. V can take input two different ways: *input* and *args*. It can even take both at the same time! Choosing how you take input can sometimes save you many bytes. Here is how the two input formats work: * The *input* is the text that is loaded into the buffer. Generally, this is more convenient for string inputs. * The *args* are stuffed into the first *n* registers, depending on how many args are given. For example, if 5 args are given, these will be loaded into registers a-e. Since you can run these registers with `@<reg>`, these are generally more convenient for numeric input. Lets make a hypothetical example. Our hypothetical challenge is: > > Given a string *s*, and an integer *n*, output *s* *n* times, separated by a newline. > > > In vim, you can only take input into the buffer. So you'd need to take the input on two lines, for example ``` n s ``` And run ``` DJY@-pdd ``` The `D` to delete n into register '-', the `J` to remove the extra newline, and then `@-p` to paste s *n* times, and dd to take care of the extra copy. In V, you can take *s* as input, and *n* as an arg. Then you could shorten this too: ``` @apdd ``` of course, there's still a few ways to shorten this even more. For example, `Ä` makes *n* copies, rather than pasting *n* times. And `À`, or `<M-@>` will cycle through all of these args, so the first time it's called it is equivalent to `@a`. So you can simply do: ``` ÀÄ ``` The `À` will command will also loop back once you go through all of the args. So if you have 3 arguments, running `À` repeatedly will run ``` @a @b @c @a @b @c @a ... ``` ]
[Question] [ [Related](https://codegolf.stackexchange.com/questions/110825/calculate-elo-rating-expected-score) ## Task Your task is to calculate the new [Elo rating](https://en.wikipedia.org/wiki/Elo_rating_system) ([FIDE rating system](https://en.wikipedia.org/wiki/Elo_rating_system#FIDE_ratings)) for a player after winning, losing or drawing a game of chess. To calculate the Elo rating two formulas are needed: ``` R' = R0 + K*(S - E) E = 1 / (1 + 10 ^ ((R1 - R0) / 400)) ``` where: * `R'` is the new rating for player0, * `R0` is the current rating of player0 and `R1` is the current rating of player1, * `S` is the score of the game: `1` if player0 wins, `0` if player0 loses or `0.5` if player0 draws, * `K` = `40` if the given history has a length < 30, even if it exceeds 2400 * `K` = `20` if the given history has a length >= 30 and never exceeds 2400 (<2400), * `K` = `10` if the given history has a length >= 30 and exceeds 2400 at any point (>=2400) (if history has a length < 30 but a max value >= 2400 `K` will equal 40) ## Input * History of player0's ratings as an array of positive integers greater than 0, where the last item is the players current rating. If no history is given, the current rating will be 1000 * Rating of player1 as an integer * Score, either 1, 0 or 0.5 ## Output `R'`, A decimal integer of player0's new rating ## Examples ``` input: [], 1500, 1 K = 40 (length of history is less than 30) E = 1 / (1 + 10 ^ ((1500 - 1000) / 400)) = 0.0532 R' = 1000 + 40*(1 - 0.0532) = 1038 output: 1038 input: [1000, 1025, 1050, 1075, 1100, 1125, 1150, 1175, 1200, 1225, 1250, 1275, 1300, 1325, 1350, 1375, 1400, 1425, 1450, 1475, 1500, 1525, 1550, 1575, 1600, 1625, 1650, 1675, 1700, 1725], 1000, 0 K = 20 (length of history is more than 30 but never exceeds 2400) E = 1 / (1 + 10 ^ ((1000 - 1725) / 400)) = 0.9848 R' = 1725 + 20*(0 - 0.9848) = 1705 output: 1705 input: [1000, 1025, 1050, 1075, 1100, 1125, 1150, 1175, 1200, 1225, 1250, 1275, 1300, 1325, 1350, 1375, 1400, 1425, 1450, 1475, 1500, 1525, 1550, 1575, 1600, 1625, 1650, 1800, 2100, 2500], 2200, 0.5 K = 10 (length of history is more than 30 and exceeds 2400) E = 1 / (1 + 10 ^ ((2200 - 2500) / 400)) = 0.8490 R' = 2500 + 10*(0.5 - 0.8490) = 2497 output: 2497 ``` ## Test cases: ``` [2256,25,1253,1278,443,789], 3999, 0.5 -> 809 [783,1779,495,1817,133,2194,1753,2169,834,521,734,1234,1901,637], 3291, 0.5 -> 657 [190,1267,567,2201,2079,1058,1694,112,780,1182,134,1077,1243,1119,1883,1837], 283, 1 -> 1837 [1665,718,85,1808,2546,2193,868,3514,436,2913,6,654,797,2564,3872,2250,2597,1208,1928,3478,2359,3909,581,3892,1556,1175,2221,3996,3346,238], 2080, 1 -> 248 [1543,2937,2267,556,445,2489,2741,3200,528,964,2346,3467,2831,3746,3824,2770,3207,613,2675,1692,2537,1715,3018,2760,2162,2038,2637,741,1849,41,193,458,2292,222,2997], 3814, 0.5 -> 3002 ``` # Notes You won't get an input with fewer scores than 30 and a maximum score higher than 2400 This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins! [Answer] # [Octave](https://www.gnu.org/software/octave/), 106 bytes This assumes the history never contains a zero. ``` @(h,r,s)(h=[1e3,h])(n=nnz(h))+((40-(20*(n>30)))-(10*((n>30)&(max(h)>2401))))*(s-(1/(1+10^((r-h(n))/400)))) ``` This outputs (after some formatting): ``` Correct - Calculated 1038 - 1037.87 1705 - 1705.3 2497 - 2496.51 ``` [Try it online!](https://tio.run/##1dFNbsIwEAXgPafIpmUGkjDjn4QugipxDKBSBImCRE0V0qrq5VPnIZUz1AvL77Mtz8jX41B/NWNb5Xk@vlKX9umNqat22ti0OzCFKoQf6piXRE4yMrKgsLHCzBlpDPf0TO/1dzy2MU407vGCbnF/RbpUeSPqs44C88rJdJPH9qM/h6Gl@fba981xSLJkW1@On5d6aE77MOfZ3wkVu07iyJKn8z5oKf6RjHspH2metrQ7pIl6kThzGpuaRVJBFuOn2WNdTmuFK1zhCjdwAzdwA7dwC7dwC3dwB3dwB7/X4eEe7uEFvIAX8AJewkvjpyZQtPynJtaTGNQTH5TYhEERkvv45b8 "Octave – Try It Online") --- Note: According to the FIDE-scoring system: If you play 41 games against a player having a score of 5000 (more than 2000 points higher than the highest achieved score ever), you'll end up with a score of **2400**. I believe that fewer scores than 30, and a maximum score higher than 2400 should be considered invalid input (but that's OP's decision). [Check it here](https://tio.run/##LY5NCsIwEIX3OUU26oxNcaJxY0nxAp5AKoQ2IQFNJakiXr5W6@597wde3w7macfR6SN4kURG8Pos7U74BiHqGN/gEQsARSVsaQ2x3hEiliAnmGkJN/OaavVWkZwyXEOe8g3IQtIFIJUeIuJG0XeJFctaVizpPRFVjHmuufxJ1ycewhcPSv78sxfuf6ypmI0dc/cU4uBgdTKvcDNXnts@WW7cYBNXxFP/iF0@8EVYifkWjuMH) [Answer] # [Python 3](https://docs.python.org/3/), 106 bytes ``` def f(h,b,s):a=([1e3]+h)[-1];return round(a+((len(h)<30)*4or-~(max(h)<2400))*10*(s-1/(1+10**((b-a)/400)))) ``` [Try it online!](https://tio.run/##1dFNTsMwEAXgPafwcpwf6vFPggqcxPIiVROlEjiV40qw4erBfpwCL0ZP3yz8pLl/53WL5jiu8yIWWrtLt8vz9E6eZxPaVfqew2ua8yNFkbZHvNLUEn3MkVb5ZpRs7Jb6H/qcvipoq5SUDauG9p5PxG2JDdGln@QJOymPZUsiz3sWtyi896ET7JQqM3Tes0JU2tXpkMeaGc5whjNcwzVcwzXcwA3cwA3cwi3cwi38r4KDO7iDD/ABPsAH@Agftav9UVr9k/4vVTT6lA9La6FRQj27EM5Porx7usVMCzX1TuVkvw "Python 3 – Try It Online") --- **without rounding, 98 bytes**: ``` def f(h,b,s):a=([1e3]+h)[-1];return((len(h)<30)*4or-~(max(h)<2400))*10*(s-1/(1+10**((b-a)/400)))+a ``` [Try it online!](https://tio.run/##1dFNTsMwEIbhPafwcpwfOuOfBBU4ieVFKhKlEiSV40plw9VD/HEKvBiNHi/8Sr5953ld7L5/jJOaaG4uzabPwzsFGW2sZx1aia9pzPe0EH2OC836zbKu3JraH/oaHgWMY9a6Eq5oa@VEUh9rRXRpB33Cna6HfVqTyuOW1XVRIYTYKPHMx4xNCMJY2fgyPfa@7AIXuMAFbuAGbuAGbuEWbuEW7uAO7uAO/pfg4R7u4R28g3fwDt7De@NLP6L5n/S/FDHoOR48qpVBBD/7GM9P6ji3dF0yTVSVf9J6/wU "Python 3 – Try It Online") [Answer] # [R](https://www.r-project.org/), 109 bytes ``` function(p,s,h=1000,l=length(h))round(h[l]+`if`(l<30,40,`if`(any(h>2400),10,20))*(s-1/(1+10^((p-h[l])/400)))) ``` Returns an anonymous function that takes several arguments: `p`, player 1's rating, `s`, the score of the game, and `h`, the history. Technically takes another argument `l` but it defaults to the length of `h`. `h` defaults to `1000` so if there is no historical record of games, no value is provided for `h`. [Try it online!](https://tio.run/##1dHBbsIwDAbgO0@xowMBbCduOdC9CGJiYitBqgJq4cDTd8m/pyCH6M@nRLaVce67uX/m8@N6y3T3k0@dMLMfuuE3Xx6JknPj7Zl/KB2G4@p07U807AP7yB6H7/yi9KmR2Xlhr@zckqa1bElWwl9E93V96bb1RllzT2KlgLjFosRai/35P3wIq9XdkNuaBS5wgQtc4QpXuMIDPMADPMAjPMIjPMINbnCDG7yBN/AG3sBbeKvmMIDWPnhj7zHCroqin1Kw/Mf8Bw "R – Try It Online") [Answer] # JavaScript (ES7), 124 bytes This is a valid JavaScript anonymous function. Add `f=` at the beginning and invoke like `f(arg1,arg2,arg3)`. Assumes that the first element of history is not 0 (which is allowed). ``` (a,r,s)=>(e=a.some(c=>c>2400),a=a[0]?a:[1e3],Math.round((y=a.pop())+((a.length<30?40:(e?20:10))*(s-1/(1+10**((r-y)/400)))))) ``` ``` let f= (a,r,s)=>(e=a.some(c=>c>2400),a=a[0]?a:[1e3],Math.round((y=a.pop())+((a.length<30?40:(e?20:10))*(s-1/(1+10**((r-y)/400)))))) btnTrigger.onclick = () => { let a = inputA.value.split`,`.map(c=>parseInt(c,10)),      r = parseInt(inputR.value,10),    s = parseFloat(inputS.value,10);  console.log(f(a,r,s)); } ``` ``` <p>Add a Single Comma in History input box for empty History</p> <input type="text" id="inputA" placeholder="Comma Separated History"> <input type="text" id="inputR" placeholder="Value for R1"> <input type="text" id="inputS" placeholder="Value for S"> <button type="button" id="btnTrigger">Submit</button> ``` [Answer] # JavaScript, 105 bytes ``` (h,r,s,u=h.length?h.pop():1e3,k=h.length>28?h.some(v=>v>2400)?10:20:40)=>u+k*s-k/(1+10**((r-u)/400))+.5|0 ``` [Answer] # oK, 66 bytes ``` {*|x+_.5+(40-(10*2+|/2399<x)*29<#x)*z-1%1+exp((y-*|x)%400)*log 10} ``` [Try it online.](http://johnearnest.github.io/ok/?run=f%3A%7B%2a%7Cx%2B_.5%2B%2840-%2810%2a2%2B%7C%2F2399%3Cx%29%2a29%3C%23x%29%2az-1%251%2Bexp%28%28y-%2a%7Cx%29%25400%29%2alog%2010%7D%0A%0Aa%3Af%5B1000%2C1025%2C1050%2C1075%2C1100%2C1125%2C1150%2C1175%2C1200%2C1225%2C1250%2C1275%2C1300%2C1325%2C1350%2C1375%2C1400%2C1425%2C1450%2C1475%2C1500%2C1525%2C1550%2C1575%2C1600%2C1625%2C1650%2C1800%2C2100%2C2500%3B2200%3B0.5%5D%20%2F2497%0A%0Aa%2C%3Af%5B2256%2C25%2C1253%2C1278%2C443%2C789%3B3999%3B0.5%5D%20%2F809%0A%0Aa%2C%3Af%5B1543%2C2937%2C2267%2C556%2C445%2C2489%2C2741%2C3200%2C528%2C964%2C2346%2C3467%2C2831%2C3746%2C3824%2C2770%2C3207%2C613%2C2675%2C1692%2C2537%2C1715%2C3018%2C2760%2C2162%2C2038%2C2637%2C741%2C1849%2C41%2C193%2C458%2C2292%2C222%2C2997%3B3814%3B0.5%5D%20%2F3002%0A%0Aa) For regular k, add two bytes by turning `log` and `exp` into ``log` and ``exp` respectively. [Answer] ## Haskell 158 bytes ``` g h o s=round$p+k*(s-1/(1+10**((o-p)/400))) where p=if(l h<1)then 1000else last h k=40-(if(l h)>=30then 20else 0)-if(any(>=2400)h)then 10else 0 l=length ``` `g` is a function that takes a list `h` representing the `h`istory of the player, `o`, the `o`pponent points and,`s` the `s`core of the game. ]
[Question] [ ## Introduction Suppose we have a network of railroads. Each junction in the network is controlled by a *switch*, which determines whether an incoming train turns left or right. The switches are configured so that each time a train passes, the switch changes direction: if it was pointing left, it now points right, and vice versa. Given the structure of the network and the initial positions of the switches, your task is to determine whether a train can eventually pass through it. This challenge was inspired by [this article](https://arxiv.org/abs/1605.03546). ## Input Your input is a non-empty list **S** of pairs **S[i] = (L, R)**, where each of **L** and **R** is an index of **S** (either 0-based or 1-based), in any reasonable format. This includes a **2 × N** matrix, an **N × 2** matrix, two lists of length **N**, or a list of length **2N**. Each pair represents a junction of the network, and **L** and **R** point to the junctions that are reached by turning left and right from the junction. They may be equal and/or point back to the junction **i**. All junctions initially point left. ## Output A train is placed on the first junction **S[0]**. On each "tick", it travels to the junction that its current switch points to, and that switch is then flipped to point to the other direction. Your output shall be a truthy value if the train eventually reaches the last junction **S[length(S)-1]**, and a falsy value if is doesn't. ## Example Consider this network: [![Network of railroads](https://i.stack.imgur.com/BV7i4.png)](https://i.stack.imgur.com/BV7i4.png) This corresponds to the input `[(1,2),(0,3),(2,0),(2,0)]` The train travels the following route: ``` [0] -L-> [1] -L-> [0] -R-> [2] -L-> [2] -R-> [0] -L-> [1] -R-> [3] ``` Since the train reached its destination, the last junction, the correct output is truthy. For the input `[(1,2),(0,3),(2,2),(2,0)]` we have the following route: ``` [0] -L-> [1] -L-> [0] -R-> [2] -L-> [2] -R-> [2] -L-> [2] -R-> ... ``` This time, the train got stuck in the junction `2`, and will never reach the destination. The correct output is thus falsy. ## Rules and scoring You can write a full program or a function, and the lowest byte count wins. Consider skimming the article, as it may contain useful info for writing a solution. ## Test cases These have 0-based indexing. ``` [(0,0)] -> True [(0,1),(0,0)] -> True [(0,0),(1,0)] -> False [(1,2),(0,3),(2,0),(1,2)] -> True [(1,2),(0,3),(2,2),(1,2)] -> False [(1,2),(3,0),(2,2),(1,2)] -> True [(1,2),(2,0),(0,2),(1,2)] -> False [(0,2),(4,3),(0,4),(1,2),(4,1)] -> True [(4,0),(3,0),(4,0),(2,0),(0,4)] -> True [(1,4),(3,2),(1,4),(5,3),(1,0),(5,2)] -> True [(3,1),(3,2),(1,5),(5,4),(1,5),(3,2)] -> True [(1,2),(5,0),(3,2),(2,4),(2,3),(1,6),(1,2)] -> False [(4,9),(7,3),(5,2),(6,4),(6,5),(5,4),(3,2),(6,8),(8,9),(9,1)] -> False [(2,7),(1,5),(0,8),(9,7),(5,2),(0,4),(7,6),(8,3),(7,0),(4,2)] -> True [(4,9),(7,3),(3,2),(8,3),(1,2),(1,1),(7,7),(1,1),(7,3),(1,9)] -> False [(0,13),(3,6),(9,11),(6,12),(14,11),(11,13),(3,8),(8,9),(12,1),(5,7),(2,12),(9,0),(2,1),(5,2),(6,4)] -> False [(6,0),(1,2),(14,1),(13,14),(8,7),(6,4),(6,10),(9,10),(10,5),(10,9),(8,12),(14,9),(4,6),(11,10),(2,6)] -> False [(1,3),(9,17),(5,1),(13,6),(2,11),(17,16),(6,12),(0,8),(13,8),(10,2),(0,3),(12,0),(3,5),(4,19),(0,15),(9,2),(9,14),(13,3),(16,11),(16,19)] -> True ``` [Answer] ## [CJam](http://sourceforge.net/projects/cjam/), ~~30~~ 29 bytes ``` 0l~_,m!{_2$=(@@2$+3$\t}*,(])& ``` Uses 0-based inputs and prints the index of the terminal node if the terminal node is ever reached. This is super inefficient. You wouldn't want to test this on inputs with more than 10 nodes. The test link below uses `2\#` instead of `m!` which isn't *quite* enough for all possible inputs, but it passes all test cases in a few seconds (and one would have try fairly hard to find a test case that doesn't pass). [Try it online!](http://cjam.tryitonline.net/#code=cU4vezpMOwoKMEx-XywyXCN7XzIkPShAQDIkKzMkXHR9KiwoXSkmCgpdbn0v&input=W1swIDBdXQpbWzAgMV0gWzAgMF1dCltbMSAyXSBbMCAzXSBbMiAwXSBbMSAyXV0KW1sxIDJdIFszIDBdIFsyIDJdIFsxIDJdXQpbWzAgMl0gWzQgM10gWzAgNF0gWzEgMl0gWzQgMV1dCltbNCAwXSBbMyAwXSBbNCAwXSBbMiAwXSBbMCA0XV0KW1sxIDRdIFszIDJdIFsxIDRdIFs1IDNdIFsxIDBdIFs1IDJdXQpbWzMgMV0gWzMgMl0gWzEgNV0gWzUgNF0gWzEgNV0gWzMgMl1dCltbMiA3XSBbMSA1XSBbMCA4XSBbOSA3XSBbNSAyXSBbMCA0XSBbNyA2XSBbOCAzXSBbNyAwXSBbNCAyXV0KW1sxIDNdIFs5IDE3XSBbNSAxXSBbMTMgNl0gWzIgMTFdIFsxNyAxNl0gWzYgMTJdIFswIDhdIFsxMyA4XSBbMTAgMl0gWzAgM10gWzEyIDBdIFszIDVdIFs0IDE5XSBbMCAxNV0gWzkgMl0gWzkgMTRdIFsxMyAzXSBbMTYgMTFdIFsxNiAxOV1dCltbMCAwXSBbMSAwXV0KW1sxIDJdIFswIDNdIFsyIDJdIFsxIDJdXQpbWzEgMl0gWzIgMF0gWzAgMl0gWzEgMl1dCltbMSAyXSBbNSAwXSBbMyAyXSBbMiA0XSBbMiAzXSBbMSA2XSBbMSAyXV0KW1s0IDldIFs3IDNdIFs1IDJdIFs2IDRdIFs2IDVdIFs1IDRdIFszIDJdIFs2IDhdIFs4IDldIFs5IDFdXQpbWzQgOV0gWzcgM10gWzMgMl0gWzggM10gWzEgMl0gWzEgMV0gWzcgN10gWzEgMV0gWzcgM10gWzEgOV1dCltbMCAxM10gWzMgNl0gWzkgMTFdIFs2IDEyXSBbMTQgMTFdIFsxMSAxM10gWzMgOF0gWzggOV0gWzEyIDFdIFs1IDddIFsyIDEyXSBbOSAwXSBbMiAxXSBbNSAyXSBbNiA0XV0KW1s2IDBdIFsxIDJdIFsxNCAxXSBbMTMgMTRdIFs4IDddIFs2IDRdIFs2IDEwXSBbOSAxMF0gWzEwIDVdIFsxMCA5XSBbOCAxMl0gWzE0IDldIFs0IDZdIFsxMSAxMF0gWzIgNl1d) ### Explanation This doesn't have any loop or terminal detection. Instead we simply iterate the system often enough that we *know* we've hit a loop, recording the history, and then we check whether we've reached the terminal node at any point. If we don't visit the terminal node, we only modify the states of `N-1` nodes (if `N` is the total number of nodes). Each of the nodes has two different states, and the train can be on any one of those nodes (thanks to ais523 for pointing this out), so there are `2(N-1)*(N-1)` different states we can visit before entering a loop or reaching the terminal node. Since we start from one of these states we know that after `2(N-1)*(N-1)` transitions, we've either entered a loop or reached the terminal node. That's a fairly lengthy expression. However, `N!` is almost never less than `2(N-1)*(N-1)`. In fact, the only `N` for which that's the case is `3`, where the number of possible states is `8` and `N!` gives only `6`. That said, it's not necessarily the case that it's possible to reach all theoretical states in any of the possible inputs. It's fairly easy to check this exhaustively: the neighbours of the last node are always irrelevant, so we can simply consider all inputs of the form `[[a b] [c d] [0 0]]` where at least one of `abcd` contains `2` (otherwise, the terminal state is guaranteed to be unreachable). There are only 65 of these states, and I ran them through [a slightly modified program](http://cjam.tryitonline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zIgMl0gWzAgMF1dCltbMiAwXSBbMCAwXSBbMCAwXV0KW1syIDBdIFswIDFdIFswIDBdXQpbWzIgMF0gWzAgMl0gWzAgMF1dCltbMiAwXSBbMSAwXSBbMCAwXV0KW1syIDBdIFsxIDFdIFswIDBdXQpbWzIgMF0gWzEgMl0gWzAgMF1dCltbMiAwXSBbMiAwXSBbMCAwXV0KW1syIDBdIFsyIDFdIFswIDBdXQpbWzIgMF0gWzIgMl0gWzAgMF1dCltbMiAxXSBbMCAwXSBbMCAwXV0KW1syIDFdIFswIDFdIFswIDBdXQpbWzIgMV0gWzAgMl0gWzAgMF1dCltbMiAxXSBbMSAwXSBbMCAwXV0KW1syIDFdIFsxIDFdIFswIDBdXQpbWzIgMV0gWzEgMl0gWzAgMF1dCltbMiAxXSBbMiAwXSBbMCAwXV0KW1syIDFdIFsyIDFdIFswIDBdXQpbWzIgMV0gWzIgMl0gWzAgMF1dCltbMiAyXSBbMCAwXSBbMCAwXV0KW1syIDJdIFswIDFdIFswIDBdXQpbWzIgMl0gWzAgMl0gWzAgMF1dCltbMiAyXSBbMSAwXSBbMCAwXV0KW1syIDJdIFsxIDFdIFswIDBdXQpbWzIgMl0gWzEgMl0gWzAgMF1dCltbMiAyXSBbMiAwXSBbMCAwXV0KW1syIDJdIFsyIDFdIFswIDBdXQpbWzIgMl0gWzIgMl0gWzAgMF1d), which finds the first transition after which the terminal state is reached (or `-1` if it's unreachable). As it turns out, it's impossible to construct an input which requires more than 6 transitions to reach the terminal state, just what we need. Hence, I'm using `N!` as the upper bound of iterations. ``` 0 e# Push a zero. This is the initial node index of the train. l~ e# Read and evaluate the input. _,m! e# Compute the factorial of N. { e# Run this block N! times. _ e# Copy the list of LR pairs. 2$= e# Copy the current node index and extract the corresponding pair. ( e# Pull off the first neighbour - this is where the train moves next. @@ e# Pull list of pairs and the list with the other neighbour on top. 2$+ e# Copy the first neighbour and append it. This effectively, reverses e# the pair so that next time the other destination from the current e# node is picked. 3$ e# Copy the current node again. \ e# Swap it with the reversed pair. t e# Write the reversed pair back into the full list of pairs. e# In summary, one iteration extracts the first neighbour of the e# current node and leaves it on the stack, and swaps the neighbours e# of that node for future visits. }* e# At the end, we've got all the reachable nodes on the stack, and e# the list of all pairs still on top. ,( e# Compute N-1 from the list of pairs. ]) e# Wrap everything in a list and remove N-1 from it. & e# Compute the set intersection all reachable nodes with N-1. ``` [Answer] # Perl, 52 + 2 = 54 bytes ``` $F[$1/($@++<@F<<@F)]=~s/(.+),(.+)/$2,$1/ while$1<$#F ``` Run with `-ap` (2 byte penalty). Input is a single line in the format `1,2 0,3 2,2 2,0`. Prints a copy of the input (which is truthy in Perl, as it's a string more than one byte long) to standard output on success, or crashes via dividing by zero (producing nothing on standard output; the null string is falsey) on failure. The algorithm is very simple; we simply simulate the movement of the train, remembering its current location in `$1` (whose initial value is zero when seen as an integer, and which automatically updates to hold the first capture group every time a regex is run), and the current states of the track by overriding `@F` (which holds the input array, and is input via the `-a` option on the command line). In order to detect that we've got stuck in a loop, we use `$@` to count the number of steps taken; if this exceeds the number of switches times 2 to the power of the number of switches (a formula that can be conveniently written in Perl as `@F<<@F` and which is only slightly higher than the actual upper bound), we're necessarily stuck in a loop, because seeing the same (track, train) state twice will cause an infinite loop in this problem, and we've already been through more states than there are *distinct* states (so by the pigeonhole principle, we must have seen at least one twice). [Answer] # Haskell, ~~114~~ ~~95~~ ~~88~~ 84 bytes ``` (o%h)g|elem(o,g)h=1<0|(a,(l,r):b)<-splitAt o g=null b||(l%((o,g):h)$a++(r,l):b) 0%[] ``` Keeps a history of visited (location, network) pairs to be able to decide a failure. Junctions tuples are swapped when visited. Usage: ``` 0%[]<$>[[(0,0)] ,[(0,1),(0,0)] ,[(0,0),(1,0)] ,[(1,2),(0,3),(2,0),(1,2)] ,[(1,2),(0,3),(2,2),(1,2)] ,[(1,2),(3,0),(2,2),(1,2)] ,[(1,2),(2,0),(0,2),(1,2)] ,[(0,2),(4,3),(0,4),(1,2),(4,1)] ,[(4,0),(3,0),(4,0), (2,0),(0,4)] ,[(1,4),(3,2),(1,4),(5,3),(1,0),(5,2)] ,[(3,1),(3,2),(1,5),(5,4),(1,5),(3,2)] ,[(1,2),(5,0),(3,2),(2,4),(2,3),(1,6),(1,2)] ,[(4,9),(7,3),(5,2),(6,4),(6,5),(5,4),(3,2),(6,8),(8,9),(9,1)] ,[(2,7),(1, 5),(0,8),(9,7),(5,2),(0,4),(7,6),(8,3),(7,0),(4,2)] ,[(4,9),(7,3),(3,2),(8,3),(1,2),(1,1),(7,7),(1,1),(7,3),(1,9)] ,[(0,13),(3,6),(9,11),(6,12),(14,11),(11,13),(3,8),(8,9),(12,1),(5,7),(2,12),(9,0),(2,1),(5,2), (6,4)] ,[(6,0),(1,2),(14,1),(13,14),(8,7),(6,4),(6,10),(9,10),(10,5),(10,9),(8,12),(14,9),(4,6),(11,10),(2,6)] ,[(1,3),(9,17),(5,1),(13,6),(2,11),(17,16),(6,12),(0,8),(13,8),(10,2),(0,3),(12,0),(3,5),(4,19),(0, 15),(9,2),(9,14),(13,3),(16,11),(16,19)]] [True,True,False,True,False,True,False,True,True,True,True,False,False,True,False,False,False,True] ``` Ungolfed: ``` rails location history network | elem state history = False --We are stuck in a loop | otherwise = null b || (rails l newHistory swapped) --b is empty when location is last element in list where (a, (left, right):b) = splitAt location network swapped = a ++ (right, left):b state = (location, network) newHistory = state:history ``` Thanks @Zgarb for saving 4 bytes [Answer] # Python ~~135~~ 133 bytes -1 byte thanks to Angs (`l>len(c)-2` rather than `l==len(c)-1`) ``` def f(c,p=0,l=0,h=[]):j=len(c);p=p or[0]*j;s=p[:],l;r=2*(l>j-2)or(s in h);n=c[l][p[l]];p[l]=1-p[l];return r-1if r else f(c,p,n,h+[s]) ``` **[repl.it](https://repl.it/Eclc/1)** Returns `1` (truthy) if the goal is reached; or `0` (falsey) if a state is reached that has been reached before. Otherwise recurses updating the state. `c` is the network. `p` is the current state of each switch (initialised to all left as `[0]*len(c)` on the first run). `l` is the current location. `h` is the state history, to which `s`, a tuple of a copy of `p` and `l`, is added. ]
[Question] [ **This question already has answers here**: [Code Golf: Number of paths!](/questions/1326/code-golf-number-of-paths) (9 answers) Closed 7 years ago. ### Definition Define the **n**th term of the CRAU sequence as follows. 1. Begin with the singleton array **A = [n]**. 2. Do the following **n** times: For each integer **k** in **A**, replace the entry **k** with **k** natural numbers, counting from **1** to **k**. 3. Compute the sum of all integers in **A**. For example, if **n = 3**, we start with the list **[3]**. We replace **3** with **1, 2, 3**, yielding **[1, 2, 3]**. We now replace **1**, **2**, and **3** with **1**, **1, 2** and **1, 2, 3** (resp.), yielding **[1, 1, 2, 1, 2, 3]**. Finally, we perform the same replacements as in the previous step for all six integers in the array, yielding **[1, 1, 1, 2, 1, 1, 2, 1, 2, 3]**. The sum of the resulting integers is **15**, so this is the third CRAU number. ### Task Write a program of a function that, given a strictly positive integer **n** as input, computes the **n**th term of the CRAU sequence. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). May the shortest code in bytes win! ### Test cases ``` 1 -> 1 2 -> 4 3 -> 15 4 -> 56 5 -> 210 6 -> 792 7 -> 3003 8 -> 11440 9 -> 43758 10 -> 167960 11 -> 646646 12 -> 2496144 13 -> 9657700 ``` ### Related * [Simplicial polytopic numbers](http://oeis.org/wiki/Simplicial_polytopic_numbers) * [OEIS A001791: Binomial coefficients C(2n,n-1)](https://oeis.org/A001791) [Answer] # MATL, 5 bytes ``` EGqXn ``` [Try it online,](http://matl.tryitonline.net/#code=RUdxWG4&input=NQ) or [verify all test cases!](http://matl.tryitonline.net/#code=RUdxWG4&input=WzEgMiAzIDQgNSA2IDcgOCA5IDEwIDExIDEyIDEzXQ) Explanation: ``` E #Double the input Gq #Push "input - 1" Xn #Calculate "nchoosek" on the two numbers ``` [Answer] # Python, 65 bytes ``` def f(k): n,p=2*k,1 for i in range(1,k):p=p*n//i;n-=1 return p ``` Explanation: It's a simplified version of n choose k. See [this sequence](https://oeis.org/A001791). [Answer] ## [Retina](https://github.com/mbuettner/retina), 27 bytes ``` $ $.`$* M!&+%`.+(?=1)|^.+ 0 ``` Input in unary, using `0` as the unary digit. [Try it online!](http://retina.tryitonline.net/#code=JAokLmAkKgpNISYrJWAuKyg_PTEpfF4uKwow&input=MDAwMA&debug=on) [Answer] # J, 5 bytes ``` <:!+: ``` Uses the binomial coefficient of (2*n*, *n*-1). For **22 bytes**, this is a possible solution based on using the process described in the challenge. ``` [:+/([:;<@(1+i.)"0)^:] ``` ## Usage Note: Extra commands used to format output for multiple input. ``` f =: <:!+: (,.f"0) >: i. 13 1 1 2 4 3 15 4 56 5 210 6 792 7 3003 8 11440 9 43758 10 167960 11 646646 12 2496144 13 9657700 ``` ## Explanation ``` <:!+: Input: n +: Double the value of n to get 2*n <: Decrement n to get n-1 ! Calculate the binomial coefficient of (2*n, n-1) and return [:+/([:;<@(1+i.)"0)^:] Input: n ] Identify function, gets the value n ( ... )^: Repeat the following n times with an initial value [n] ( )"0 Means rank 0, or to operate on each atom in the list i. Create a range from 0 to that value, exclusive 1+ Add 1 to each to make the range from 1 to that value <@ Box the value [:; Combine the boxes and unbox them to make a list and return [:+/ Sum the values in the list after n iterations and return ``` ]
[Question] [ Here we go again! This is my last flag for now! I originally wanted to do my national flag but I thought the stars were too hard so I posted [Print the British Flag!](https://codegolf.stackexchange.com/questions/52643/print-the-british-flag) instead, which itself was inspired by [Print the American Flag!](https://codegolf.stackexchange.com/questions/52615/print-the-american-flag). This challenge would be better for 3 September (Australian National Flag Day) or 26 January (Australia Day) but I couldn't wait that long! The Commonwealth Star is a bit messy but I'm pleased with the rest of the design. Once again you need to view it at 90 degrees. Produce the following design in the fewest bytes! ``` ________________________________________________ |XXXXXXXXXXXXXXXXXXXXXXXX\ \XXXX 0000 XXXX//0/| |XXXXXXXXXXXXXXXXXXXXXXXX0\ \XXX 0000 XXX//0/ | |XXXXXXXXXXXXXXXXXXXXXXXX\0\ \XX 0000 XX//0/ | |XXXXXXXXXXXXXXXXXXXXXXXX\\0\ \X 0000 X//0/ /| |XXXXXXXXXXXXXXXXXXXXXXXXX\\0\ \ 0000 //0/ /X| |XXXXXXXXXXXXXXXXXXXXXXXXXX\\0\ 0000 /0/ /XX| |XXXXXXXXXXXXXXXXXXXXXXXXXXX\\0\ 0000 0/ /XXX| |XXXXXXXXXXXXXXXXXXXXXXXXXXXX\\0\ 0000 / /XXXX| |XXXXXXXX|\XXXXX-/XXXXXXXXXXXX\\0 0000 /XXXXX| |XXXXX-XX| \XX- /XXXXXXXXXXXXXX\\ 0000 /XXXXXX| |XXXXX\ -| --XXXXXXX 0000 | |XXXXXXX\ -XXXXX000000000000000000000000| |XXXXXXX/ -XXXXX000000000000000000000000| |XXXXX/ -| --XXXXXXX 0000 | |XXXXX-XX| /XX- \XXXXXXXXXXXXXX/ 0000 \\XXXXXX| |XXXXXXXX|/XXXXX-\XXXXXXXXXXXX/ 0000 0\\XXXXX| |XXXXXXXXXXXXXXXXXXXXXXXXXXXX/ / 0000 \0\\XXXX| |XXXXXXXXXXXXXXXXXXXXXXXXXXX/ /0 0000 \0\\XXX| |XXXXXXXXXXXXXXXXXXXXXXXXXX/ /0/ 0000 \0\\XX| |XXXXXXXXXXXXXXXXXXXXXXXXX/ /0// 0000 \ \0\\X| |XXXXXXXXXXXXXXXXXXXXXXXX/ /0//X 0000 X\ \0\\| |XXXXXXXXXXXXXXXXXXXXXXXX /0//XX 0000 XX\ \0\| |XXXXXXXXXXXXXXXXXXXXXXXX /0//XXX 0000 XXX\ \0| |XXXXXXXXXXXXXXXXXXXXXXXX/0//XXXX 0000 XXXX\ \| |XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX| |XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX| |XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX| |XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX| |XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX| |XXXXXXXXXXXXXXXXXXXXXXXXX|\/|XXXXXXXXXXXXXXXXXXX| |XXXXXXXXXXXXXXXXXXXXXXXX> >XXXXXXXXXXXXXXXXXX| |XXXXXXXXXXXXXXXXXXXXXXXXX|/\|XXXXXXXXXXXXXXXXXXX| |XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX| |XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX| |XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX| |XXXXXX|\/|XXXXXXXXXXXXXXXXXXXXXXXXXXXX|\/|XXXXXX| |XXXXX> >XXXXXXXXXXXXXXXXXXXXXXXXXX> >XXXXX| |XXXXXX|/\|XXXXXXXXXXXXXXXXXXXXXXXXXXXX|/\|XXXXXX| |XXXXXXXXXXXXXXXXXXXXX/|XXXXXXXXXXXXXXXXXXXXXXXXX| |XXXXXXXXXXXXXXXXXXX> >XXXXXXXXXXXXXXXXXXXXXXXX| |XXXXXXXXXXXXXXXXXXXXX\|XXXXXXXXXXXXXXXXXXXXXXXXX| |XXXXXXXXXXXXXXXXXXXXXXXXXXXX|\/|XXXXXXXXXXXXXXXX| |XXXXXXXXXXXXXXXXXXXXXXXXXXX> >XXXXXXXXXXXXXXX| |XXXXXXXXXXXXXXXXXXXXXXXXXXXX|/\|XXXXXXXXXXXXXXXX| |XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX| |XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX| |XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX| |XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX| ``` Things to watch out for: there is a space at the end of the first line. No other trailing spaces are allowed. The dimensions are 50 x 49 (48 x 48 plus borders on three sides).The fifth star (5-pointed) in the Southern Cross is slightly smaller and a different design from the others (7-pointed). A trailing newline is allowed but not required. My code editor has a thumbnail view of the code at the side. This is what this design looks like: ![Thumbnail of ASCII-Art Australian Flag](https://i.stack.imgur.com/dPD2k.png) Not bad! [Answer] # Python 2, 446 Bytes Just decodes the Base64 and decompresses using zlib. ``` import zlib,base64 print zlib.decompress(base64.b64decode("eNrl1MFtwzAMBdCeMwUXEOgJPIcPBLqIhk8ofkq2QdFQb215iZDkgdSXZfpeLHrVY1JCJPpJtH2KSNfMG9c52WBORAUlRL7MDNJESsT6dGIiG8yNE4gjIzCdmMiJGyMQDwQGXUycSW2ncBS+GScQnZTPUhMtxPc+neAXJ0KlUqtS8Gfq5V2sxmAyvjS0TWoQXiW8PljbPuv25bp97kTkun1dWiJF7sKPEubhKLmdILrA5ETFOEqYlDCeRd++mYyYGIPBJARiXDGYhECcLrKZjJg4vy6ayQYzcXkpqXk4l6j+C6nCdY3s+ljti11Y6q9MbBJPEJ+TWTxBfKNLHE8Q32wvyZQx2bMpZ12k/jTkKMechDk+dQly/FMX+Q3ohQN5")) ``` [Answer] # dash, 261 bytes ``` 0000000: 7a6361743c3c27270a1f8b0801010101010203e5d3c98d04 zcat<<''................ 0000018: 410844d1fb58110ea4480bda0e0e48e308bef7fad5cc4a89 A.D..X...H....H.......J. 0000030: db2c717f0944a9f43a8c5ed2bf4948e1d748fb1ac9af31db .,q..D..:.^..IH..H....1. 0000048: 96df938d8108a186040622444b3010210cd2198810de110c .........."DK0.!........ 0000060: 44889e6020889e602088b724c36f59f6c140847892e59e0a D..` ..` [[email protected]](/cdn-cgi/l/email-protection).... 0000078: f725441908a24868a5ee59cb1f118110be0be89907dadfa4 .%D...Hh..Y............. 0000090: 884d894d17e37c735f0a440d8744d4f924ed81cb20201bd3 .M.M..|s_.D..D..$... .. 00000a8: 7c4a844114184823360403698541309056d4621848235c10 |J.A..H#6..i.A0.V.b.H#\. 00000c0: c734045104d31044114c431045309049fe0bc9b09c919324 .4.Q...D.LC.E0.I.......$ 00000d8: 9d86532cf25736463dc7f541aa9ee3fa20554f5f5f7b8be5 ..S,.W6F=..A.... UO__{.. 00000f0: f0fc135b8c1a8be3297d4f03424f13424f7ff847be ...[....)}O.BO.BO..G. ``` It should be possible to beat this score with manual compression and a terse language, but if your going to use a widely available compressor (and don't think you can get away with calling zcat a non-Turing complete programming language), dash is probably the best option. I chose [zopfli](https://github.com/google/zopfli) as the compressor since it is compatible with the Coreutils program zcat and achieves better compression than gzip, bzip2 and xz. Note that zcat will print a warning to STDERR, which is allowed by default per [consensus on Meta](http://meta.codegolf.stackexchange.com/q/4780). ### Testing This is how I created and tested the program: ``` $ echo "zcat<<''" > flag.sh $ git clone https://github.com/google/zopfli.git $ make -C zopfli $ zopfli/zopfli -c --i100000 flag.txt >> flag.gz $ head -c 252 flag.gz | tr \\000 \\001 >> flag.sh $ dash flag.sh 2>&- | md5sum - flag.txt 168400d97bf59ebff194a6d13495cc26 - 168400d97bf59ebff194a6d13495cc26 flag.txt ``` Head strips the last 9 bytes from the gzip file, which aren't required for successful decompression. Fortunately, the gzip file only contains NUL bytes in its header, which can be replaced with SOH bytes without affecting the output. [Answer] # CJam, ~~250~~ ~~246~~ 231 bytes ``` S'_48*S"0H:+-86:0@6CEM00":i~'X*a*["3|\5-/2-2| \2- /3\ -| 0--4\00-"6,_s\'Xf*0S5*ter sE/_W%{"\/"_W%er}:R%+"X|\/|X> "_W%+6/___"XX/|X> >XX\|"5/C,'X6*"//0/ /"+2*f>8f< _2>\W%2>.{R" 00 ":_@}" 0 0"[A4A24].*+s_W%+24/]{..e&fm>m<}/{N'|@'|}/ ``` The linefeeds are purely cosmetic and do not contribute to the byte count. Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=S'_48*S%220H%3A%2B-86%3A0%406CEM00%22%3Ai~'X*a*%5B%223%7C%5C5-%2F2-2%7C%20%5C2-%20%2F3%5C%20-%7C%200--4%5C00-%226%2C_s%5C'Xf*0S5*tersE%2F_W%25%7B%22%5C%2F%22_W%25er%7D%3AR%25%2B%22X%7C%5C%2F%7CX%3E%20%20%22_W%25%2B6%2F___%22XX%2F%7CX%3E%20%20%20%3EXX%5C%7C%225%2FC%2C'X6*%22%2F%2F0%2F%20%20%2F%22%2B2*f%3E8f%3C_2%3E%5CW%252%3E.%7BR%22%2000%20%22%3A_%40%7D%22%200%200%22%5BA4A24%5D.*%2Bs_W%25%2B24%2F%5D%7B..e%26fm%3Em%3C%7D%2F%7BN'%7C%40'%7C%7D%2F). ### Idea We start by pushing the background of the flag, i.e., 48 strings of 48 **X**'s each. Now, we generate all 7 foreground images, i.e., the different types of stars and the miniature British flag. ``` "3|\5-/2-2| \2- /3\ -| 0--4\00-" ``` encodes the big star. After replacing each positive number with that many **X**'s, each **0** with a string of 5 spaces and splitting the result into chunks of length 14, we obtain the following: ``` XXX|\XXXXX-/XX -XX| \XX- /XXX \ -| --XX XX\ - ``` If we repeat these strings, in reversed order, and swap the slashes, we obtain the desired big star: ``` XXX|\XXXXX-/XX -XX| \XX- /XXX \ -| --XX XX\ - XX/ - / -| --XX -XX| /XX- \XXX XXX|/XXXXX-\XX ``` For the middle star, we simply push the string `"X|\/|X> "`, concatenate it with a reversed copy of itself and chop the result into strings of length 6: ``` X|\/|X > > X|/\|X ``` Now, we push the small star as `"XX/|X> >XX\|"` chopped into strings of length 5: ``` XX/|X > > XX\| ``` (The missing **X** doesn't matter since the background already contains it.) Finally, we push the small flag, using almost exactly the same approach as in [Print the British Flag!](https://codegolf.stackexchange.com/a/52662) Now that we have all parts, we start to assemble them. By using twofold vectorized logical AND on the background and the big star, we can replace each truthy character of the background (and all are truthy) by the corresponding character of the big star. We now rotate the array of strings, and the strings themselves as well, so that the first middle star should be in the upper left corner, then repeat the process from the last paragraph to incorporate this star. In the same fashion, we paint the remaining stars and the small flag over the background. After assembling all parts, we only have to add the vertical bars, linefeeds and underscores. ### Code ``` S'_48*S e# Push a space, a string of 48 underscores and another space. "0H:+-86:0@6CEM00" :i~ e# Cast each char to int and dump. e# This pushes 48 72 58 43 45 56 54 58 48 64 54 67 69 77 48 48. e# All but the last two integers are rotation amounts. 'X* e# Push a string of 48 X's. a* e# Wrap 48 copies of that string in an array. [ e# "3|\5-/2-2| \2- /3\ -| 0--4\00-" 6,_s e# Push [0 1 2 3 4 5] and "012345". \'Xf* e# Replace the array with ["" "X" "XX" ... "XXXXX"]. 0S5*t e# Replace "" with " ". er e# Perform transliteration. sE/ e# Flatten and chop into chunks of length 14. _W% e# Copy and reverse the order of the chunks. { e# Define a function: "\/" e# Push that string. _W% e# Push a reversed copy. er e# Perform transliteration. }:R% e# Save in R and map over the second array of chunks. + e# Concatenate. "X|\/|X> " _W% e# Push a reversed copy. +6/ e# Concatenate and chop into chunks of length 6. ___ e# Copy the resulting array three more times. "XX/|X> >XX\|" 5/ e# Split into chunks of length 5. C,'X6*"//0/ /"+2*f>8f<_2>\W%2>.{R" 00 ":_@}" 0 0"[A4A24].*+s_W%+24/ e# https://codegolf.stackexchange.com/a/52662 ] { e# For each array of strings in the preceding array of arrays: ..e& e# Perform twofold vectorized logical AND. fm> e# Pop an integer from the stack and rotate each string that many e# units to the right. m< e# Pop an integer from the stack and rotate the array of strings e# that many units to the left/strings up. }/ e# { e# For each string in the resulting array: N'| e# Push a linefeed and a vertical bar. @ e# Rotate the string on top of them. '| e# Push an additional vertical bar. }/ e# ``` [Answer] # Python 2 - 1258 bytes ``` import zlib v=len l=zlib.decompress("x\x9c\x95\x94I\x12\x83 \x10E\xaf\xc2\x05,F\xd1l<\x87\x0b\xaar\x11\x0f\x1f\t44\x9fv\xe1\"\xd5\x08y\xbfG\x08\xbb\xfaZ\xa5\xd4\xfd\xbb\\P\xe7m\x93+\xdf)(u\xe6\xf5mM\xb5\xf9[\xdfg\xc6\x16{1\xcep\xd6\x03\xebgV\x01\x9fP\xc3\x81\x86\x03\r\x07\x1aN\xd0\xb0\xa0ae\x8d\x9e\xcb*\xeb@\x1c\x12\x7f6\x8d8j\x84\xd1\xff\xc4:\xcen#\xebGv\xe0<\xe7\xf69n\xee\x93l`\xcc\xde\xd7i-\xeb\xe5\x1f\x9f\xebZ\xa4\x13*\xbf2\x9e\x18\x16\x7f\xeb[\xd5*\xf9\xd6\xde\x90\x96\xaf\xfbq\xd6J\x95\xc9\xec\x15K\xad\x97-\x9f\x99\xc2fK\xccFL\xd9[\xb2\xc6=\x07\x06\xce\xf5\xd3\xf9J\xe7/|>\xe4\xac!\xe7d\xcbLk?\xceM\x8ar\xfd5\xab\x7f\xca\xf5\xaf\xbd\x1az\xefz\x9fZ\xcfa\x8e\xf8\xff\xa9\x7f)\xc0|\xc1\xdc\x1a\xe8K\xe3<\xcc4r\xdcg\x00v\x98\xe9U\xf49\xc5\x8bq\x0fw*\xc8\x1a\xd2\xfd~\xd0\xe2\xef\x04\xc61\xbd3\xa8aA\xc3\x82\x86\xf4\xde\t\x1aC.\xc4J\xef,\xb0\x7f.\xec\xbd\x1eo\xd7\xb5\x07W\xd5+\xef\xddg\xaa\xefQ\xfbxX\x99\xd5-\x9e\xcf;\xffl\xee\x9b\x7f\xb7\xcf{\xc2\x9b\xd0b\xaa3\xd8\xbe\xf9]`\\\x8b\x91\xe9\xb7=\xae\xefl\xeb\x03\xcf\x91r;<\xf9\r\x13\x93\x90\x91r\xb1q\xbaw\xbd\xbe2\xdb\xeb\x1b\xdf\xd5\x97\xd6?\xd9\xaczF") n=''.join([i[-1]*int(i[:v(i)-1].replace(' ',''))for i in[l[i:i+4]for i in range(0,v(l),4)]]) print''.join(n[i]if(i+2)%50 else n[i]+'\n'for i in range(v(n))) ``` I decided to encode the flag using [run length encoding](https://en.wikipedia.org/wiki/Run-length_encoding), then compressed it using zlib. In the program, it just decodes all of this and prints it to the console. ]
[Question] [ We have a lot of IPV4 address, to group into subnets, so we need a tool for doing this: Our list is very ugly, not ordered and sometime in subnet notation, sometime in simple address. **Sample:** ``` 192.168.5.16/30 192.168.5.18 192.168.2.231/27 192.173.17.0/24 192.168.1.5/32 192.168.5.18/32 192.168.3.0/24 192.168.2.231/27 192.168.2.245/29 192.168.4.0/29 192.173.16.0/24 192.173.18.0/24 192.173.19.0/24 10.100.12.24 ``` some explanation about the input (*our old list*): * each line hold only **1** IPV4 *subnet* * if a line don't contain any subnet info like on line `2`, it's a single ip, so the 32 bit mask is to be considered. * subnet info is in the *CIDR* form: `IPV4/integer` where integer is mask length * IPV4 is not necessarely the *base* (first in range) of subnet * list is not sorted * list is not short... could make more the 60k entries... * there is repetition, overlap of subnets... lot of *useless lines* ( The last is the main reason we need to build this tool! ;-) From this sample list we want to obtain shortened, sorted and cleaned list like: ``` 10.100.12.24/32 192.168.1.5/32 192.168.2.224/27 192.168.3.0/24 192.168.4.0/29 192.168.5.16/30 192.173.16.0/22 ``` Where all lines is subnet and all IPV4 part is base IP (begin of range), sorted, and without overlap or repetitions. And where all IP present somewhere in input is present and no one more! **CIDR** For informations about: * Subnetting <http://en.wikipedia.org/wiki/IPv4_subnetting_reference> * CIDR notation <http://en.wikipedia.org/wiki/Classless_Inter-Domain_Routing#CIDR_notation> **Code golf** * Input values could be given as you will, (arguments, read from file or STDIN) * Output to STDOUT, one subnet per line. * Output has to be sorted by the unsigned integer value of IPV4 (big-endian) * Output has to contain as few lines as possible * Of course, sum of output subnet must match sum of input subnet! **no more, nor less!** So `0.0.0.0/0` which override everything is not accepted! (unless it's the only valid answer, see last test) * Use of libraries forbiden! Standard loophole applies * Shortest code wins! **Test cases** For testing this, (under bash) I use something like: ``` for i in {167772416..167774464};do echo $[i>>24].$[i>>16&255].$[i>>8&255].$[i&255] done ``` as input, this must render: ``` 10.0.1.0/24 10.0.2.0/23 10.0.4.0/22 10.0.8.0/24 10.0.9.0/32 ``` or ``` for i in {167772416..167774464};do [ $i -gt 167773316 ] && [ $i -lt 167773556 ] || echo $[i>>24].$[i>>16&255].$[i>>8&255].$[i&255]/30 done ``` Note, I've added `/30` after each ip. this will do a lot of overlap! ``` 10.0.1.0/24 10.0.2.0/23 10.0.4.0/25 10.0.4.128/29 10.0.5.116/30 10.0.5.120/29 10.0.5.128/25 10.0.6.0/23 10.0.8.0/24 10.0.9.0/30 ``` Extreme test rule ``` 63.168.3.85/2 64.168.3.85/2 192.168.3.85/2 191.168.3.85/2 ``` This **special** case must render: ``` 0.0.0.0/0 ``` **Accepted answers** As this question seem not so easy, I will add *time from question* to the list > > 1. [CJam, 101](https://codegolf.stackexchange.com/a/48212/9424) - user23013 - 38 hours > 2. [Perl, 223](https://codegolf.stackexchange.com/a/48370/9424) - nutki - 1 week > 3. [Pure bash, 1040](https://codegolf.stackexchange.com/a/48263/9424) - F.Hauri - 4 days > > > [Answer] # CJam, 101 95 94 ``` qN/{'//('./1\+256b2b\{i)<}/}%_|{{):T;_aM+:M(a&}gT+}%${_2$#!{;}*}*]{_(!a32*+32<8/2fb'.*'/@,(N}% ``` The `{~}2j` construct didn't make it shorter... [Try it here](http://cjam.aditsu.net/#code=qN%2F%7B%27%2F%2F%28%27.%2F1%5C%2B256b2b%5C%7Bi%29%3C%7D%2F%7D%25_%7C%7B%7B%29%3AT%3B_aM%2B%3AM%28a%26%7DgT%2B%7D%25%24%7B_2%24%23!%7B%3B%7D*%7D*%5D%7B_%28!a32*%2B32%3C8%2F2fb%27.*%27%2F%40%2C%28N%7D%25&input=192.168.5.16%2F30%0A192.168.5.18%0A192.168.2.231%2F27%0A192.173.17.0%2F24%0A192.168.1.5%2F32%0A192.168.5.18%2F32%0A192.168.3.0%2F24%0A192.168.2.231%2F27%0A192.168.2.245%2F29%0A192.168.4.0%2F29%0A192.173.16.0%2F24%0A192.173.18.0%2F24%0A192.173.19.0%2F24%0A10.100.12.24). ([And link for Firefox](http://cjam.aditsu.net/#code=qN%2F%7B%27%2F%2F%28%27.%2F1%5C%2B256b2b%5C%7Bi%29%3C%7D%2F%7D%2525_%7C%7B%7B%29%3AT%3B_aM%2B%3AM%28a%26%7DgT%2B%7D%2525%24%7B_2%24%23!%7B%3B%7D*%7D*%5D%7B_%28!a32*%2B32%3C8%2F2fb%27.*%27%2F%40%2C%28N%7D%2525&input=192.168.5.16%2F30%0A192.168.5.18%0A192.168.2.231%2F27%0A192.173.17.0%2F24%0A192.168.1.5%2F32%0A192.168.5.18%2F32%0A192.168.3.0%2F24%0A192.168.2.231%2F27%0A192.168.2.245%2F29%0A192.168.4.0%2F29%0A192.173.16.0%2F24%0A192.173.18.0%2F24%0A192.173.19.0%2F24%0A10.100.12.24).) ### Explanation ``` qN/ " Read each line. "; { " For each line: "; '// " Split by / "; ('./ " Split first item by . "; 1\+256b2b " The address + 2^32 in base 2, which always has length 33 "; \{i)<}/ " For each other items N (if any), get the first N+1 bits. "; }% _| " Remove duplicates. "; { " For each item (each array of bits): "; { " Do: "; ):T; " Remove last bit and save it in T. "; _aM+:M " Add the array to M. "; (a#) " Find the array in the original M. "; }g " while it is found. "; T+ " Append the last T back. "; }% $ " Sort. "; { " Reduce and wrap in array: "; _2$#! " Test if the previous string is a prefix of the current. "; {;}* " If so, discard it. "; }*] { " For each item (each array of bits): "; _(!a32*+32< " Remove first bit and pad to 32 bits to the right. "; 8/2fb'.* " Convert to IP address. "; '/@,( " Append / and original length - 1. "; N " Append a newline. "; }% ``` [Answer] # Perl, 172 ~~223 245~~ Using hashes was not necessary. The removal allowed for a significantly shorter code, though the idea is the same. ``` #!perl -lp0a $_=join$\,sort map{1x(s/\d*./unpack B8,chr$&/ge>4?$&:32)&$_}@F;1while s/^(.*) \1.*/$1/m||s/^(.*)0 \1.$/$1/m;s!^.*!(join'.',map{ord}split'',pack B32,$&).'/'.length$&!gme ``` Test [me](http://#!perl%20-lp0a%20$_=join$%5C,sort%20map%7B1x(s/%5Cd*./unpack%20B8,chr$&/ge%3E4?$&:32)&$_%7D@F;1while%20s/%5E(.*)%20%5C1.*/$1/m%7C%7Cs/%5E(.*)0%20%5C1.$/$1/m;s!%5E.*!(join'.',map%7Bord%7Dsplit'',pack%20B32,$&).'/'.length$&!gme). Older version with explanation: ``` #!perl -lp0a s/(^|\.)(\d+)/sprintf"%08b",$2/ge,/\D/&&($_=$`|2x$',y/0-3/##01/)for@F;$_=join$\,sort@F;1while s/^((\d*)#*) \2.*/$1/mg||s/^(\d*)0(#*) \1[1]\b#*/$1#$2/mg;s!.+!$&.'/'.$&=~y/01//!ge;y/#/0/;s!\d{8}\B!$&.!g;s!\d{8}!"0b$&"!gee ``` Test [me](http://ideone.com/xHIIab). First convert input to textual format (`s/(^|\.)(\d+)/sprintf"%08b",$2/ge,/\D/&&($_=$p|2x$',y/0-3/##01/)`): ``` 00############################## 01############################## 11############################## 10############################## ``` Sort it (`$_=join$\,sort@F`): ``` 00############################## 01############################## 10############################## 11############################## ``` Clean using two regexps: one to remove duplicates and more specific addresses and the second to join two adjacent networks into one with a longer mask (`s/^((\d*)#*)\n\2.*/$1/mg` and `s/^(\d*)0(#*)\n\1[1]\b#*/$1#$2/mg`). ``` ################################ ``` And convert back to the original form (`s!.+!$&.'/'.$&=~y/01//!ge;y/#/0/;s!\d{8}\B!$&.!g;s!\d{8}!"0b$&"!gee`): ``` 0.0.0.0/0 ``` [Answer] ## Ruby - 425 (broken - see comment below) ``` a=(0..32).map{[]} l=->m{2**m-1<<32-m} $<.map{|i|/\//=~i=i[?/]?i:i.chop+'/32' s=$'.to_i n=$`.split(?.).inject(0){|v,d|v*256+d.to_i} next if s.times.any?{|t|a[t].any?{|e|n&l[t]==e[1]}} s.upto(32){|t|a[t].reject!{|e|e[1]&l[s]==n}} a[s]<<[i,n] (b=k=n&l[s] break if(y=a[s+1].select{|e|e[1]&l[s]==b}).size<2 a[s+1]-=y a[s]<<[(0..3).map{k,i=k.divmod(256);i}.reverse*?.+?/+s.to_s,b])until(s-=1)<0} puts a.flatten(1).sort_by{|v|v.pop} ``` [Answer] ### Pure bash ~~1100~~ ~~1079~~ 1040 **Edited:** A little ~~better~~ more *golfed*! ``` #!/bin/bash -i alias d=done e=unset f=printf\ -v g=local h=else i=then j=for k=while C=do E=fi n(){ g s e i;j i in ${!u[@]};C [ $1 -ge $[i+1] ]&&[ $1 -le $[u[i]+1] ]&&s=$i [ $2 -ge $[i-1] ]&&[ $2 -le $[u[i]-1] ]&&e=$i;d;if [ "$s" ];i if [ "$e" ];i \ [ $s -ne $e ]&&{ u[s]=${u[e]};e u[e];};h [ $1 -lt $s ]&&{ u[$1]=${u[s]};e u[s ];s=$1;};[ $2 -gt ${u[s]} ]&&u[s]=$2;E;h if [ "$e" ];i [ $1 -lt $e ]&&{ u[$1 ]=${u[e]};e u[e];e=$1;};[ $2 -gt ${u[e]} ]&&u[e]=$2;h u[$1]=$2;E;E;};q(){ g s=${1#*/} m=${1%/*} z;[ -z "${s//*.*}" ]&&s=32;y $s z;set -- ${m//./ } m=$[$1<<24|$2<<16|$3<<8|$4];n $[m&z] $[m|((2**32-1)^z)];};y(){ f $2 "%u" $[ ( 2**32-1)^(~0^~0<<(32-$1))];};r(){ f $2 "%s" $[$1>>24].$[$1>>16&255].$[$1>>8& 255].$[$1&255];};t(){ g s z;k [ "$1" ];C s=32;k y $[s-1] z&&[ $1 = $[($1>>(33 -s))<<(33-s)] ]&&[ $2 -ge $[$1|((2**32-1)^z)] ];C ((s--));d;r $1 x;echo $x/$s y $s z;if [ $2 -gt $[$1|((2**32-1)^z)] ];i set -- $[1+($1|((2**32-1)^z))] $2 h shift 2;E;d;};k read w;C q $w;d;p=-1;j o in ${!u[@]};C [ $o -gt $p ]&&p=${u[ o]}&&t $o ${u[o]};d ``` which work quickly, even on wide ranges! ``` ./myscript.sh <<<"63.168.3.85/2\n64.168.3.85/2\n192.168.3.85/2\n191.168.3.85/2" 0.0.0.0/0 ./myscript.sh < <(for i in {167772416..167774464};do [ $i -gt 167773316 ] && [ $i -lt 167773556 ] || echo $[i>>24].$[i>>16&255].$[i>>8&255].$[i&255]/30 done) 10.0.1.0/24 10.0.2.0/23 10.0.4.0/25 10.0.4.128/29 10.0.5.116/30 10.0.5.120/29 10.0.5.128/25 10.0.6.0/23 10.0.8.0/24 10.0.9.0/30 ``` [Answer] ### Javascript ~1335 While total js is 2009, the essential part is contained in two function and main routine. html, css and ~674 chars of javascript in only cosmetic. ``` var g={};function B(){document.getElementById('z').addEventListener('click',go); window.addEventListener('resize',C);C();}function C(){document.getElementById('y' ).setAttribute('style','height:'+(window.innerHeight-46-document.getElementById( 'y').offsetTop).toFixed(0)+"px");document.getElementById('x').setAttribute( 'style','height:'+(window.innerHeight-46-document.getElementById('x').offsetTop ).toFixed(0)+"px");}function go(){document.getElementById('y').innerHTML=''; document.getElementById('A').innerHTML='...running...';w() }function u(q,j){var o=Object.keys(g).sort(function(a,b){return a-b}),s,e;for(var i=0;i<o.length;i++){if((q*1>=o[i]*1+1)&(q<=g[o[i]]*1+1))s=1*o[i];if((j*1>=o[i]-1 )&(j<=g[o[i]]-1))e=1*o[i]};if(typeof(s)!=='undefined'){if(typeof(e)!=='undefined' ){if(1*s<1*e){g[s]=g[e];delete g[e]}}else{if(1*q<1*s){g[q]=g[s];delete g[s];s=q}; if(1*j>1*g[s])g[s]=j}}else{if(typeof(e)!=='undefined'){if(1*q<1*e){g[q]=g[e]; delete g[e];e=q};if(1*j>1*g[e])g[e]=j}else{g[q]=j}}}function v(f,p){var e,ie,c='' ;while(typeof(f)!=='undefined'){e=32;while((ie=(~0<<(33-e))>>>0)&&(f==((f>>(33-e) )<<(33-e))>>>0)&&(p>=(((~0<<32)^ie)|f)>>>0)&&(e>0))e--;c+=(f>>24&255)+"."+(f>>16& 255)+"."+(f>>8&255)+"."+(f&255);c+='/'+e+'<br/>';ie=e>0?(~0<<(32-e))>>>0:0;if(p>( (f|(~0<<32)^ie))>>>0){var d=f;f=1*1+((f|((~0<<32)^ie))>>>0)}else{f=undefined}} return c}function w(){var l=[];g={};document.getElementById('A').innerHTML+= '<br/>reading...';var n=document.getElementById('x').value.split("\n");for(var i=0;i<n.length;i++){if(!n[i].match("/"))n[i]+="/32";var s=n[i].match( /(\d+)\.(\d+)\.(\d+)\.(\d+)\/(\d+)/);if((s)&&(s.length==6)){var k=(s[1]<<24|s[2] <<16|s[3]<<8|s[4])>>>0;var e=(~0<<(32-s[5]))>>>0;var t=(~0&k&e)>>>0;var r=(((~0 <<32)^e)|t)>>>0;u(t,r);}};var o=Object.keys(g).sort(function(a,b){return a-b}); var h=-1;for(i=0;i<o.length;i++){if(1*o[i]>1*h){h=g[o[i]];document.getElementById ('y').innerHTML+=v(o[i],g[o[i]]);}}document.getElementById('A').innerHTML+= '<br/>printing...'};window.onload=B; ``` ``` body{font-family:Sans;background:#9ac;}#z{position:absolute;top:3em;right:2%;} span button, span input{font-size:.63em;}#A{width:50%;min-height:3.4em;background: #679;border:1px solid black;border-color:white black black white;border-radius: .5em;padding:.2em 1em .2em 1em;margin:1em 0px .1em 0px;margin-left:24%;color: #cdf;box-shadow: 2px 2px 4px black;}#y{width:72%;overflow:auto;margin-left:24%; background:#bce;padding:1em;border-radius:.8em;border:1px solid black;box-shadow: 2px 2px 4px;border-color:white black black white;}#x{position:fixed;top:1.5em; left:1%;padding:1em;width:18%;anchor:left;height:33em;border-radius:.3em;border: 1px solid black;border-color:white black black white;box-shadow:2px 2px 4px;} ``` ``` <button id="z"> GO </button><textarea id="x"></textarea><div id="A">---</div><pre id="y"></pre> ``` ]
[Question] [ From [Erich Friedman's Math Magic](https://erich-friedman.github.io/mathmagic/0912.html), (problem #2 on that page) your challenge is to find the edge elimination number of a connected graph. A single **edge elimination** is the removal of an edge from a graph, without disconnecting the graph, except for creating lone vertices. For instance, in the graph below, the two leftmost edges and the rightmost edge may be legally eliminated, but the center edge may not, because that would lead to two disconnected components larger than a single vertex. ![Example Graph](https://i.stack.imgur.com/YU2M8.gif) An **edge elimination sequence** is the elimination of every edge in a graph in a specified order. Each elimination must be legal at the point in the sequence when it is performed. For instance, one legal edge elimination sequence on the above graph would be to remove the rightmost edge, then the center edge, then the top-left edge, then the bottom-left edge. The **edge elimination number** of a graph is the number of different edge elimination sequences that a graph has. For instance, the above graph has an edge elimination number of 14. There are 4 sequences starting with the top left edge, 4 with the bottom left edge, and 6 with the right edge. **Input:** The input graph is guaranteed to be connected. The graph will be given as a list of edges with labeled vertices. for instance, the above graph might be given as: ``` [(0,2), (1,2), (2,3), (3,4)] ``` Within that requirement, whatever format is most convenient for your language/code is fine. Don't cheese this. (e.g. no code in the vertex labels.) **Code:** You may write a program taking input from the command line or from STDIN, or a function, or a verb, or your language's equivalent. This is code golf, fewest bytes wins. **Tests:** ``` One edge: [(0,1)] 1 Path: [(0,1), (1,2), (2,3), (3,4)] 8 Triangle with two additional edges off one vertex: [(0,1), (1,2), (0,2), (0,3), (0,4)] 92 Randomly generated: [(0, 2), (0, 4), (1, 2), (1, 4), (2, 5), (3, 4), (3, 5)] 1240 [(0, 2), (0, 3), (1, 3), (1, 4), (1, 5), (2, 3), (3, 4), (3, 5)] 16560 ``` Again, this is code golf, fewest bytes wins. Please ask any clarifying questions, or tell me if I've done something wrong. [Answer] ## APL (77) ``` {0=⍴,⍵:1⋄C←0/⍨⍴V←∪∊G←⍵⋄0∊C⊣{C[V⍳⍵]:⍬⋄C[V⍳⍵]←1⋄∇¨⍵~⍨∊G/⍨⍵∊¨G}⊃V:0⋄+/∇¨⍵∘~∘⊂¨⍵} ``` This is a function that takes a list of edges as a graph, i.e.: ``` {0=⍴,⍵:1⋄C←0/⍨⍴V←∪∊G←⍵⋄0∊C⊣{C[V⍳⍵]:⍬⋄C[V⍳⍵]←1⋄∇¨⍵~⍨∊G/⍨⍵∊¨G}⊃V:0⋄+/∇¨⍵∘~∘⊂¨⍵} (0 2)(0 3)(1 3)(1 4)(1 5)(2 3)(3 4)(3 5) 16560 ``` (Incidentally, this takes about half a second on my computer.) So the format is `[[v1,v2], [v1,v2], ...]`. To pass in a single-edge graph, you need to enclose it first, otherwise you get `[0,1]` instead of `[[0,1]]`: ``` {0=⍴,⍵:1⋄C←0/⍨⍴V←∪∊G←⍵⋄0∊C⊣{C[V⍳⍵]:⍬⋄C[V⍳⍵]←1⋄∇¨⍵~⍨∊G/⍨⍵∊¨G}⊃V:0⋄+/∇¨⍵∘~∘⊂¨⍵} ⊂0 1 1 ``` Explanation: * Base case 1 (empty graph): + `0=⍴,⍵:1`: if the graph is empty, return `1`: the current path has emptied the graph while keeping it connected. * Base case 2 (unconnected graph): + `C←0/⍨⍴V←∪∊G←⍵`: store the list of edges in `G`, the vertices in `V`, and a `0` for each vertex in `C`. + `{`...`}⊃V`: See if the graph is connected. Starting with the first vertex: - `C[V⍳⍵]:⍬`: if the vertex has already been visited, do nothing - `C[V⍳⍵]←1`: mark the current vertex as visited - `G/⍨⍵∊¨G`: find each edge this vertex is connected to - `⍵~⍨∊`: find all vertices involved in those edges, except the current vertex - `∇¨`: visit all those vertices + `0∊C`...`:0`: afterwards, if one of the vertices is not visited, the graph is no longer connected. The current path is invalid, so return `0`. * Recursive case: + `⍵∘~∘⊂¨⍵`: For each edge, create the graph formed by removing that edge, along with any orphaned vertices, from the current graph. + `∇¨`: For each of those graphs, find its edge elimination number. + `+/`: Sum those. [Answer] # [Pyth](https://github.com/isaacg1/pyth), 23 ``` L?/1lbf!tfaYTbbsmy-b]db ``` Explanation: `L`: defines a function, `y`, of one input, `b`. Returns the value of its body. `?`: \_ if \_ else \_ The first argument to `?` will be the value returned if we terminate. The second will be the termination test, and the third will be the recursive case. `/1lb`: If we terminate, there are two possibilities: we have reached a graph with 1 edge, or we have reached a clearly disconnected graph, which thus has more than one edge. `/1lb` is 1, floor divided by the length of the input graph. This returns 1 in the base case of a 1 edge graph, or 0 in any disconnected termination case. `faYTb`: This is the inner filter of 2nd argument. It filters out every edge `Y` that overlaps with the edge `T` of the outer filter. `a` is setwise intersection. `!tfaYTb`: `!` is logical not, `t` is tail, so this will be `True` if there is exactly 1 edge sharing a vertex with `T`, or `False` otherwise. `f!tfaYTbb`: This runs the above test on every edge in the graph. It is evaluated in a boolean context, and it is truthy if any edge in the graph shares no vertices with any other edge in the graph. If this is the case, we terminate, because the graph is either disconnected or has 1 edge. Note that there are some disconnected graphs that we do not terminate on, but their recursive calls will eventually terminate with a return value of 0. `smy-b]db`: This is the recursive case. We take the sum, `s`, of the edge elimination number, `y`, of the graph with each edge removed. `-b]d` is `b` with the edge `d` removed, `y-b]d` is the EEN of that graph, and `my-b]db` is this value for `d` being each edge in the graph, and `smy-b]db` is the sum of those values. Tests: (`yQ` runs the function on the input) ``` $ pyth -c 'L?/1lbf!tfaYTbbsmy-b]dbyQ' <<< '[(0,1)]' 1 $ pyth -c 'L?/1lbf!tfaYTbbsmy-b]dbyQ' <<< '[(0,1), (1,2), (2,3), (3,4)]' 8 $ pyth -c 'L?/1lbf!tfaYTbbsmy-b]dbyQ' <<< '[(0,1), (1,2), (0,2), (0,3), (0,4)]' 92 $ pyth -c 'L?/1lbf!tfaYTbbsmy-b]dbyQ' <<< '[(0,2), (0,4), (1,2), (1,4), (2,5), (3,4), (3,5)]' 1240 $ pyth -c 'L?/1lbf!tfaYTbbsmy-b]dbyQ' <<< '[(0,2),(0,3),(1,3),(1,4),(1,5),(2,3),(3,4),(3,5)]' 16560 ``` [Answer] # Python, 228 bytes ``` p=lambda l,r,d:reduce(lambda y,x:p(y[0]|set(x),[],y[1])if(x[0]in y[0]or x[1]in y[0])else(y[0],y[1]+[x]),d,(l,r)) def c(h): k=0 for i in range(len(h)):g=h[:i]+h[i+1:];k+=len(g)<2 or p(set(g[0]),[],g)[1]==[]and c(g) return k ``` One edge: ``` c([(0,1)]) 1 ``` Path: ``` c([(0,1), (1,2), (2,3), (3,4)]) 8 ``` Triangle with two additional edges off one vertex: ``` c([(0,1), (1,2), (0,2), (0,3), (0,4)]) 92 ``` Randomly generated: ``` c([(0, 2), (0, 4), (1, 2), (1, 4), (2, 5), (3, 4), (3, 5)]) 1240 c([(0, 2), (0, 3), (1, 3), (1, 4), (1, 5), (2, 3), (3, 4), (3, 5)]) 16560 ``` Explanation: In the first Statement I create a function that checks if a given graph d is connected. ``` p=lambda l,r,d:reduce(lambda y,x:p(y[0]|set(x),[],y[1])if(x[0]in y[0]or x[1]in y[0])else(y[0],y[1]+[x]),d,(l,r)) ``` The idea of this is: You have to reduce a graph with the given edge-tuples to a list which contains every connected point, called connected\_set and a list with all not-connected-yet tuples, called not\_connected. Core is the reduce-function, which is a built-in what calls every a given function with two parameters for each element in a list. Reduce works so: reduce(callable, list, initial) ``` 1. callable(initial, list[0]) returns element 2. callable(element, list[1]) ... 3. callable(element, list[n]) ``` For given code I return a tuple contained of (connected\_set, not-connected-yet). The initial value is the connected\_set containing of the first found point of the graph. the not-connected-yet is initial en empty list. ``` lambda y,x:p(y[0]|set(x),[],y[1])if(x[0]in y[0]or x[1]in y[0])else(y[0],y[1]+[x]) ``` means: ``` def reducer((connected_set, not-connected-yet), element): #an edge is connected, if left or right point is in connected_set if element[0] in connected_set or element[1] in connected_set: #add both points to connected_set connected_set |= set([x[0], x[1]) #resolve not-connected-yets check_graph(connected_set, not-connected-yet=[], list=not-connected-yet) return (connected_set, not-connected-yet) else return (connected_set, not-connected-yet + [element] def check_graph(connected_set, not-connected-yet, list): return reduce(reducer, list, (connected_set, not-connected-yet)) ``` A Graph is connected, when check\_graph returns a tuple, which second element is an empty list. The rest is addition: ``` def c(h): k=0 for i in range(len(h)):g=h[:i]+h[i+1:];k+=len(g)<2 or p(set(g[0]),[],g)[1]==[]and c(g) return k ``` means readable: ``` def count_graph(graph) sequences = 0 #iterate over the possibilities to eliminate an edge on given graph # e.g.: graph = [1, 2, 3] # i=0: parted_graph = [2, 3] # i=1: parted_graph = [1, 3] # i=2: parted_graph = [2, 3] for i in range(len(graph)): parted_graph = graph[:i] + graph[i+1:] if len(parted_graph) < 2: # a graph with one edge is result of a sequence so raise num sequences += 1 else: # continue eliminating if graph is connected if check_graph(set(parted_graph[0]), [], parted_graph)[0] == []: sequences += count_graph(parted_graph) return sequences ``` ]
[Question] [ Today computers use millions of bytes of memory, and decimal or hexadecimal notations get less and less informative. Most human-readable formatting just display the number with the highest unit prefix. What about the rest? I devised a notation that I use for myself, and since then, I'm often faced with re-implementing it in various languages. I thought I could share it, and that it make for a good case for code-golfing too. **The rules** * The program is given an integer as its input. It can be taken from a decimal or hexadecimal representation in a text file and then parsed, or from the "system innards". * It should outputs a representation of that number somehow * The limits are the system's limit. For practical purposes, assume 64 bits unsigned, so that the maximum number is 0xFFFFFFFFFFFFFFFF, and the unit suffixes will be k (kibi), M (mebi), G (gibi), T (tebi), P (pebi), E (exbi). * zeros should be skipped. Example: 5G + 10k should be written 5G;10k, and not 5G;0M;10k;0 * It frequently happens, e.g. for memory ranges, that a number is just one less than a number with a nicer representation. For instance, 0xffff would be displayed as 63k;1023, though it is 64k minus 1. An exclamation mark denotes this, so that 0xffff should be displayed as !64k. ***Examples*** * 0 : 0 * 1023: !1k * 1024: 1k * 1025: 1k;1 * 4096: 4k * 0x100000 : 1M * 0xFFFFF : !1M * 0x20000f : 2M;15 * 0x80003c00 : 2G;15k * 0xFFFFFFFFFFFFFFFF : !16E + For 32 bits users, use 0xFFFFFFFF, which is, as everybody knows, !4G. + And 128 bits users can go up to... wait that's big! Anyway, feel free... [Answer] ## Haskell, ~~335~~ ~~333~~ 332 ``` f 0=["0"] f n=let l=mod n 1024;s=f$div(n+1)1024;in if l==1023 then "!":s else show l:s g []=[] g ((_,"0"):s)=g s g ((_,"!"):s)=let(c,z):t=g s in(c,'!':z):t g ((c,n):s)=(c,n):g s h ('_',s)=';':s h (c,s)=';':(s++[c]) r n=let x=tail$concatMap h$reverse$g$zip"_kMGTPE"$f$read n in if x=="" then "0" else x main=do x<-getLine;return$r x ``` [Answer] ## Windows PowerShell, 207 ~~214~~ ~~226~~ ~~230~~ ~~247~~ ~~271~~ ~~319~~ ~~339~~ ~~360~~ ``` $v=1PB*1KB filter t{[Math]::Floor($n/$v)}$(,0*!($n=[Convert]::ToUInt64(($i="$input"),10+6*($i[1]-gt60))) 'EPTGMk'[0..5]|%{if($n%$v+1-eq$v){$v-- "!$(t)$_" $n=0}if(t){"$(t)$_" $n%=$v}$v/=1kb} ,$n*!!$n)-join';' ``` Test run: ``` ./friendly2.ps1: PASS: '2047' -> '!2k' ./friendly2.ps1: PASS: '4096' -> '4k' ./friendly2.ps1: PASS: '0x80003c00' -> '2G;15k' ./friendly2.ps1: PASS: '2049' -> '2k;1' ./friendly2.ps1: PASS: '0x1' -> '1' ./friendly2.ps1: PASS: '4097' -> '4k;1' ./friendly2.ps1: PASS: '0xFFFFF' -> '!1M' ./friendly2.ps1: PASS: '0xa000' -> '40k' ./friendly2.ps1: PASS: '1022' -> '1022' ./friendly2.ps1: PASS: '0x100000' -> '1M' ./friendly2.ps1: PASS: '2048' -> '2k' ./friendly2.ps1: PASS: '0x20000f' -> '2M;15' ./friendly2.ps1: PASS: '0' -> '0' ./friendly2.ps1: PASS: '0x0' -> '0' ./friendly2.ps1: PASS: '1' -> '1' ./friendly2.ps1: PASS: '0x80aef3' -> '8M;43k;755' ./friendly2.ps1: PASS: '14636699861675008' -> '13P;1023M;27k' ./friendly2.ps1: PASS: '0xFFFFFFFFFFFFFFFe' -> '15E;1023P;1023T;1023G;1023M;1023k;1022' ./friendly2.ps1: PASS: '1023' -> '!1k' ./friendly2.ps1: PASS: '4095' -> '!4k' ./friendly2.ps1: PASS: '0xFFFFFFFFFFFFFFFF' -> '!16E' ./friendly2.ps1: PASS: '1025' -> '1k;1' ./friendly2.ps1: PASS: '1024' -> '1k' ``` [Answer] ## Scala, 295 characters ``` object F extends App{type S=String;def f(l:BigInt,s:S,p:S,g:Int,q:Int):S={val j=l&1023;return if(l+g>0)f(l>>10,if((j+g<1024&&j+g-q>0)||l-q<0)";"+"!"*(g-q)+(j+g-q)+p(0)+s else s,p.tail,(j.toInt+g)/1024,0)else s};val x=readLine.split('x');print(f(BigInt(x.last,4+x.size*6),""," kMGTPE",1,1).tail)} ``` With some line breaks to aid readability (though not much): ``` object F extends App { type S=String def f(l:BigInt,s:S,p:S,g:Int,q:Int):S= { val j=l&1023 return if(l+g>0)f(l>>10,if((j+g<1024&&j+g-q>0)||l-q<0)";"+"!"*(g-q)+(j+g-q)+p(0)+s else s,p.tail,(j.toInt+g)/1024,0)else s } val x=readLine.split('x') print(f(BigInt(x.last,4+x.size*6),""," kMGTPE",1,1).tail) } ``` [Answer] # JavaScript, ~~461~~ ~~452~~ ~~423~~ ~~269~~ ~~267~~ 247 ``` function(n){for(k=1024,M=k*k,G=M*k,T=G*k,P=T*k,E=P*k,y='EPTGMk',r='';n;){for(i=-1,f=0;++i<6;)n==(v=eval(x=y[i]))-1?(r+='!1'+x,n=0,f=1):n>=v?(r+=Math.floor(n/v)+x+';',n%=v,f=1):0;f?0:(r+=n,n=0);}return r?r[l=r.length-1]==';'?r.substring(0,l):r:'0'} ``` [Answer] ## Ruby 1.9, 130 ~~167 181 191 203~~ characters ``` n=eval gets u=1023 x=n&u<u ?n<1??0:"":(n+=1;?!) s=[] 6.downto(0){|i|a=1024**i;n/a>0&&s<<[n/a,"EPTGMk"[6-i]]*""&&n=n%a} puts x+s*?; ``` Passes all testcases from [Joey's answer](https://codegolf.stackexchange.com/questions/2610/formatting-numbers/2613#2613). [Answer] ## C#, 302 ~~323~~ Direct conversion of my PowerShell solution. ``` using System;class F{static void Main(){var s=Console.ReadLine();ulong n=Convert.ToUInt64(s,s.IndexOf('x')==1?16:10),v=1L<<60,b;s=n<1?"0":"";foreach(var x in "EPTGMk"){b=0;if(n%v==v-1){s+="!"+(n/--v)+x;n=0;}if(n/v>0){s=s+(n/v)+x;n%=v;b=1;}if(b>0&&n>0)s+=';';v/=1024;}if(n>0)s+=n;Console.Write(s);}} ``` [Answer] ## Python, 138 chars ``` N=input() M=1023 s='0'[N:] if N&M==M:N+=1;s='!' print s+';'.join('%d'%b+k for b,k in zip([N>>60-10*i&M for i in range(7)],'EPTGMk ')if b) ``` ]
[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 7 years ago. [Improve this question](/posts/1328/edit) Given 4 numbers n1, n2, n3, n4, and a goal n5, obtain n5 using n1 through n4 combined with any operations. Eg. Given four numbers 2,3,4,5 and the goal as 8, output (one of many) is `2-3+4+5` EDIT: This is a variation of a game played at my son's school. Paranthesis, powers, unary operations (log, factorial) are allowed; the expressions tend to get complicated. However, unary operations can be applied only once on a number. Essentially, the tree should be: ``` goal /\ / \ / \ expression1 expression2 /\ /\ / \ / \ / \ / \ term1 term2 term3 term4 ``` where *term#i* is either 1. one of the numbers, or 2. one of the numbers with an unary operation. [Answer] ## Python - 146 chars ``` from itertools import* f=lambda*l:[s for s in((3*"%s%%s"+"%s")%a%o for o in product(*['+-/*']*3)for a in permutations(l[:4]))if eval(s)==l[4]] ``` [Answer] ## Python (159) ``` from itertools import* f=lambda*l:[a+f+b+g+c+h+d for f,g,h in product('+-/*',repeat=3)for a,b,c,d in permutations(map(str,l[:4]))if eval(a+f+b+g+c+h+d)==l[4]] ``` **Example:** ``` >>> f(2,3,4,5,8) ['2+4+5-3', '2+5+4-3', '4+2+5-3', '4+5+2-3', '5+2+4-3', '5+4+2-3', '2+5+4/3', '3+5+2/4', '5+2+4/3', '5+3+2/4', '2+4-3+5', '2+5-3+4', '4+2-3+5', '4+5-3+2', '5+2-3+4', '5+4-3+2', '3+5-2/4', '4+5-3/2', '5+3-2/4', '5+4-3/2', '2+4/3+5', '3+2/4+5', '5+2/4+3', '5+4/3+2', '2+4*5/3', '2+5*4/3', '2-3+4+5', '2-3+5+4', '4-3+2+5', '4-3+5+2', '5-3+2+4', '5-3+4+2', '3-2/4+5', '4-3/2+5', '5-2/4+3', '5-3/2+4', '2/4+3+5', '2/4+5+3', '4/3+2+5', '4/3+5+2', '3/5+2*4', '3/5+4*2', '5/3*2*4', '5/3*4*2', '2*4+3/5', '4*2+3/5', '2*4-3/5', '4*2-3/5', '4*5/3+2', '5*4/3+2'] ``` [Answer] # Ruby1.9.1 - 158 chars ``` g=->a,&b{a.permutation.each &b} f=->*a{t=a.pop g.(a){|n|g.(['+','-','*','/']*3){|k|s=[n[0],k[9],n[1],k[10],n[2],k[11],n[3]].join '' return s if eval(s)==t}}} ``` Lambda function `f` returns the first solution it finds. eg. ``` f[2,3,4,5,8] #gives "2-3+4+5" ``` [Answer] ## Perl Not golfed as this is a code-challenge and not code-golf. Aiming for complete solution; uses reverse polish notation. Enjoy cryptic variable names and weird coding style ;) ``` #!perl -l use strict; use warnings; use Math'Combinatorics; use Math'RPN; my @do=qw(add sub mul div mod pow); my @uo=qw(sqrt sin cos tan log exp); sub u(@){my%h;$h{"@$_"}=$_ for@_;values%h} sub ms ($$$) { my($c,$d,$f)=@_; my @r; my $o = new Math'Combinatorics count => $c, data => $d, frequency => $f; while (my @x = $o->next_multiset) {push @r, [@x]} @r; } my $r = shift; my $a = ~~@ARGV; my @p = u permute @ARGV; my @d = ms $a-1, \@do, [(~~@do) x @do]; my @u = ms $a, \@uo, [(~~@uo)x@uo]; my @t; push @t, [unpack "(A)$a", sprintf "%0${a}b", $_] for 0..2**$a-1; my @pu = (); for my $pp (@p) { for my $uoo (@u) { for my $tt (@t) { my @opu = (); for my $g (0..$a-1) { push @opu, $pp->[$g]; push @opu, $uoo->[$g] if $tt->[$g]; } push @pu, \@opu; } } } @pu = u @pu; for my $ppu (@pu) { for my $doo (@d) { my @e = (@$ppu,@$doo); my $z; eval {$z=rpn(@e)}; $z = $r-1 if $@; print "@e = $z" if $z==$r; } } ``` usage example: ``` > perl ./mc.pl 14 3 4 4 4 sqrt 3 4 add mul = 14 4 sqrt 4 3 add mul = 14 4 exp 3 exp 4 exp mod mod = 14 4 exp 3 exp 4 sqrt mul mod = 14 ``` ]
[Question] [ You are the treasurer and you have received information that a counterfeit coin has entered the treasury. All you know is that the counterfeit coin is lighter than the original. Knowing how many coins you have in total and using only a balance scale, you need to determine the minimum number of weighings to determine which coin is counterfeit before it disappears from the treasury. --- Your function must accept only one integer (which will be more than 1) and must output 2 things: * the minimum number of weighings without lucky chances * steps on how to find counterfeit coin **Step** - a moment when you use balance scale **Without lucky chances** means that your number must be the maximum among the minimum steps required. For example let's say that you have 5 coins: 1. You can split them to 3 groups by 2, 2 and 1 (this isn't a step) 2. Weighing the groups 2 and 2 (this is a step) 2.1 If they are equal then the remaining coin is counterfeit 2.2. If one of the groups is lighter then the counterfeit coin is in that group 3. Weigh each remaining coin (this is a step) 3.1 The coin that is lighter is the counterfeit coin So the minimum number of weighings without lucky chances is 2 but with lucky chances it is 1 because we can find the counterfeit coin at step 2. The output steps must be easy to understand. Please add a detailed explanation of how to read the output steps. For example the previous example can be represented like this: ``` [5(2,2) 2(1,1)] - 2 ``` Where the: * `[]` - means the possible scenarios * `x(y,z)` - `x` means remaining coins after previous step, `(y,z)` means how many coins (from `x`) on each side of balance scale I am weighing * `'space'` - means the next step/scenario * `- x` - means the minimum number of weighings without lucky chances Here is an example with `8`. The output can be shown like this: ``` [8(3,3) [2(1,1)] [3(1,1)]] - 2 ``` After first step we have two different scenarios because: 1. if the 2 groups of 3 are equal then the counterfeit coin is in the group of 2 coins 2. if the 2 groups of 3 aren't equal then the counterfeit coin is on one of the groups of 3 It is enough to to weigh only 2 different coins in each scenario to find the counterfeit coin. Regardless of the scenario, the minimum number of weighings without lucky chances is 2 Here are the possible outputs for 2 to 9 coins: ``` 2 --> [2(1,1)] - 1 3 --> [3(1,1)] - 1 4 --> [4(2,2) 2(1,1)] - 2 5 --> [5(2,2) 2(1,1)] - 2 6 --> [6(2,2) 2(1,1)] - 2 7 --> [7(3,3) 3(1,1)] - 2 8 --> [8(3,3) [2(1,1)] [3(1,1)]] - 2 9 --> [9(3,3) 3(1,1)] - 2 ``` You can output any of the possible steps of how to find the counterfeit coin. For example for `10` we have 5 different scenarios. You can output any of them: ``` 10 --> [10(5,5) 5(2,2) 2(1,1)] - 3 10 --> [10(4,4) [2(1,1)] [4(2,2) 2(1,1)]] - 3 10 --> [10(3,3) [3(1,1)] [4(2,2) 2(1,1)]] - 3 10 --> [10(2,2) [2(1,1)] [6(3,3) 3(1,1)]] - 3 10 --> [10(1,1) 8(3,3) [2(1,1)] [3(1,1)]] - 3 ``` The shortest code in each programming language wins! [Answer] # [Python](https://www.python.org), 77 bytes *-4 from @TheThonnu* ``` f=lambda n:n<4and[1]or(m:=-~n//3,p:=n-2*m,f(m),f(p),max(f(m)[-1],f(p)[-1])+1) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3fdNscxJzk1ISFfKs8mxMEvNSog1j84s0cq1sdevy9PWNdQqsbPN0jbRyddI0cjWBRIGmTm5ihQaIF61rGAsWATE0tQ01IYauKSjKzCsBqjA31oQKwewDAA) If input is 2 or 3, returns `[1]` meaning only one trivial weighing is required, otherwise returns a 5-tuple (number of coins to weigh on each side at this step, number of coins to set aside at this step, steps to follow with the lighter side of coins if there was a lighter side, steps to follow with the set-aside pile if the scale balanced, worst-case number of steps required). Naturally the third and fourth elements of the tuple recurse. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 44 bytes ``` ⊞υNW⊖⌈υ«≔⊕÷⊖ι³θ≔⁺⁻υ⟦⊕ι⟧⟦θ⁻⊕ι⊗θ⟧υ⟦⪫⟦⊕ιθL↨ι³⟧ ``` [Try it online!](https://tio.run/##XY4xi8JAEIVr8ysWqxlYC7nCwkpJEzklfbCIcTADm8klu@MJ4m/f21PkTpvHwHvvm9e09dj0tYuxVN@CWlPIl4addgcaAXGZfbfsyEBOzUgdSaAjbOsLd9qBIqK5ZpOV93wSKOQvUkjI@cxHeikyWvOBSYYEftZKpx62LEnT@@o/hXGfwtVgzcN/9azJez24dA94D@ovtRxZAlSbngWq90IifZKcQgvr2hPwfc7emqmZJsIyu8W4mMfZ2f0A "Charcoal – Try It Online") Link is to verbose version of code. Outputs sets of three integers: coins left, coins to weigh (per side), worst case number of remaining weighings. Explanation: Inspired by @ParclyTaxel's Python answer. ``` ⊞υN ``` Start with `n` coins. ``` W⊖⌈υ« ``` Repeat until there is only `1` coin left. ``` ≔⊕÷⊖ι³θ ``` Calculate how many coins to weigh. ``` ≔⁺⁻υ⟦⊕ι⟧⟦θ⁻⊕ι⊗θ⟧υ ``` Update the set of possible numbers of remaining coins. ``` ⟦⪫⟦⊕ιθL↨ι³⟧ ``` Output the coins left, coins to weigh and steps left. [Answer] # Mathematica, 106 bytes Modified from [@Parcly Taxel's answer](https://codegolf.stackexchange.com/a/257888/110802) --- Golfded version, [try it online!](https://tio.run/##y00syUjNTSzJTE78nxadF68Qq2Bl@983P6U0JzW6OlenQCctVyetQCc3scKtVscTqMTGRKfasFYn11b3UU@HU2aJX35JdF6svvGjnk7rAts8XSOtXGuIRgegTocCHd/EimifxOISBy2QCIxVEKttWBsb@5@LKy3a3DhWXz@gKDOv5D8A) ``` Module[{m,p,fm,fp,maxF},If[n<4,{1},m=-⌈BitNot[n]/3⌉;p=n-2*m;{m,p,f@m,f@p,Max[Last@*f@m,Last@*f@p]+1}]] ``` Ungolfed version ``` f[n_] := Module[ {m, p, fm, fp, maxF}, If[n < 4, {1}, m = -Ceiling[BitNot[n]/3]; p = n - 2*m; fm = f[m]; fp = f[p]; maxF = Max[Last[fm], Last[fp]] + 1; {m, p, fm, fp, maxF} ] ] f[73]//Print ``` [Answer] # [Python](https://www.python.org), 2551 bytes, ``` import math def find_counterfeit_coin(num_coins): steps = [] # Base case if num_coins == 2: steps.append((2, (1, 1))) return 1, steps # Determine the largest power of 3 less than num_coins power = math.floor(math.log(num_coins - 1, 3)) group_size = 3 ** power # First weighing remaining_coins = num_coins while remaining_coins > 2 * group_size: steps.append((remaining_coins, (group_size, group_size))) remaining_coins -= 2 * group_size # Split remaining coins into groups of size group_size or less group_sizes = [] while remaining_coins > group_size: group_sizes.append(group_size) remaining_coins -= group_size if remaining_coins > 0: group_sizes.append(remaining_coins) # Weigh each group for group in group_sizes: if group == group_size: steps.append((group, (group_size, group_size))) else: steps.append((group, (1, 1))) # Determine which group contains the counterfeit coin if len(group_sizes) == 1: num_weighings = power + 1 return num_weighings, steps elif len(group_sizes) == 2: if group_sizes[0] == group_sizes[1]: num_weighings = power + 1 return num_weighings, steps else: num_weighings = power + 2 steps.append((group_sizes[0], (1, 1))) return num_weighings, steps else: # Combine two groups of equal size to create a larger group combined_group_size = group_size * 2 combined_groups = [sum(group_sizes[i:i+2]) for i in range(0, len(group_sizes), 2)] # Recursively find the counterfeit coin in the larger group recursive_weighings, recursive_steps = find_counterfeit_coin(sum(group_sizes)) num_weighings = power + recursive_weighings # Add steps for weighing the smaller groups for group in combined_groups: steps.append((group, (1, 1))) # Add steps from recursive call steps += recursive_steps # Weigh the two groups that produced the combined group for i in range(0, len(group_sizes), 2): if group_sizes[i] == group_sizes[i+1]: steps.append((combined_group_size, (group_sizes[i], group_sizes[i+1]))) else: steps.append((combined_group_size, (group_sizes[i], combined_group_size - group_sizes[i]))) return num_weighings, steps ``` [Attempt This Online!](https://ato.pxeger.com/run?1=nVZJbtswFF03p_hANpKHwFY2RQAV6IAeoF10ERiBKn3ZBChSJaka6VW6yabd9ETtRboth8iiKNpxqoUsSn9670_-_rO9VzvOHn6RpuVCQVOo3Y9O1cuXf178vaiwhpqw6q7kHVMoaiRKPxOWsK6xDzK9uQB9SYWthBxuN_Zob5fwppAIpb7ZM6nhoAZ5DplTPahfFW2LrEqSbAHJegHrNE0PEgJVJxjo11bW9_IOdWgNYQhqh0ALsUWpoOV7FMBruAaKUupvBRv8W1UnklvQVzXlXCT2kfLtABCWxun1Yyhbwbv2TpJvqPWuYTZzRvxw3hOh3e-RbHeEbS9c8E1BmD714INA9jtCcSL1CjKYeR6P0RXoafIGnYWnP6Zz7GuZB858RB9bStSgAk6FMMWdgjQ0W048eriwvAeseTVyDHQMsGegh-3hOoUqQKRrcOpxddJRIJ_6zHwyWQYsyp3TtK9rDd2eNEW-wcGLjsIJ5HkU7jTHVuqszCKVZ1nyG2zSSDo3PSSdbaYKQ5TpLm8Q2DLoSaXIvNhkapCthzBMufcdYUrAdd4c1mF_jwQnvY70iKtsyq37ervajEmWt-vNmJ6nYzsnvjj1x2xnTyXoEH1kFD6DLj-eS3jLm892TO79xsUvXUFd--qGLgUWCqFwc1R4ZW2u0lmo7kZz0DvMPGhjYdv5smtG-MgNmWeb1LYMMe0iCrbFZLWYZHkBWbo5mPZAfcCyE5J8RXpvd1W0TI3pw3IIQYnegk_l8LJfbfFFGCDy0nQs9xF3MVyvq-pxqxpyelGLQjYFpT2MQXk0dwLynzsRjgcjeDNA0Mud0vFagnkekhez6CanQeNVo97RenELXnUl9ol0MIKUnVcvY9DBYCCTwUDm4WiYchVpgNFUNnYXE6th904Hxf96ijXkMsAZzemJAeL-__3WidArPomXfbZKUyf38OB-_wE) --- Though it can be considered as an algorithm, it is a pathway for others to write short code from it. This solution uses a recursive approach to find the minimum number of weighings required to find the counterfeit coin. The algorithm works by dividing the coins into groups and weighing the groups against each other, gradually reducing the number of remaining coins until the counterfeit coin is found. The number of groups and their sizes are chosen so that the maximum number of coins are weighed at each step. The output of the function is a tuple containing the minimum number of weighings and a list of tuples representing the steps taken to find the counterfeit coin. Each tuple in the list represents a weighing, and contains the number of coins weighed and the sizes of the groups weighed against each other. The steps can be interpreted as a tree, where each level represents ]
[Question] [ J-uby is the [Language of the Month for June 2022](https://codegolf.meta.stackexchange.com/questions/24817/language-of-the-month-for-june-2022-j-uby), so I'm looking for tips for golfing in it. As usual, please post one tip per answer, and avoid general tips such as "remove whitespace" or "avoid comments". [Answer] # `reduce` to `/` Let's say we have an array of: ``` a=[1,2] ``` If we want to find the sum: ``` a.reduce:+ ``` Golfed: ``` :+/a ``` Just swap the `a` and `:+` before placing a `/` smack in the middle! [Answer] # `join` to `*` Say we have an array: ``` a=[1,2] ``` To join it with commas: ``` a.join',' ``` However this seems too long, let's replace it with `*`: ``` a*',' ``` Or even better: ``` a*?, ``` [Answer] # Conversions ``` number.abs #To abs value number.| Object.to_i #To integer Z[Object] Object.to_f #To float Q[Object] Object.to_s #To string S[Object] Object.to_a #To array A[Object] Hash[Object] #To hash H[Object] ``` All these make sure of single letters for conversions. [Answer] # Flip your comparisons `x < 1` in tacit J-uby is `~:<&1` but the equivalent `1 > x` is a byte shorter: `:>&1`. ]
[Question] [ On Unix-like systems, the `ls` command lists files. GNU's version of `ls` also colors them according to their properties and the environment variable `LS_COLORS`. The main file property that `ls` bases its colors on is the file's **mode**. In this challenge, you will determine what keys from LS\_COLORS `ls` should look for a given mode. ## File modes A file's mode determines what [type of a file it is](https://en.wikipedia.org/wiki/Unix_file_types) (is it a normal file? a socket? a pipe? a directory?) and [what permissions it has](https://en.wikipedia.org/wiki/File-system_permissions) (can the owner execute it? can everyone write to it?). The mode is given by a 16-bit unsigned integer. The highest 4 bits determine the file's type, the next 3 bits determine certain special attributes, and the remaining 9 bits determine user, group, and world permissions (3 bits each). The grouping-up by 3s makes it very common write these permissions in octal: ``` type special permissions | type sp perms ---- ------- ----------- | -- -- ----- (bin) 1111 111 111 111 111 | (oct) 17 7 7 7 7 ``` The top 4 bits will take on one of these values. Any other values can produce undefined behavior: ``` Binary Octal File type --------- ----- ---------------- 0b1100... 014... socket 0b1010... 012... symbolic link 0b1000... 010... regular file 0b0110... 006... block device 0b0100... 004... directory 0b0010... 002... character device 0b0001... 001... FIFO (named pipe) ``` The remaining 4 octets can have any value. each bit is a flag which can be set independently from the others: ``` ????------------- Filetype, see above ----1------------ SUID: Execute this file with the UID set to its owner -----1----------- SGID: Execute this file with the GID set to its group ------1---------- Sticky: Users with write permissions to this dir cannot move or delete files within owned by others -------1--------- User read: The owner of the file can read this --------1-------- User write: The owner of the file can write to this ---------1------- User exec: The owner of the file can execute this -----------111--- Group r/w/x: The group of this file can read/write/execute --------------111 Other r/w/x: All users can read/write/execute ``` ## LS\_COLORS GNU's `ls` uses the environment variable LS\_COLORS to add color to the files it lists. The variable LS\_COLORS is a colon-delimited list of `key=value` rules. Some of those keys are for file names (e.g.: `*.tar=01;31`), but we care about the file type keys. ``` ln Symbolic link. pi Named pipe bd Block device cd Character device or Symbolic link pointing to a non-existent file so Socket tw Directory that is sticky and other-writable (+t,o+w) ow Directory that is other-writable (o+w) and not sticky st Directory with the sticky bit set (+t) and not other-writable di Directory su Normal file that is setuid (u+s) sg Normal file that is setgid (g+s) ex Executable normal file (i.e. has any 'x' bit set in permissions) fi Normal file ``` Now when `ls` finds a match in the above list, it only applies that color *if that key exists* in LS\_COLORS. If a directory is sticky and other-writeable, but no `tw` key is in LS\_COLORS, it will fall back to `ow`, then fall back to `st`, then fall back to `di`. The list above is ordered to give the same result as `ls`. ## Challenge Take as an integer input any valid file mode, and output the fallback list of two-character codes. **Input:** A file mode with a valid file type, in any convenient integer format that is at least 16 bits. **Output:** The corresponding **ordered** list of two-character keys for a file with that mode, in fallback order. Since all codes are two characters, the concatenated string (e.g.: `"twowstdi"`) is also acceptable, as it is still unambiguous. Additionally, printing the codes in reverse order (`di st ow tw`) is also fine, as long as it is consistent for all inputs. Example: * Input: `17389` (in octal: `0041755`) * Output: `["st", "di"]` (the sticky bit `0001000` is set, and it is an directory `0040000`.) Test cases (these are in octal, and a symbolic equivalent for your convenience): ``` Input Symbolic Output | Note: ------- ---------- ------------- | ----- 0140000 s--------- so | socket 0147777 srwsrwsrwt so | suid/sgid/sticky/other-writeable does not apply 0120000 l--------- ln | symbolic link (you MAY choose to output "or" instead) 0127777 lrwsrwsrwt ln | 0060000 b--------- bd | block device 0067777 brwsrwsrwt bd | 0020000 c--------- cd | character device 0027777 crwsrwsrwt cd | 0010000 p--------- pi | pipe 0017777 prwsrwsrwt pi | 0040755 drwxr-xr-x di | directory 0041755 drwxrwxr-t st di | sticky bit set 0040002 d-------w- ow di | other-writable 0041777 drwxrwxrwt tw ow st di | sticky + other-writeable 0046000 d--S--S--- di | suid/sgid only apply to normal files 0100000 ---------- fi | normal file 0100000 ---------T fi | sticky bit only applies to directories 0100100 ---x------ ex fi | executable file 0100010 ------x--- ex fi | 0100001 ---------x ex fi | 0104000 ---S------ su fi | suid 0106777 -rwsrwsrwx su sg ex fi | suid has priority over sgid and executable 0102000 ------S--- sg fi | sgid 0102777 -rwxrwsrwx sg ex fi | sgid has priority over executable 0110000 ?--------- <undefined> | Unknown filetype, any output is valid ``` Standard loopholes are forbidden. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shorter answers are best. --- Similar Challenges: [File Permissions](https://codegolf.stackexchange.com/questions/163691/file-permissions), [Do I have permission?](https://codegolf.stackexchange.com/questions/149452/do-i-have-permission) [Answer] # [JavaScript (Node.js)](https://nodejs.org), 141 bytes ``` c=>(E='',x=c>>8,y=c>>13,y-2?y-4?E:(x&8?'su':E)+(x&4?'sg':E)+(c&73?'ex':E):(x&c&2?'tw':E)+(c&2?'ow':E)+(x&2?'st':E))+'pcdbfls'[y]+'ididino'[y] ``` [Try it online!](https://tio.run/##bVRLb6MwEL7nV4x6KKCEJKTpQ61ItFr1uKfdy6qtVDBO4q2LETYB1Oa3Z8cYgmnjoEQTf4/xeJh/0T6SJGeZ8lOR0OMmPJJw5T6GjjOpQrJa3U1q/RNcTWp/sa795frx3q0u79aOLJz7R2@MwRKDrQnI5e3V2qGVjjSOXC7Wjiq7TQxE2dEwkEoH3tjJSBJvuHSe6pexwxL8pEIHRyJSqUBRqX5GkkoI4XUeLOe4AKTfLcBAQL8@MSRvVI0Qe4sLt/PSPOoMtmDJTG71l2LkrZ4JtaO5X@ZM0SjmFBKBzqlQEGUZr1F0YRLgdgI8HYrW77HgjABn6Ru4tSjg14@/QHZCSApKgChUVii4EPkFMDwkjRJPS5t8uZ3vUHo0n98Y/9j2j5OBf8yxApDQPSNUM4xsbMsOGQhqj0VsWTKUJbsoj4iieS/dZkxsafJVOjDSmS2dsYF0xjItFxi5zJYbIkeIWs5vr68Bkryscl8/uJEM9RKWU6JEXmt40MM1o@kCZTHwwpq7h5gpkLpz5rrLFshpEy51yqIccPpG0X1ifHTynU@TvCo1rXU7@YzhS5dp9k1TJHT83Tz@90OdehVEymvTkLqbUpG/Rxw2jFOJ9WnKjVK@Xe/NUMqinCH8@U6wKnQyZ/hmoH1XawwbraDVqk7mtLLkPjGkpGiqZiUQnBKozpHaLAMry@osaNkd5Xc/HoqBvS6jRt401@V3vVYZpNx2ogYJu0hiQzI8n6pB7LH7myuI0sQ6iNZbWEVsLxDFBs5b47zonKveeWudxSDPOPeGr6OpxBtQrvOcOt4U64jvpYvzhkK40nOHetP3KBv80zJmz/JjMTnMPINwn1iKw2gCE5TP8CZp8uJpyhPdR9xtNr1@b5rTjEeEujOYbSfgON6L9zDaiBxcM687uZMYiE0/xD34GOGIaJA5lQVXONY3rctDuyU4nXKxdTtAGJ7UYA0f0Dq02we4//pf7w4HVD0c/wM "JavaScript (Node.js) – Try It Online") *-7 bytes thanks to @Arnauld!* Takes the file mode as an integer and returns the colour string without spaces. ## Commented ``` // Saving these values to single char variables allows the logic below to be shorter c=>(E='',x=c>>8,y=c>>13, y-2? y-4? // Other type colors (none) E // File colors :(x&8?'su':E)+(x&4?'sg':E)+(c&73?'ex':E) // Directory colors :(x&c&2?'tw':E)+(c&2?'ow':E)+(x&2?'st':E) // The top three bits uniquely identify the mode )+'pcdbfls'[y]+'ididino'[y] ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 87 bytes ``` ≔◧⍘N²¦¹⁷θ≡﹪Σ…θ⁴¦⁸¦⁶so⁵ln⁴ΦfiexsgsuI§⟦1⌈✂θχφ³§θ⁶§θ⁵⟧⊘κ³bd²Φdistowtw⁼κ&κI⁺⁺§θ¹⁵§θ⁷1¹cd¦pi ``` [Try it online!](https://tio.run/##XY9fa8IwFMXf/RShTzfQQautju1JZWPCHAUfxx5iEjWY/k1iO8Y@e3fjZtEF7oF7cnPPL/zAGl4y3fdzY9S@gIyJV7mzsGBGbmyjij2sisrZN5dvZQM0JGOseIZS08eRaZXlBwLrUjhdwsblsPzkWi4PZQV1SBKKg/eUkq8Rx41k@kAyXGohMGWA789mOpi6GMzkYj4rbTE52CnZmb1xQUiWzFiY21UhZAfvQYzWmnUqx/SNVlz65DjyFaFOPMNlGm@mt21KP0LywvRJCjhSf/4IJgPWVgxY4/9YQhlbtrZFhqfaMW3gGJKFsq0ycl4I351xM@3Mr1xlx@kty8yj4n/oNUc8cPAzh5A75rQd3Ep597vv41kSRf3dSf8A "Charcoal – Try It Online") Link is to verbose version of code. Takes input in decimal and outputs without separators and in reverse order. Explanation: ``` ≔◧⍘N²¦¹⁷θ ``` Convert the input to base 2 and left-pad it to 17 bits with spaces. This ensures that it starts with a space, guaranteeing consistent behaviour of the `Sum` operator; other choices would have required extra bytes to arrange zero padding. ``` ≡﹪Σ…θ⁴¦⁸ ``` Take the first four bits, convert to decimal, and reduce modulo 8. (The alternatives was either to spend more bytes padding with zeros to allow me to convert from base 2 or to spend more bytes taking a copy of the input and integer dividing it by 4096.) ``` ⁶so ``` It's a socket. ``` ⁵ln ``` It's a symbolic link. ``` ⁴ΦfiexsgsuI§⟦1⌈✂θχφ³§θ⁶§θ⁵⟧⊘κ ``` It's a file. Filter on the file subtypes according to whether (one of) the relevant bits are set. ``` ³bd ``` It's a block device. ``` ²Φdistowtw⁼κ&κI⁺⁺§θ¹⁵§θ⁷1 ``` It's a directory. Filter on the subtypes according to the combination of set bits. The base 10 conversion is safe here as the numbers 10, 11, 100, 101, 110 and 111 all end in the same three digits in both decimal and binary. ``` ¹cd ``` It's a character device. ``` pi ``` It had better be a named pipe. ]
[Question] [ ## Background This is loosely based on the now closed [Kaomoji question](https://codegolf.stackexchange.com/questions/219146/typing-faces-with-programming) asked a few hours ago. Kaomojis are sequences of characters designed to express a given emotion. In this [code-challenge](/questions/tagged/code-challenge "show questions tagged 'code-challenge'"), you'll be writing a program that takes a Kaomoji as input, and must output the emotion expressed by the Kaomoji. ## Input A Kaomoji. In this challenge, there are 13 categories of emotions the kaomojis can express: 1. [Joy](https://pastebin.com/hPAFsCi7) 2. [Love](https://pastebin.com/rjJ0nL2P) 3. [Embarrassment](https://pastebin.com/LKSbAXuH) 4. [Sympathy](https://pastebin.com/eMwsPD1s) 5. [Dissatisfaction](https://pastebin.com/dc89LMe9) 6. [Anger](https://pastebin.com/CKkv3Ace) 7. [Sadness](https://pastebin.com/0N3g4q5S) 8. [Pain](https://pastebin.com/bhHjjh0Y) 9. [Fear](https://pastebin.com/7Mf1MDhd) 10. [Indifference](https://pastebin.com/8yEcLmjt) 11. [Confusion](https://pastebin.com/mJJqA8N7) 12. [Doubt](https://pastebin.com/Xy0bCXex) 13. [Surprise](https://pastebin.com/vH0Wg9nc) You will be given one kaomoji from any of these lists as input. [This link](http://kaomoji.ru/en/) contains all of the kaomojis in this challenge. Here's a [pastebin](https://pastebin.com/tpje7V2k) version. ## Output Your program should output the emotion expressed by the kaomoji. You can express this as an integer (i.e., Joy = 1, Love = 2, etc), or output a string containing the emotion. ## Scoring Your score is (B+1)\*exp(3W/(360-W)), where B is the number of bytes in your program, and W is the number of kaomojis that your program incorrectly categorizes. Lowest score wins! [Answer] # JavaScript (ES6), Score 643 ### ~~656 651 646~~ 642 bytes, no error Returns an integer from **1** to **13**. ``` s=>`qv%s!u.r0vPyqv*s"r'yqyu@y2r%{ }1u!v(u{y8|!ru;rur&z+z,w'z-{){{0x'r*z/{Py$t w#z,xFt,}qzr.{#s$t%vv6{@s&v z$x@{!{6v,sCr6s<v z.r s*w=w,r0u5s r){,y!s-s%v8t.xrqyWr7r?z#uBz9r&v#v5yBw+w"})vNw-u4sz)y"zEu/z r"}/rqw w\\t0|(r*rw(uAw&v {uYw#x wqz*|)v2u/|'v!r#sBs}0w&r2y&s r%r6w+}){"r2{-usqw'}C|/v$y={!r!x!t/rt>r1r"svuCy*{qr>v1x2r6x#{5{.wv8wGwqr!r:vJ|#r#u%uqst-}'r"z\`zqw uHy$sYr-z0w#|3{8x7vqz.w!|Ez$uvw!z.{t'w+{5x&|.xmrt"s,u"vuqwy{$t5u&s'wAv"vsTw#z%u*z0s r/w v#}+w'r9}0r0|AvxHv,r*}qw:x r3w}!u0v(w{qvv"y.rSr0w4yr#r.}qw"}%s"v#r!w!u/| tCs u`.replace(/[ -p]/g,c=>"q".repeat(c[C='charCodeAt']()-30))[C]([...s].map((c,i)=>s^=c[C]()<<i%5)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otCYuEEVsq9P1VVh2m/QNYsESY1qw7qko1rJt2era3I6pYa1oLRS9QLlJ@pwHtRKVMWa62X6b4Szj@yRzTJhNpbLCdK1x@gklhh@zo@dx0u0Yd1Bu/14axYQ0Lvjsec@tufQBV9ze0GOuYB87HH@cVPBDStMJDYCiHpOTf3sZY9Iq9Y80qADEBiWRYW1LGvQR@LQXo1yT1Fhqy6KgmvJY4UvCKiLQ4X74tDmJWBtXmonI5Fa3FFHqUFbfyghkoZ7BlRqq4M67vAu14O1VYFBqX67zNwbEAbV4ieCBjAcPmhg2vmgt4eH36WfdjyXN@EB8twphxYWejtWa73HCy9jl9duoaCw3at4@e8Wip69f4mh3cA7QahrXIyTsnGQV@2TGbiPCyekP0HaR4bpE3TdJg4uKnsThy6m1AY/Z6PnMfokI12as0VeatqRje6C9zfTWG1VNka3dPEiVuTxPtFrw3cFxwmSWzTjchcvq5coUm7vrJd1@cMJUPwID4GPZJsOn8MfaO9O/gG545aOj2EuAbVV6rxWvQLgCvLdspzLWatxo1QyhdfK1Ixs5piEYcSTg9aEdU@v3RMJfeoqTl4VICZBtXs45@5WdPE@ozZLx0ePlY8thg8MTYQUwhohZcrAwZPqElZUO6GKE/oJLsNZdo0g8v51HR@9iGiPTpAyT2gnZBsijrEOuU2/CG0dH5ddizO3p6@5mKyX7Xy5gtf2uvjtZfy/). ### How? The input string is turned into an integer **N** with: ``` [...s].reduce((p, c, i) => p ^ c.charCodeAt() << i % 5, 0) ``` (using `.map()` instead of `.reduce()` in the golfed code) Example for `٩(◕‿◕。)۶`: ``` code | << | shifted bit-mask ------+----+-------------------- 1641 | 0 | 11001101001 40 | 1 | 101000. 9685 | 2 | 10010111010101.. 8255 | 3 | 10000000111111... 9685 | 4 | 10010111010101.... 65377 | 0 | 1111111101100001 41 | 1 | 101001. 1782 | 2 | 11011110110.. ------+----+-------------------- XOR = 110010100100101110 = 207150 ``` In the lookup string: * The emotions are encoded as `'q'` to `'}'` (ASCII codes 113 to 125). * The characters `' '` to `'p'` (ASCII codes 32 to 112) encode a run of consecutive `'q'` (which, in addition to 'joy', also depicts an unused slot). The length of such a run is `ord(c) - 30` (minimum = 2, maximum = 82). We first [expand the lookup string](https://tio.run/##bVLLThsxFN3zFbYnk3lkXgQSAjSUENGiLiokKlWoVCIKI2iVJvG1fe/Ynvn2dFh01@2956Wj83uFK7WGX3udb3cv9eHwwObsWWKouCmgwnsrMVUCIiutubZjCD3rjg3H2Hg7azmYSzAwdCOXUeRyn3hfNRGkrvT3dqAZBS5rPumskw4KH6iBDhGn/loNkblBc@25n2KmljBVH/pLAUylNKcMKjNRDBKfWa5yFeJMFw1I@x3O4KMLzI07hyEGOLE3NCLRJfiVcnOqXGKFuzWlYyC6EiQxenrSVRtDChSbBfW@3jxS0DCSLm0THJuyjZBDoG5UV9EQxnbYO4cwpVGXeAFjnxslKeqWbYkDO/cceMN1CfoKjkEoNEubeglXeNyMYdoEfuILwhl9JgkcLvBLG0BgQiOVzrsIhHt6dn0wc2cH6hFyV1HQnvhZc4bSFcTbWzcwSNwVXkc08pNm2BbNH9BCZUagkWT9QE/MUEW0QIHqW19yaFJX9bFLYhh0I4rgvKugahfY3GEGaSfpomFwQh03FcbkJaKwBTxARacWAih6hOhCJTAATrwvhemlYub58uiobvar7Uv90k/joYB6v1mt67j8wfL9z/I1Y2s2v2JCivdXvdLxuli/rWDZz2mh44Tl7KRKkl5mvduq3aYuNrvX@J9ksam3r/qNjZhg76zVWtegRA//Hzq5PBz@Ag) to 4048 characters by replacing `/[ -p]/g` with the runs of `'q'` and then extract the relevant character with the following hash formula, which was found by brute-forcing some random values during a few minutes: ``` N % 8788 * 3672 % 4051 ``` The final answer is the ASCII code of the character modulo 56. ]
[Question] [ I'm new to code golf challenges. My problem came up in [Advent of Code 2020 Day 8](https://adventofcode.com/2020/day/8) The input is an array of arrays. In part two of the problem one needs to run several trials to produce a result by changing an element in the input array. My current code is this (comments added to explain what's going on): ``` p input.each_with_index { |val, i| next if val[0] != :acc # not all elements need to be experimented with changed = input.dup # clone input to make a change # change the first element of the value at input position i (but keep the rest) changed[i] = val.dup.tap { |v| v[0] = v[0] == :nop ? :jmp : :nop } result = try_with(changed) # run the experiment break result if result[1] == :terminate # success condition end ``` So, that's quite a lot of code for something relatively simple. Can I make it shorter? Can I have a simple generator that produces different versions of the same array? My complete code for day 8 is [here](https://paste.ofcode.org/RfLdnvUqxWbRiz7EyFxN2Y) **Edit:** As suggested in the comments, I'll try to put the problem my snippet is solving as a code golf challenge (note that this is just my snippet): In ruby you have `input`: an array of instructions. Each element of `input` is another array of two elements, where the first is a symbol (the instruction name) which is one three: `:acc`, `:jmp`, or `:nop`, and the second is an integer (the instruction argument). You also have a function `try_with` which works with such an array, executes the instructions and returns `[n, :terminate]` if the program terminates or `[n, :loop]` if the program is an endless loop. `n` is the value of the accumulator after the execution. The original input is a loop. If you change *one* of the instructions in the input array from `:nop` to `:jmp` **or** from `:jmp` to `:nop`, and keep the argument, it will result in a terminating program. What is the value of the accumulator after you find and execute the terminating program? **The original AOC2008D8 problem** You have a file with valid assembly. Each line is a three character instruction and a (possibly negative) integer argument separated by a single space. Example ``` nop +0 acc +1 jmp +4 acc +3 jmp -3 acc -99 acc +1 jmp -4 acc +6 ``` Instructions are `acc` add arg to accumulator and increment ip, `jmp` add arg to ip, `nop` ignore arg and just increment ip. Then... what I said above about the snippet-only problem Changing the next-to-last line in the example from `jmp` to `nop` results in a termination with acc value: 8 [Answer] # [Ruby](https://www.ruby-lang.org/), ~~102~~ ~~99~~ ~~98~~ 95 bytes ``` (k=input.map &:dup)[$.-=1][0]=%i[nop jmp acc][k[$.][0]<=>:jmp]until(r=try_with k||$:)[1]>:t;p r ``` [Try it online!](https://tio.run/##bVJhb4IwEP3ur7hkboMoROKyRBT3Q5pm6aCETixNKTMu/nd2V2Ri4gfSd3fv3r32sN3XuS9kCc6eP0/KVYEIZwAizyGDFSJlrqBSrWvsGSPGMaybxkDRIALIRStBMGU4W3GfOVVSQ0oqjhCBRXalJHxLqhgnE@730QzcoTRSJwzd3DGGZqkLf6pyNBgrndddIT8CZUJ4gpN8/ZHIc9LKAoQ37lsArHSd1cDQ3hJSKgzzZN2iHt0cjcSt@pX/OlaKvEIdNEKzoSk9VLp1tsudanT7UBynH5UWTvI72@Oj7nY4bjbk6ZspbTpHb83o3ktYrPgSWOrFFonH@GKI3yb59S0frW/5aLN53BxNm98574ND5gfHR2HgJS06E7J5HGUJLTZ7Vox2QJvCFs4OWKPCLtuTHu@0U3Vgs/FXgsPlMk9D3OI@dVsDtu//AA "Ruby – Try It Online") I assume that `input` and `try_with` are mandatory names for the Advent of Code challenge. If not, the code can obviously be even shorter. Here, I also assume that the `try_with` method will accept invalid input, that is, an array whose elements are not of the form `[:instruction, integer]`. See below for a slightly longer version in case `try_with` strictly requires valid input. See commented code below for a complete list of ideas used. Apart from generic code-golf tips such as 'use short variable names', or common Ruby tips such as 'omit parentheses in method calls', here are some specific tips for the problem posed: * Instead of `each_with_index`, use a counter variable ~~together with an anonymous lambda and `redo`~~ together with `until` (or `while`) in modifier form. For the counter, a good choice in this case is the predefined global variable `$.`, which is initialised to `0`. Processing the `input` array in reverse (by decrementing `$.` in place) is the best approach. Incrementing `$.` in place doesn't work (because `input[0]` would be skipped); incrementing `$.` at the end of the loop would cost bytes. * Only call `dup` at the lowest level, that is, on the elements of `input`, not on `input` itself. * Lexicographical comparisons work with symbols, so `>:t` is better than `== :terminate`, for example. * It turns out to be slightly shorter to use the spaceship operator `<=>` instead of a ternary conditional to choose between instructions. In the code, `k[$.][0]<=>:jmp` returns `-1` if the current instruction is `:acc`, `0` if it is `:jmp`, and `1` if it is `:nop`. Use these values to index into an array of the three symbols, ordered such that the correct replacement is chosen. ``` (k= # use parentheses to define variables inline input.map &:dup # only duplicate the lowest-level arrays, and do all at once )[$.-=1][0] # use $. as a counter and decrement in place =%i[nop jmp acc][k[$.][0]<=>:jmp] # use the spaceship operator to choose between instructions until # loop with until (r=try_with k # omit parentheses in the call to try_with ||$:)[1] # on the first iteration (only), k is nil so pass the predefined array $: to try_with as dummy input >:t; # test for >:t instead of ==:terminate p r # print the result ``` --- # [Ruby](https://www.ruby-lang.org/), 98 bytes ``` p->{(k=input.map &:dup)[$.-=1][0]=%i[nop jmp acc][k[$.][0]<=>:jmp];(r=try_with k)[1]>:t||redo;r}[] ``` [Try it online!](https://tio.run/##bVLtbsIwDPzPU1jaVytoRcU0iULZg0TRlLVBzYAkStMhNvbsnZ2uo0j8qHKxz@eLXde@n7pKbsG709tR@ToS8QRAlCUUMEek7B@oVeONO@GNcbzujbFQGUQApWgkCKYsZ3MeIsdaashJxRMiMC3@KBlfkSresxH342B7bp8aqCOGNleMvljqKpxqOxhMlS73bSVfI2VjuIOjfPqUyPPSyQpEMB5KAJz0rdPA0N4Mckr0/eS@QT16ORpJG/Ul/3WcFGWNOmiEeoPZBqh0411bemV0c1Mcux@UFl7yK9vDUNdrbDfp4/RNlLatp1kzevcMpnM@A5YHsWkWME4M8fMovrjEk8UlniyXt4uTcfEL551NNt/RrgjN04Ow8JhXrY3ZfZoUGS23eFCM9kDbwjLOdpijxLrYkCZfRa4YfiXYxbjBTe7PZxy9WbkfxrvuFw "Ruby – Try It Online") Use this version if `try_with` rejects `$:` as valid input. Here, we iterate using an anonymous lambda and `redo`. ]
[Question] [ > > Your challenge is to turn a Japanese word and a dictionary pitch accent number into a new string where the rises and falls in pitch are marked: e.g. **(2, ウシロ)** → `ウ/シ\ロ`. > > > To help you out with this, I'll explain a little about Japanese phonology. > > > # Background: on *moras* For the purpose of this challenge, we will write Japanese words in [katakana](https://en.wikipedia.org/wiki/Katakana), the simplest Japanese syllabary. A word consists of one or more **moras**, each of which consists of 1. one of: ``` アイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワンッガギグゲゴザジズゼゾダヂヅデドバビブベボパピプペポ ``` 2. **optionally** followed by one of: ``` ャュョ ``` For example, シャッキン consists of 4 moras: **シャ, ッ, キ, ン**. *※ The three optional characters are small versions of katakana `ヤユヨ` (ya yu yo).   For example, キャ is **ki + small ya**, pronounced **kya** (1 mora), whereas キヤ is **kiya** (2 moras).* # Background: pitch accents Japanese words are described by a certain contour of high and low pitches. For example, **ハナス** (**hanasu**, speak) is pronounced ``` ナ / \ ハ ス–··· ``` meaning the pitch goes up after **ハ ha**, then falls after **ナ na**, and stays low after **ス su**. (That is to say: Unaccented grammar particles after **su** will be low again). We might describe this contour as “low-high-low-(low…)”, or `LHL(L)` for short. In a dictionary, the pitch of this word would be marked as **2**, because the pitch falls after the *second* mora. There are a few possible pitch patterns that occur in Tōkyō dialect Japanese, and they are all given a number: * **0**, which represents `LHHH…HH(H)`. This is *heibangata*, monotone form. ``` イ–バ–ン–··· ··· / or / ヘ ナ ``` * **1**, which represents `HLLL…LL(H)`. This is *atamadakagata*, “head-high” form. ``` イ キ \ or \ ノ–チ–··· ··· ``` * **n ≥ 2**, which represents `LHHH…` (length **n**) followed by a drop to `L…L(L)`. For example, センチメエトル has pitch accent number **4**: ``` ン–チ–メ / \ セ エ–ト–ル–··· ``` Such a word must have **≥ n** moras, of course. *※ Note the difference between* **ハシ [0]** *and* **ハシ [2]**: ``` シ–··· シ / vs / \ ハ ハ ··· ``` You can hear the different pitch accent numbers demonstrated [here ♪](https://www.youtube.com/watch?v=fDI_S3pTSNM). # The challenge Given an integer **n ≥ 0** (a pitch accent number as above) and a valid word of at least **n** moras, insert `/` and `\` into it at points where those symbols would occur in the diagrams above; i.e. at points in the word where the pitch rises or falls. The output for **(2, ハナス)** would be: ``` ハ/ナ\ス ``` And the output for **(0, ヘイバン)** would be: ``` ヘ/イバン ``` Remember: you must correctly handle sequences like キョ or チャ as a single mora. The output for **(1, キョウ)** is `キョ\ウ`, not `キ\ョウ`. > > **Instead of `/` and `\`, you may pick any other pair of distinct, non-katakana Unicode symbols.** > > > This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"): the objective is to write the shortest solution, measured in bytes. # Test cases One per line, in the format `n word → expected_output`: ``` 0 ナ → ナ/ 0 コドモ → コ/ドモ 0 ワタシ → ワ/タシ 0 ガッコウ → ガ/ッコウ 1 キ → キ\ 1 キヤ → キ\ヤ 1 キャ → キャ\ 1 ジショ → ジ\ショ 1 チュウゴク → チュ\ウゴク 1 ナニ → ナ\ニ 1 シュイ → シュ\イ 1 キョウ → キョ\ウ 1 キャンバス → キャ\ンバス 2 キヨカ → キ/ヨ\カ 2 キョカ → キョ/カ\ 2 ココロ → コ/コ\ロ 2 ジテンシャ → ジ/テ\ンシャ 3 センセイ → セ/ンセ\イ 3 タクサン → タ/クサ\ン 4 アタラシイ → ア/タラシ\イ 4 オトウト → オ/トウト\ 6 ジュウイチガツ → ジュ/ウイチガツ\ ``` Generated by this [reference solution](https://tio.run/##lVI7TwJBEO73V0x3EA2CGgsSYmVhZWOHFChLWL07LssSpZNdY3w0xp@giPFBLHyHgv/i/BCc2UMTNDGx2Zud77Hf7F7SMY1mvDAeqyhpagNaClGTdUiU2Wpk1CzsZosCIIISQbm6imvVMMwEuTK6S3RX6K4rywGziKTqoKBUgjwrAExVhSQLgtx2U8WZqFwoVrIe0dK0dQxROV@BGQjmAlqZTaAMv1wK/3TZ2JiyaclUH6naD7ma6H85q7/ysc/0KWK3oUIJ67rtjzK6k56Y3ho5qzhpm0w210pCRV8PJlrFxjNmIfg4PKe7m1w1t7OsZKLc25KJgdW1Fa2bOvXd1LK6Mx7nAd2JoNU@ojtGd8G1e0A7Qvvq6yNqottH1/W0F3RuAtkLtHdoe76@9/1HtH1RoO3Ar2/EpEfl2nX5gW0f7RPaB985QXfqaa8e6qVC4n@b@N@Cgp2hfRfzPiTnHPj6Dd0hoyy/FAvUGfrtkK14SyPQIM/UFItp2hG6G@YTgTu3PB1FckdiKTVME/Y4LU908Ak). [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 68 bytes (UTF-8) ``` \d+(.[ャュョ]?) $1/$&$*1\ /1\b /. / +`1(1*.)(.[ャュョ]?) $2$1 ``` [Try it online!](https://tio.run/##ZU8xTsNAEOz3HQeyE8mXcxAtJY/ASAFBkYYiygfYRSiEhjfETiIQkYsE2ZELHjMPMbuHqGhOszOzs3Oz@/n04aY/SS4nfXE3TLIrSAlZQ7bXFym54N2pG4SCfChuiXxGnoaTkIRBlv4z5y70/QiypBF4D3mBrBRKDf4GN8Z@QsQ03lAA7@xpVdIEhfJoYbwBH8C1EUvIq3maKFRxR71/6/G8HnoDHymPuTrtDLaQZ9NstaQxuItTZynj2EdbfSlHZ@CVEfJuZpWV@IAsrIgs6Dxm/daqrKL94ekH "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: ``` \d+(.[ャュョ]?) $1/$&$*1\ ``` Convert the number to unary, wrap it in `/\`, and insert it after the first mora. ``` /1\b ``` If the number was 1, then delete it and the `/`, leaving the `\`. ``` /. / ``` Subtract 1 from the number, but in the case of `0`, this deletes the `\`, leaving the `/`. ``` +`1(1*.)(.[ャュョ]?) $2$1 ``` Move the `\` one mora to the right for each remaining `1`. [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 45 characters / 51 bytes\* / 83 bytes ``` {S←⍵⊂⍨~⍵∊'ャュョ'⋄S[⍺~0],←'\'⋄S[0~⍨⍺≠1],←'/'⋄∊S} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///vzr4UduER71bH3U1PepdUQdidXSpP25e/Lh56ePm5eqPuluCox/17qoziNUBqlSPgYgYAFWuAAo/6lxgCJHQB0kA9QbX/v/vBhSggcFcj/qmAkUMFNwUgAZ1qUP5hmB@01oY3wzC3wGyqGnZ46Ylj5sbHzetedzcog4A "APL (Dyalog Unicode) – Try It Online") The second score only applies if the three Katakana characters in the code can be counted as a different encoding than the other portion of the code. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 32 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` O%62ḟ€“579‘œṗ⁸Ḋ⁹‘+Ị$,2¤œṖżCØ.ḟƊ} ``` A full program accepting a list of characters and a non-negative integer which prints using `0` for `/` and `1` for `\`. **[Try it online!](https://tio.run/##y0rNyan8/99f1czo4Y75j5rWPGqYY2pu@ahhxtHJD3dOf9S44@GOrkeNO4EC2g93d6noGB1aApKZdnSP8@EZekA9x7pq/////7hpx@PmpY@blj1uWvK4ufFx05rHzS3/zQA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##XZLBTsJAEIbvPMUG9GR1BRXjxZj4AJ4N5eiF8AIeTOiuIVgvRhPloDGBCpHQcEBDSYkkEHyPdh6kznbbddsDh/7/N//szNC4ajavo@hiu1oJvPeQjcPW69HxSdjqbp6C@UtoeYFnh9YchZ3At7eMysoRzvNmcb7u7mHNr30TbRbr4RnF6gb@yquByLF@DNKQgWT3lIStt8soqtX2DVIEbhfrhJRI2H4k@EELhtTZFPgd8J7msimVWsrwCbAlsJmeMKFSUzlj4FyksYEeNaZKRrIck64OuKbSPYwDPtRdz5RaynAL@AdmAfsCNtHfIwxTOYq3gd9nBjdRUB1ncZojAFKSHWcyx/l/LbbPDSUkMzMR8D5w3OQDsHmO7JvKQb6S7Fys3c3tnE0RdRXkAW@LUvGkfmYpuNO2qSwsOIgL/Fjyk4FS2qdSToaSKF4Ob/qNjo4uqZRFNqKHMdoTNP8UvbLBPaqcJFsWjIB3xCF4R6dHVMni4tV0RHlNRxxQ/IVuM4OiTXO@Waj/AQ "Jelly – Try It Online"). ### How? ``` O%62ḟ€“579‘œṗ⁸Ḋ⁹‘+Ị$,2¤œṖżCØ.ḟƊ} - Main Link: list of characters S, integer N O - convert to ordinals %62 - modulo by 62 “579‘ - code-page indices list = [53,55,57] - (representing the three optional characters) € - for each ordinal: ḟ - filter discard if in [53,55,57] ⁸ - chain's left argument, S œṗ - partition before truthy indices - (so before the non optional character positions) Ḋ - dequeue (remove the leading empty list) œṖ - partition at indices... ¤ - nilad followed by (links) as a nilad: ⁹ - chain's right argument, N ‘ - increment $ - last two links as a monad: + - add Ị - insignificant? (1 if 1; 0 if 2+) ,2 - pair with 2 } - use right argument, N, for... Ɗ - last three links as a monad: C - compliment = 1-N ḟ - filter discard if in... Ø. - bits = [0,1] - (i.e. if N=0:[0], if N=1:[1], otherwise:[0,1]) ż - zip together - e.g. [[["ジュ"],0],[["ウ","イ","チ","ガ","ツ"],1]] - implicit (smashing) print - e.g. ジュ0ウイチガツ1 ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~63~~ 60 bytes *-3 bytes thanks to Lynn's suggestion to use other separators than `/ \`* ``` ->\n{&{S:g[.<[ャュョ]>?]=$/~7 x!$++*?+^-n~1 x(++$==n>0)}} ``` [Try it online!](https://tio.run/##XVLRSgJBFH3Or5hgkd1WnaxQSHf0F6LeHAMfNALbxDUwRKGZELOXvkHNSBQfLDR88GPmQ2yuO@4sPiyz59wzZ@aeO7VyvZraPjyjaAU52zihbivaur68KySyBcGHgn8K/lUkuaJj4E4aNY8N2z7J2bdxt5NETdO2DcdxyanVbm@fvDK6KXuNTETa5RvIiZinMXSVFbxP1IqJFduzbCH4m@ADohBWUCv4XLCNYEu1e44VDHlMBefgxMbKZoo1A7qkT89UeUbD7Eq6yfZUbUUV1Ar@AgGwsWA/gs2J5qgmQ@q@4O/7Vin8h85a7pxGRCMKMHxHebZuBBA97GI3EZnbh2B/WjekmgT12T5fiHim82ULCjgkWQnehb1wn@E@Bplgl2oW5Od@ab1j17qNNfaZoBUllGOSs/uVRSXcYJ8B353wwucHoOXfcFRgOsABGfgq@UTwHiTPe0o7wQHjTzYVNObPbQTzgmfySnQFH5Tk1kykVi25yM7L51t5rMP7jRNkGm4MGZ78yhZqRY7uPVSRnGUangVkolEvuZ6ZxYhSghyCsmmUBLP29h8 "Perl 6 – Try It Online") Curried function. Uses `7 1` instead of `/ \`. ### Explanation ``` ->\n{ # Block taking argument n &{ # Return a block S:g # Replace globally [.<[ャュョ]>?] # regex for mora =$/ # with match ~7 # followed by 7 x!$++*?+^-n # if i==1 and n!=1 # should be read as (! $++) * (? +^ - n) # +^ is bitwise negation like ~ in C # ? converts to Bool like !! in C # so ?+^-n is like !!~-n or !!(n-1) or n!=1 ~1 # followed by 1 x(++$==n>0) # if i==n and n>0 } } ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 60 bytes ``` n=>s=>s.replace(/.[ャュョ]?/g,s=>i=--n-i?s+1:n?s:s+2,i=0) ``` [Try it online!](https://tio.run/##dZLBTsJAEIbvPgU32mBZQOMBU3kQ64FgITWkJdR4d8cQxIvPAIiR0HBAA4YDD7MPUme6BbZ1SXpo/plv/tmZeWg@NcNW3@s9Wn5w78ZtO/btmxC/ct/tdZst12DlWwETAR8CPu8arHOOUc@2LN/yGmGpWvcbYT0s1c49u2LGrcAPg65b7gYdo21UTKMoYFQ0zesCYwX6Z8UzTQ5fCXgVMD5m8hVLJV0@LAXfCb5WKi9ZKmnrLwQAufCZYrFgRzVHVRMqUpIjx9EnbdAUR6Okbhwn1XQAPNMs@Uzwb8GXygtIJ3If0cIjAW/qPBFAQdvYOvGZKo2tU4fpiediy9kJkZK0dBLAw8DdvQv@m8Um1Ng@koNr6cpp61F25XxFXKQnNgIGVJTeMVHnjXscSD8ZytEXCb1N4tvsRLZMqtqpSA6PCq/tB/MUbsekmrjmucuEGxMKX9RSxnLMDgGtq6TnAoZ0CjBU0Dk7qP@v8Wo/I3lcUzoouvsXdVIYZbkwVor/AA "JavaScript (Node.js) – Try It Online") ]
[Question] [ One day, I saw the challenge to [multiply two strings](https://codegolf.stackexchange.com/questions/125470/multiply-two-strings) and I thought I might be able to do one better. That challenge was fake. It was elementwise maximum. It was not real multiplication. So I set out to make something real. Real division between two strings. I quickly realized that this would make an amazing challenge, as the algorithm was surprisingly complex and interesting to implement. I then realized that it was actually easily reduced into a mere few operations. I'm still doing the challenge, though. Enough with the backstory. Let's go. ## Method To divide two strings, do the following, where `x` is the first string and `y` the second: * If `x` does not contain `y`, return a space and a period concatenated to `x`. + For example, `testx` and `blah` would become `.testx`, with a space at the beginning. * Otherwise, return every occurrence of `y` in `x`, a period, then `y` divided by `x` with every occurrence of `y` removed, with all the periods removed. + For example, `eestestst` and `est` would become `estest.est`. ## Challenge Write a program or function that, given two strings via [standard input](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods), returns the first string divided by the second. You may assume that both input strings will only contain letters between ASCII codepoints 33 and 45, and between codepoints 47 and 126 (yes, space and period are intended to be excluded), and that the operation does not require more than 10 layers of recursion. You are not required to divide the empty string by itself. ## Test cases ``` test, es => es. es test, blah => .test okayye, y => yy. y testes, es => eses. es battat, at => atat. at see, es => .see see, e => ee. e same, same => same. aabb, ab => ab.ab eestestst, est => estest.est aheahahe, aheah => aheah.aheah ah -={}[];:"'!@#$%^&*()~`\|/.<>_+?, ^&*()~` => ^&*()~`. ^&*()~` best, => . ``` ## Scoring As this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the submission with the least amount of bytes wins. [Answer] # [Python 2](https://docs.python.org/2/), ~~88~~ ~~85~~ ~~84~~ 77 bytes ``` f=lambda x,y,d='.':y in x and y*x.count(y)+d+f(y,x.replace(y,''),'')or' '+d+x ``` [Try it online!](https://tio.run/##ZZDBboMwDIbvewpLOwRW5MOOk9i7OMWIqjQgSKX46ZmTQQk0kh3H/uQ/9ii@G9z3srR1Tw/bEIRKqqY2aH4Ebg4CkGtAvgJeh6fzhZSX5tIWUgWceOzpyhobU0YbJgNGy2EZp5vz0BbG8@xNBYZnU8J6PqH@BZ5R7eMNtD11G5pAwFjaweFOIhxRebVMoAiCHBuq6kF7VT5rW/Kekrr6HCVNo/odnZnP42zf1NI7l2GrOqt2xtEjgenOpWMCYQeJrE0/tKdFkkWyGchpbr@tPQ20zh3zeFgmdUydutQ5xkr/d40PTF7j5Q8 "Python 2 – Try It Online") --- Saved * -1 byte, thanks to LyricLy * -7 bytes, thanks to Dead Possum [Answer] # Java (JDK 11), 146 bytes ``` String f(String x,String y){int c=x.replace(y," ").split(" ",-1).length-1;return c<1?" ."+x:y.repeat(c)+"."+f(y,x.replace(y,"")).replace(".","");} ``` [Try it online using Java 10!](https://tio.run/##jZPLVoMwEIb3PsUYb8QC2m1prS/gymWpOtC00NLAIUMtp@KrY8DUy6awSf4M39zCZI07dNaLTR0mqBQ8YSwPZwCKkOIQ6mfKY7mCpWXE3jai5IdYEoSTvZuLLMFQWKXNgHFXZUlMlpa2M@RuIuSKImfo5YKKXEI4Hk4ZuGywH2k/gaTdQj5g2rLU8l80xvnPUQONwatqgKwIEl2cqXGXxgvY6rpNjbM5IG96AHguFYmtmxbkZvoTJdJaWoyEImYDE0on8HqAQYJRB5pusCxFA5c9gurMffIHSLrFBtXraVQJ0SvkkevCcNty7X4aRQyCtsSgAxRt43S8@66OMBIY6aWN3egO3pkcqtncG/ns5vzx4vLq5frW4p9vvv9x544fXgfTJpAxdt27@e8Gq37fgxl@M7nmpGxon0JaSOLwPXlm2qV4Nz5WI8MI81nLzf9Mtn/PbGUyVfUX "Java (JDK 10) – Try It Online") This TIO emulates `String::repeat` of Java 11 by writing [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen)'s implementation as a helper method with the same amount of bytes. ## Explanations ``` String f(String x,String y){ // int c=x.replace(y," ").split(" ",-1).length-1; // Count the number of occurrences of y in x. // replace(y," ") fixes the issue on special characters for the split hereafter // .split(" ",-1) makes sure that there are trailing elements return c<1 ? // If there are no occurrence, return " ."+x // " ."+x : // Else return y.repeat(c) // y, c times + "." // append a dot + f(y,x.replace(y,"")).replace(".",""); // y divided by x without y, and remove all dots } ``` [`String.repeat(int)`](https://download.java.net/java/early_access/jdk11/docs/api/java.base/java/lang/String.html#repeat(int)) only exists since Java 11, hence the JDK 11 header. Alas and to my knowledge, there are currently no Java 11 online compiler / tester... [Answer] ## Python 2, 72 bytes ``` lambda f,s:(s*f.count(s)+'.'*(s in f))+s*(s in f)+(' .'+f)*(f.find(s)<0) ``` [Answer] # [Proton](https://github.com/alexander-liao/proton), 75 bytes ``` f=(x,y)=>(u=x.count(y))?y*u+'.'+f(y,x.replace(y,'')).replace('.',''):' .'+x ``` [Try it online!](https://tio.run/##bY/RCoMwDEXf9xW@pZ3iBwzcviWViGPOikZovr7GgsPiXtLk3Jvbdpo9@zHGrjGhEts8zdqEuvXryEasfcl9LaGGsjNShXqmacCWtAew9jeqYQcPKNQZ4jS/dbszwLQwVAXQou7bBbsB@0zwHxShXZLLgmZckxwyY8rSehYWoj/2g@YQv4mm8ywgOpeiXYYpPYaPn@X3Yk/Ya0l7e69q3AA "Proton – Try It Online") [Answer] # [Physica](https://github.com/Mr-Xcoder/Physica), ~~81 75~~ 67 bytes ``` f=>x;y;d='.':y∈x&&y*x.count[y]+d+f[y;Replace[x;y;''];'']||' '+d+x ``` [Try it online!](https://tio.run/##bY9BCoMwEEX3PYUrByp4gAZ7htKtuJjoSKS2SpNCBjyA5@xF0iQgGOwik/Dfn5@ZWbEeWnSur65WsOgqKOHC33W1ec5nW7bT52Vqboqu6GsWd5pHbKkOXoAmnGWBDDy27vYevLevwZA2IDIgDU1zOshyRJWA6YHMFBAfGnzGMUmiMRizfN0DTfTHvqmpiM@oxnsPEKWM0TKRKQ5jts3Sf1ERKl9iX3h76n4 "Physica – Try It Online") Utilizes [Dead Possum's golfs](https://codegolf.stackexchange.com/questions/166511/divide-two-strings/166512#comment402579_166512) on [TFeld's answer](https://codegolf.stackexchange.com/a/166512/59487). [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 105 bytes ``` ¶.*$ $&¶. /^(.*)¶.*\1/{*>|""L`(?<=(.*)¶.*)\1|\.$ (?<=(.*)¶.*)\1|\.$ )`(.*)¶(.*) $2¶$1 .*¶(.*)¶(.*) $2$1 ``` [Try it online!](https://tio.run/##bZHPTsMwDMbvfgpTstF2xVV3hLXjxoU3oIw6UqQi/kkkl2qFx9oD7MVKnHTswiHO55/82VbyZdzLB1fTIu1SyrMCJWLdIK1ArY8HVQG16X03HQ@UK1BLf0O5kyohbVXu82ZMkocu3W7qE87aamxJwX8Msi4iiX8z8pjPFNVaVdPkjHUFGiv7GEv@QET6jXuBSJLD5ysPgylwEDYMhEOoM/Zsnu2anWPfgJ1g9pp8BGvMqRTJJzMIVuONYPndA4nC5CYEZq19Kx1aafICTBjr4toujhZAsib3hnsfvEdUsImgmHIP1/X@@/Hp9ia5uri7VIvdMk@zn64dS9o0z6ttgTMR6yzpJECHpwl/h78 "Retina – Try It Online") Link includes test suite, but code normally takes `y` then `x` on separate lines. Explanation: ``` ¶.*$ $&¶. ``` Append a newline and a `.` This expression is cumbersome in order to deal with an empty second input, where `$` would otherwise match twice. ``` /^(.*)¶.*\1/{ ``` Repeat while `x` contains `y`. ``` *>|""L`(?<=(.*)¶.*)\1|\.$ ``` Output all of the matches of `y` in `x`, plus the `.` on the first pass. ``` (?<=(.*)¶.*)\1|\.$ ``` And then delete them all. ``` )`(.*)¶(.*) $2¶$1 ``` Swap over `x` and `y` and repeat. ``` .*¶(.*)¶(.*) $2$1 ``` Output the `.` if `x` never contained `y`, and `y`. [Answer] # [JavaScript (Babel Node)](https://babeljs.io/), 90 bytes *Based on [Olivier Grégoire Answer](https://codegolf.stackexchange.com/a/166513/78039)* ``` (_,x)=>(l=_.match(RegExp(x,`g`)))?l.join``+`.`+f(x,_.replace(x,'')).split`.`.join``:` .`+_ ``` [Try it online!](https://tio.run/##LYvBDcMgEARb8Q@QMQVEInmlgTTAYXIQrAsggyy6JzzyW83MHvay1Z2xtG23O9KW8huH14Mb2YW@c9JGfW1zH/7C8OyFdwkBhBAPUkeOCWAFBauf3KgTC1mHczMmhKqFYpv2H95gmaUZLqeaCRXlwD1nDWtjcmFY52cZPw "JavaScript (Babel Node) – Try It Online") [Answer] # [Stax](https://github.com/tomtheisen/stax), 28 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` Çûù=a┐µ¬▄↑ivܰ{⌐╨[£èvÇu┴▓<v~ ``` [Run and debug it](https://staxlang.xyz/#p=8096973d61bfe6aadc1869769af87ba9d05b9c8a768075c1b23c767e&i=%22test%22,+%22es%22%0A%22test%22,+%22blah%22%0A%22okayye%22,+%22y%22%0A%22testes%22,+%22es%22%0A%22battat%22,+%22at%22%0A%22see%22,+%22es%22%0A%22see%22,+%22e%22%0A%22same%22,+%22same%22%0A%22aabb%22,+%22ab%22%0A%22eestestst%22,+%22est%22%0A%22aheahahe%22,+%22aheah%22%0A%22-%3D%7B%7D[]%3B%3A%5C%22%27%21%40%23%24%25%5E%26*%28%29%7E%60%5C%7C%2F.%3C%3E_%2B%3F%22,+%22%5E%26*%28%29%7E%60%22%0A%22best%22,+%22%22&a=1&m=2) ]
[Question] [ Prior to the decimalisation of Sterling in February 1971, a pound (**£** - from Roman *libra*) comprised 20 shillings (**s** - *solidus*), each of 12 pennies (**d** - *denarius*). Additionally, until 1960, each penny could be divided into four farthings (some parts of the Commonwealth also had fractions of farthings, but we'll ignore those in this question). Your task is to write a simple adding machine for financial quantities in the old system. You will receive a set of **strings**, and emit/return a single string that represents the total of all the inputs. The format of input and output strings is as follows (adapted from [Wikipedia: £sd](https://en.wikipedia.org/wiki/%C2%A3sd)): 1. For quantities less than 1 shilling, the number of pence followed by the letter `d`: ``` ¼d -- smallest amount representable 1d 11¾d -- largest value in this format ``` 2. For quantities less than £1, `/` is used to separate shillings and pence, with `-` as a placeholder if there are no pence: ``` 1/- -- smallest amount in this format 1/6 19/11¾ -- largest value in this format ``` 3. For quantities of £1 or greater, we separate the parts with `.`, and include the units: ``` £1 £1.-.¼d -- one pound and one farthing £1.1s.- -- one pound and one shilling £999.19s.11¾d -- largest value needed in this challenge ``` The inputs will never sum to £1000 or more (i.e. you can assume the pounds will fit into 3 digits). Input will be as *strings* by any of the usual input methods (as an array of strings, as a single string with newlines or other separators, as individual arguments, etc). There will be no additional characters (not mentioned above) in each string. Output will be as a single string, by any of the usual output methods (standard output stream, function return value, global variable, etc.). You may include additional spaces around the numbers if that helps. ## Examples (assuming my mental arithmetic is up to scratch!) 1. Input: `¼d`, `¼d` Output: **`½d`** 2. Input: `11¾d`, `¼d` Output: **`1/-`** 3. Input: `£1`, `6d`, `9d` Output: **`£1.1s.3d`** 4. Input: `£71.11s.4¼d`, `12/6`, `8/-`, `8/-`, `2½d` Output: **`£73.-.¾d`** --- If (and only if) your language/platform cannot represent the farthings (yes, I'm looking at you, ZX81!), you may use the letters `n`, `w` and `r` instead, to mean ¼ (o**n**e), ½ (t**w**o) and ¾ (th**r**ee) respectively. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest working program (in bytes) is the winner. Please indicate the source character-coding if it's not UTF-8 (and not determined by the language). Standard loopholes which are no longer funny are not permitted. [Answer] # [Clean](https://clean.cs.ru.nl), ~~555~~ ... 504 bytes *Uses ANSI codepage `Windows-1252`, but since TIO treats Clean source files as UTF-8, all invalid UTF-8 character literals are represented with octal escape sequences and counted as one byte.* ``` import StdEnv,Text,StdLib n=0.0 e=entier r=toReal *0="" *n=fromInt n ?'\274'=".25" ?'\275'=".5" ?'\276'=".75" ?c={c} @s=r{#d\\c<-:s,d<-: ?c|all((<>)c)['sd\243']} $s|"9"<s%(0,0)=(map@(split"."s)++[n,n])%(0,2)|endsWith"d"s=[n,n,@s]=[n:map@(split"/"s)] ^[x,y,z]#d=e z #p=if(z>r d){'\273'+toChar(e((z-r d)/0.25))}"" #(y,d)=(d/12+e y,d rem 12) #[x,y,d:_]=map*[y/20+e x,y rem 20,d] |x>""=join"."["\243"+++x,y+++if(y>"")"s""-",d+++if(z>n)(p+++"d")"-"]|y>""=join"/"[y,d+++if(z>n)p"-"]=d+++p+++"d" ``` # ``` ^o foldr(zipWith(+))[n,n,n]o map$ ``` A partial function literal, taking `[String]` and returning `String`. [Try it online!](https://tio.run/##TZJLj5swEMfv/hSW2Sp2IOGRVxvF2ZW2Pay0h6pbqQfCVhRDlwoMwk4VSPLVS8fQx17s@c3Dnr/HSZHGsi8rcSxSXMa5RK6Lg@UCc1xXRynUwJslsO8uR1gNEIywBli4yz4v66rR@EmLD/Kn8zk9aQfsx/wbktybeyjlqdR52qCG6@pTGhdo6nFC0FTyrKnKB6mxRLeTA9w14WQerMhIK0N/YW1gYyjh5@SK7hRvzpY4HJLdbKscASu@TS5xUVC627OEhRMlDiBnEl3RjbqQd2Sn3lDP8RinZVzfUVUXuSZzophth9KRETPhgF1S0P4l1y9EEMVNxLlTERjbV2UulEXoOTw5rdNFluAp7pBV8zyj3b7Bgp1N04uJrav7l7ihKaXdzPhdDwQydgX9Fm0dAd0I1w/sFAPgJi2xHzBkDQeL7deIw6XTsHUDD1LAOaQEniMidDntCeE/qlyCipAYscS2bUiCFRppIcyIImRGHDG6ur1ktAYbtDHwR5f23xkuCdvXebWJc@P4U9A/6bjRyMLZUSY6ryTM/7nCWVWIhnZ5bd6M2owNTyajCj5VfYP4//Sxx40/9301X5p5C@IQP3DXsL11oU0SmLkLEvW/kqyIv6t@9vDYv29lXObJCB@LWGdVUw4w/rPf) [Answer] # [APL (Dyalog Classic)](https://www.dyalog.com/), ~~265~~ 260 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?") *Now works even for edge cases not in the example cases.* Full program. Prompts (STDERR) for input (STDIN) of list of strings. Outputs to STDOUT. Assumes `⎕IO` (**I**ndex **O**rigin) to be `0`, which is default on many systems. `0(('^0' '$',d)⎕R('' 'd',f)⍕2↓t)r(r←' 0d' ' 0?'⎕R'/-' '/'⊢d⎕R f,∘'d'⍕1↓t)('£',⍕⊃t)(∊'£'(⍕⊃t)'.','-'('s',⍨⍕1⊃t)[×1⊃t]'.','-d' '-'⎕R'-' ''⊢'d',⍨(d,⊂'^0')⎕R(f,'-')⍕2⊃t)[5⌊2⊥×t←v⊤+/((v←0 20 12)⊥(¯3+6×'£'=⊃)↑∘⍎('-' '\D',⍨f←,¨'nwr')⎕R('0 ',⍨1↓¨d←('\.',⍕)¨25 5 75))¨⎕]` [Try it online!](https://tio.run/##bVFNS8NAEL33V@xBmF26@dhoWj2IFy@CIHi1FUqXiFBUktLiVaGWYIsipZ6tQm7@h/SfzB@JMxsVKeawO/PevHkzm97NwLO3vcH1hdcf9LLssl/hfHF0gpOnsIHTh@PMVqGUcB6CgC3QVhF9KoEyCzpROFtEOHkZqlSmpAERWqJEeABcB4FHWQCYv1nORaJx@kpKkhknk1CuQFOK@T1lOM0ZkD8A@KDBAwkZFxVOxvjZeumCbl3Anl7tyIbsx@ORQlqN@R2PXw@ecLt6atcnxsecwo/1ckjjjzB/bwZSjnh9EYXCRIpIWX5uN1vrJY@2TzqFk2faA2dz6fw6h84rIZUuC7gap99uEArH8K5lYYmX0PHdvqosoljEoh0rCqm6W9FzV8J99OoNuKKtBJ@NP6Ax6X9wuTKMthy3t8m1jW9M5u/UHU0UtPje5Z/ze0XjDaMaJvQL "APL (Dyalog Classic) – Try It Online") (or [equivalent Unicode edition](https://tio.run/##bVHBSsNAEL33K/YgzIZukt1oWj2IFy@CIHi1FQpLvBSUthS8KtQSbFGk1LNVyM0fsD1s/2R@JM5sqkgxl5l5b968mU3nphva2073@qrE6ezkDEdPuobjh9O@LbWUcKlBwA4oGxB9LoEqCyoLcDJLcPQyCHqyRxoQ2hIl9BFwH8QhVTFg/ma5FpnC8SspSWa8TIJbgKIS83uqcJwzIH8AiEBBCBL63FR4GeMX67lP2lUDe4aVIxuyH69HCmkV5ne8frV4xuOqrf2cFB9zSj/W8wGtP8T8vR5LOeTzRaKFSQIipfvcrTfWc17tkHQBjp7pDpxMpfdrHXuvjFTKFeC@3NKtNoaghSf5XFdYapHQivzJgSuSVKSimQaUUne7pBcvhf/o4Ws0iS4TPtT@wMa41b@EWxiGG5482OaaJjKmH@1tppokbnDc55/0GxK33DKrcIa/AQ "APL (Dyalog Unicode) – Try It Online") sporting proper fractions) ## Explanation This program has five parts; one that handles input, conversion, summation, and *selection* of output format, and one for each of the four possible output formats which are: 1. *less* than a shilling: `¼d`–`11¾d` 2. a whole number of shilling, which is the same format as 3. *between* a shilling and a pound: `1/-`–`19/11¾` 4. *whole* pounds: `£1`, `£2`,… `£999` 5. *everything* else: `£1.-.¼d`–`£999.19s.11¾d` The overall structure of the program is:  `0(` *less* `)r(r←'` *between* `)(` *whole* `)(` *everything* `)[` *selection* `]` This uses *selection* to index from a list of all possible formats. The initial `0` is a placeholder for output format 0 which does not exist. `r←` assigns format 4. to the variable `r`, which is then used as format 2. ### input, conversion, summation, and *selection* of output format `5⌊2⊥×t←v⊤+/((v←0 20 12)⊥(¯3+6×'£'=⊃)↑∘⍎('-' '\D',⍨f←,¨'nwr')⎕R('0' ' ',⍨1↓¨d←('\.',⍕)¨25 5 75))¨⎕`  `⎕` prompt for (evaluated) user input (list of strings)  `(`…`)¨` on each string, apply the following tacit function:   `25 5 75` the numeric list `[25,5,75]`   `(`…`)¨` on each number, apply the following function:    `⍕` the string representation    `'\.',` preceded by an escaped (for PCRE) period   `d←` store that in `d` (for **d**ecimals; `["\.25","\.5","\.75"]`)   `1↓¨` drop one character from each; `[".25",".5",".75"]`   `'0 ',⍨` append the two characters; `[".25",".5",".75","0"," "]`   `(`…`)⎕R` PCRE **R**eplace the following strings with the above:    `,¨'nwr'` ravel (make into own vector) each of these characters; `["n","w","r"]`    `f←` store in `f` (for **f**ractions)    `'-' '\D',⍨` append these two strings; `["n","w","r","-","\D"]`   `⍎` execute as APL statement (this gives a numeric list)   `∘` then   `(`…`)↑` take this many elements (padding with zeros as needed):    `⊃` the first of the argument (one of the strings)    `'£'=` Boolean (0 or 1) whether it is a pound symbol    `6×` multiply by six; gives 6 if string had pound(s), 0 if not    `¯3+` add negative three; gives 3 if string had pound(s), −3 if not Taking a negative number of elements takes from the right and pads on the left if needed. Taking a positive number of elements takes from the left and pads on the right if needed. Thus we now have pounds, shillings, and pence in fixed positions in a length-3 list for each input string.   `(`…`)⊥` convert to regular number (pence) from the following mixed-base:    `0 20 12` 12 pence per shilling, 20 shilling per pound, no amount of pounds convert up    `v←` store in `v` (for **v**alues)  `+/` sum (lit. plus reduction)  `v⊤` convert to mixed-base `v`  `t←` store in `t` (for **t**otal)  `×` signum of those values  `2⊥` convert to regular number from base-2 (binary)  `5⌊` find the minimum of five and that. Gives 1 for pence-only, 2 for shilling only, 3 for shilling and pence, 4 for pounds only, and 5 for pounds and change. ### *everything* else `∊'£'(⍕⊃t)'.','-'('s',⍨⍕1⊃t)[×1⊃t]'.','-d' '-'⎕R'-' ''⊢'d',⍨(d,⊂'^0')⎕R(f,'-')⍕2⊃t`  `2⊃t` the third (pence) value of `t`  `⍕` string representation of that  `⎕R(`…`)` PCRE **R**eplace the following strings:   `f,'-'` the list `f` followed by a dash; `["n","w","r","-"]`  `(`…`)` with:   `⊂'^0'` this string (regex: leading zero)   `d,` appended to `d`; `["\.25","\.5","\.75","^0"]`  `'d',⍨` append a "d" to that  `'-d' '-'⎕R'-' ''` remove stray "d"s and dashes (caused by less than a whole pence)  `…'.',` prepend the following and a period to that:   …`]` use    `1⊃t` the second element of `t` (the shilling)    `×` the signum of that (i.e. whether we have any shilling or not)   `'-'`…`[` to index from a dash and the following:   `1⊃t` the second element of `t` (the shilling)   `⍕` the string representation of that   `'s',⍨` followed by an "s"  `'£'(`…`)'.',` prepend a pound sign, and the below, and a period to that:   `⊃t` the first element of `t` (the pounds)   `⍕` the string representation of that  `∊` **ϵ**nlist (flatten) ### *whole* pounds `'£',⍕⊃t`  `⊃t` the first element of `t` (the pounds)  `⍕` the string representation of that  `'£',` prepend a pound symbol ### *between* a shilling and a pound `' 0d' ' 0?'⎕R'/-' '/'⊢d⎕R f,∘'d'⍕1↓t`  `1↓t` drop one element from `t` (leaving the shillings and the pence)  `⍕` the string representation (space separated) of that  `,∘'d'` append a "d" to that (lit. apply the append function with a curried right argument)  `d⎕R f` PCRE **R**eplace `d` (`["\.25","\.5","\.75"]`) with `f` (`["n","w","r"]`)  `⊢` yield that (separates the following from `d`)  `' 0d' ' 0?'⎕R'/-' '/'` PCRE **R**eplace:   no-pence with slash-dash   leading pence-zero with slash ### *less* than a shilling `('^0' '$',d)⎕R('' 'd',f)⍕2↓t`  `2↓t` drop the first two elements of `t` (leaving just pence)  `⍕` the string representation of that  `⎕R(`…`)` PCRE **R**eplace with the following:   `'' 'd',f` the list `f` preceded by these two strings; `["","d","n","w","r"]`  `(`…`)` where the following occur:   `'^0' '$',d` the list `d` preceded by these two strings; `["^0","$","\.25","\.5","\.75"]`    the first is a leading zero    the second marks the end of a string [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 252 bytes ``` .+/.+ £.$&d m`(?<!d)$ ./d m`^(?!£) £./ s. / ([¼½¾])?d d0$1 T`¼½¾`123 [-\d]+ $* +`.(1*)/(1*)d(1*)¶£(1*).(1*)/(1*)d $4.$1$5/$2$6d$3 +`d1111 1d +`/1{12} 1/ +`\.1{20} 1. (.)(1*) $1$.2 \b0 - T`d`_¼½¾`.$ -?d(.) $1d £-.-/ £-.(.+)d $1 (\..+)/ $1s. -s - .-.-d ``` [Try it online!](https://tio.run/##TU8xUgMxDOz3F5nRMHY8lk5OOBpm7hN0ucDBKAUFFIQuw2vuD1QJhT92yECBC2m13pXXb4f359fHZeEknFBnpivDyxSG25VFAkub7sOwqnNs14IjQxB29Vwv9WsfB4N1pLibfplJywa7PNo@gdZIEwddR2nFWqmfdW79Hw3aMildCxXqjTZuMvUDNYeiJy0fUHE8sp5K5wMjcGxmuJELxqcO2TPY9PAXgwl5MFe5wjx55iz46YFTe1MRRnYoDv1P@egL2FWGZanzjbI6va1ngxbpob1klHqxbw "Retina 0.8.2 – Try It Online") Explanation: ``` .+/.+ £.$&d m`(?<!d)$ ./d m`^(?!£) £./ s. / ``` Reformat the input into a fixed format `£<l>.<s>/<d>d<f>`. ``` ([¼½¾])?d d0$1 T`¼½¾`123 [-\d]+ $* ``` Convert to unary. ``` +`.(1*)/(1*)d(1*)¶£(1*).(1*)/(1*)d $4.$1$5/$2$6d$3 +`d1111 1d +`/1{12} 1/ +`\.1{20} 1. ``` Add up the values. ``` (.)(1*) $1$.2 \b0 - T`d`_¼½¾`.$ -?d(.) $1d £-.-/ £-.(.+)d $1 (\..+)/ $1s. -s - .-.-d ``` Convert back to decimal and format for display. ]
[Question] [ I'm trying to strip down my python code to be as few lines as possible. The task: count how many square numbers are below 100. Here's my code so far: ``` m = 0 for x in range(0, 100): m+=1-(-((-((x+1)**(0.5)-((x+1)**(0.5))//1))//1)); print(m) ``` That addition statement adds 1 to m (the counter) only when (x+1) is a perfect square. Is it possible to shorten anything? Maybe find a way to print without using a counter -- such as printing a summation in a form such as: ``` print(sum(min,max,variable,statement)) ``` [Answer] For the exact question posed: since we know that **1** is a perfect square and all integers between that and the maximal one (here **9**) will be included we can simply find that maximal one: ``` print((100-1)**.5//1) ``` (`//1` performing integer division by one to remove any fractional part may be replaced with `/1` prior to Python 3.) with both endpoints (an inclusive `start` and exclusive `stop` equivalent to a `range`) this could be extended to a function (negative inputs catered for with `max`): ``` f=lambda start, stop:print(max(0,stop-1)**.5//1-max(0,start)**.5//1) ``` [Answer] For the record, below is another approach using additions and multiplications only. The square of ***N*** is the sum of the ***N*** first odd positive integers: ``` 1^2 = 1 2^2 = 1 + 3 = 4 3^2 = 1 + 3 + 5 = 9 4^2 = 1 + 3 + 5 + 7 = 16 etc. ``` Consequently, if we are to compute all perfect squares up to a given limit, each one can be quickly deduced from the previous one. Hence the following possible algorithms: ``` # with 3 variables, using addition only s = i = 1 n = 0 while s < 100: n += 1 i += 2 s += i print(n) ``` ``` # with 2 variables, using addition and multiplication s = 1 n = 0 while s < 100: n += 1 s += n * 2 + 1 print(n) ``` Or as a recursive lambda: ``` f = lambda x, s=0, n=0: f(x, s+n*2+1, n+1) if s < x else n-1 print(f(100)) ``` [Answer] This works (47 chars): ``` print(sum(map(lambda n:0==n**.5%1,range(100)))) ``` `n**.5` will return a float, which will be a whole number if n is a perfect square. We can then do `%1` to get the fractional part, which will be `0` if `n` is a perfect square, so adding `0==` will give us a boolean of whether or not `n` is a perfect square. We can then make that into a `lambda` function and `map` that onto the range, which will give us a list of booleans, which can be summed to give us how many `True` values were there. As in Ben Frankel's answer, it's actually shorter to use list comprehension than `map`. I didn't think of that. That gets us down to 41 chars. ``` print(sum(0==n**.5%1for n in range(100))) ``` EDIT: removed one byte by replacing `not` with `0==` [Answer] How about this? ``` print(sum(x==int(x**.5)**2for x in range(1,101))) ``` This is a sum of boolean values, so they are treated as `0` for `False` and `1` for `True`. EDIT: As in Riker's answer, `x**.5%1==0` is shorter than `x==int(x**.5)**2`. ]