r/dailyprogrammer • • Jul 18 '14

Comment downvotes are disabled

37 Upvotes

The mods and you guys have suggested several times that downvotes should be disabled. Lo and behold it has been done. This is to aid constructive criticism and prevent downvoting because someone used a language you didn't like.

Enjoy :D


r/dailyprogrammer • • Nov 11 '15

[2015-11-11] Challenge #240 [Intermediate] Economic/Social modeling and queries

30 Upvotes

This is a task of reading a small database, and querying it and processing results, or building a model from the data.

You have been tasked with saving Humanity from politicized bickering preventing any honest discourse of economic and social policy.

It is 2040, and ever since the beginning of the 2016 Trump economist beheading regime (yes he is still your ruler), honest economic information became even more suppressive than in the beginning of the millenium. Good luck.

the core model

The cornerstone of any society is the "make food available" (farmer/hunter/gatherer/magician/importer from intergalactic worlds) person.

A society is made up of citizens (P), Slaves, Animals, and Machines. Each (of the 4) category consumes $10000 (constant unit-inflation proof) per unit per year to sustain itself. 1 person is 1 unit of citizen. 1 slave-human is 1 unit of slave and its consumption cost includes security. 1 unit of animals is however many (fractional is ok) animals it takes to cost $10000 in resources to maintain. 1 unit of machine is similar to animals but includes the purchase and operating costs (a $50k tractor would be 1/5th of a unit that can be shared).

sample input:

Input is a list of records (space delimited fields) each record describes one group in society:

Group name, population of that group, production($) from each group unit, PSAM (category), tax factor(1 is max, meaning that all of that group's production is taxable (if there is a tax rate). 0 would mean their production value is not taxable)

 farmer 50 30000 P 1  
 spouse 30 15000 S 0.5  
 police 1 0 P 0  
 hippie 4 -3000 S 0.8  

The above numbers suggest that farmers produce $30k worth of stuff. Their (a farmer's) spouses help them produce another $15k (but the couple consumes $20k together). A policeman doesn't produce anything, but his presence may limit the number and destruction caused by hippies. Thieves destroy value in the sense that it discourages production if work will be stolen, or producers attacked. A hippie is a euphemism for thief, beggars and scamsters, as viewed by the established society. The word hippie is chosen because they may be unfairly persecuted, and simply misunderstood. For every 1 police, 1 hippie is scared away. 1 hippie joins society for every 10 establishment households. Taxation (or alternate socialization) must be introduced to afford police.

Spouses, children and hippies are classified as slaves, for unfortunate convenience. The coding allows the simplification of their production flowing to a household, and to indicate that they do not take spouses of their own.

The other cornerstone of civilization is making children. A farmer's child might produce along the formula: (age - 6)* 1000 for age <= 18. It may be easier to model as total cost of $160k less production benefit of $55k, and so net cost of $105K, or $7k per year.

This simplification of the cost of children being $7k/year for 16 years to farmers is probably the most useful and easiest to model. We can make separate entries for non-farmer-spouses production value, and non-farmer-children may cost $10k/year for 16 years (same as all people and production units).

more complete input

 farmer 50 30000 P 1  
 clothier 5 22000 P 1
 builder 5 22000 P 1
 miscellaneous 5 10000 P 1
 entertainer 5 5000 P 0.5
 hippie 7 -3000 S 0.8   
 farmer-spouse 0 15000 S 0.5  
 spouse 0 8000 S 0.5  
 farmer-child 0 3000 S 0
 child 0 0 S 0
 police 0 0 P 0  

New categories needing explanation: Clothiers and builders production value is what is needed by society for sustainability. More can be added to provide "premium" value. Entertainers as a group indicate part of the sustainable need for entertainment, but the sustainabiliy value contributed by each is deemed low to indicate that they are not high need and depend more on audience than audience depends on them. Miscellaneous covers communication, policy, perhaps basics of transportation, containers for farmer products, special children products...

The tax field represents the percentage of production or destruction that is taxable. A 50% taxability for entertainers reflects the point that much of their production escapes accountability. Spouses similarly provide value that is not taxable. Theives/hippies have a high 80% taxability because their destruction is assumed to be a tax deduction to those that lose value.

The model is meant to adapt to various stages of industrialization. The input above is meant as a platform for exploring sustainability

challenge questions

1 . What is the surplus produced by the above society?

2 . What surplus spending rate (after the $10k to meet their own and other family needs) must exist to allow other professions to exist and survive? (assuming uniform surplus spending rate in all society, other professions exist only if farmers spend sufficiently.) You can save this surplus spending rate as a field for each profession (even if they are all initially equal)

These first 2 problems don't directly help with problem 3 and 4. They are warm up queries (though may be relevant in open problem 5). Something to notice that is being ignored is that way more food is being produced than there are eaters.

3 . With the constraint that every group member can have only 1 spouse, and that a spouse is needed for a child, how many 1 child famillies can the society support? (spouses are conjured from thin air - like mail order or something)

You will probably note here that the clothier/builder populations can only afford a spouse and a child if hippie/thiefs do not directly harm them. You may assume the easier charity from mainly farmers compensates for individual losses, or model (harder) random child mortality equal to one gypsy act per year.

4 . A sustainable population requires 2 children per family. Of the above professions, only farmers can produce enough to self-sustain. What number of farmers is needed to support the rest of society (with a sustainable population)? (this magic number is if 100% of each family surplus were taxed and distributed according to need)

5 . Taxation has been ignored so far. Use whatever taxation rate you would like to see, and measure how many fewer families it sustainably generates. If you have an alternate social policy

tips and cheats

Databases and spreadsheets are allowed. Class or record structures should help too.

An easier challenge than SOLVING for numbers, and one I expect from most solutions, is to create a measuring program. ie. if some numbers are plugged in, a program/function measures the output from those numbers, and you can change plugged in numbers until the input is valid, and creates maximized output.

The challenge is mostly to organize data and code so that you can query and extend it in ways that are asked, and/or could interest you.

If you want to do anything else with this record format, but different inputs, just post your inputs (please put any new columns at the end)

Bonus challenges: (will perhaps form basis for harder challenge next month)

Analyze effects of a productivity innovation.

Compare the effects of a taxation system to support bureaucracy vs. one of basic income.


r/dailyprogrammer • • Jul 25 '12

[7/25/2012] Challenge #81 [easy] (Numerical Calculus I)

4 Upvotes

For a lot of the questions today we are going to be doing some simple numerical calculus. Don't worry, its not too terrifying.

For the easy problem, write a function that can take in a list of y-values that represents a function sampled on some domain. The domain can be specified as a list of x-values or two values for the x-minimum and x-maximum (the x-coordinates of the endpoints)

This function should output another list of values that represents the derivative of that function over the same domain.

Python example:

print derivative(xmin=-1,xmax=1,y=[-1.0,-.5,0,.5,1.0])

outputs:

[1.0,1.0,1.0,1.0,1.0]

Bonus 1) Write the same function but for the indefinite integral.

Bonus 2) This is sort-of an alternate version of the problem... if your language supports first-order functions (that is, functions as data), then write a function that takes a function A as an argument and returns a function A'. When A' is evaluated at x, it computes an approximation of the derivative at x

