C in constant space (via).
#include <stdio.h>
static int spiral_index(int x, int y) { int p; if (y * y >= x * x) { p = 4 * y * y - y - x; if (y < x) p -= 2 * (y - x); } else { p = 4 * x * x - y - x; if (y < x) p += 2 *(y - x); } return p; }
int main(void) { int n; scanf("%d", &n);
int sx = n % 2 ? n / 2 : (1 - n) / 2; int ex = n % 2 ? (1 - n) / 2 - 1: n / 2 + 1; int dx = n % 2 ? -1 : 1; int sy = n % 2 ? (1 - n) / 2 : n / 2; int ey = n % 2 ? n / 2 + 1 : (1 - n) / 2 - 1; int dy = n % 2 ? 1 : -1; for (int y = sy; y != ey; y += dy) { for (int x = sx; x != ex; x += dx) printf("% 3d", n * n - spiral_index(x, y)); putchar('\n'); } }
Ruby affords a pretty straightforward solution:
n, alphabet = gets.split(/\s+/)
words = n.to_i.times.reduce([]) { |words| words << gets.chomp }
puts words.sort_by { |word| word.split('').map { |letter| alphabet.index(/#{letter}/i) } }
I was going to do another one of my non-alphanumeric programs, but I can't figure out how to simulate #gets
without using any numbers or letters. :/
Edit to include a link to a C solution I wrote up just to make sure I still could.
Edit the Second
So I ended up accepting my fate; I concede that I'm addicted to the lambda calculus and its manifestation as symbol-laden Ruby code. To that end, here is my completely non-alphanumeric solution to today's problem.
As I mentioned, I've not yet discovered a way to obtain user input in Ruby without using letters, so this program cheats a bit by passing the data as parameters to the Gorellian procedure (called $________
in the code). Still, it's a workaround I can deal with, as the rest of the program is pretty glorious, and it was a hell of a lot of fun to tinker with.
C++ solution, with a few (mildly obfuscating) tricks:
#include <iostream> #include <string> #include <cctype> using namespace std;
enum action { ENCRYPT, DECRYPT }; string crypt(action type, int nrails, string data) { int cyclesize = 2*(nrails-1); string ret(data); int pos = 0, i, a; int & rpos = type ? i : pos, & dpos = type ? pos : i; for (int rail = 0; rail < nrails; ++rail) { for (i = rail, a = 2*rail; i < data.length(); a = cyclesize - a, i += a) { if (a==cyclesize) continue; ret[rpos] = data[dpos]; ++pos; } } return ret; }
int main() { string data; action act; int nrails; cin >> data >> nrails; if (data == "enc") act = ENCRYPT; else if (data == "dec") act = DECRYPT; else { cout << "Unknown action.\n"; return 1; }
while (isspace(cin.peek())) cin.ignore(); getline(cin, data);
cout << crypt(act, nrails, data); return 0; }
Simple implementation that also scans input for Letters (according to the Unicode Letter
property) so invalid chars in the input will be ignored.
sub score($s) { my @l = $s.comb(/<:Letter>/); @l».lc.unique.map(-> $k { $k => @l.grep($k) - @l.grep($k.uc) }).sort(-*.value) }
for < abcde dbbaCEDbdAacCEAadcB EbAAdbBEaBaaBBdAccbeebaec > -> $s { say score($s) }
OUTPUT:
(a => 1 b => 1 c => 1 d => 1 e => 1) (d => 2 b => 2 a => 1 c => 0 e => -2) (c => 3 d => 2 e => 1 a => 1 b => 0)
Not perfect, but here we go, C++: http://ideone.com/t25IJ
typedef pair<char, uint8_t> RunLength;
vector<RunLength> runLengthEncode(const string& s) { if(s == "") return {}; vector<RunLength> res;
size_t i = 0, nextPos; while(s.npos != (nextPos = s.find_first_not_of(s[i], i + 1)) ) { auto diff = nextPos - i; assert(diff <= 255); res.push_back( {s[i], diff} ); i = nextPos; } res.push_back( {s[i], s.size() - i} ); return res; }
string runLengthDecode(const vector<RunLength>& encoding) { string res; auto addFun = [&res](const RunLength& rl) { res += string(rl.second, rl.first); }; for_each(encoding.begin(), encoding.end(), addFun); return res; }
My solution using only HTML and CSS. (This does not use the commend like, but is still a neat example). I included it only in jsfiddle since that is the best way to view the results.
The encode function can be rewritten using the the &&&
function from Control.Arrow
(I love that type of notation)
encode = map (length &&& head) . group
Also, this is problem 10 in the 99 Haskell Problems!
The next few also deal with this type of thing, and I actually wrote a blog post about how to directly run-length encode using Haskell, located here! http://5outh.blogspot.com/2012/07/99-haskell-problems-13-run-length.html
I love Haskell for this type of problem.
I'd also like to add that Hoogle is a great resource for searching through the Haskell API. I'm hardly a Haskell pro, but it's a tool that helped me a good deal when I was in college.
Done in scratch for fun.
It could, in theory, go through the enable1 word list, however flash crashes every time I try to load that thing, so I guess we'll never know for sure.
Due to scratch's lack of nested data structures, a trie or radix tree wasn't exactly practical for how much time I wanted to spend on this, so I went with a modified binary search instead, it's pretty slow and I don't recommend it.
The method you are looking for is 'sorted' example:
"hello".sorted // returns "ehllo"
The official scaladoc documentation for scala and can be very useful for finding methods like sorted.
C# w/ Linq:
static void number114WordLadder() { var list = File.ReadAllLines("selected_four-letter_words.txt");
var needle = "puma"; Func<string, string[], string[]> matcher = (s, l) => (from li in l where li.Where((c, i) => c != s[i]).Count() == 1 select li).ToArray();
var bonus1 = (from li in list where matcher(li, list).Length == 33 select li).First();
matcher(needle, list).ToList().ForEach(Console.WriteLine); Console.WriteLine("Bonus 1: " + bonus1); }
I've been trying to implement new intrinsic functions introduced in COBOL 2014 for GnuCOBOL. So far, I've created a patch which provides three functions which format dates/times according to an ISO 8601 format, such as "YYYY‑MM‑DD" or "hh:mm:ss". For example:
MOVE 45296 TO seconds-from-midnight DISPLAY FORMATTED-TIME("hh:mm:ss.ssZ" seconds-from-midnight) *> Displays "12:34:56.00Z"
It's been interesting working in C and it's made me realise how much C++ gives you – I miss programs that fail with uncaught exceptions rather than cryptic segfaults.
Fortran .... just multiply the adjacency matrix by itself N times; non-zero entries in A^n indicate there's a n-step path to get from i to j.
EDIT - moved the source code to ideone.com: here
switching back and forth between "undirected" (as I assumed) and "directed" gives different answers, as discovered multiple times in this thread by other people.
undirected graph
radius: 3 diameter: 5 center points: 16, 20, 21, 24, 29, 30, 33, 35
directed graph
radius: 3 diameter: 6 center points: 35
C++: Partial solution.
Dear god... I quit! This challenge is giving me a headache.
I've managed to brute-force generate (all?) the possibilities with (a few?) false positives... I wrote a simple "matrix" class and then printed the words onto it letter by letter. To solve the problem of vertical/horizontal and forwards/backwards, I just rotate the matrix four times during the possibilities search.
Output is at the bottom of the page.
EDIT: Now it's a bit less crappy.
This is my first entry in this sub so I don't know if JavaScript is laughed at here, but it's what you're getting.
http://jsfiddle.net/pendensproditor/cLqt2/
Since I take it these are pure logic exercises, I skipped the speed-optimization or input-sanitizing or error-checking that I might clutter a real app with.
EDIT: Updated it to handle these test cases.
The trouble with using a dictionary is that it's not representative of natural sentences, which is what's being decoded in the challenge. It just captures the letter frequencies of individual words, losing the frequencies of the words themselves. For example, in natural English, "the" appears far more frequently than the vast majority of other words, but in a dictionary it only appears once. The letters T, H, and E will be underrepresented from a straight dictionary analysis.
So as input, you should use something closer to what you want to decode, which would be a big pile of prose. You could feed it some books from Project Gutenberg — though given the age of the material, this only covers older dialects of English, with (likely) a slightly different histogram — or reddit comments.
In Python (the bonus question),
#!/usr/bin/env python #-- coding: utf-8 --
from mechanize import Browser
br = Browser() br.addheaders = [('User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1')] br.set_handle_robots(False) url = "http://finance.yahoo.com/" br.open(url) br.select_form (name="quote") name = raw_input("Enter company name: ") br['s'] = name response = br.submit() verify = response.read() quot = verify.split('time_rtq_ticker')[-1].split('<span id=')[1].split('</span')[0].split('>')[-1] print quot
Output here,
➜ python finance.py Enter company name: Google 571.50 ➜ python finance.py Enter company name: Apple 584.12 ➜ python finance.py Enter company name: Yahoo 15.48
C
#include <stdio.h> #include <unistd.h>
int main() { unsigned char b[85], i, j, k, p[26] = "8r2e0ddi6t!Z@?>#943hi!715"; while(putchar('\n'), read(0, b, 84)) for(i = j = 0; i < 27; i += 3, putchar(p[j]), j = 0) for(k = 11; k < 16; k++) j = (j << 1) | !(b[i + p[k] - 34] - 32); return 0; }
My C skills are a bit rusty, feel free to point anything that seems wrong or unclear.
Edit: see it work on ideone
If you're completely new to programming, I'd recommend you to search the internet for python tutorials. Python is a simple, but quite powerful programming language that's easier to learn than most other languages.
If you already have some experience in programming, I'd recommend you to take a look at Java, as it can teach you what's called "object-oriented-programming".
If you're just looking for a text editor, I'd recommend Atom.
Personally I like coding in Eclipse, an extremely versatile IDE (integrated development environment - basically a text editor, a compiler and a debugger in one application), which can handle a ton of languages, including Java, Python, C, C++, Go, Kotlin, Scala, ...
My tiling windows manager (bspwm) is implementing a binary search tree to partition the screen. Every window is a leaf. Every container is a node with a left and right set to either another container or a leaf (window). Of course windows have other properties too, like the title, size etc. but those aren't interesting regarding the binary tree. Window movement results in a rotation of that binary tree.
It may be a bit overengineered, but I like it. If I would program a game or something where rooms are of matter, I would always implement a binary tree to describe my room hierarchy, because it for example simplifies problems like pathfinding down to a level where I only have to cross the current room. Which in some cases can be partitioned again.
For actual searching and sorting problems I highly suggest using a fibonacci tree or a fibonacci heap instead. For example the priority_queue of the C++ STL implements one.
Nothing is "un-doable" in C that can be done in any other Turing-complete programming language. You could use libcurl to grab the HTML and libtidy to walk the DOM in search of relevant elements.
Of course, you could just as well forsake the prior work in this area and use raw sockets and string manipulation if you had the time and inclination.
I love making nice looking images for my research using Blender, but sadly, the scientific plugins difficult to use and do a lot of stupid things that are not intuitive to the user.
Instead of using those, I'm working on making a more powerful and simple plugin to allow me to plot and visualize molecular systems, with animation capabilities. There are a few functions I need to tweak before I post it to GitHub, but it'll be there soon. For now, here's a rough sample of the types of systems I can import. All the coding is done with python and Blender's own API.
That Mathematica code of yours is surprisingly well formatted/indented. Most Mathematica programs longer than few lines long I see around are badly formatted.
Probably here the phrase "same algorithm" is right only at a higher level, because that Mathematica code is very far from C++ level and semantics.
Well written Python code is usually no more than about one hundred times slower than C++, but once in a while you reach a ratio of two hundreds, as in your case. Generally in Python there are ways to reduce such gap, reaching 20-30-50 times, but to do it sometimes you have to write Python in a low-level style, that is not very pythonic and not nice looking. Psyco or PyPy help reduce that C++-Python gap by about one order of magnitude.
I am currently trying to translate your nice Mathematica code to Python, but I am not expert in Mathematica and for me it's not a quick translation job, despite your Mathematica code is quite short.
I'd like to see your C++ code, there are several paste sites that accept 400+ lines long pastes, like http://codepad.org/
Maybe your C++ will help my Python translation, or will help me create a significantly shorter version in D language :-) I'd like to write a translation of your two programs that is short enough and fast enough :-)
javascript - Try it online!
// warmup flipfront=(a,n)=>[...a.slice(0,n).reverse(),...a.slice(n)] // global flipfront=n=>[...a.slice(0,n).reverse(),...a.slice(n)] // global, in-place flipfront=n=>{for(i=0;i<n/2;)[a[i],a[n-++i]]=[a[n-i-1],a[i]]}
// challenge pancake==>a.map((,o,$,i=a.length-o)=>flipfront(a.indexOf(Math.max(...a.slice(0,i)))+1)||flipfront(i))
05AB1E with Bonus
For fun
'd¡`sFDL.Rs}U)DO„: +sðýJ
Explanation below
input is already in stack stack = ['3d6'] 'd¡ split input string on 'd' stack = [['3', '6']] ` put all items from list on stack stack = ['3', '6'] s swap top two items stack = ['6', '3'] F for N in range(0, a): stack = ['6'] D duplicate top item stack = ['6', '6'] L push [1..a] stack = ['6', [1, 2, 3, 4, 5, 6]] .R pick random item stack = ['6', 1] s swap top two items stack = [1, '6'] } end for loop body stack = [1, 5, 4, '6'] U get rid of top item stack = [1, 5, 4] )D duplicate stack stack = [[1, 5, 4], [1, 5, 4]] O sum of top item stack = [[1, 5, 4], 10] „: + concatenate ": " stack = [[1, 5, 4], '10: '] s swap top two items stack = ['10: ', [1, 5, 4]] ðý join list by space stack = ['10: ', '1 5 4'] J join everything together stack = ['10: 1 5 4'] top stack item gets printed stack = []
JavaScript:
const dice = () => Math.ceil(Math.random() * 6); const peek = fn => (n, idx) => { fn(n, idx); return n; }; const table = input => input .split('\n') .map(line => line.split(' ')) .map(line => line.map(digit => parseInt(digit))); const beats = input => input .split('\n') .map(line => line.split(' ')) .map((line, idx) => ({note: line[0], start: parseInt(line[1]), duration: parseInt(line[2]) })) .reduce((acc, line) => ({...acc, [line.start]: [...acc[line.start] || [], line] }), {}); const challenge = (beats, table) => [...Array(table.length).keys()] .map(n => dice() + dice()) .map((result, idx) => table[idx][result - 2]) .map(measure => beats[measure]) .map(peek((measure, idx) => measure.map(peek(beat => beat.start = idx)))) .reduce((acc, measure) => acc.concat(measure), []) .map(beat => beat.note + ' ' + beat.start + ' ' + beat.duration) .join('\n');
To call the function, use:
challenge(beats(/** beats content /), table(/* table content */));
Example output:
B4 0 2 D5 0 2 G2 0 1 G4 0 2 G5 0 2 C5 1 0 E5 1 0 D5 1 0 F5 1 0 E5 2 1 G5 2 1 G3 3 1 B2 4 2 D3 4 2 G5 4 1 G3 5 0 F3 5 0 E3 6 2 E5 6 1 G3 6 2 D2 7 1 F#5 7 0 A5 7 0 B2 8 2 D3 8 2 G5 8 1 C3 9 1 E3 9 1 G5 9 0 C6 9 0 C5 10 1 C3 11 1 E3 11 1 G5 11 1 C3 12 2 E3 12 2 G4 12 1 C3 13 1 C5 13 1 E4 13 1 C2 14 1 F5 15 0 D5 15 0
I love when things come together and I can write the logic as functional programming oneliners. An example can be found on JSBin.
> Iterated through each point and did a BFS [Breadth First Search] fill on all untouched x's I found. I used BFS instead of DFS because I wanted to be able to scale to larger problems without stack overflow. >
You could also avoid that by converting the recursion into a while loop and have a stack that you put subproblems on, and on each iteration of the loop pop the top off the stack and check it. That way you avoid any risk of going into stack overflow, and you avoid recursion overhead all together.
And thanks for generating the larger input! I like using gist to upload larger files like that. It works up to about 25 megabytes, and it has a nice command line client, so you can do it directly from the terminal instead of pasting the entire thing in the website. And you can get a link directly to a raw text file.
Building ontop of /u/The_Droide's answer
Instead of Eclipse I'd personally suggest a JetBrains IDE for your language of choice
If you're starting to learn python I'd suggest (without having tried it myself) PyCharm Edu, which has integrated learning tools of some sort for a Python IDE
Other than that I can really suggest their Java and their JavaScript IDE's which are what I use.
What you need is algorithms. Algorithm is the strategy to solve the problem. Once you understand the strategy, you can use any tools to solve it. You're learning how to use your tools, not how to solve the problem.
Imo the best (and hardest) book to learn algorithm is MIT's Introduction to Algorithms. If you're in college then I believe they have algorithm class in your third year.
For this specific problem, the algorithm I used is longest common subsequence (LCS), which belongs to dynamic programming. DP is basically recursion + some tricks to avoid re-calculation of sub-problems. It is one of the hardest technique, but LCS is fairy simple once you understand it.
I'm really new around here, but I've appreciated these algorithm-type challenges. I haven't coded (other than SQL) in a good long time, and I haven't taken a CS class this century (and trust me, my CS AP in Turbo Pascal wasn't exactly a shining beacon), so they're giving me the opportunity to actually learn the CS-y stuff I didn't learn before. It's been fun. I had a blast with the "Chester" problem.
I'm also slowly working my way through CLRS Introduction to Algorithms, but ... it's sort of a bear.
Computing 2, which is called "Introduction to Algorithms." It's a general core subject that goes over many essential data structures and algorithms. Although this isn't normally in the course, it was just for an assingment.
Searching around, I found this stack overflow thread:
https://stackoverflow.com/questions/153724/how-to-round-a-number-to-n-decimal-places-in-java
It mentions the possible complications of your approach, as well as gives some other approaches (see comments on second popular answer). I think the straightforward String.format
might be the best solution, if you don't mind trailing decimals.
[insert time]
function Logic(length) { this.input = [0]; this.length = length; this.printTo = document.getElementById("printTo");
this.count = function count() { for (var i = 0; i <= this.length; i++) //loop through the input num times {
this.printTo.innerHTML += this.input.join("")+"<br>"; //print to screen for each loop that occurs
for (var num in this.input) //cycle through each item and check it's value { if (this.input[num] == 0) { this.input.push(1); //append the appropriate value } else { this.input.push(0); //append the appropriate value } } } } } var deploy = new Logic(6); deploy.count();
This outputs:
0 01 0110 01101001 0110100110010110 01101001100101101001011001101001 0110100110010110100101100110100110010110011010010110100110010110
It can be seen live here: http://jsfiddle.net/fuy6hk8z/
Is innerHTML a hacky way of getting it to the screen/is there a better way to do it?
Thanks for the tips /u/the_dinks. It's hard out here for a noob like me. :)
It looks like it restarts ~~every 9 months (start to start) and last for 3 months~~ right after (+/- a month) the course ends. The first link I posted, you can see the available sessions to the right. Next class starts in ~~June~~ January, maybe?
Edit I can't tell time... at least some of the time. Sessions seem to be back-to-back.
Thanks for the warm welcome!
I had used the JCommander library for an assignment in a class some time ago, so it was an easy go-to solution. Someone on Stack Overflow compiled a list of argument parsing libraries, which is where I found the solution originally.
I don't know its merits over any of the other libraries, but it mostly fit the bill for the problem. It would have been awesome if it would handle positional arguments.. I feel that would have fit the problem definition a little more closely.
I'll try something new next time :P
K&R is a relict, the 2nd edition has been published 26 years ago. C has changed since then, specifically C99 has been out. Also programming practices have significantly evolved. I would recommend C Programming: A Modern Approach 2nd edition by K. N. King instead.
I am sure that it could be done more efficiently -- I also did regex at first, but didn't come out quite as well as you two -- and so I threw it away and went with a different solution:
require 'zlib' i = Zlib::Inflate.inflate(Marshal.load(File.open 'i')) puts File.read('c').split("\n").keep_if {i.slice!(0).to_i < 1}
Just went through the large list and encoded a 1 or 0 for whether to keep or not, then compressed the binary string with zlib (not sure what the better way is to compress that in Ruby, though I'm sure there is one). The script above is to load that string back in, inflate, and filter. Even super-sloppy like I did it, it's 1616 bytes all together with the zlibbed file.
Files for testing: https://www.dropbox.com/s/87mafzfsrcqfpq2/real_fake_words.zip
Heres a demonstration:
http://codepad.org/o9UGpWXI and https://www.theraheemfamily.co.uk/~ali/c/optimization/2015/10/27/simple-c-tricks.html
counting up shows this:
What happens is compare strlen to -28(%rbp) this is i then jump to .L3 (the beginging of the for loop).
> movl -28(%rbp), %ebx
> movq -24(%rbp), %rax
> movq %rax, %rdi
> call strlen
> cmpq %rax, %rbx
> jb .L3
Counting down to zero from strlen.
> cmpl $0, -28(%rbp)
> jne .L5
Compaire -28(%rbp) i to 0 jump if not equal to .L5 (beginging of forloop counting down).
So 5 instructions + a function call v 2 instructions
Pre and post incrememnt did not make a difference but may do depending on your compiler and code.
Obfuscated C version. It will only look at the first three lines of input, has a hard-coded line length of 333 numbers (1001 characters including the \n and the \0), and will fail HARD if there's any invalid data.
See it work on ideone.
#include <stdio.h> char a[3][1001]; int main(int ) { for (=0; <3; ++) fgets(a[],1001,stdin); for (=0; a[0][_]>13; _+=3) putchar("492068581763"[(a[1][_]&16|a[1][_+2]&8|a[2][_]&4|a[1][_+1]&2|a[0][_+1]&1)%13]); return 0; }
I've been using Haskell for around a month (my first commit was the 15th of June.) I am finding understanding the language to be challenging - I haven't even reached moands yet. I come from an imperative background, had never met pattern matching before, let alone map
, maps
and fold
- It felt like I was learning to program again.
Also, there seems to be a distinct lack of Haskell exercises. After reading a chapter in LYAH I usually try a few problems from project Euler, or a selection of problems from the 99 haskell problems wiki page.
Done in scratch
This one was tricky due to scratch's lack of regex or being able to test for string contains, so that had to be done manually.
the optional bonus is also in there - although due to flash crashing if I put in a list of 170,000 words, I had to use a shortened list which only contains the 11941 words that actually contain ie or ei
F#
let test = "-1 ↑↑↑ 3"
let rec arrow_note x y a = let result = pown x y if a = 1 then result else arrow_note x result (a - 1)
let vals = test.Split [|' '|] arrow_note (int vals.[0]) (int vals.[2]) vals.[1].Length |> printfn "%d"
Made a JSFiddle for you. I changed your markup slightly so it's compatible with jsfiddle.
Remember kids, when you code something in html js css, upload it to jsfiddle to share it with your friends! (or use codepen.)
Reactive javascript (using bacon.js for a simple message bus). Fun :)
Watch decoder() and lock() chatting back and forth on the jsfiddle.
var msg = function (type, data) { return {type: type, data: data} } function filterBus(bus, type) { return bus.filter(function (m) {return m.type === type}) }
function decoder (bus, a, b, c) { var steps = [ {dir: "cw", dest: 0}, {dir: "cw", dest: 0}, {dir: "cw", dest: a}, {dir: "ccw", dest: a}, {dir: "ccw", dest: b}, {dir: "cw", dest: c} ] var step = steps.shift();
var positions = filterBus(bus, "position") positions.onValue( function (m) { if (m.data === step.dest) { if (steps.length == 0) bus.end() else { step = steps.shift() } } bus.push(msg("spin", step.dir)) }) }
function lock(bus, n) { var position = 0 function spinCCW() { position -= 1 if (position < 0) position = n - 1 } function spinCW() { position = (position + 1) % n }
var requests = filterBus(bus, "spin") requests.onValue ( function (m) { if (m.data === "cw") spinCW() else if (m.data === "ccw") spinCCW() bus.push(msg("position", position)) }) }
function clickCounter (bus, callback) { filterBus(bus, "spin") .reduce(0, function (a, b) {return a + 1}) .onValue( function (final) { callback(final) }) }
function init(n, a, b, c) { var bus = new Bacon.Bus()
decoder(bus, a, b, c) lock(bus, n) clickCounter(bus, function(x) { console.log(x) })
bus.push(msg("position", null)) } init(5, 1, 2, 3)
JavaScript
Okay after a slow start because of rules confusion I've got a live animated link! CodePen Feedback always welcome. I know I should have used canvas, maybe next time...
No problem!
Here's codecademy's intro to bitwise operators:
http://www.codecademy.com/courses/python-intermediate-en-KE1UJ/0/1
I will say that it fails in explaining why or when we should use them.
AutoHotkey - I didn't code the Function, but I saw others using built in Permutation functions.. meh.
#import NextLex.ahk ; https://autohotkey.com/boards/viewtopic.php?t=258
Chalinput := [1234, 1243, 234765, 19000]
For e, v in ChalInput r .= NextLex(v) "`n"
MsgBox % Clipboard := r
Output:
1243 1324 235467 90001
This is a nice short solution. I didn't knew about collections.Counter() before.
I hope I'm not to late, this is my Python 2.7 solution:
import urllib2
targeturl = "https://www.gutenberg.org/cache/epub/47498/pg47498.txt" book = urllib2.urlopen(targeturl).read() words = book.split()
#Iterates through all words in the book, if the word is already in there its count is
#increased. If not it counts iterations, should this exceed the dictionaries size,
#it adds the word to the dict.
count = 0
wordcount = {}
for word in words:
for key in wordcount:
if(key==word):
wordcount[key] += 1
count = 0
else:
count += 1
if(count>=len(wordcount)):
w = {word:1}
wordcount.update(w)
#Sorts the dict. so the words with the biggest count are displayed last/ #guaranteed to be displayed. print sorted(wordcount.iteritems(), key=lambda(k,v):(v,k))
I'd like to have some feedback. Also I encounter a problem if I use
if(key==string.lower(word)) ... w = {string.lower(word):1}
it saves the html tags in the word dict. instead of the "bookwords".
Clojure, bonus version:
;; list of function words taken from ;; http://myweb.tiscali.co.uk/wordscape/museum/funcword.html ;; I've omitted most of them, see link for full version
(def fwords (set (clojure.string/split "a about ..." #"\W+")))
(def text (clojure.string/lower-case (slurp "https://www.gutenberg.org/cache/epub/47498/pg47498.txt")))
(def content (re-seq #"(?s)start.***(.?)*** end.*" text))
(def tokenized (clojure.string/split (second (first content)) #"\W+"))
(def scrubbed (remove fwords tokenized))
(def words (sort-by val (frequencies scrubbed)))
The results:
(doall (map println (drop 2539 words)))
[bird 16] [squirrel 16] [upon 16] [small 17] [ground 17] [wolf 24] [little 25] [nature 27] [life 29] [birds 42]
The function words are there so we don't end up with a thousand "the" as the top result. Content extraction refers to the bonus challenge. Nasty looking regex, I should google how to write literals in Java regexp. Splitting the words on \W removes some valid words ("one-piece"), but also removes punctuation and contracted forms. Hurray for set filtering. And the built-in frequencies function - I've written that one so many times over the years that I can't help but to wonder why it isn't in more stdlibs. The result is shocking - a bird magazine can't seem to stop talking about things avian in nature :)
Yes, I'm almost certain it can be done with Church and some elbow grease, but passing the relevant data as parameters instead of real input always feels like cheating a bit. Still, it's too damned fun, so I'm pretty sure I'll be posting a non-alphanumeric solution sometime later today. I'm thrilled you enjoyed the interpreter, and thanks for the motivation!
It pains me deeply and emotionally that you define the function's return type, name, and opening bracket all on separate lines.
I use gotos all the time to clean up and exit gracefully instead of just returning an EXIT_FAILURE because abruptly exiting doesn't properly free memory.
Chapter 7 of the Linux kernel coding style guide touches on the use of gotos in C code:
> The rationale for using gotos is: > > - unconditional statements are easier to understand and follow > - nesting is reduced > - errors by not updating individual exit points when making modifications are prevented > - saves the compiler work to optimize redundant code away
Might look a little antiquated, but they're still super useful.
Javascript
function typoglycemia(s){ var words = s.split(/[^a-zA-Z]+/); var punctuation = s.split(/[a-zA-Z]+/); punctuation.shift(); words.pop(); var punctuationIndex = 0; var string = ""; for(var i = 0; i < words.length; ++i){ if(words[i].length <= 2){ string += words[i] + punctuation[punctuationIndex]; ++punctuationIndex; continue; } var chars = words[i].split(""); var newWord = []; newWord[0] = chars[0]; newWord[chars.length-1] = chars[chars.length-1]; var possibleChars = []; for(var p = 1; p < chars.length-1; ++p){ possibleChars.push(chars[p]); newWord[p] = -1; } for(var p = 1; p < newWord.length-1; ++p){ newWord[p] = possibleChars.splice(Math.floor(Math.random()*possibleChars.length), 1)[0]; } string += newWord.join("") + punctuation[punctuationIndex]; ++punctuationIndex; } return string; }
var text = "According to a research team at Cambridge University, it doesn't matter in what order the letters in a word are, the only important thing is that the first and last letter be in the right place. The rest can be a total mess and you can still read it without a problem. This is because the human mind does not read every letter by itself, but the word as a whole. Such a condition is appropriately called Typoglycemia."; console.log(typoglycemia(text));
Correctly handles punctuation. This ended up being a lot more messy than anticipated. Also, apparently regexpal and node have subtly different interpretations of matching at the start and end the text.
More CHR in SWI-Prolog (and, as usual, I'm late to the party). It's packaged as a PrologScript.
#!/usr/bin/env swipl
:- use_module(library(chr)).
:- initialization main.
main :- prompt(_, ''), read_line_to_term(NumLines), read_n_lines_to_terms(NumLines, Positions), maplist(position, Positions), closest_positions(Pair), format('(~w) (~w)~n', Pair), halt.
%% LOGIC
points_distance((X1,Y1), (X2,Y2), D) :- D is sqrt((X2 - X1)^2 + (Y2 - Y1)^2).
%% CONSTRAINTS
:- chr_constraint position/1, distance/2, closest_positions/1.
distance @ position(P1), position(P2) ==> P1 @< P2 | points_distance(P1, P2, D), distance([P1,P2], D).
minimum_distance @ distance(,A) \ distance(,B) <=> A < B | true.
clean_up_positions @ closest_positions() \ position() <=> true.
return @ closest_positions(C), distance(P,_) <=> C = P.
%% IO
read_line_to_term(T) :- read_line_to_codes(current_input, Cs), read_term_from_atom(Cs, T, []).
read_n_lines_to_terms(N, Points) :- length(Points, N), maplist(read_line_to_term, Points).
Usage
$ cat 232_input1.txt | ./232.pl (5.305665745194435,5.6162850431000875) (5.333978668303457,5.698128530439982)
clpfd is an acronym for Constraint Logic Programming over Finite Domains, which is a special case of constraint logic programming.
Rather than using a std::stringstream to do int-string conversions, you can use the functions std::to_string and std::stoull, etc., from <string>. To reverse a string, you can also use the std::reverse function from <algorithm>. That being said, you have a faster option: use division/modulo by 10 to extract the rightmost digit one at a time. This way, there's no need for int-string conversions at all.
If you want an easily-installed arbitrary-precision integer, as well as large fixed-precision integers and floats, you can get the Boost library. It's a big library, look under boost::multiprecision. It also includes various other utilities you might find useful sometime, and it's (almost) all in templated .hpp files for easy inclusion in your code. For example, boost::lexical_cast<target_type> is a faster catch-all function for integer-string or even integer-char array conversions, and vice-versa.
ANSI C - deals with case and punctuation, rewrites string in place :
int ispalindrome( char *sentence ) { if( sentence && *sentence ) { char *dst = sentence ; char *src = dst ;
/* in place overwrite copy of just the alpha chars as lowercase. */ while( *src ) { if( isalpha( *src ) ) *dst++ = tolower( *src ) ; ++src ; }
/* look for symmetry / src = sentence ; --dst ; while( src < dst ) { if( *src != *dst ) return 0 ; ++src ; --dst ; } } / return TRUE for ** symmetric strings ** NULL ** "" */ return 1 ; }
Program in C with the bonus (no super bonus unfortunately) http://codepad.org/Hskwpohy
stan:easy cooper$ ./morse ".... . .-.. .-.. --- / -.. .- .. .-.. -.-- / .--. .-. --- --. .-. .- -- -- . .-. / --. --- --- -.. / .-.. ..- -.-. -.- / --- -. / - .... . / -.-. .... .- .-.. .-.. . -. --. . ... / - --- -.. .- -.--"
HELLO DAILY PROGRAMMER GOOD LUCK ON THE CHALLENGES TODAY
stan:easy cooper$ ./morse -e "thanks for the challenge"
- .... .- -. -.- ... / ..-. --- .-. / - .... . / -.-. .... .- .-.. .-.. . -. --. .
stan:easy cooper$ ./morse "- .... .- -. -.- ... / ..-. --- .-. / - .... . / -.-. .... .- .-.. .-.. . -. --. ."
THANKS FOR THE CHALLENGE
C++:
updated: http://codepad.org/RZCVI6ZH
Runs from the command line and generates x passwords of optional y length. The default password length is 8 characters.
For example:
passgen 16 - generates 16 passwords of 8 characters.
passgen 16 25 - generates 16 passwords of 25 characters.
Sample output:
I generally do that [ run the files straight through the compiler ] on one off things [ say, daily programmer solutions ] and most one-off things are single file only, but some have been more.
If I am doing something that has more than a handful files or has complex requirements [ generated code, multiple binaries, shared code split out into a library, etc ], I'll hook it into a build system of some sort [ I generally prefer SCons, but that's me ].
Simple recursive solution, returns a sequence, but can call .join
method on the function as required.
sub fold(UInt $n = 0) { return (1,) unless $n; flat .cache, 1, .reverse.map(* +^ 1) with samewith($n - 1) }
To get the same output as in description, with line breaks for readability
fold(8).batch(78)».join».say Try it online!
EDIT: Non-recursive version, essentially a translation of /u/TotalPerspective's one-liner
sub folds(UInt $n = 0) { my $s = 1; $s ~= 1 ~ $s.flip.trans('10' => '01') for ^$n; return $s; }
Returns a string, and obviously has better performance characteristics than my recursive solution.
C#
var input = new List<string>() { "4", "/bin/thing:/bin/thing-3", "/bin/thing-3:/bin/thing-3.2", "/bin/thing/include:/usr/include", "/bin/thing-3.2/include/SDL:/usr/local/include/SDL", "/bin/thing/include/SDL/stan" };
int linksCount = int.Parse(input[0]); var links = new Dictionary<string, string>();
for(int i = 0; i < linksCount; i++) { int currentLink = i + 1; var split = input[currentLink].Split(':'); links.Add(split[0], split[1]); }
Func<string, string> resolve = (trash) => "trash"; resolve = (directory) => { var folders = directory.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
var result = ""; foreach(var folder in folders) { result += "/" + folder; if(links.ContainsKey(result)) { result = links[result]; result = resolve(result); } }
return result; };
Console.WriteLine(resolve(input.Last()));
Tested with LinqPad.
Instead of using the numerical values of characters, you can use the character constant values. E.g.,
while(strlen(tail)<c-48)
could be
while(strlen(tail) < c-'0')
This is useful because it '0' is a lot more meaningful in this case than 48. It can also be used like this:
if (c >= 'a' && c <= 'z')
This is a little unrelated but, the difference between uppercase and lower case is 32 or 0x20 where lower case letters have 0x20 set and upper case do not. Example
Actually not that difficult... Reversing would be rather difficult with the character used for 'B' as that's in the supplemental character area and can't be represented by a java/clojure char.
Edit: realized I didn't reverse the individual strings....
E2: apparently I annoyed CompileBot by editing too quick or something. Here's the ideone run: http://ideone.com/feG5BW
+/u/CompileBot clojure
(ns challenge0156-hard.core (:require [clojure.java.io :refer [reader]]))
(defn upside-down-char [c] (case c \b \q \q \b \d \p \p \d \n \u \u \n \a \u0250 \c \u0254 \e \u01dd \f \u025f \g \u0253 \h \u0265 \i \u0131 \j \u027e \k \u029e \m \u026f \r \u0279 \t \u0287 \v \u028c \w \u028d \y \u028e \M \W \W \M \A \u2200 \B (apply str (Character/toChars 0x10412)) \C \u0186 \D \u15e1 \E \u018e \F \u2132 \G \u2141 \J \u017f \K \u22ca \L \u2142 \P \u0500 \Q \u038c \R \u1d1a \T \u22a5 \U \u2229 \V \u039b \Y \u2144 \6 \9 \9 \6 \7 \u3125 \5 \u078e \4 \u3123 \3 \u218b \2 \u218a \1 \u21c2 . \u02d9 ! \u00a1 \? \u00bf c))
(defn upside-down-line [line] (apply str (map upside-down-char (reverse line))))
(defn upside-down-text [] (doseq [line (reverse (line-seq (reader in)))] (println (upside-down-line line))))
(upside-down-text)
Input:
This is some text that I am writing! Soon it will be just 4 lines of upside down text. How did they do it? We will all know soon.
C: I know could have just checked if the score wasn't 1, 2, 4, or 5, but that wouldn't be as fun. I programmed this in Ideone because I only have access to a Chromebook right now.
#include <stdio.h> #define POSSIBLE_POINTS_LENGTH 4
int possiblePoints[POSSIBLE_POINTS_LENGTH] = { 3, 6, 7, 8 };
int checkIfValid(int score) { int i, j; if (score < 0) return 0; for (i = 0; i < POSSIBLE_POINTS_LENGTH; ++i) { if (score % possiblePoints[i] == 0) { return 1; } else { for (j = 0; j < POSSIBLE_POINTS_LENGTH; ++j) { if (checkIfValid(score - possiblePoints[j])) { return 1; } } } } return 0; }
int main(void) { int score; scanf("%d", &score); if (checkIfValid(score)) { printf("Valid Score"); } else { printf("Invalid Score"); } return 0; }
It doesn't exactly conform to the specs outlined in the challenge, but I wrote it mostly just to see if I could. That said, here's my Whitespace program to print the *n*th Sierpinski carpet and the pseudo-assembly used to generate it.
I used the standard power series to obtain the exponential. As it's all the problem calls for, my multiplication method only takes square matrices into account. I also didn't strictly approach the limit, instead just iterating the series for twice the size of the matrix. Outside of a few aesthetic qualms, though, I'm pretty happy with how this turned out.
I did some research. Apparently you can do:
data Note = ... deriving (Enum, Bounded)
Then maxBound
will return the last constructor.
Javascript, ES2015
A functional approach
const getBestBuy = (arr) => { return arr .reduce((tuples, curr, i, all) => { const sell = all.slice(Math.min(i + 2 - all.length, -1)) .sort((a, b) => b - a) .slice(0, 1)[0] || 0 return tuples.concat([[curr, sell, sell - curr]]) }, []) .sort((a, b) => b[2] - a[2]) .map(item => [item[0], item[1]])[0] }
const res = getBestBuy(getInput()) console.log(res)
And the input function:
function getInput() { return '9.20 8.03 10.02 8.08 8.14 8.10 8.31 8.28 8.35 8.34 8.39 8.45 8.38 8.38 8.32 8.36 8.28 8.28 8.38 8.48 8.49 8.54 8.73 8.72 8.76 8.74 8.87 8.82 8.81 8.82 8.85 8.85 8.86 8.63 8.70 8.68 8.72 8.77 8.69 8.65 8.70 8.98 8.98 8.87 8.71 9.17 9.34 9.28 8.98 9.02 9.16 9.15 9.07 9.14 9.13 9.10 9.16 9.06 9.10 9.15 9.11 8.72 8.86 8.83 8.70 8.69 8.73 8.73 8.67 8.70 8.69 8.81 8.82 8.83 8.91 8.80 8.97 8.86 8.81 8.87 8.82 8.78 8.82 8.77 8.54 8.32 8.33 8.32 8.51 8.53 8.52 8.41 8.55 8.31 8.38 8.34 8.34 8.19 8.17 8.16'.split(' ') }
JSBin to test it: http://jsbin.com/wimasogupu/1/edit?js,console
JavaScript, feedback welcome! :)
Threw together a basic demo on jsbin.
Edits:
String.prototype.replace
(inspired by /u/oprimo's excellent answer) instead of re.exec
, which was really ugly.import { isEqual, shuffle } from 'lodash';
function scramble(fullWord, initChar, innerChars, endChar) { const toScramble = innerChars.split(''); let scrambled = [...toScramble];
if (scrambled.length === 2) { // if there's only two letters, we can just reverse the array and consider // it scrambled. This also lets us escape infinitely scrambling in words // like 'keep' or 'foot' scrambled.reverse(); } else { // otherwise, we need to guarantee that the letters are actually scrambled. // English doesn't have any five letter words where the middle letters are // all the same, so we can get away with just checking if the shuffled // letters are equal to the original letters. while (isEqual(scrambled, toScramble)) { scrambled = shuffle(scrambled); } }
return initChar + scrambled.join('') + endChar; }
function typoglycemify(text) { const wordPattern = /(\w)(\w{2,})(\w)/g; const newText = text.replace(wordPattern, scramble);
return newText; }
If you're using node you can read the data from input (see here for an example). Otherwise if you want to practice hooking up to the DOM you can set up a simple html page with a textbox and read it from there.
Or if you want to skip the parsing section, you could just create a JSON object instead of a string.
For simply messing around with regex or testing that a regex actually does what you expect, I highly recommend Regex101. It also has a handy quick reference for nearly every feature regex has to offer, plus the ability to easily switch between a few common regex engines that all work slightly differently.
Note: I typed the link from memory, if it doesn't work a simple Google search should suffice.
> Command-line args don't seem to be working for me at the moment
==
in C does not do string comparison, because it compares only values, and in C a string is just a pointer and a convention for what the data it points to should look like. So unless the pointers to them are exactly the same, even two apparently identical strings will never compare equal using ==
.
Have a look at strcmp. :)
JavaScript. Trying to do it with as many built in functions as possible, rather than loops, similar to -P-e-t-e-r-'s implementation it uses sets, but checks the size of the set (effectively a uniqueness check), and then again to ensure there are only n
items:
// parse and arrange into rows, columns and array of all values const rows = raw.split("\n").map(x => x.split(" ")); const columns = rows[0].map((x,i) => rows.map(x => x[i])) const all = rows.reduce((all, row) => all.concat(row),[]);
// calculate n const n = rows.length;
// create a set of all rows & columns const sets = rows.map(x => new Set(x)).concat(columns.map(x => new Set(x)));
// check if it's latin let isLatin = sets.reduce((isLatin, set) => isLatin && set.size === n, true) && new Set(all).size === n;
Javascript (without regex).
console.log(compressSentence("I heard the pastor sing live verses easily.")); console.log(compressSentence("Deep episodes of Deep Space Nine came on the television only after the news.")); console.log(compressSentence("Digital alarm clocks scare area children."));
function compressSentence(sentence) { let words = sentence.split(" "); let finalSentence = words.shift();
words.reduce((lastWord, word) => { for (let i = Math.min(lastWord.length, word.length); i > 0; i--) { if( lastWord.slice(lastWord.length - i, lastWord.length) === word.slice(0, i)) { finalSentence += word.slice(i, word.length) return word; } } finalSentence += " " + word; return word; }, finalSentence);
return finalSentence; }
Output:
I heard the pastor sing liverses easily. Deepisodes of Deep Space Nine came on the televisionly after the news. Digitalarm clockscarea children.
JavaScript
fiddle: http://jsfiddle.net/path411/7XqZZ/
function EncodeRunLength(input) { var input = input.split(''); var length = 0; var last = input[0]; var encoding = []; for(var i=0, iL =input.length; i<iL; i++) { var thischar = input[i]; if(thischar == last) { length++; } else { encoding.push([length, last]); length = 1; last = thischar; } } encoding.push([length, last]); return encoding; }
function DecodeRunLength(input) { var decoded = input.map(function(ele) { return multiplyletter(ele[0],ele[1]); });
function multiplyletter(iterations, letter) { var output = ''; for(var i=0; i<iterations; i++) { output += letter; } return output; } return decoded.join(''); }
Great work!
Seems like the output for Challenge #2 is a bit wide for a reddit comment, though. If you want to show off your result in a more readable way, feel free to use a service like gist or hastebin to show it off. I've made a note of it in the challenge description. Or just put it in that nice GitHub repo you used for the problem :)
JavaScript
This isn't really a true response to the challenge, but I made a quick .pgm viewer in a codepen here. I was going to do the full challenge, but I ran out of free time.
~ is the regexp match operator
[] denotes a range of characters, []+ means 1 or more occurences of that range
^ and $ are the start and end of a string (meaning that the whole input string, in this case w.word, must match the regexp
so, for example:
^[bnik]+$ means "a string of length 1 or more, composed only by the characters: b,n,i,k (in any order)"
in this example bikini is the longest word matching that regexp (words come from enable1.txt), the word "bikinis" would not match because 's' is not in the range
through2
is just another stream object. Same with process.stdin
and process.stdout
. They're all functions that will produce/consume/process input/output or some combination thereof.
This stream-handbook, is a good resource in case you were interested.
As for process
in nodejs being like the window
object for the browser? I'm not sure. Though the process
object is globally available, I believe the top-level object is global
. More on globals in nodejs.
I'm not sure if there's some master list of events somewhere, but a lot of the events for the core modules are in the docs. Take a look at the table of contents for Streams. For the readable class, there's 5 events documented there. You can emit your own events and listen for them with EventEmitter as well.
Also check out process if you want to pull in the market and currency as arguements instead of hard-coding them in.
Same here. I work more with express and 3rd party packages than some of the lower level node APIs. But you're right, the docs and online tutorials for this type of stuff seem lacking. There's enough tutorials on how to setup an express app for your new SPA to last you weeks, but working with core modules is kind of just left to the docs. The book I recommended earlier helped me understand Node's event loop, and provides a lot of examples that might be beneficial for you. One warning though is that the book also attempts to introduce you to es6 at the same time, and doesn't use semicolons (which just felt really dirty).
The way you know that you have all of the data is to add an event listener for 'end' or even 'close'. The docs don't really say which one is preferred, but the difference between the end and the close event is that the connection has completely closed. In any case, they appear to both only emit once and only after you have all the data.
But no, you shouldn't think of doing the parsing and other logic 'after' res.end(). Don't think of your code executing from top to bottom because that isn't what is happening most of the time in Node. The event listener, for example, is a callback function. Think of it like you are registering a function with Node (on its event loop) that will only be invoked when the response emits the 'end' event. In the example, the on method is how you add/register the event listener/callback function. The callback will only be invoked on the particular event. And here it makes sense to put your logic in that callback.
The condition in the while loop is a method to take input repetitively until std::cin gets invalid input like a char instead of an int or an EOF flag. Also since the input format is int:char:int the character in the middle needs to be removed from the input stream, there are multiple ways to do this but I chose to store it in a char variable; 'trash'.
As for the big ass std::cout chain. The first statement is printing what hour it is from one to twelve, therefore mod 12 is used. But since mod 12 only has a output range of 0-11, you have to add 1 after the mod operation to make the range 1-12. Problem is that then everything gets shifted by 1, 'twelve' becomes 'one', 'one' becomes 'two'. So to shift it back 11 is added before doing the mod operation: ((in + 11) % 12) + 1.
Also if you're trying to learn C++ I would recommend reading the book C++ Primer, It's an extremely good and thorough book. I think you can find the pdf file for free if you search on google.
Thinking about they way you implemented your for loop the last element in your "garland_list" will always be the biggest.
garland_list = ["a", "al", "alf", "alfa"] // alfalfa
this can be changed:
if word[:x] == word[-x:]: garland_list.append(word[:x])
to this:
if word[:x] == word[-x:]: longest_substring = word[:x]
the refactored code ends up looking like this:
<SPOILER>
def main(word): longest_substring = "" for x in range(1,len(word)): if word[:x] == word[-x:]: longest_substring = word[:x] return len(longest_substring) </SPOILER>
tests
print(main("programmer")) print(main("tart")) print(main("onion")) print(main("alfalfa"))
edit:
In the book Clean Code by Robert C. Martin he says don't put the variable's type in the variable's name. I can't find the exact quote, but here is an excerpt from an article with the same idea.
>Be kind to those will maintain your code and never use the variable’s type in the variable’s name. If accountList is a list then don’t use the word list in the variables name. Confusion may be caused as its possible that the variable type changes from a list to an object of a different type.
If were still using a list I'd change "arland_list" to "garlands" or "substrings." :^) But in the end it is all up to preference!
"The C++ Programming Language" by Bjarne Stroustrup is one of, if not the greatest books to learn the language. As the developer of C++, Stroustrup knows exactly what he's talking about.
The books is mainly aimed at people who already know a programming language and gives great hints for developers moving from Java and C.
I'm reaching to my favorite tool, the z3 satisfiability solver. I didn't enforce connectivity; seems real-world crosswords are already unique without it.
Code here. It took 220 seconds to solve the first challenge example, and OutOfMemorys on the second one. I'm pretty disappointed by this performance because usually SAT solvers can solve human-solvable puzzles quickly.
Now gets the bonus as well. See the code in action!
--process as a list of two-element lists graph = {} results = {} firstline = true matrix = {}
--read the input file and create the necessary structure for line in io.lines("dp266input.txt") do if firstline then _, _, total = string.find(line, "(%d+)") total = tonumber(total) for i = 1, total do matrix[i] = {} for k = 1, total do matrix[i][k] = 0 end end firstline = false else local _, _, x, y = string.find(line, "(%d+)%s(%d+)") x = tonumber(x) y = tonumber(y) table.insert(graph, {x, y}) matrix[x][y] = 1 matrix[y][x] = 1 end end
--fill the results table for i = 1, total do results[i] = 0 end
--count items for _, v in ipairs(graph) do results[v[1]] = results[v[1]] + 1 results[v[2]] = results[v[2]] + 1 end
--print results for i, v in ipairs(results) do print("Node " .. i .. " has a degree of " .. v) end
--print adjacency matrix for i, v in ipairs(matrix) do local row = "" for _, k in ipairs(matrix[i]) do row = row .. k .. " " end print(row) end
It's the Go programming language. It's great and easy to learn. I understand the confusion because when I said "Go" in my original comment it doesn't look like a proper name. That's why it's often called Golang, like in r/golang.
: upc ( str -- n ) 11 CHAR: 0 pad-head [ digit> ] { } map-as [ <evens> sum 3 * ] [ <odds> sum + ] bi 10 mod [ 0 ] [ 10 swap - ] if-zero ;
Generic C++ solution. Runs pretty much instantaneously, even for /u/Blackshell's input. I have a special case for 0, because it saves iterations for every other possible input.
Implementation: http://ideone.com/ZLRIqk
#include <iostream> #include <utility>
template <typename T> inline std::pair<T, T> fib_step(const std::pair<T, T>& n) { return std::make_pair(n.first + n.second, n.first); }
template <typename T> T find_largest_factor(T target) { auto divisor = T(1); auto fibs = std::make_pair(T(2), T(1)); while (fibs.first < target) { fibs = fib_step(fibs); if (target % fibs.first == 0) divisor = fibs.first; } return target / divisor; }
template <typename T> void print_fibonacciish(T target) { if (target == T(0)) { // special case std::cout << "0\n"; return; } auto start = find_largest_factor(target); auto fibs = std::make_pair(start, T(0)); std::cout << "0 " << start; while (fibs.first < target) { fibs = fib_step(fibs); std::cout << ' ' << fibs.first; } std::cout << '\n'; }
int main() { // regular inputs print_fibonacciish(21); print_fibonacciish(84);
// challenge inputs print_fibonacciish(0); print_fibonacciish(578); print_fibonacciish(123456789);
// /u/Blackshell's input print_fibonacciish(38695577906193299L);
return 0; }
C++ - a fun solution using std::partial_sum
twice to calculate all the weights without multiplication. Ideone link with examples
#include <algorithm> #include <iostream> #include <string> #include <vector>
struct invalid_char { char c; }; template <typename It> std::vector<int> split_values(It beg, It end) { std::vector<int> ret; std::transform(beg, end, std::back_inserter(ret), [](char c) { if (c >= 'a' && c <= 'z') return c - 'a' + 1; if (c >= 'A' && c <= 'Z') return c - 'A' + 1; throw invalid_char{c}; }); std::partial_sum(ret.begin(), ret.end(), ret.begin()); std::partial_sum(ret.begin(), ret.end(), ret.begin()); return ret; }
int main() { std::string s; while (std::cin >> s) { if (s.length() <= 3) { std::cout << s << " does not balance.\n"; continue; } auto forward = split_values(s.begin(), s.end()); auto back = split_values(s.rbegin(), s.rend());
auto f = forward.begin(), fend = forward.end() - 2; for (auto b = back.rbegin() + 2; f != fend && *f != *b; ++f, ++b);
if (f != fend) { auto len = std::distance(forward.begin(), f) + 1; std::cout << s.substr(0, len) << ' ' << s[len] << ' ' << s.substr(len+1) << " - " << *f << '\n'; } else { std::cout << s << " does not balance.\n"; } } return 0; }
https://repl.it/@DannyOuyang/SG-Progressive-Tax
Was just learning Python 3 and doing an exercise to calculate Singapore's progressive tax...
Anyway, all bonus parts done; only difference is my input file stores values as: rate,marginal income (rate in %, not decimal)
JS
js
function additivePersistence(n) {
let _n = n;
let i = 0;
// While the n-copy isn't 1 digit long...
while (_n >= 10) {
// Convert it into an array of digits.
let a = []
// * Split the n-copy into 2 parts: its rightmost digit and everything else.
let nRight = _n % 10, nRest = (_n - (_n % 10)) / 10
// * Append the rightmost digit onto the array.
a.push(nRight)
// * While the rest of the n-copy is greater than 0...
while(nRest > 0) {
// * * Split the rest of the number into, again, its rightmost digit and everything else.
nRight = nRest % 10
nRest = (nRest - (nRest % 10)) / 10
// * * Append the rightmost digit onto the array.
a.push(nRight)
}
// * Flip the array so that the first digit is in position 0.
a.reverse()
// * Add the digits together and make it the new n-copy.
_n = a.reduce((a, v) => a + v)
// * Step up the counter.
i++;
}
return i;
}
https://repl.it/@fifiinart/2019-01-28-Challenge-374-Easy
JS:
function warmup1(array) {
var a = array.slice()
for (let i = 0; i < a.length; i++) {
if (a[i] === 0) {
a.splice(i, 1)
i--
}
}
return a;
}
const warmup2 = array => array.slice().sort((a, b) => b - a)
const warmup3 = (n, array) => n > array.length
const warmup4 = (n, array) => array.slice().map((v, i, a) => i - n < 0 ? v - 1 : v)
function hh(array) {
let a = array.slice();
while (true) {
a = warmup1(a);
if (a.length === 0) return true;
a = warmup2(a);
let n = a.splice(0, 1);
if (warmup3(n, a)) return false;
a = warmup4(n, a);
}
}
console.log(`Out of the people there, ${hh([5, 3, 0, 2, 6, 2, 0, 7, 2, 5]) ? "nobody was lying." : "at least someone was lying."}`) // Out of the people there, at least someone was lying.
I developed it (here)[https://repl.it/@fifiinart/2019-05-20-Challenge-378-Easy].
R
havelHakimi <- function(data) { result <- F
repeat { # Remove all 0's. data <- data[data != 0] if (length(data) == 0) { result <- T break }
# Sort the counts. data <- sort(data, decreasing = T)
# Remove the first answer. n <- data[1] data <- data[-1]
if (n > length(data)) { result <- F break }
# Subtract 1 from the first n counts. data <- sapply(seq_along(data), function(count) { ifelse(count <= n, data[count] - 1, data[count]) }) }
result }
R
​
fit1 <- function(crateX, crateY, boxX, boxY) {
# Calculate the max boxes that fit in 2 dimensions.
fitx <- floor(crateX / boxX)
fity <- floor(crateY / boxY)
fitx * fity
}
​
fit2 <- function(crateX, crateY, boxX, boxY) {
# Allow rotating all boxes by 90 degrees (boxX x boxY or boxY x boxX).
max(fit1(crateX, crateY, boxX, boxY), fit1(crateX, crateY, boxY, boxX))
}
​
fit3NoRotation <- function(crateX, crateY, crateZ, boxX, boxY, boxZ) {
# Calculate the max boxes that fit in 3 dimensions.
fitx <- floor(crateX / boxX)
fity <- floor(crateY / boxY)
fitz <- floor(crateZ / boxZ)
​
fitx * fity * fitz
}
​
fit3 <- function(crateX, crateY, crateZ, boxX, boxY, boxZ) {
# Allow rotating all boxes by 90 degrees in 3 dimensions.
max(fit3NoRotation(crateX, crateY, crateZ, boxX, boxY, boxZ),
fit3NoRotation(crateX, crateY, crateZ, boxX, boxZ, boxY),
fit3NoRotation(crateX, crateY, crateZ, boxY, boxX, boxZ),
fit3NoRotation(crateX, crateY, crateZ, boxY, boxZ, boxX),
fit3NoRotation(crateX, crateY, crateZ, boxZ, boxX, boxY),
fit3NoRotation(crateX, crateY, crateZ, boxZ, boxY, boxX))
}
My JavaScript submission: http://jsfiddle.net/pendensproditor/L3F9Q/
The browser definitely starts to choke around the 25th sequence.
It seemed natural to store each binary as a boolean and only convert to 1s and 0s when displaying it. But now I'm wondering if a huge string of 1s and 0s would be more performant than a huge array of booleans. But most likely the bottleneck is in rendering, not in calculating.
According to php.net there's a function called easter_date() which makes it really easy to know when Easter is. I looped through the years 2015 to 2025.
PHP:
<?php for ($i = 2015; $i <= 2025; $i++) { echo date("M-d-Y", easter_date($i)) . "<br>"; } ?>
Output:
2015/4/5 2016/3/27 2017/4/16 2018/4/1 2019/4/21 2020/4/12 2021/4/4 2022/4/17 2023/4/9 2024/3/31 2025/4/20
I completed Introduction to Interactive Programming in Python on Coursera and it was a really great experience. CheckIO is now my source of challenges ;)
Thanks for all the input!
For the defines, I had a feeling something was wrong but I wasn't quite sure what was a better replacement. I had completely forgotten about constexpr variables and only thought there were constexpr functions, but I now realize there are both. I'll remember to use those instead of defines when needed.
As for random_shuffle, I did see that there was a C++11 shuffle replacement but I wasn't able to get it working with what I had read (at least not very quickly since I was working fast). The thing I came across said to do this:
auto engine = std::default_random_engine{}; std::shuffle(std::begin(cards_), std::end(cards_), engine);
But that didn't work as intended, so I fell back to random_shuffle for the time being. Thanks for letting me know how to use it properly.
You're also right about the get_words thing. I hadn't thought about not enough words being taken since the input was hard coded to be within a certain range. I really should have noticed that. Also regarding the for each thing, I'm genuinely surprised I didn't use that. I usually use it whenever possible since I like the syntax over the longer version I ended up with. I guess I wasn't paying attention.
I really like the range alternative compared to the switch statement. I didn't think of being able to pass a pair like that, but it does make it cleaner. I think that the last fix is a bit complex though. I think if it was split into multiple lines for readability it would be better for me at least. If there's a performance boost I'd definitely take it, but for a program like this that doesn't really matter much.
And again, thanks for the input. I don't know a ton about C++11 so it's good to get some practice and improvements.