EDIT: devil's assassin gave a decently good explaination of the problem, I'm stealing it here and modifying it a bit.

for those of you who don't know, the derivative can be defined as the slope of the tangent line at a particular point. I'm assuming he wants a numerical derivative, making this a programming exercise and not a math one. We need to interpolate those values into a derivative. If you have some set of numbers N = {a1,a2,a3,a4,...,an} and some domain set S={b1,b2,...,bn} you can find the slope between two points on this line. Now this is a /bad/ approximation, but it can be made better through limiting the step size.

Basically, here is the formula:

f'(x) = lim h->0(f(x+h) - f(x))/h

the "lim" part, means that this only works when h is REALLY small (pretty much 0, but without being exactly 0 so there is no dividing by 0). So you can modify this:

f'(x) ~= f(x+h)-f(x)/h

Basically, what you do here is use compute the slope between the current point and the next point for each point. Use the slope equation from two points.


r/dailyprogrammer • • Sep 08 '12

[9/08/2012] Challenge #97 [difficult] (Markdown to HTML)

3 Upvotes

Markdown is the text markup system used by reddit in comments and text submissions. Write a script that converts a piece of Markdown into HTML.


r/dailyprogrammer • • Feb 17 '12

[2/17/2012] Challenge #9 [difficult]

4 Upvotes

The U.S government has commissioned you to catch the terrorists!

There is a mathematical pyramid with the following pattern:

1

11

21

1211

111221

312211

you must write a program to calculate up to the 40th line of this pyramid. If you don't, the terrorists win!


r/dailyprogrammer • • Apr 15 '13

[04/15/13] Challenge #122 [Easy] Sum Them Digits

1 Upvotes

(Easy): Sum Them Digits

As a crude form of hashing function, Lars wants to sum the digits of a number. Then he wants to sum the digits of the result, and repeat until he have only one digit left. He learnt that this is called the digital root of a number, but the Wikipedia article is just confusing him.

Can you help him implement this problem in your favourite programming language?

It is possible to treat the number as a string and work with each character at a time. This is pretty slow on big numbers, though, so Lars wants you to at least try solving it with only integer calculations (the modulo operator may prove to be useful!).

Author: TinyLebowski

Formal Inputs & Outputs

Input Description

A positive integer, possibly 0.

Output Description

An integer between 0 and 9, the digital root of the input number.

Sample Inputs & Outputs

Sample Input

31337

Sample Output

8, because 3+1+3+3+7=17 and 1+7=8

Challenge Input

1073741824

Challenge Input Solution

?

Note

None


r/dailyprogrammer • • Oct 20 '12

[10/20/2012] Challenge #104 [hard] (Image color analyzer)

11 Upvotes

Sorry for taking the last challenge down but it seems it was already done. I had searched for "slide puzzle" -- what they're usually called -- but not "15 puzzle."

Anyway, new challenge! Make a program that analyzes the color of an image. What the majority colors are, specifically. Output if they fall into red, blue, green, etc. because saying "1 instance of <obscure color here>" takes of space, especially if that obscure color is a blue or red or green.

Example input:

$ color_analyze image.jpg

Example output:

Pixels that are red: 15
Pixels that are blue: 227 Pixels that are green: 1,745


r/dailyprogrammer • • Feb 14 '12

[2/14/2012] Challenge #6 [intermediate]

7 Upvotes

create a program that can remove all duplicate strings from a .txt. file. for example, "bdbdb" -> "bd"


we are really sorry about this :( .. I just woke up now and am looking at this disaster. We promise to give a bonus question soon ...

for those who still have time, here is the modified question:

remove duplicate substrings.

Ex: aaajtestBlaBlatestBlaBla ---> aaajtestBlaBla

another example:

aaatestBlaBlatestBlaBla aaathisBlaBlathisBlaBla aaathatBlaBlathatBlaBla aaagoodBlaBlagoodBlaBla aaagood1BlaBla123good1BlaBla123

output desired: aaatestBlaBla aaathisBlaBla aaathatBlaBla aaagoodBlaBla aaagood1BlaBla123

I am really sorry for the vagueness. Hopefully will not be repeated again :(


r/dailyprogrammer • • Sep 26 '14

[26/09/2014] Challenge #181 [Hard] Deconstructing Audio

33 Upvotes

Description

You're part of an innovative new company whose primary goal is to improve the music catalogue and its databases for integration with Apple,Linux and Microsoft products. You notice a significant lack of metadata given by users and wonder if there's a way to automate the process instead.

Formal Inputs & Outputs

Given an audio file that contains music (this won't work on speech or anything irregular) you must create a program that can determine the BPM/Tempo of that audio file.

Input description

On input you should pass your file through for analysis.

Output description

The program should output the Beats per minute of a song

For example

120bpm

or

79bpm

Here is a good website to test your results against

Notes/Hints

For the less musically inclined, make sure your music is in 4/4(common time) before analyzing. Analyzing odd time signatured songs might make this significantly harder. This brings us neatly to the bonus challenge...

There are a few ways to go about this challenge from the exceedingly simple; Pulling the data from an already existing database. Or the actual way, using various signal processing techniques to arrive at an accurate result.

Here is a good article on beat detection and implementing the algorithm

http://archive.gamedev.net/archive/reference/programming/features/beatdetection/index.html

You may also want to check out Comb filtering

Bonus

Output the time signature of the song

Finally

We have an IRC channel over at

webchat.freenode.net in #reddit-dailyprogrammer

Stop on by :D

Have a good challenge idea?

Consider submitting it to /r/dailyprogrammer_ideas


r/dailyprogrammer • • Feb 18 '15

[2015-02-18] Challenge #202 [Intermediate] Easter Challenge

34 Upvotes

Description:

Given the year - Write a program to figure out the exact date of Easter for that year.

Input:

A year.

Output:

The date of easter for that year.

Challenge:

Figure out easter for 2015 to 2025.


r/dailyprogrammer • • Mar 30 '12

[3/30/2012] Challenge #33 [difficult]

3 Upvotes

Travelling Salesman problem.

There are N cities numbered from 0..N-1. A salesman is located at city 0. He wishes to visit all cities exactly once and return back to city 0. There are K toll booths. Each toll booth has a certain range of functioning. The parameters for toll k are given as x_k and y_k. If the salesman travels from city i to j, he has to pay 1 dollar toll fee to each toll p having x_p >= i and y_p <= j. Calculate the cheapest way for the salesman to complete his tour.

Input :

The first line contains T the number of test cases. T test cases follow. The first line of each test case contains two space seperated integers N and K. Each of the next K lines contains 2 integers, the ith line containing x_i and y_i (0 <= x_i,y_i < N). A blank line seperates two test cases.

Output :

Output T lines, one for each test case, containing the required answer.

Edit: Also since some people have problems, here are two solutions .. just see it for reference! link1 link2


r/dailyprogrammer • • Apr 10 '12

[4/10/2012] Challenge #38 [difficult]

6 Upvotes

Write a function that tests whether large numbers are prime or not, with extremely high certainty. There are several primality tests that can do this. Fairly simple ones include the Fermat Test and the even better Miller-Rabin test. The Wikipedia articles have pseudocode you can implement.

Use your function and a random number generator to post a 100-digit prime. You can test your result at Wolfram|Alpha.


r/dailyprogrammer • • Jul 25 '12

[7/25/2012] Challenge #81 [difficult] (Matrix Exponential)

4 Upvotes

For a lot of the questions today we are going to be doing some simple numerical calculus. Don't worry, its not too terrifying.

Write a function that can calculate the Matrix Exponential for a 4x4 (or nxn) matrix. This function is extremely valuable for lots of different scientific areas.

There are LOTS of ways to do it!

For testing, here is a matrix.

0.00000  -1.00000   3.00000   0.50000
1.00000   0.00000   0.45000   0.10000
-3.00000  -0.45000   0.00000   0.40000
-0.50000  -0.10000  -0.40000   0.00000

And the resulting matrix exponential (as computed by GNU Octave)

-0.9276446  -0.2437849  -0.2285533   0.1667568
-0.2809791   0.7661246   0.5148905   0.2626626
-0.0150871   0.5946104  -0.7613132  -0.2580951
 0.2455577  -0.0077772  -0.3210194   0.9146516

r/dailyprogrammer • • Sep 13 '17

[2017-09-13] Challenge #331 [Intermediate] Sum of digits of x raised to n

55 Upvotes

Description

For some xn, find the sum of its digits. The solution to this problem is extremely simple. Say, I give you 34. You could calculate 3n and add the digits.

However things might get a bit complex for 5100. It's a 70-digit number. You could come up with a larger data type that could handle the product of that number and then you could add each number... but where's the fun in that?

This is today's challenge. Find the sum of the digits of some xn without directly calculating the number and adding the digits.

Some simple examples with values that you're familiar with:

25 = 32 = 3 + 2 = 5

53 = 125 = 1 + 2 + 5 = 8

27 = 1 + 2 + 8 = 11

Note that I have not summed the digits of 11.

We'll work with powers and bases greater than zero.

Input Description

Base Power

means basepower

2 ^ 1000

means 21000

Output Description

Display the sum of the digits of basepower.

Challenge Input

2 1234

11 4000

50 3000

Challenge Output

1636

18313

9208


If you have any challenges, please share it at /r/dailyprogrammer_ideas!

Edit : If you're unable to come up with an idea, like the one is Project eulers 16, then feel free to solve it using your own data types (if required). Please consider it as the last option.


r/dailyprogrammer • • Mar 13 '13

[03/13/13] Challenge #121 [Intermediate] Bytelandian Exchange 2

15 Upvotes

(Intermediate): Bytelandian Exchange 2

This problem uses the same money-changing device from Monday's Easy challenge.

Bytelandian Currency is made of coins with integers on them. There is a coin for each non-negative integer (including 0). You have access to a peculiar money changing machine. If you insert a N-valued coin, it pays back 3 coins of the value N/2,N/3 and N/4, rounded down. For example, if you insert a 19-valued coin, you get three coins worth 9, 6, and 4. If you insert a 2-valued coin, you get three coins worth 1, 0, and 0.

This machine can potentially be used to make a profit. For instance, a 20-valued coin can be changed into three coins worth 10, 6, and 5, and 10+6+5 = 21. Through a series of exchanges, you're able to turn a 1000-valued coin into a set of coins with a total value of 1370.

Starting with a single N-valued coin, what's the maximum value you could get using this machine? Be able to handle very large N.

Author: Thomas1122

Formal Inputs & Outputs

Input Description

The value N of the coin you start with

Output Description

The maximum total value of coins you can potentially exchange that coin for.

Sample Inputs & Outputs

Sample Input

1000

Sample Output

1370

Challenge Input

10000000000 (aka 1010 aka 10 billion)

Challenge Input Solution

???

Note

Hint: use recursion!

Please direct questions about this challenge to /u/Cosmologicon


r/dailyprogrammer • • Dec 11 '15

[2015-12-09] Challenge #244 [Easy]er - Array language (part 3) - J Forks

42 Upvotes

This challenge does not require doing the previous 2 parts. If you want something harder, the rank conjunction from Wednesday's challenge requires concentration.

Forks

A fork is a function that takes 3 functions that are all "duck defined" to take 2 parameters with 2nd optional or ignorable.

for 3 functions, f(y,x= default): , g(y,x= default): , h(y,x= default): , where the function g is a "genuine" 2 parameter function,

the call Fork(f,g,h) executes the function composition:

 g(f(y,x),h(y,x))  (data1,data2)

1. Produce the string that makes the function call from string input:

  sum divide count

(above input are 3 function names to Fork)

2. Native to your favorite language, create an executable function from above string input

or 3. create a function that takes 3 functions as input, and returns a function.

  Fork(sum, divide ,count)  (array data)

should return the mean of that array. Where divide works similarly to add from Monday's challenge.

4. Extend above functions to work for any odd number of function parameters

for 5 parameters, Fork(a, b, c, d, e) is:

   b(a, Fork(c,d,e))      NB. should expand this if producing strings. 

challenge input

(25 functions)

 a b c d e f g h i j k l m n o p q r s t u v w x y

r/dailyprogrammer • • Oct 04 '15

ANNOUNCEMENT - We're Hiring

135 Upvotes

UPDATE

new moderators have been identified and you'll see them in coming weeks.

We're Hiring

Hiring moderators, that is. Moderating for /r/DailyProgrammer is not a walk in the park. Each challenge written must be as suitable as possible for as many people as possible, not to mention other work aside from writing challenges. We run a close-knit team of mods here, and sometimes we're rushing around on weeknights trying to get the daily challenge out on time! Therefore we think that adding two or three extra members to the team would be helpful for all involved, as you'll get more varied and fleshed-out challenges. Your role as a moderator will include:

  • Being able to write your share of the challenges reliably and somewhat predictably on-time.

  • Having good English writing and communication skills; explaining challenges well is not as easy as it seems.

  • Being a competent computer programmer. Your language of choice is irrelevant; the universal skills are the important part. ( Writing challenges that are challenging and interesting, while still being solvable and enjoyable, to as many people as possible. (To extend on this, a good knowledge of reddit's Markdown is important.)

  • Being able to help users via the moderator mail system, and handle unsuitable user comments responsibly and maturely.

Having the experience of writing challenges could be a great thing to include in a job application; it shows you have the skills to not only solve the challenges, but to formulate them effectively and clearly. If you think you have what it takes, read on!

Application

We're not going to make the application too formal. We want a few things in the application:

  • Past programming evidence. Evidence of past projects, existing solutions to DailyProgrammer and examples of contributions to open-source projects are the sort of stuff we're looking for. We don't want a great big portfolio of your work; something such as a link to a GitHub/GitLab/BitBucket/Codeplex profile would be ideal, so we can see the sort of stuff you've done.

  • Prior challenge submission. We need an example of the sort of challenge that you are capable of writing. Head on over to /r/DailyProgrammer_Ideas and show us what you can do! Include a link to your challenge in your application - remember to read the sidebar in that subreddit to submit your challenge correctly. If you've already submitted a challenge in the past, you can just link to that one instead, rather than writing another one.

  • Availability. We don't ask too much of you - a few of hours of your time per week should be enough! Give us a brief overview of when you'll be available or not.

  • General programming/academic experience. A sentence or two describing the programming languages you enjoy/work with, any relevant qualifications, and anything in the world of programming, tech and CS that interests you. This isn't really necessary, so omit it if you want, but we'll be able to get a better understanding of who you are. If you have a programming-related blog or anything similar, we'd love to check it out!

Submit a comment on this post including the above stuff, we'll have a read through them, and we'll get in touch shortly. We're looking for around two or three members here, so don't feel at all bad if you don't get a response. We'll put you onto the shortlist for next time!

Signed, The /r/DailyProgrammer team


r/dailyprogrammer • • Aug 01 '12

[8/1/2012] Challenge #84 [difficult] (City-Block TSP)

8 Upvotes

Like many people who program, I got started doing this because I wanted to learn how to make video games.

As a result, my first ever 'project' was also my first video game. It involved a simple text adventure I called "The adventure of the barren moor"

In this text adventure, there are N (<=10) 'interest points' on an infinite 2-D grid. The player (as described in the 'easy' challenge) can move one unit at a time on this grid towards one of these interest points. The interest point they are told to move to is chosen at random. They also start at a random interest point. It is important to note that the player cannot move diagonally in any sense, the player must move parallel to one of the axis.

Given a set of interest points specified as 2-D integer coordinates, what is the minimum number of steps a player could take to get to them all and win the game? (order doesn't matter).
What is the maximum number of steps? Assume the player heads optimally towards whichever interest point is randomly chosen until he gets it.

For reference, my solution produces a maximum of 1963 steps and a minimum of 617 steps on this input:

62 -67
4 -71
-86 71
-25 -53
-23 70
46 -34
-92 -62
-15 89
100 42
-4 43

EDIT: To clarify this a bit, what I mean is that you want to find the 'best possible game' and 'worst possible game'. So this min/max is over all possible starting locations. Also, you do not have to get back to the starting point.


r/dailyprogrammer • • Sep 26 '16

[2016-09-26] Challenge #285 [Easy] Cross Platform/Language Data Encoding part 1

48 Upvotes

We will make a binary byte oriented encoding of data that is self describing and extensible, and aims to solve the following problems:

  • portability between 32 and 64 (and any other) bit systems, and languages, and endian-ness.

  • type system independent of underlying language.

  • Allow heterogeneous arrays (differing types of array elements) where the underlying language has poor support for them.

  • leverage power of homogeneous arrays in a language.

  • support records regardless of underlying language (array of records is homogeneous, even though a record is a heterogeneous list of fields)

  • Allow ragged arrays (a table where each row is a list, but the rows do not have a uniform size (or shape))

  • Provide basic in memory compression. Allow deferred decoding of partial data.

1. base64 encoding (used in later challenges)

To read and write binary data on reddit, we will use base64 encoding, https://www.reddit.com/r/dailyprogrammer/comments/4xy6i1/20160816_challenge_279_easy_uuencoding/

2. Extendible byte base.

Any size integer can be coded into a variable byte array by using the maximum byte value as a marker to add the next byte value to decode the total.

This is useful for coding numbers that you think can be limited to around 255 or close to it, without being "hard constrained" by that limit. "256 possible op codes (or characters) ought to be enough for everyone forever thinking"

unsigned byte input
12
255
256
510
512 44 1024

last input is a list of 3 integers to encode

sample outputs
12
255 0
255 1
255 255 0
255 255 2 44 255 255 255 255 4

every element that is not 255 marks the end of "that integer" in a list. You should also write a decoder that transforms output into input.

3. multibyte and variable byte encodings

Instead of a single byte target encoding, 2,4,8 and variable defined byte sizes are also desirable to cover integers with larger ranges. An account balance might have a 40 bit practical limit, but you might not guarantee it forever. 64 bits might not be enough for Zimbabwe currency balances for example.

For compressing a list of numbers, often it is useful to set the whole list to one "byte size". Other choices include,

  • setting an enum/table of possible byte size codings of 1 2 4 8 sizes, and then encoding, the number of elements, the table/enum size and definition, and then 2 lists (enum key, data items)

  • interleave bytesize, data

The latter will often be longer for long lists, but does not encode the table so is simpler to encode/decode.

Encoding format for table definition:

  1. 4 bytes: first 30 bits - length of list. last 2 bits: key into 1 2 4 8. If first 30 bits are max value, then following 4 bytes are added to count until a non-max value is taken. Similar to challenge #2.

  2. list of byte lengths defined by key in 1. If last 2 bits of 1 are 3 (signifies up to 8 distinct integer sizes), then this list has 8 items. If there only 6 distinct integer size codings, then the last 2 items in this list would be ignored and set to 0. Values over 255 are encoded as in challenge 2.

  3. list of ordered data encodings in boolean form, if there are more than 1. 1 bit for 2, 2 bits for 4, 3 bits for 8.

  4. list of data elements.

challenges
encode list of integers from 0 to 1025 using 8 or 16 bit variable encoding. With the shortest encoding that will contain the number. Just print the sum of all the bytes as result for output brevity.

solution

  1. first 4 bytes are (1025 * 4) + 1 (leading 0 bytes for smaller than "full size" numbers)

  2. 2 byte list: 1 2

  3. 0 for first 256 bits, 1 for remaining bits (total 1032 bits long with padding)

  4. 256 + (769 * 2) bytes long encoding of the numbers.

4. balanced signed numbers

Some numbers are negative. The common computer encoding for signed number ranges is to subtract half the max power of 2 from the value. A signed byte has range -128 to 127, where a 0 value corresponds to -128 (in our encoding).

For numbers outside this range encoded in a single byte, the process is to take the first byte to determine the sign, and then following bytes add or subtract up to 255 per byte until a non 255 value is reached.

5. unbalanced signed numbers

Instead of the midpoint marking 0, a byte can encode a value within any defined range. Another important application is to use "negative" numbers as codes of some sort. These include:

  • An expectation that negative numbers are less frequent and smaller relative to 0

  • coding special values such as null, infinity, undeterminable (0/0)

  • Using codes to hint at extended byte encodings and sign of the number, or even data type

sample 0 index codes (for 16 reserved codes) (new paragraph for multiline explained codes)
Null
Infinity
Negative Infinity
Negative 1 byte
Negative 2 bytes
Negative 4 bytes
Negative 8 bytes
Negative custom byte length (value is encoded into 2 numbers. First is byte length (in 255 terminated bytes, followed by that number of bytes to represent the number)

Positive 1 byte (first number indicates range of 468 to 723). 467 could have been encoded as 255 254 without this special code.

Positive 2 byte
Positive 4 byte
Positive 8 byte
Positive 16 byte
Positive 64 byte
Positive custom byte length (3 to 262 excluding other defined lengths) Positive custom 2 byte length (16 bit unsigned number defines byte length of number, followed by encoded number)

sample inputs
10
123123
-55
Null

sample output
26
9 123123
3 54 (minimum range value is -1)
0

challenge input

192387198237192837192837192387123817239182737 _44 981237123

array of 3 numbers (_44 is -44) to be encoded


r/dailyprogrammer • • Apr 10 '12

[4/10/2012] Challenge #38 [easy]

5 Upvotes

Implement Dijkstra's algorithm in any way you can :)


r/dailyprogrammer • • Aug 09 '12

[8/8/2012] Challenge #86 [intermediate] (Weekday calculations)

9 Upvotes

Today's intermediate challenge comes from user nagasgura

Calculate the day of the week on any date in history

You could use the Doomsday rule to program it. It should take in a day, month, and year as input, and return the day of the week for that date.


r/dailyprogrammer • • May 19 '12

[5/19/2012] Challenge #54 [difficult]

6 Upvotes

For this challenge, make a program that finds the determinant of a square matrix. You do not need to use any exceedingly complex methods, using expansion by cofactors is entirely sufficient (if you have no idea what that is, the always helpful Khan Academy here to help. Wikipedia also has you covered.

What is the determinant of the following matrix?

 -5   0   1  -3   0  -4   2  -2   0   2
 -5  -1  -4   4  -2  -5   0  -4   3  -3
 -4   5   3   3   0   0  -2  -2   2   2
 -4  -1   5  -3  -3  -5  -2  -5   3  -1
  4   5   2  -5   2  -4   1  -1   0  -3
 -2  -4  -3  -1   4  -5  -4   2   1   4
  5   5   2  -5   1  -3  -2  -1  -5   5
  1   4  -2   4   3   2   1   0   3  -2
  3   0  -4  -3   0   1  -3   0   1   2
 -1  -4  -3  -1  -4   1   2  -5   2  -1

Note: the whole purpose of this challenge is to write the code for calculating the determinant yourself. Therefore, you are not allowed to use library functions that are designed to calculate things like this. The matrix should be represented by the native array construct of your language, not any special data type designed to operate on mathematical matrices. That means no NumPy, no using fancy functions in Mathematica or Matlab! You are allowed to use these to test whether or not your function works, but that's it.


r/dailyprogrammer • • Mar 13 '12

[3/13/2012] Challenge #23 [difficult]

6 Upvotes

Sort a given set of strings based on a unique collating sequence for each position in a string. Given N collating sequences, to sort strings of length greater than N, sequence i mod N is used at character position i.

For example, consider the three collating sequences:
collating sequence 0 is: ASCII-order-ignore-case
collating sequence 1 is: reverse-ASCII-order
collating sequence 2 is: a-z 0-9 ASCII-order A-Z

In this example the strings

The Cat in the Hat
the Rain in Spain
The RAIN in Spain
Beavis and Butthead

Note that the last ordering says lower case comes before digits; and digits before everything not upper case; and upper case follows all.

The allowable notations for collating sequences are:

ASCII-order
ASCII-order-ignore-case
reverse-ASCII-order
reverse-ASCII-order-ignore-case
a-z
A-Z
0-9

These can occur in any order without repetition.

Input will be in the form:

N
description of collating sequence 1
..
..
description of collating sequence N
line 1
line 2
..
..
line unknown number

So for the given example, the input would look like:

3
ASCII-order-ignore-case
reverse-ASCII-order
a-z 0-9 ASCII-order A-Z
The Cat in the Hat
the Rain in Spain
The RAIN in Spain
Beavis and Butthead

  • from a programming competition


r/dailyprogrammer • • Feb 15 '12

[2/15/2012] Challenge #7 [difficult]

10 Upvotes

This challenge will focus on creating a bot that can log into Reddit!

Write a program that can log into a working Reddit account.

Since this challenge is vague, bonus points are awarded for a few different things:

  • If the bot can navigate the site and view posts

  • If the bot can make posts

  • If the bot can make statistics from the front page/any subreddit. These statistics include time on front page, number of comments, upvotes, downvotes, etc.

The more functionality in your bot, the better.


r/dailyprogrammer • • Dec 09 '15

[2015-12-09] Challenge #244 [Intermediate] Higher order functions Array language (part 2)

43 Upvotes

Monday's challenge is a prerequisite. Sorry.

J theory

Adverbs and Conjunctions in J (modifiers as a shorter group name) are primarily used to implement higher order functions.

An adverb takes 1 parameter (that may be a function ) and may return a function (for today, assume it can only return a function). Adverb parameter name is u.

A conjunction takes 2 parameters and may (does today) return a function. Conjunction parameter names are u and v.

From Monday, the function parameters in our array language all have 2 parameters x and y.

In J, adverbs appear to the right of their u function parameter, and x ( if not missing) and y appear to the left and right of the group (called verb phase). More adverbs and conjunctions can appear to the right of the verb phrase, and the evaluation order inside a verb phrase is left to right. ie. function returned by first adverb, is an input the to next adverb on its right.

In J, Conjunctions have their u parameter (can be a verb phrase without parentheses) on the left, and their v parameter on the right. If v is not parenthesized, then only one token (function or array or variable) is the v conjunction parameter. More adverbs and conjunctions can be added to the right of the verb phrase.

You can use your language's natural parsing rules instead.

1. an insert adverb

This is actually easy and already implemented as reduce and foldright in most languages. It is / in J

    +/ 1 2 3 4   NB. +/ is the whole verb phrase
10
   1 + 2 + 3 + 4
10

an adverb in general takes one parameter (that may be a verb/function), and may return a function. The insert adverb does take a function as parameter (add in above example), and the result is a monad function (a function that ignores its 2nd x parameter). It may be easier, to model the insert function as the complete chain:

Insert(u, y):

where u is the function parameter, and y is an array where u is applied between items of y. But an ideal model is:

 Insert(u):  NB. find a function to return without needing to look at y parameters.  

The result of Insert ignores any x parameter.

The definition of item in J:
A list (1d array) is a list of "scalar items"
A table (2d array) is a list of "list items"
A brick (3d array) is a list of "table items"

so,

   iota 2 3
0 1 2
3 4 5
  +/ iota 2 3                  NB. or:   (add insert) (iota 2 3)
3 5 7
  0 1 2 + 3 4 5
3 5 7
    +/ iota 10 5              NB. or:   insert(add) iota ([2, 3])

225 235 245 255 265

      iota 3 2 4                NB. result has 3 items
0 1 2 3    
4 5 6 7    

8 9 10 11  
12 13 14 15

16 17 18 19
20 21 22 23

   +/ iota 3 2 4              NB. remember insert applies between items.
24 27 30 33
36 39 42 45


   +/ +/ iota 3 2 4
60 66 72 78

Implement an insert adverb in your favorite language.

J definition of insert (variation from builtin to ignore x parameter) : insert =: 1 : 'u/@:]'

2. a swap adverb

swap is an adverb that reverses the x and y parameters to its function parameter such that y is passed x, and x is passed y. If there is no x, parameter, then the function is passed (y,y)

a perhaps easy model is: the signature swap(u, x, y=x): but a better signature would be swap(u): and return a composition of u and the swapping mechanics needed.

swap is ~ in J. iota is from Monday's challenge.

   2 3 iota~ 1  NB. 1 + iota 2 3
1 2 3
4 5 6
   iota~ 4      NB. 4 + iota 4
4 5 6 7

   iota~/ 2 2 4   NB. insert swap iota between items of 2 2 4
4 6
   iota~/ 2 4
4 5

   iota insert~   2 2 3     NB. swap (insert iota) between items of 3 2 3.  
2 3 4 5    
6 7 8 9    
10 11 12 13

14 15 16 17
18 19 20 21
22 23 24 25

last result is same as if swap is ommitted, because insert has been defined to ignore x parameter, and swap duplicates y as x. swap applies to the function after insert (result of insert)

   swap(add) ([1, 2, 3])   NB. y is copied into x parameter
2 4 6


implement a swap adverb.

3. Compose conjunction.

Composition of functions u and v should be familiar. An easy model is:

compose(u,v,y,x): creating equivalent result to u(v(y, x))

note that the u function ignores its x parameter (x default value will be passed to it)

An ideal signature for compose, is compose(u,v): (In J, compose is @:)

   2 3 iota@:+ 1 2         NB.  compose(iota, add)([2,3],[1,2])
0 1 2 3 4     
5 6 7 8 9     
10 11 12 13 14

4. append itemize, and joincells functions

In Monday's bonus and iota function, the request was to make a recursive function that would then joincells of its recursive calls to make one large array.

if you append 2 lists together, you get 1 larger list. A scalar appended with a list or scalar is also a list.

The itemize function takes an array and increases its dimensions by 1, creating a single item in a higher dimension. itemize on a scalar creates a list of 1 item. itemize on a list creates a table with 1 record (that contains the original list). itemize on a table creates a 3d array with 1 item that is a table.

If you append 2 items of the same dimensions, the result is 2 items. 1 record appended to 3 records is 4 items of records (a table with 4 items). (the difference between a record and a list is that a record is a table with 1 row (item). A list is a collection of scalar (items))

If you append a smaller-dimensioned item (list) with a larger-dimensioned item (record), the smaller-dimensioned item is itemized until it is the same dimension as the larger item. append of an item with empty item (empty can still be high dimensioned) results in 1 item of the largest-dimensioned-parameter.

   3 4 5 , iota 0 0 0  NB. append list with empty 3d array.
3 4 5

above result looks like a list, but is a brick (3d) with 1 table item, that has 1 record item.

the joincells function is something that was used by iota (whether you realized it or not) on the bonus applications of Monday's challenge.

cells are an internal list of arrays. The algorithm is:
Find the largest dimensioned cell (array in the list). With iota, create an empty cell that is 1 dimension higher than that maximum dimension. (for example: if all the cells are lists, then iota 0 0 creates an empty 0 record table.
With that new cell added on the right of the list of cells, insert(append) all the cells. (foldright append to all of the cells). As an alternative to the iota call, you may also repeatedly itemize each of the cell arrays until they are one dimension higher than the max-dimension-cell.

  itemize(y , x=ignored):   Rank _ _         NB. adds 1 dimension to y  
  append(y , x):   Rank _ _                      NB. joins x (first) to y (last).  see itemize preprocessing rules above.  
  joincells(listofarrays):  internal function  NB. see above algorithm.  Though an internal function, can also be implemented with boxes.

   (itemize 4) append  1 2 3      NB. scalar 4 made into list append to other list = list
4 1 2 3

   (itemize 4) append (itemize 1 2 3)  NB. list append to table = table.  Fills are applied to shorter list.
4 0 0
1 2 3

   1 2 3 joincells  7         NB. though internal, if there are only 2 arrays to join, it works as a f(y,x) function.
1 2 3
7 0 0

    1 2 3 joincells  iota 2 4
1 2 3 0
0 0 0 0

0 1 2 3
4 5 6 7

    1 2 3 4 joincells  iota 2 3   NB. fills are applied on the append stage.
1 2 3 4
0 0 0 0

0 1 2 0
3 4 5 0

try to implement joincells as compose(insert(append), pretransform_arrays_function):

5. Rank conjunction

This is the main challenge of the day...

The Rank conjunction can be used to split up a function call into many function calls that each results in a cell, and then the joincells function above turns those individual function calls into a single array result.

While each function has a built in default rank, the rank conjunction can lower the "operating" rank of a function. This is easier to understand as splitting the inputs to the function. " is the rank in J. the v (right) argument to rank can be:

1 number: splits y argument into cells of that dimension. x rank is infinity (or is ignored).
2 numbers: splits y into cells of first number dimension, and splits x into 2nd number dimension.

Rank(u, _ _) specifies rank infinity for x and y which is the same as no rank modifier at all since the full arrays of x and y will be passed to u.

you may use 32000 as a substitute for infinity, or the default value for both "v parameters" to Rank.

Rank(iota, 0 0) will split the y and x parameters into scalars and call iota for each split

pR 1 3 iota("0 0) 3 4 NB. "(0 0) is Rank(u, 0 0) (an adverb) iota("0 0) is Rank(iota, 0 0). returns a function. 1 2 3 0 3 4 5 6

equivalent to:

   (1 iota 3) joincells (3 iota 4)
1 2 3 0
3 4 5 6

1 2 + 3 4 5 NB. an error in J, because only length 1 items are expanded to match the other argument lengths.

   1 2 +("0 1) 3 4 5  NB. using rank to pass compatible lengths. (the order of rank v parameters in J is reversed because x is on the left, and y on the right.
4 5 6
5 6 7

   1 2 +("1 0) 3 4 5
4 5
5 6
6 7

Note in the last 2 examples, 2 items were matched with 1 item (first), and 1 item was matched with 3 items (2nd). When matching different length items, if the lower array count is 1 item, then it is copied the number of times needed to be the same length as the other array.

   (add insert) iota 10 5  NB. seen before puts insert between rows.  end result is sum of columns.
225 235 245 255 265

    (add insert)"1 iota 10 5  NB. cells are the rows.  result of each cell is sum of rows (a scalar).  joincells makes a list.
10 35 60 85 110 135 160 185 210 235

the last call is equivalent to Compose(Rank(insert(add)), 1), iota)([10,5])

6. simple functions

Left(y,x): return y ] in J
Right(y,x): return swap(Left)(y, x=missing) NB. returns y if there is no x. [ in J
double(y,x=ignored): return swap(add) y NB. ignores x.

   double  5
10
  1 2 3 double~  5  NB. swapped so passes x as y.
2 4 6
  double~  5 2     NB.  if there was an x, then double that.  Since there isn't, double y.
10 4
  double~/  5 2    NB. insert(swap(double))([5,2])
10
  5 double~  2
10