title
stringlengths 3
86
| language
stringlengths 1
35
| task
stringlengths 41
8.77k
| solution
stringlengths 60
47.6k
|
---|---|---|---|
Vogel's approximation method | Python from Ruby | Vogel's Approximation Method (VAM) is a technique for finding a good initial feasible solution to an allocation problem.
The powers that be have identified 5 tasks that need to be solved urgently. Being imaginative chaps, they have called them "A", "B", "C", "D", and "E". They estimate that:
* A will require 30 hours of work,
* B will require 20 hours of work,
* C will require 70 hours of work,
* D will require 30 hours of work, and
* E will require 60 hours of work.
They have identified 4 contractors willing to do the work, called "W", "X", "Y", and "Z".
* W has 50 hours available to commit to working,
* X has 60 hours available,
* Y has 50 hours available, and
* Z has 50 hours available.
The cost per hour for each contractor for each task is summarized by the following table:
A B C D E
W 16 16 13 22 17
X 14 14 13 19 15
Y 19 19 20 23 50
Z 50 12 50 15 11
The task is to use VAM to allocate contractors to tasks. It scales to large problems, so ideally keep sorts out of the iterative cycle. It works as follows:
:Step 1: Balance the given transportation problem if either (total supply>total demand) or (total supply
A B C D E W X Y Z
1 2 2 0 4 4 3 1 0 1 E-Z(50)
Determine the largest difference (D or E above). In the case of ties I shall choose the one with the lowest price (in this case E because the lowest price for D is Z=15, whereas for E it is Z=11). For your choice determine the minimum cost (chosen E above so Z=11 is chosen now). Allocate as much as possible from Z to E (50 in this case limited by Z's supply).
Adjust the supply and demand accordingly. If demand or supply becomes 0 for a given task or contractor it plays no further part. In this case Z is out of it. If you choose arbitrarily, and chose D see here for the working.
Repeat until all supply and demand is met:
2 2 2 0 3 2 3 1 0 - C-W(50)
3 5 5 7 4 35 - 1 0 - E-X(10)
4 5 5 7 4 - - 1 0 - C-X(20)
5 5 5 - 4 - - 0 0 - A-X(30)
6 - 19 - 23 - - - 4 - D-Y(30)
- - - - - - - - - B-Y(20)
Finally calculate the cost of your solution. In the example given it is PS3100:
A B C D E
W 50
X 30 20 10
Y 20 30
Z 50
The optimal solution determined by GLPK is PS3100:
A B C D E
W 50
X 10 20 20 10
Y 20 30
Z 50
;Cf.
* Transportation problem
| from collections import defaultdict
costs = {'W': {'A': 16, 'B': 16, 'C': 13, 'D': 22, 'E': 17},
'X': {'A': 14, 'B': 14, 'C': 13, 'D': 19, 'E': 15},
'Y': {'A': 19, 'B': 19, 'C': 20, 'D': 23, 'E': 50},
'Z': {'A': 50, 'B': 12, 'C': 50, 'D': 15, 'E': 11}}
demand = {'A': 30, 'B': 20, 'C': 70, 'D': 30, 'E': 60}
cols = sorted(demand.iterkeys())
supply = {'W': 50, 'X': 60, 'Y': 50, 'Z': 50}
res = dict((k, defaultdict(int)) for k in costs)
g = {}
for x in supply:
g[x] = sorted(costs[x].iterkeys(), key=lambda g: costs[x][g])
for x in demand:
g[x] = sorted(costs.iterkeys(), key=lambda g: costs[g][x])
while g:
d = {}
for x in demand:
d[x] = (costs[g[x][1]][x] - costs[g[x][0]][x]) if len(g[x]) > 1 else costs[g[x][0]][x]
s = {}
for x in supply:
s[x] = (costs[x][g[x][1]] - costs[x][g[x][0]]) if len(g[x]) > 1 else costs[x][g[x][0]]
f = max(d, key=lambda n: d[n])
t = max(s, key=lambda n: s[n])
t, f = (f, g[f][0]) if d[f] > s[t] else (g[t][0], t)
v = min(supply[f], demand[t])
res[f][t] += v
demand[t] -= v
if demand[t] == 0:
for k, n in supply.iteritems():
if n != 0:
g[k].remove(t)
del g[t]
del demand[t]
supply[f] -= v
if supply[f] == 0:
for k, n in demand.iteritems():
if n != 0:
g[k].remove(f)
del g[f]
del supply[f]
for n in cols:
print "\t", n,
print
cost = 0
for g in sorted(costs):
print g, "\t",
for n in cols:
y = res[g][n]
if y != 0:
print y,
cost += y * costs[g][n]
print "\t",
print
print "\n\nTotal Cost = ", cost |
Voronoi diagram | Python | A Voronoi diagram is a diagram consisting of a number of sites.
Each Voronoi site ''s'' also has a Voronoi cell consisting of all points closest to ''s''.
;Task:
Demonstrate how to generate and display a Voroni diagram.
See algo [[K-means++ clustering]].
| from PIL import Image
import random
import math
def generate_voronoi_diagram(width, height, num_cells):
image = Image.new("RGB", (width, height))
putpixel = image.putpixel
imgx, imgy = image.size
nx = []
ny = []
nr = []
ng = []
nb = []
for i in range(num_cells):
nx.append(random.randrange(imgx))
ny.append(random.randrange(imgy))
nr.append(random.randrange(256))
ng.append(random.randrange(256))
nb.append(random.randrange(256))
for y in range(imgy):
for x in range(imgx):
dmin = math.hypot(imgx-1, imgy-1)
j = -1
for i in range(num_cells):
d = math.hypot(nx[i]-x, ny[i]-y)
if d < dmin:
dmin = d
j = i
putpixel((x, y), (nr[j], ng[j], nb[j]))
image.save("VoronoiDiagram.png", "PNG")
image.show()
generate_voronoi_diagram(500, 500, 25) |
Wagstaff primes | Python | Definition
A ''Wagstaff prime'' is a prime number of the form ''(2^p + 1)/3'' where the exponent ''p'' is an odd prime.
;Example
(2^5 + 1)/3 = 11 is a Wagstaff prime because both 5 and 11 are primes.
;Task
Find and show here the first ''10'' Wagstaff primes and their corresponding exponents ''p''.
;Stretch (requires arbitrary precision integers)
Find and show here the exponents ''p'' corresponding to the next ''14'' Wagstaff primes (not the primes themselves) and any more that you have the patience for.
When testing for primality, you may use a method which determines that a large number is probably prime with reasonable certainty.
;Note
It can be shown (see talk page) that ''(2^p + 1)/3'' is always integral if ''p'' is odd. So there's no need to check for that prior to checking for primality.
;References
* Wikipedia - Wagstaff prime
* OEIS:A000979 - Wagstaff primes
| """ Rosetta code Wagstaff_primes task """
from sympy import isprime
def wagstaff(N):
""" find first N Wagstaff primes """
pri, wcount = 1, 0
while wcount < N:
pri += 2
if isprime(pri):
wag = (2**pri + 1) // 3
if isprime(wag):
wcount += 1
print(f'{wcount: 3}: {pri: 5} => ',
f'{wag:,}' if wcount < 11 else f'[{len(str(wag))} digit number]')
wagstaff(24)
|
War card game | Python from Julia | War Card Game
Simulate the card game War. Use the Bicycle playing card manufacturer's rules. Show a game as played. User input is optional.
References:
:* Bicycle card company: War game site
:* Wikipedia: War (card game)
Related tasks:
* [[Playing cards]]
* [[Card shuffles]]
* [[Deal cards for FreeCell]]
* [[Poker hand_analyser]]
* [[Go Fish]]
| """ https://bicyclecards.com/how-to-play/war/ """
from numpy.random import shuffle
SUITS = ['♣', '♦', '♥', '♠']
FACES = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A']
DECK = [f + s for f in FACES for s in SUITS]
CARD_TO_RANK = dict((DECK[i], (i + 3) // 4) for i in range(len(DECK)))
class WarCardGame:
""" card game War """
def __init__(self):
deck = DECK.copy()
shuffle(deck)
self.deck1, self.deck2 = deck[:26], deck[26:]
self.pending = []
def turn(self):
""" one turn, may recurse on tie """
if len(self.deck1) == 0 or len(self.deck2) == 0:
return self.gameover()
card1, card2 = self.deck1.pop(0), self.deck2.pop(0)
rank1, rank2 = CARD_TO_RANK[card1], CARD_TO_RANK[card2]
print("{:10}{:10}".format(card1, card2), end='')
if rank1 > rank2:
print('Player 1 takes the cards.')
self.deck1.extend([card1, card2])
self.deck1.extend(self.pending)
self.pending = []
elif rank1 < rank2:
print('Player 2 takes the cards.')
self.deck2.extend([card2, card1])
self.deck2.extend(self.pending)
self.pending = []
else: # rank1 == rank2
print('Tie!')
if len(self.deck1) == 0 or len(self.deck2) == 0:
return self.gameover()
card3, card4 = self.deck1.pop(0), self.deck2.pop(0)
self.pending.extend([card1, card2, card3, card4])
print("{:10}{:10}".format("?", "?"), 'Cards are face down.', sep='')
return self.turn()
return True
def gameover(self):
""" game over who won message """
if len(self.deck2) == 0:
if len(self.deck1) == 0:
print('\nGame ends as a tie.')
else:
print('\nPlayer 1 wins the game.')
else:
print('\nPlayer 2 wins the game.')
return False
if __name__ == '__main__':
WG = WarCardGame()
while WG.turn():
continue
|
Water collected between towers | Python | In a two-dimensional world, we begin with any bar-chart (or row of close-packed 'towers', each of unit width), and then it rains,
completely filling all convex enclosures in the chart with water.
9 ## 9 ##
8 ## 8 ##
7 ## ## 7 ####
6 ## ## ## 6 ######
5 ## ## ## #### 5 ##########
4 ## ## ######## 4 ############
3 ###### ######## 3 ##############
2 ################ ## 2 ##################
1 #################### 1 ####################
In the example above, a bar chart representing the values [5, 3, 7, 2, 6, 4, 5, 9, 1, 2] has filled, collecting 14 units of water.
Write a function, in your language, from a given array of heights, to the number of water units that can be held in this way, by a corresponding bar chart.
Calculate the number of water units that could be collected by bar charts representing each of the following seven series:
[[1, 5, 3, 7, 2],
[5, 3, 7, 2, 6, 4, 5, 9, 1, 2],
[2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1],
[5, 5, 5, 5],
[5, 6, 7, 8],
[8, 7, 7, 6],
[6, 7, 10, 7, 6]]
See, also:
* Four Solutions to a Trivial Problem - a Google Tech Talk by Guy Steele
* Water collected between towers on Stack Overflow, from which the example above is taken)
* An interesting Haskell solution, using the Tardis monad, by Phil Freeman in a Github gist.
| def water_collected(tower):
N = len(tower)
highest_left = [0] + [max(tower[:n]) for n in range(1,N)]
highest_right = [max(tower[n:N]) for n in range(1,N)] + [0]
water_level = [max(min(highest_left[n], highest_right[n]) - tower[n], 0)
for n in range(N)]
print("highest_left: ", highest_left)
print("highest_right: ", highest_right)
print("water_level: ", water_level)
print("tower_level: ", tower)
print("total_water: ", sum(water_level))
print("")
return sum(water_level)
towers = [[1, 5, 3, 7, 2],
[5, 3, 7, 2, 6, 4, 5, 9, 1, 2],
[2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1],
[5, 5, 5, 5],
[5, 6, 7, 8],
[8, 7, 7, 6],
[6, 7, 10, 7, 6]]
[water_collected(tower) for tower in towers] |
Weird numbers | Python 3 | In number theory, a perfect either).
In other words, the sum of the proper divisors of the number (divisors including 1 but not itself) is greater than the number itself (the number is ''abundant''), but no subset of those divisors sums to the number itself (the number is not ''semiperfect'').
For example:
* '''12''' is ''not'' a weird number.
** It is abundant; its proper divisors '''1, 2, 3, 4, 6''' sum to '''16''' (which ''is'' > 12),
** but it ''is'' semiperfect, e.g.: '''6 + 4 + 2 == 12'''.
* '''70''' ''is'' a weird number.
** It is abundant; its proper divisors '''1, 2, 5, 7, 10, 14, 35''' sum to '''74''' (which ''is'' > 70),
** and there is no subset of proper divisors that sum to '''70'''.
;Task:
Find and display, here on this page, the first '''25''' weird numbers.
;Related tasks:
:* Abundant, deficient and perfect number classifications
:* Proper divisors
;See also:
:* OEIS: A006037 weird numbers
:* Wikipedia: weird number
:* MathWorld: weird number
| '''Weird numbers'''
from itertools import chain, count, islice, repeat
from functools import reduce
from math import sqrt
from time import time
# weirds :: Gen [Int]
def weirds():
'''Non-finite stream of weird numbers.
(Abundant, but not semi-perfect)
OEIS: A006037
'''
def go(n):
ds = descPropDivs(n)
d = sum(ds) - n
return [n] if 0 < d and not hasSum(d, ds) else []
return concatMap(go)(count(1))
# hasSum :: Int -> [Int] -> Bool
def hasSum(n, xs):
'''Does any subset of xs sum to n ?
(Assuming xs to be sorted in descending
order of magnitude)'''
def go(n, xs):
if xs:
h, t = xs[0], xs[1:]
if n < h: # Head too big. Forget it. Tail ?
return go(n, t)
else:
# The head IS the target ?
# Or the tail contains a sum for the
# DIFFERENCE between the head and the target ?
# Or the tail contains some OTHER sum for the target ?
return n == h or go(n - h, t) or go(n, t)
else:
return False
return go(n, xs)
# descPropDivs :: Int -> [Int]
def descPropDivs(n):
'''Descending positive divisors of n,
excluding n itself.'''
root = sqrt(n)
intRoot = int(root)
blnSqr = root == intRoot
lows = [x for x in range(1, 1 + intRoot) if 0 == n % x]
return [
n // x for x in (
lows[1:-1] if blnSqr else lows[1:]
)
] + list(reversed(lows))
# --------------------------TEST---------------------------
# main :: IO ()
def main():
'''Test'''
start = time()
n = 50
xs = take(n)(weirds())
print(
(tabulated('First ' + str(n) + ' weird numbers:\n')(
lambda i: str(1 + i)
)(str)(5)(
index(xs)
)(range(0, n)))
)
print(
'\nApprox computation time: ' +
str(int(1000 * (time() - start))) + ' ms'
)
# -------------------------GENERIC-------------------------
# chunksOf :: Int -> [a] -> [[a]]
def chunksOf(n):
'''A series of lists of length n,
subdividing the contents of xs.
Where the length of xs is not evenly divible,
the final list will be shorter than n.'''
return lambda xs: reduce(
lambda a, i: a + [xs[i:n + i]],
range(0, len(xs), n), []
) if 0 < n else []
# compose (<<<) :: (b -> c) -> (a -> b) -> a -> c
def compose(g):
'''Right to left function composition.'''
return lambda f: lambda x: g(f(x))
# concatMap :: (a -> [b]) -> [a] -> [b]
def concatMap(f):
'''A concatenated list or string over which a function f
has been mapped.
The list monad can be derived by using an (a -> [b])
function which wraps its output in a list (using an
empty list to represent computational failure).
'''
return lambda xs: chain.from_iterable(map(f, xs))
# index (!!) :: [a] -> Int -> a
def index(xs):
'''Item at given (zero-based) index.'''
return lambda n: None if 0 > n else (
xs[n] if (
hasattr(xs, "__getitem__")
) else next(islice(xs, n, None))
)
# paddedMatrix :: a -> [[a]] -> [[a]]
def paddedMatrix(v):
''''A list of rows padded to equal length
(where needed) with instances of the value v.'''
def go(rows):
return paddedRows(
len(max(rows, key=len))
)(v)(rows)
return lambda rows: go(rows) if rows else []
# paddedRows :: Int -> a -> [[a]] -[[a]]
def paddedRows(n):
'''A list of rows padded (but never truncated)
to length n with copies of value v.'''
def go(v, xs):
def pad(x):
d = n - len(x)
return (x + list(repeat(v, d))) if 0 < d else x
return list(map(pad, xs))
return lambda v: lambda xs: go(v, xs) if xs else []
# showColumns :: Int -> [String] -> String
def showColumns(n):
'''A column-wrapped string
derived from a list of rows.'''
def go(xs):
def fit(col):
w = len(max(col, key=len))
def pad(x):
return x.ljust(4 + w, ' ')
return ''.join(map(pad, col))
q, r = divmod(len(xs), n)
return unlines(map(
fit,
transpose(paddedMatrix('')(
chunksOf(q + int(bool(r)))(
xs
)
))
))
return lambda xs: go(xs)
# succ :: Enum a => a -> a
def succ(x):
'''The successor of a value. For numeric types, (1 +).'''
return 1 + x if isinstance(x, int) else (
chr(1 + ord(x))
)
# tabulated :: String -> (a -> String) ->
# (b -> String) ->
# Int ->
# (a -> b) -> [a] -> String
def tabulated(s):
'''Heading -> x display function -> fx display function ->
number of columns -> f -> value list -> tabular string.'''
def go(xShow, fxShow, intCols, f, xs):
w = max(map(compose(len)(xShow), xs))
return s + '\n' + showColumns(intCols)([
xShow(x).rjust(w, ' ') + ' -> ' + fxShow(f(x)) for x in xs
])
return lambda xShow: lambda fxShow: lambda nCols: (
lambda f: lambda xs: go(
xShow, fxShow, nCols, f, xs
)
)
# take :: Int -> [a] -> [a]
# take :: Int -> String -> String
def take(n):
'''The prefix of xs of length n,
or xs itself if n > length xs.'''
return lambda xs: (
xs[0:n]
if isinstance(xs, list)
else list(islice(xs, n))
)
# transpose :: Matrix a -> Matrix a
def transpose(m):
'''The rows and columns of the argument transposed.
(The matrix containers and rows can be lists or tuples).'''
if m:
inner = type(m[0])
z = zip(*m)
return (type(m))(
map(inner, z) if tuple != inner else z
)
else:
return m
# unlines :: [String] -> String
def unlines(xs):
'''A single string derived by the intercalation
of a list of strings with the newline character.'''
return '\n'.join(xs)
# until :: (a -> Bool) -> (a -> a) -> a -> a
def until(p):
'''The result of repeatedly applying f until p holds.
The initial seed value is x.'''
def go(f, x):
v = x
while not p(v):
v = f(v)
return v
return lambda f: lambda x: go(f, x)
# MAIN ----------------------------------------------------
if __name__ == '__main__':
main() |
Word frequency | Python | Given a text file and an integer '''n''', print/display the '''n''' most
common words in the file (and the number of their occurrences) in decreasing frequency.
For the purposes of this task:
* A word is a sequence of one or more contiguous letters.
* You are free to define what a ''letter'' is.
* Underscores, accented letters, apostrophes, hyphens, and other special characters can be handled at your discretion.
* You may treat a compound word like '''well-dressed''' as either one word or two.
* The word '''it's''' could also be one or two words as you see fit.
* You may also choose not to support non US-ASCII characters.
* Assume words will not span multiple lines.
* Don't worry about normalization of word spelling differences.
* Treat '''color''' and '''colour''' as two distinct words.
* Uppercase letters are considered equivalent to their lowercase counterparts.
* Words of equal frequency can be listed in any order.
* Feel free to explicitly state the thoughts behind the program decisions.
Show example output using Les Miserables from Project Gutenberg as the text file input and display the top '''10''' most used words.
;History:
This task was originally taken from programming pearls from Communications of the ACM June 1986 Volume 29 Number 6
where this problem is solved by Donald Knuth using literate programming and then critiqued by Doug McIlroy,
demonstrating solving the problem in a 6 line Unix shell script (provided as an example below).
;References:
*McIlroy's program
| import collections
import re
import string
import sys
def main():
counter = collections.Counter(re.findall(r"\w+",open(sys.argv[1]).read().lower()))
print counter.most_common(int(sys.argv[2]))
if __name__ == "__main__":
main() |
Word frequency | Python 3.7 | Given a text file and an integer '''n''', print/display the '''n''' most
common words in the file (and the number of their occurrences) in decreasing frequency.
For the purposes of this task:
* A word is a sequence of one or more contiguous letters.
* You are free to define what a ''letter'' is.
* Underscores, accented letters, apostrophes, hyphens, and other special characters can be handled at your discretion.
* You may treat a compound word like '''well-dressed''' as either one word or two.
* The word '''it's''' could also be one or two words as you see fit.
* You may also choose not to support non US-ASCII characters.
* Assume words will not span multiple lines.
* Don't worry about normalization of word spelling differences.
* Treat '''color''' and '''colour''' as two distinct words.
* Uppercase letters are considered equivalent to their lowercase counterparts.
* Words of equal frequency can be listed in any order.
* Feel free to explicitly state the thoughts behind the program decisions.
Show example output using Les Miserables from Project Gutenberg as the text file input and display the top '''10''' most used words.
;History:
This task was originally taken from programming pearls from Communications of the ACM June 1986 Volume 29 Number 6
where this problem is solved by Donald Knuth using literate programming and then critiqued by Doug McIlroy,
demonstrating solving the problem in a 6 line Unix shell script (provided as an example below).
;References:
*McIlroy's program
| """
Word count task from Rosetta Code
http://www.rosettacode.org/wiki/Word_count#Python
"""
from itertools import (groupby,
starmap)
from operator import itemgetter
from pathlib import Path
from typing import (Iterable,
List,
Tuple)
FILEPATH = Path('lesMiserables.txt')
COUNT = 10
def main():
words_and_counts = most_frequent_words(FILEPATH)
print(*words_and_counts[:COUNT], sep='\n')
def most_frequent_words(filepath: Path,
*,
encoding: str = 'utf-8') -> List[Tuple[str, int]]:
"""
A list of word-frequency pairs sorted by their occurrences.
The words are read from the given file.
"""
def word_and_frequency(word: str,
words_group: Iterable[str]) -> Tuple[str, int]:
return word, capacity(words_group)
file_contents = filepath.read_text(encoding=encoding)
words = file_contents.lower().split()
grouped_words = groupby(sorted(words))
words_and_frequencies = starmap(word_and_frequency, grouped_words)
return sorted(words_and_frequencies, key=itemgetter(1), reverse=True)
def capacity(iterable: Iterable) -> int:
"""Returns a number of elements in an iterable"""
return sum(1 for _ in iterable)
if __name__ == '__main__':
main()
|
Word ladder | Python | Yet another shortest path problem. Given two words of equal length the task is to transpose the first into the second.
Only one letter may be changed at a time and the change must result in a word in unixdict, the minimum number of intermediate words should be used.
Demonstrate the following:
A boy can be made into a man: boy -> bay -> ban -> man
With a little more difficulty a girl can be made into a lady: girl -> gill -> gall -> gale -> gaze -> laze -> lazy -> lady
A john can be made into a jane: john -> cohn -> conn -> cone -> cane -> jane
A child can not be turned into an adult.
Optional transpositions of your choice.
| import os,sys,zlib,urllib.request
def h ( str,x=9 ):
for c in str :
x = ( x*33 + ord( c )) & 0xffffffffff
return x
def cache ( func,*param ):
n = 'cache_%x.bin'%abs( h( repr( param )))
try : return eval( zlib.decompress( open( n,'rb' ).read()))
except : pass
s = func( *param )
open( n,'wb' ).write( zlib.compress( bytes( repr( s ),'ascii' )))
return s
dico_url = 'https://raw.githubusercontent.com/quinnj/Rosetta-Julia/master/unixdict.txt'
read_url = lambda url : urllib.request.urlopen( url ).read()
load_dico = lambda url : tuple( cache( read_url,url ).split( b'\n'))
isnext = lambda w1,w2 : len( w1 ) == len( w2 ) and len( list( filter( lambda l : l[0]!=l[1] , zip( w1,w2 )))) == 1
def build_map ( words ):
map = [(w.decode('ascii'),[]) for w in words]
for i1,(w1,n1) in enumerate( map ):
for i2,(w2,n2) in enumerate( map[i1+1:],i1+1 ):
if isnext( w1,w2 ):
n1.append( i2 )
n2.append( i1 )
return map
def find_path ( words,w1,w2 ):
i = [w[0] for w in words].index( w1 )
front,done,res = [i],{i:-1},[]
while front :
i = front.pop(0)
word,next = words[i]
for n in next :
if n in done : continue
done[n] = i
if words[n][0] == w2 :
while n >= 0 :
res = [words[n][0]] + res
n = done[n]
return ' '.join( res )
front.append( n )
return '%s can not be turned into %s'%( w1,w2 )
for w in ('boy man','girl lady','john jane','alien drool','child adult'):
print( find_path( cache( build_map,load_dico( dico_url )),*w.split())) |
Word search | Python 3.x | A word search puzzle typically consists of a grid of letters in which words are hidden.
There are many varieties of word search puzzles. For the task at hand we will use a rectangular grid in which the words may be placed horizontally, vertically, or diagonally. The words may also be spelled backwards.
The words may overlap but are not allowed to zigzag, or wrap around.
;Task
Create a 10 by 10 word search and fill it using words from the unixdict. Use only words that are longer than 2, and contain no non-alphabetic characters.
The cells not used by the hidden words should contain the message: ''Rosetta Code'', read from left to right, top to bottom. These letters should be somewhat evenly distributed over the grid, not clumped together. The message should be in upper case, the hidden words in lower case. All cells should either contain letters from the hidden words or from the message.
Pack a minimum of 25 words into the grid.
Print the resulting grid and the solutions.
;Example
0 1 2 3 4 5 6 7 8 9
0 n a y r y R e l m f
1 y O r e t s g n a g
2 t n e d i S k y h E
3 n o t n c p c w t T
4 a l s u u n T m a x
5 r o k p a r i s h h
6 a A c f p a e a c C
7 u b u t t t O l u n
8 g y h w a D h p m u
9 m i r p E h o g a n
parish (3,5)(8,5) gangster (9,1)(2,1)
paucity (4,6)(4,0) guaranty (0,8)(0,1)
prim (3,9)(0,9) huckster (2,8)(2,1)
plasm (7,8)(7,4) fancy (3,6)(7,2)
hogan (5,9)(9,9) nolo (1,2)(1,5)
under (3,4)(3,0) chatham (8,6)(8,0)
ate (4,8)(6,6) nun (9,7)(9,9)
butt (1,7)(4,7) hawk (9,5)(6,2)
why (3,8)(1,8) ryan (3,0)(0,0)
fay (9,0)(7,2) much (8,8)(8,5)
tar (5,7)(5,5) elm (6,0)(8,0)
max (7,4)(9,4) pup (5,3)(3,5)
mph (8,8)(6,8)
| import re
from random import shuffle, randint
dirs = [[1, 0], [0, 1], [1, 1], [1, -1], [-1, 0], [0, -1], [-1, -1], [-1, 1]]
n_rows = 10
n_cols = 10
grid_size = n_rows * n_cols
min_words = 25
class Grid:
def __init__(self):
self.num_attempts = 0
self.cells = [['' for _ in range(n_cols)] for _ in range(n_rows)]
self.solutions = []
def read_words(filename):
max_len = max(n_rows, n_cols)
words = []
with open(filename, "r") as file:
for line in file:
s = line.strip().lower()
if re.match(r'^[a-z]{3,' + re.escape(str(max_len)) + r'}$', s) is not None:
words.append(s)
return words
def place_message(grid, msg):
msg = re.sub(r'[^A-Z]', "", msg.upper())
message_len = len(msg)
if 0 < message_len < grid_size:
gap_size = grid_size // message_len
for i in range(0, message_len):
pos = i * gap_size + randint(0, gap_size)
grid.cells[pos // n_cols][pos % n_cols] = msg[i]
return message_len
return 0
def try_location(grid, word, direction, pos):
r = pos // n_cols
c = pos % n_cols
length = len(word)
# check bounds
if (dirs[direction][0] == 1 and (length + c) > n_cols) or \
(dirs[direction][0] == -1 and (length - 1) > c) or \
(dirs[direction][1] == 1 and (length + r) > n_rows) or \
(dirs[direction][1] == -1 and (length - 1) > r):
return 0
rr = r
cc = c
i = 0
overlaps = 0
# check cells
while i < length:
if grid.cells[rr][cc] != '' and grid.cells[rr][cc] != word[i]:
return 0
cc += dirs[direction][0]
rr += dirs[direction][1]
i += 1
rr = r
cc = c
i = 0
# place
while i < length:
if grid.cells[rr][cc] == word[i]:
overlaps += 1
else:
grid.cells[rr][cc] = word[i]
if i < length - 1:
cc += dirs[direction][0]
rr += dirs[direction][1]
i += 1
letters_placed = length - overlaps
if letters_placed > 0:
grid.solutions.append("{0:<10} ({1},{2})({3},{4})".format(word, c, r, cc, rr))
return letters_placed
def try_place_word(grid, word):
rand_dir = randint(0, len(dirs))
rand_pos = randint(0, grid_size)
for direction in range(0, len(dirs)):
direction = (direction + rand_dir) % len(dirs)
for pos in range(0, grid_size):
pos = (pos + rand_pos) % grid_size
letters_placed = try_location(grid, word, direction, pos)
if letters_placed > 0:
return letters_placed
return 0
def create_word_search(words):
grid = None
num_attempts = 0
while num_attempts < 100:
num_attempts += 1
shuffle(words)
grid = Grid()
message_len = place_message(grid, "Rosetta Code")
target = grid_size - message_len
cells_filled = 0
for word in words:
cells_filled += try_place_word(grid, word)
if cells_filled == target:
if len(grid.solutions) >= min_words:
grid.num_attempts = num_attempts
return grid
else:
break # grid is full but we didn't pack enough words, start over
return grid
def print_result(grid):
if grid is None or grid.num_attempts == 0:
print("No grid to display")
return
size = len(grid.solutions)
print("Attempts: {0}".format(grid.num_attempts))
print("Number of words: {0}".format(size))
print("\n 0 1 2 3 4 5 6 7 8 9\n")
for r in range(0, n_rows):
print("{0} ".format(r), end='')
for c in range(0, n_cols):
print(" %c " % grid.cells[r][c], end='')
print()
print()
for i in range(0, size - 1, 2):
print("{0} {1}".format(grid.solutions[i], grid.solutions[i+1]))
if size % 2 == 1:
print(grid.solutions[size - 1])
if __name__ == "__main__":
print_result(create_word_search(read_words("unixdict.txt")))
|
Word wrap | Python | Even today, with proportional fonts and complex layouts, there are still cases where you need to wrap text at a specified column.
;Basic task:
The basic task is to wrap a paragraph of text in a simple way in your language.
If there is a way to do this that is built-in, trivial, or provided in a standard library, show that. Otherwise implement the minimum length greedy algorithm from Wikipedia.
Show your routine working on a sample of text at two different wrap columns.
;Extra credit:
Wrap text using a more sophisticated algorithm such as the Knuth and Plass TeX algorithm.
If your language provides this, you get easy extra credit,
but you ''must reference documentation'' indicating that the algorithm
is something better than a simple minimum length algorithm.
If you have both basic and extra credit solutions, show an example where
the two algorithms give different results.
| >>> import textwrap
>>> help(textwrap.fill)
Help on function fill in module textwrap:
fill(text, width=70, **kwargs)
Fill a single paragraph of text, returning a new string.
Reformat the single paragraph in 'text' to fit in lines of no more
than 'width' columns, and return a new string containing the entire
wrapped paragraph. As with wrap(), tabs are expanded and other
whitespace characters converted to space. See TextWrapper class for
available keyword args to customize wrapping behaviour.
>>> txt = '''\
Reformat the single paragraph in 'text' to fit in lines of no more
than 'width' columns, and return a new string containing the entire
wrapped paragraph. As with wrap(), tabs are expanded and other
whitespace characters converted to space. See TextWrapper class for
available keyword args to customize wrapping behaviour.'''
>>> print(textwrap.fill(txt, width=75))
Reformat the single paragraph in 'text' to fit in lines of no more than
'width' columns, and return a new string containing the entire wrapped
paragraph. As with wrap(), tabs are expanded and other whitespace
characters converted to space. See TextWrapper class for available keyword
args to customize wrapping behaviour.
>>> print(textwrap.fill(txt, width=45))
Reformat the single paragraph in 'text' to
fit in lines of no more than 'width' columns,
and return a new string containing the entire
wrapped paragraph. As with wrap(), tabs are
expanded and other whitespace characters
converted to space. See TextWrapper class
for available keyword args to customize
wrapping behaviour.
>>> print(textwrap.fill(txt, width=85))
Reformat the single paragraph in 'text' to fit in lines of no more than 'width'
columns, and return a new string containing the entire wrapped paragraph. As with
wrap(), tabs are expanded and other whitespace characters converted to space. See
TextWrapper class for available keyword args to customize wrapping behaviour.
>>> |
World Cup group stage | Python | It's World Cup season (or at least it was when this page was created)!
The World Cup is an international football/soccer tournament that happens every 4 years. Countries put their international teams together in the years between tournaments and qualify for the tournament based on their performance in other international games. Once a team has qualified they are put into a group with 3 other teams.
For the first part of the World Cup tournament the teams play in "group stage" games where each of the four teams in a group plays all three other teams once. The results of these games determine which teams will move on to the "knockout stage" which is a standard single-elimination tournament. The two teams from each group with the most standings points move on to the knockout stage.
Each game can result in a win for one team and a loss for the other team or it can result in a draw/tie for each team.
:::* A win is worth three points.
:::* A draw/tie is worth one point.
:::* A loss is worth zero points.
;Task:
:* Generate all possible outcome combinations for the six group stage games. With three possible outcomes for each game there should be 36 = 729 of them.
:* Calculate the standings points for each team with each combination of outcomes.
:* Show a histogram (graphical, ASCII art, or straight counts--whichever is easiest/most fun) of the standings points for all four teams over all possible outcomes.
Don't worry about tiebreakers as they can get complicated. We are basically looking to answer the question "if a team gets x standings points, where can they expect to end up in the group standings?".
''Hint: there should be no possible way to end up in second place with less than two points as well as no way to end up in first with less than three. Oddly enough, there is no way to get 8 points at all.''
| from itertools import product, combinations, izip
scoring = [0, 1, 3]
histo = [[0] * 10 for _ in xrange(4)]
for results in product(range(3), repeat=6):
s = [0] * 4
for r, g in izip(results, combinations(range(4), 2)):
s[g[0]] += scoring[r]
s[g[1]] += scoring[2 - r]
for h, v in izip(histo, sorted(s)):
h[v] += 1
for x in reversed(histo):
print x |
Write float arrays to a text file | Python 2.6 | Write two equal-sized numerical arrays 'x' and 'y' to
a two-column text file named 'filename'.
The first column of the file contains values from an 'x'-array with a
given 'xprecision', the second -- values from 'y'-array with 'yprecision'.
For example, considering:
x = {1, 2, 3, 1e11};
y = {1, 1.4142135623730951, 1.7320508075688772, 316227.76601683791};
/* sqrt(x) */
xprecision = 3;
yprecision = 5;
The file should look like:
1 1
2 1.4142
3 1.7321
1e+011 3.1623e+005
This task is intended as a subtask for [[Measure relative performance of sorting algorithms implementations]].
| >>> import math
>>> x = [1, 2, 3, 1e11]
>>> y = map(math.sqrt, x)
>>> y
[1.0, 1.4142135623730951, 1.7320508075688772, 316227.76601683791]
>>> writedat("sqrt.dat", x, y)
>>> # check
...
>>> for line in open('sqrt.dat'):
... print line,
...
1 1
2 1.4142
3 1.7321
1e+011 3.1623e+005 |
Write float arrays to a text file | Python 3 | Write two equal-sized numerical arrays 'x' and 'y' to
a two-column text file named 'filename'.
The first column of the file contains values from an 'x'-array with a
given 'xprecision', the second -- values from 'y'-array with 'yprecision'.
For example, considering:
x = {1, 2, 3, 1e11};
y = {1, 1.4142135623730951, 1.7320508075688772, 316227.76601683791};
/* sqrt(x) */
xprecision = 3;
yprecision = 5;
The file should look like:
1 1
2 1.4142
3 1.7321
1e+011 3.1623e+005
This task is intended as a subtask for [[Measure relative performance of sorting algorithms implementations]].
| def writedat(filename, x, y, xprecision=3, yprecision=5):
with open(filename,'w') as f:
for a, b in zip(x, y):
print("%.*g\t%.*g" % (xprecision, a, yprecision, b), file=f)
#or, using the new-style formatting:
#print("{1:.{0}g}\t{3:.{2}g}".format(xprecision, a, yprecision, b), file=f) |
Write language name in 3D ASCII | Python | Write/display a language's name in '''3D''' ASCII.
(We can leave the definition of "3D ASCII" fuzzy,
so long as the result is interesting or amusing,
not a cheap hack to satisfy the task.)
;Related tasks:
* draw a sphere
* draw a cuboid
* draw a rotating cube
* draw a Deathstar
| py = '''\
#### # # ##### # # ### # #
# # # # # # # # # ## #
#### # # ##### # # # # #
# # # # # # # # ##
# # # # # ### # #'''
lines = py.replace('#', '<<<').replace(' ','X') \
.replace('X', ' ').replace('\n', ' Y') \
.replace('< ', '<>').split('Y')
for i, l in enumerate(lines):
print(' ' * (len(lines) - i) + l) |
Yellowstone sequence | Python 3.7 | The '''Yellowstone sequence''', also called the '''Yellowstone permutation''', is defined as:
For n <= 3,
a(n) = n
For n >= 4,
a(n) = the smallest number not already in sequence such that a(n) is relatively prime to a(n-1) and
is not relatively prime to a(n-2).
The sequence is a permutation of the natural numbers, and gets its name from what its authors felt was a spiking, geyser like appearance of a plot of the sequence.
;Example:
a(4) is 4 because 4 is the smallest number following 1, 2, 3 in the sequence that is relatively prime to the entry before it (3), and is not relatively prime to the number two entries before it (2).
;Task
: Find and show as output the first '''30''' Yellowstone numbers.
;Extra
: Demonstrate how to plot, with x = n and y coordinate a(n), the first 100 Yellowstone numbers.
;Related tasks:
:* Greatest common divisor.
:* Plot coordinate pairs.
;See also:
:* The OEIS entry: A098550 The Yellowstone permutation.
:* Applegate et al, 2015: The Yellowstone Permutation [https://arxiv.org/abs/1501.01669].
| '''Yellowstone permutation OEIS A098550'''
from itertools import chain, count, islice
from operator import itemgetter
from math import gcd
from matplotlib import pyplot
# yellowstone :: [Int]
def yellowstone():
'''A non-finite stream of terms from
the Yellowstone permutation.
OEIS A098550.
'''
# relativelyPrime :: Int -> Int -> Bool
def relativelyPrime(a):
return lambda b: 1 == gcd(a, b)
# nextWindow :: (Int, Int, [Int]) -> (Int, Int, [Int])
def nextWindow(triple):
p2, p1, rest = triple
[rp2, rp1] = map(relativelyPrime, [p2, p1])
# match :: [Int] -> (Int, [Int])
def match(xxs):
x, xs = uncons(xxs)['Just']
return (x, xs) if rp1(x) and not rp2(x) else (
second(cons(x))(
match(xs)
)
)
n, residue = match(rest)
return (p1, n, residue)
return chain(
range(1, 3),
map(
itemgetter(1),
iterate(nextWindow)(
(2, 3, count(4))
)
)
)
# TEST ----------------------------------------------------
# main :: IO ()
def main():
'''Terms of the Yellowstone permutation.'''
print(showList(
take(30)(yellowstone())
))
pyplot.plot(
take(100)(yellowstone())
)
pyplot.xlabel(main.__doc__)
pyplot.show()
# GENERIC -------------------------------------------------
# Just :: a -> Maybe a
def Just(x):
'''Constructor for an inhabited Maybe (option type) value.
Wrapper containing the result of a computation.
'''
return {'type': 'Maybe', 'Nothing': False, 'Just': x}
# Nothing :: Maybe a
def Nothing():
'''Constructor for an empty Maybe (option type) value.
Empty wrapper returned where a computation is not possible.
'''
return {'type': 'Maybe', 'Nothing': True}
# cons :: a -> [a] -> [a]
def cons(x):
'''Construction of a list from x as head,
and xs as tail.
'''
return lambda xs: [x] + xs if (
isinstance(xs, list)
) else x + xs if (
isinstance(xs, str)
) else chain([x], xs)
# iterate :: (a -> a) -> a -> Gen [a]
def iterate(f):
'''An infinite list of repeated
applications of f to x.
'''
def go(x):
v = x
while True:
yield v
v = f(v)
return go
# second :: (a -> b) -> ((c, a) -> (c, b))
def second(f):
'''A simple function lifted to a function over a tuple,
with f applied only to the second of two values.
'''
return lambda xy: (xy[0], f(xy[1]))
# showList :: [a] -> String
def showList(xs):
'''Stringification of a list.'''
return '[' + ','.join(repr(x) for x in xs) + ']'
# take :: Int -> [a] -> [a]
# take :: Int -> String -> String
def take(n):
'''The prefix of xs of length n,
or xs itself if n > length xs.
'''
return lambda xs: (
xs[0:n]
if isinstance(xs, (list, tuple))
else list(islice(xs, n))
)
# uncons :: [a] -> Maybe (a, [a])
def uncons(xs):
'''The deconstruction of a non-empty list
(or generator stream) into two parts:
a head value, and the remaining values.
'''
if isinstance(xs, list):
return Just((xs[0], xs[1:])) if xs else Nothing()
else:
nxt = take(1)(xs)
return Just((nxt[0], xs)) if nxt else Nothing()
# MAIN ---
if __name__ == '__main__':
main() |
Zeckendorf number representation | Python | Just as numbers can be represented in a positional notation as sums of multiples of the powers of ten (decimal) or two (binary); all the positive integers can be represented as the sum of one or zero times the distinct members of the Fibonacci series.
Recall that the first six distinct Fibonacci numbers are: 1, 2, 3, 5, 8, 13.
The decimal number eleven can be written as 0*13 + 1*8 + 0*5 + 1*3 + 0*2 + 0*1 or 010100 in positional notation where the columns represent multiplication by a particular member of the sequence. Leading zeroes are dropped so that 11 decimal becomes 10100.
10100 is not the only way to make 11 from the Fibonacci numbers however; 0*13 + 1*8 + 0*5 + 0*3 + 1*2 + 1*1 or 010011 would also represent decimal 11. For a true Zeckendorf number there is the added restriction that ''no two consecutive Fibonacci numbers can be used'' which leads to the former unique solution.
;Task:
Generate and show here a table of the Zeckendorf number representations of the decimal numbers zero to twenty, in order.
The intention in this task to find the Zeckendorf form of an arbitrary integer. The Zeckendorf form can be iterated by some bit twiddling rather than calculating each value separately but leave that to another separate task.
;Also see:
* OEIS A014417 for the the sequence of required results.
* Brown's Criterion - Numberphile
;Related task:
* [[Fibonacci sequence]]
| def fib():
memo = [1, 2]
while True:
memo.append(sum(memo))
yield memo.pop(0)
def sequence_down_from_n(n, seq_generator):
seq = []
for s in seq_generator():
seq.append(s)
if s >= n: break
return seq[::-1]
def zeckendorf(n):
if n == 0: return [0]
seq = sequence_down_from_n(n, fib)
digits, nleft = [], n
for s in seq:
if s <= nleft:
digits.append(1)
nleft -= s
else:
digits.append(0)
assert nleft == 0, 'Check all of n is accounted for'
assert sum(x*y for x,y in zip(digits, seq)) == n, 'Assert digits are correct'
while digits[0] == 0:
# Remove any zeroes padding L.H.S.
digits.pop(0)
return digits
n = 20
print('Fibonacci digit multipliers: %r' % sequence_down_from_n(n, fib))
for i in range(n + 1):
print('%3i: %8s' % (i, ''.join(str(d) for d in zeckendorf(i)))) |
Zero to the zero power | Python | Some computer programming languages are not exactly consistent (with other computer programming languages)
when ''raising zero to the zeroth power'': 00
;Task:
Show the results of raising zero to the zeroth power.
If your computer language objects to '''0**0''' or '''0^0''' at compile time, you may also try something like:
x = 0
y = 0
z = x**y
say 'z=' z
'''Show the result here.'''
And of course use any symbols or notation that is supported in your computer programming language for exponentiation.
;See also:
* The Wiki entry: Zero to the power of zero.
* The Wiki entry: Zero to the power of zero: History.
* The MathWorld(tm) entry: exponent laws.
** Also, in the above MathWorld(tm) entry, see formula ('''9'''): x^0=1.
* The OEIS entry: The special case of zero to the zeroth power
| from decimal import Decimal
from fractions import Fraction
from itertools import product
zeroes = [0, 0.0, 0j, Decimal(0), Fraction(0, 1), -0.0, -0.0j, Decimal(-0.0)]
for i, j in product(zeroes, repeat=2):
try:
ans = i**j
except:
ans = '<Exception raised>'
print(f'{i!r:>15} ** {j!r:<15} = {ans!r}') |
Zhang-Suen thinning algorithm | Python | This is an algorithm used to thin a black and white i.e. one bit per pixel images.
For example, with an input image of:
################# #############
################## ################
################### ##################
######## ####### ###################
###### ####### ####### ######
###### ####### #######
################# #######
################ #######
################# #######
###### ####### #######
###### ####### #######
###### ####### ####### ######
######## ####### ###################
######## ####### ###### ################## ######
######## ####### ###### ################ ######
######## ####### ###### ############# ######
It produces the thinned output:
# ########## #######
## # #### #
# # ##
# # #
# # #
# # #
############ #
# # #
# # #
# # #
# # #
# ##
# ############
### ###
;Algorithm:
Assume black pixels are one and white pixels zero, and that the input image is a rectangular N by M array of ones and zeroes.
The algorithm operates on all black pixels P1 that can have eight neighbours.
The neighbours are, in order, arranged as:
P9 P2 P3
P8 P1 P4
P7 P6 P5
Obviously the boundary pixels of the image cannot have the full eight neighbours.
* Define A(P1) = the number of transitions from white to black, (0 -> 1) in the sequence P2,P3,P4,P5,P6,P7,P8,P9,P2. (Note the extra P2 at the end - it is circular).
* Define B(P1) = The number of black pixel neighbours of P1. ( = sum(P2 .. P9) )
;Step 1:
All pixels are tested and pixels satisfying all the following conditions (simultaneously) are just noted at this stage.
* (0) The pixel is black and has eight neighbours
* (1) 2 <= B(P1) <= 6
* (2) A(P1) = 1
* (3) At least one of P2 and P4 and P6 is white
* (4) At least one of P4 and P6 and P8 is white
After iterating over the image and collecting all the pixels satisfying all step 1 conditions, all these condition satisfying pixels are set to white.
;Step 2:
All pixels are again tested and pixels satisfying all the following conditions are just noted at this stage.
* (0) The pixel is black and has eight neighbours
* (1) 2 <= B(P1) <= 6
* (2) A(P1) = 1
* (3) At least one of P2 and P4 and '''P8''' is white
* (4) At least one of '''P2''' and P6 and P8 is white
After iterating over the image and collecting all the pixels satisfying all step 2 conditions, all these condition satisfying pixels are again set to white.
;Iteration:
If any pixels were set in this round of either step 1 or step 2 then all steps are repeated until no image pixels are so changed.
;Task:
# Write a routine to perform Zhang-Suen thinning on an image matrix of ones and zeroes.
# Use the routine to thin the following image and show the output here on this page as either a matrix of ones and zeroes, an image, or an ASCII-art image of space/non-space characters.
00000000000000000000000000000000
01111111110000000111111110000000
01110001111000001111001111000000
01110000111000001110000111000000
01110001111000001110000000000000
01111111110000001110000000000000
01110111100000001110000111000000
01110011110011101111001111011100
01110001111011100111111110011100
00000000000000000000000000000000
;Reference:
* Zhang-Suen Thinning Algorithm, Java Implementation by Nayef Reza.
* "Character Recognition Systems: A Guide for Students and Practitioners" By Mohamed Cheriet, Nawwaf Kharma, Cheng-Lin Liu, Ching Suen
| # -*- coding: utf-8 -*-
# Example from [http://nayefreza.wordpress.com/2013/05/11/zhang-suen-thinning-algorithm-java-implementation/ this blog post].
beforeTxt = '''\
1100111
1100111
1100111
1100111
1100110
1100110
1100110
1100110
1100110
1100110
1100110
1100110
1111110
0000000\
'''
# Thanks to [http://www.network-science.de/ascii/ this site] and vim for these next two examples
smallrc01 = '''\
00000000000000000000000000000000
01111111110000000111111110000000
01110001111000001111001111000000
01110000111000001110000111000000
01110001111000001110000000000000
01111111110000001110000000000000
01110111100000001110000111000000
01110011110011101111001111011100
01110001111011100111111110011100
00000000000000000000000000000000\
'''
rc01 = '''\
00000000000000000000000000000000000000000000000000000000000
01111111111111111100000000000000000001111111111111000000000
01111111111111111110000000000000001111111111111111000000000
01111111111111111111000000000000111111111111111111000000000
01111111100000111111100000000001111111111111111111000000000
00011111100000111111100000000011111110000000111111000000000
00011111100000111111100000000111111100000000000000000000000
00011111111111111111000000000111111100000000000000000000000
00011111111111111110000000000111111100000000000000000000000
00011111111111111111000000000111111100000000000000000000000
00011111100000111111100000000111111100000000000000000000000
00011111100000111111100000000111111100000000000000000000000
00011111100000111111100000000011111110000000111111000000000
01111111100000111111100000000001111111111111111111000000000
01111111100000111111101111110000111111111111111111011111100
01111111100000111111101111110000001111111111111111011111100
01111111100000111111101111110000000001111111111111011111100
00000000000000000000000000000000000000000000000000000000000\
'''
def intarray(binstring):
'''Change a 2D matrix of 01 chars into a list of lists of ints'''
return [[1 if ch == '1' else 0 for ch in line]
for line in binstring.strip().split()]
def chararray(intmatrix):
'''Change a 2d list of lists of 1/0 ints into lines of 1/0 chars'''
return '\n'.join(''.join(str(p) for p in row) for row in intmatrix)
def toTxt(intmatrix):
'''Change a 2d list of lists of 1/0 ints into lines of '#' and '.' chars'''
return '\n'.join(''.join(('#' if p else '.') for p in row) for row in intmatrix)
def neighbours(x, y, image):
'''Return 8-neighbours of point p1 of picture, in order'''
i = image
x1, y1, x_1, y_1 = x+1, y-1, x-1, y+1
#print ((x,y))
return [i[y1][x], i[y1][x1], i[y][x1], i[y_1][x1], # P2,P3,P4,P5
i[y_1][x], i[y_1][x_1], i[y][x_1], i[y1][x_1]] # P6,P7,P8,P9
def transitions(neighbours):
n = neighbours + neighbours[0:1] # P2, ... P9, P2
return sum((n1, n2) == (0, 1) for n1, n2 in zip(n, n[1:]))
def zhangSuen(image):
changing1 = changing2 = [(-1, -1)]
while changing1 or changing2:
# Step 1
changing1 = []
for y in range(1, len(image) - 1):
for x in range(1, len(image[0]) - 1):
P2,P3,P4,P5,P6,P7,P8,P9 = n = neighbours(x, y, image)
if (image[y][x] == 1 and # (Condition 0)
P4 * P6 * P8 == 0 and # Condition 4
P2 * P4 * P6 == 0 and # Condition 3
transitions(n) == 1 and # Condition 2
2 <= sum(n) <= 6): # Condition 1
changing1.append((x,y))
for x, y in changing1: image[y][x] = 0
# Step 2
changing2 = []
for y in range(1, len(image) - 1):
for x in range(1, len(image[0]) - 1):
P2,P3,P4,P5,P6,P7,P8,P9 = n = neighbours(x, y, image)
if (image[y][x] == 1 and # (Condition 0)
P2 * P6 * P8 == 0 and # Condition 4
P2 * P4 * P8 == 0 and # Condition 3
transitions(n) == 1 and # Condition 2
2 <= sum(n) <= 6): # Condition 1
changing2.append((x,y))
for x, y in changing2: image[y][x] = 0
#print changing1
#print changing2
return image
if __name__ == '__main__':
for picture in (beforeTxt, smallrc01, rc01):
image = intarray(picture)
print('\nFrom:\n%s' % toTxt(image))
after = zhangSuen(image)
print('\nTo thinned:\n%s' % toTxt(after)) |
100 doors | Ruby | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and ''toggle'' the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
;Task:
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
'''Alternate:'''
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| class Door
attr_reader :state
def initialize
@state = :closed
end
def close
@state = :closed
end
def open
@state = :open
end
def closed?
@state == :closed
end
def open?
@state == :open
end
def toggle
if closed? then open else close end
end
def to_s
@state.to_s
end
end
doors = Array.new(100) { Door.new }
1.upto(100) do |multiplier|
doors.each_with_index do |door, i|
door.toggle if (i + 1) % multiplier == 0
end
end
doors.each_with_index { |door, i| puts "Door #{i+1} is #{door}." } |
100 prisoners | Ruby | The Problem:
* 100 prisoners are individually numbered 1 to 100
* A room having a cupboard of 100 opaque drawers numbered 1 to 100, that cannot be seen from outside.
* Cards numbered 1 to 100 are placed randomly, one to a drawer, and the drawers all closed; at the start.
* Prisoners start outside the room
:* They can decide some strategy before any enter the room.
:* Prisoners enter the room one by one, can open a drawer, inspect the card number in the drawer, then close the drawer.
:* A prisoner can open no more than 50 drawers.
:* A prisoner tries to find his own number.
:* A prisoner finding his own number is then held apart from the others.
* If '''all''' 100 prisoners find their own numbers then they will all be pardoned. If ''any'' don't then ''all'' sentences stand.
;The task:
# Simulate several thousand instances of the game where the prisoners randomly open drawers
# Simulate several thousand instances of the game where the prisoners use the optimal strategy mentioned in the Wikipedia article, of:
:* First opening the drawer whose outside number is his prisoner number.
:* If the card within has his number then he succeeds otherwise he opens the drawer with the same number as that of the revealed card. (until he opens his maximum).
Show and compare the computed probabilities of success for the two strategies, here, on this page.
;References:
# The unbelievable solution to the 100 prisoner puzzle standupmaths (Video).
# [[wp:100 prisoners problem]]
# 100 Prisoners Escape Puzzle DataGenetics.
# Random permutation statistics#One hundred prisoners on Wikipedia.
| prisoners = [*1..100]
N = 10_000
generate_rooms = ->{ [nil]+[*1..100].shuffle }
res = N.times.count do
rooms = generate_rooms[]
prisoners.all? {|pr| rooms[1,100].sample(50).include?(pr)}
end
puts "Random strategy : %11.4f %%" % (res.fdiv(N) * 100)
res = N.times.count do
rooms = generate_rooms[]
prisoners.all? do |pr|
cur_room = pr
50.times.any? do
found = (rooms[cur_room] == pr)
cur_room = rooms[cur_room]
found
end
end
end
puts "Optimal strategy: %11.4f %%" % (res.fdiv(N) * 100)
|
15 puzzle game | Ruby | Implement the Fifteen Puzzle Game.
The '''15-puzzle''' is also known as:
:::* '''Fifteen Puzzle'''
:::* '''Gem Puzzle'''
:::* '''Boss Puzzle'''
:::* '''Game of Fifteen'''
:::* '''Mystic Square'''
:::* '''14-15 Puzzle'''
:::* and some others.
;Related Tasks:
:* 15 Puzzle Solver
:* [[16 Puzzle Game]]
| require 'io/console'
class Board
SIZE = 4
RANGE = 0...SIZE
def initialize
width = (SIZE*SIZE-1).to_s.size
@frame = ("+" + "-"*(width+2)) * SIZE + "+"
@form = "| %#{width}d " * SIZE + "|"
@step = 0
@orign = [*0...SIZE*SIZE].rotate.each_slice(SIZE).to_a.freeze
@board = @orign.map{|row | row.dup}
randomize
draw
message
play
end
private
def randomize
@board[0][0], @board[SIZE-1][SIZE-1] = 0, 1
@board[SIZE-1][0], @board[0][SIZE-1] = @board[0][SIZE-1], @board[SIZE-1][0]
x, y, dx, dy = 0, 0, 1, 0
50.times do
nx,ny = [[x+dx,y+dy], [x+dy,y-dx], [x-dy,y+dx]]
.select{|nx,ny| RANGE.include?(nx) and RANGE.include?(ny)}
.sample
@board[nx][ny], @board[x][y] = 0, @board[nx][ny]
x, y, dx, dy = nx, ny, nx-x, ny-y
end
@x, @y = x, y
end
def draw
puts "\e[H\e[2J"
@board.each do |row|
puts @frame
puts (@form % row).sub(" 0 ", " ")
end
puts @frame
puts "Step: #{@step}"
end
DIR = {up: [-1,0], down: [1,0], left: [0,-1], right: [0,1]}
def move(direction)
dx, dy = DIR[direction]
nx, ny = @x + dx, @y + dy
if RANGE.include?(nx) and RANGE.include?(ny)
@board[nx][ny], @board[@x][@y] = 0, @board[nx][ny]
@x, @y = nx, ny
@step += 1
draw
end
end
def play
until @board == @orign
case key_in
when "\e[A", "w" then move(:up)
when "\e[B", "s" then move(:down)
when "\e[C", "d" then move(:right)
when "\e[D", "a" then move(:left)
when "q","\u0003","\u0004" then exit
when "h" then message
end
end
puts "Congratulations, you have won!"
end
def key_in
input = STDIN.getch
if input == "\e"
2.times {input << STDIN.getch}
end
input
end
def message
puts <<~EOM
Use the arrow-keys or WASD on your keyboard to push board in the given direction.
PRESS q TO QUIT (or Ctrl-C or Ctrl-D)
EOM
end
end
Board.new |
21 game | Ruby | '''21''' is a two player game, the game is played by choosing
a number ('''1''', '''2''', or '''3''') to be added to the ''running total''.
The game is won by the player whose chosen number causes the ''running total''
to reach ''exactly'' '''21'''.
The ''running total'' starts at zero.
One player will be the computer.
Players alternate supplying a number to be added to the ''running total''.
;Task:
Write a computer program that will:
::* do the prompting (or provide a button menu),
::* check for errors and display appropriate error messages,
::* do the additions (add a chosen number to the ''running total''),
::* display the ''running total'',
::* provide a mechanism for the player to quit/exit/halt/stop/close the program,
::* issue a notification when there is a winner, and
::* determine who goes first (maybe a random or user choice, or can be specified when the game begins).
| # 21 Game - an example in Ruby for Rosetta Code.
GOAL = 21
MIN_MOVE = 1
MAX_MOVE = 3
DESCRIPTION = "
*** Welcome to the 21 Game! ***
21 is a two player game.
Each player chooses to add 1, 2 or 3 to a running total.
The player whose turn it is when the total reaches 21 will win the game.
The running total starts at zero.
The players start the game in turn.
Enter q to quit at any time.
"
#
# Returns the best move to play.
#
def best_move(total)
move = rand(1..3)
MIN_MOVE.upto(MAX_MOVE) do |i|
move = i if (total + i - 1) % (MAX_MOVE + 1) == 0
end
MIN_MOVE.upto(MAX_MOVE) do |i|
move = i if total + i == GOAL
end
move
end
#
# Gets the move of the player.
#
def get_move
print "Your choice between #{MIN_MOVE} and #{MAX_MOVE}: "
answer = gets
move = answer.to_i
until move.between?(MIN_MOVE, MAX_MOVE)
exit if answer.chomp == 'q'
print 'Invalid choice. Try again: '
answer = gets
move = answer.to_i
end
move
end
#
# Asks the player to restart a game and returns the answer.
#
def restart?
print 'Do you want to restart (y/n)? '
restart = gets.chomp
until ['y', 'n'].include?(restart)
print 'Your answer is not a valid choice. Try again: '
restart = gets.chomp
end
restart == 'y'
end
#
# Run a game. The +player+ argument is the player that starts:
# * 1 for human
# * 0 for computer
#
def game(player)
total = round = 0
while total < GOAL
round += 1
puts "--- ROUND #{round} ---\n\n"
player = (player + 1) % 2
if player == 0
move = best_move(total)
puts "The computer chooses #{move}."
else
move = get_move
end
total += move
puts "Running total is now #{total}.\n\n"
end
if player == 0
puts 'Sorry, the computer has won!'
return false
end
puts 'Well done, you have won!'
true
end
# MAIN
puts DESCRIPTION
run = true
computer_wins = human_wins = 0
games_counter = player = 1
while run
puts "\n=== START GAME #{games_counter} ==="
player = (player + 1) % 2
if game(player)
human_wins += 1
else
computer_wins += 1
end
puts "\nComputer wins #{computer_wins} games, you wins #{human_wins} game."
games_counter += 1
run = restart?
end
puts 'Good bye!'
|
24 game | Ruby | The 24 Game tests one's mental arithmetic.
;Task
Write a program that displays four digits, each from 1 --> 9 (inclusive) with repetitions allowed.
The program should prompt for the player to enter an arithmetic expression using ''just'' those, and ''all'' of those four digits, used exactly ''once'' each. The program should ''check'' then evaluate the expression.
The goal is for the player to enter an expression that (numerically) evaluates to '''24'''.
* Only the following operators/functions are allowed: multiplication, division, addition, subtraction
* Division should use floating point or rational arithmetic, etc, to preserve remainders.
* Brackets are allowed, if using an infix expression evaluator.
* Forming multiple digit numbers from the supplied digits is ''disallowed''. (So an answer of 12+12 when given 1, 2, 2, and 1 is wrong).
* The order of the digits when given does not have to be preserved.
;Notes
* The type of expression evaluator used is not mandated. An RPN evaluator is equally acceptable for example.
* The task is not for the program to generate the expression, or test whether an expression is even possible.
;Related tasks
* [[24 game/Solve]]
;Reference
* The 24 Game on h2g2.
| class Guess < String
def self.play
nums = Array.new(4){rand(1..9)}
loop do
result = get(nums).evaluate!
break if result == 24.0
puts "Try again! That gives #{result}!"
end
puts "You win!"
end
def self.get(nums)
loop do
print "\nEnter a guess using #{nums}: "
input = gets.chomp
return new(input) if validate(input, nums)
end
end
def self.validate(guess, nums)
name, error =
{
invalid_character: ->(str){ !str.scan(%r{[^\d\s()+*/-]}).empty? },
wrong_number: ->(str){ str.scan(/\d/).map(&:to_i).sort != nums.sort },
multi_digit_number: ->(str){ str.match(/\d\d/) }
}
.find {|name, validator| validator[guess] }
error ? puts("Invalid input of a(n) #{name.to_s.tr('_',' ')}!") : true
end
def evaluate!
as_rat = gsub(/(\d)/, '\1r') # r : Rational suffix
eval "(#{as_rat}).to_f"
rescue SyntaxError
"[syntax error]"
end
end
Guess.play |
24 game/Solve | Ruby 2.1 | Write a program that takes four digits, either from user input or by random generation, and computes arithmetic expressions following the rules of the [[24 game]].
Show examples of solutions generated by the program.
;Related task:
* [[Arithmetic Evaluator]]
| class TwentyFourGame
EXPRESSIONS = [
'((%dr %s %dr) %s %dr) %s %dr',
'(%dr %s (%dr %s %dr)) %s %dr',
'(%dr %s %dr) %s (%dr %s %dr)',
'%dr %s ((%dr %s %dr) %s %dr)',
'%dr %s (%dr %s (%dr %s %dr))',
]
OPERATORS = [:+, :-, :*, :/].repeated_permutation(3).to_a
def self.solve(digits)
solutions = []
perms = digits.permutation.to_a.uniq
perms.product(OPERATORS, EXPRESSIONS) do |(a,b,c,d), (op1,op2,op3), expr|
# evaluate using rational arithmetic
text = expr % [a, op1, b, op2, c, op3, d]
value = eval(text) rescue next # catch division by zero
solutions << text.delete("r") if value == 24
end
solutions
end
end
# validate user input
digits = ARGV.map do |arg|
begin
Integer(arg)
rescue ArgumentError
raise "error: not an integer: '#{arg}'"
end
end
digits.size == 4 or raise "error: need 4 digits, only have #{digits.size}"
solutions = TwentyFourGame.solve(digits)
if solutions.empty?
puts "no solutions"
else
puts "found #{solutions.size} solutions, including #{solutions.first}"
puts solutions.sort
end |
4-rings or 4-squares puzzle | Ruby | Replace '''a, b, c, d, e, f,''' and
'''g ''' with the decimal
digits LOW ---> HIGH
such that the sum of the letters inside of each of the four large squares add up to
the same sum.
+--------------+ +--------------+
| | | |
| a | | e |
| | | |
| +---+------+---+ +---+---------+
| | | | | | | |
| | b | | d | | f | |
| | | | | | | |
| | | | | | | |
+----------+---+ +---+------+---+ |
| c | | g |
| | | |
| | | |
+--------------+ +-------------+
Show all output here.
:* Show all solutions for each letter being unique with
LOW=1 HIGH=7
:* Show all solutions for each letter being unique with
LOW=3 HIGH=9
:* Show only the ''number'' of solutions when each letter can be non-unique
LOW=0 HIGH=9
;Related task:
* [[Solve the no connection puzzle]]
| def four_squares(low, high, unique=true, show=unique)
f = -> (a,b,c,d,e,f,g) {[a+b, b+c+d, d+e+f, f+g].uniq.size == 1}
if unique
uniq = "unique"
solutions = [*low..high].permutation(7).select{|ary| f.call(*ary)}
else
uniq = "non-unique"
solutions = [*low..high].repeated_permutation(7).select{|ary| f.call(*ary)}
end
if show
puts " " + [*"a".."g"].join(" ")
solutions.each{|ary| p ary}
end
puts "#{solutions.size} #{uniq} solutions in #{low} to #{high}"
puts
end
[[1,7], [3,9]].each do |low, high|
four_squares(low, high)
end
four_squares(0, 9, false) |
99 bottles of beer | Ruby | Display the complete lyrics for the song: '''99 Bottles of Beer on the Wall'''.
;The beer song:
The lyrics follow this form:
::: 99 bottles of beer on the wall
::: 99 bottles of beer
::: Take one down, pass it around
::: 98 bottles of beer on the wall
::: 98 bottles of beer on the wall
::: 98 bottles of beer
::: Take one down, pass it around
::: 97 bottles of beer on the wall
... and so on, until reaching '''0''' (zero).
Grammatical support for ''1 bottle of beer'' is optional.
As with any puzzle, try to do it in as creative/concise/comical a way
as possible (simple, obvious solutions allowed, too).
;See also:
* http://99-bottles-of-beer.net/
* [[:Category:99_Bottles_of_Beer]]
* [[:Category:Programming language families]]
* Wikipedia 99 bottles of beer
| def bottles(beer, wall = false)
"#{beer>0 ? beer : "no more"} bottle#{"s" if beer!=1} of beer#{" on the wall" if wall}"
end
99.downto(0) do |remaining|
puts "#{bottles(remaining,true).capitalize}, #{bottles(remaining)}."
if remaining==0
print "Go to the store and buy some more"
remaining=100
else
print "Take one down, pass it around"
end
puts ", #{bottles(remaining-1,true)}.\n\n"
end |
9 billion names of God the integer | Ruby | This task is a variation of the short story by Arthur C. Clarke.
(Solvers should be aware of the consequences of completing this task.)
In detail, to specify what is meant by a "name":
:The integer 1 has 1 name "1".
:The integer 2 has 2 names "1+1", and "2".
:The integer 3 has 3 names "1+1+1", "2+1", and "3".
:The integer 4 has 5 names "1+1+1+1", "2+1+1", "2+2", "3+1", "4".
:The integer 5 has 7 names "1+1+1+1+1", "2+1+1+1", "2+2+1", "3+1+1", "3+2", "4+1", "5".
;Task
Display the first 25 rows of a number triangle which begins:
1
1 1
1 1 1
1 2 1 1
1 2 2 1 1
1 3 3 2 1 1
Where row n corresponds to integer n, and each column C in row m from left to right corresponds to the number of names beginning with C.
A function G(n) should return the sum of the n-th row.
Demonstrate this function by displaying: G(23), G(123), G(1234), and G(12345).
Optionally note that the sum of the n-th row P(n) is the integer partition function.
Demonstrate this is equivalent to G(n) by displaying: P(23), P(123), P(1234), and P(12345).
;Extra credit
If your environment is able, plot P(n) against n for n=1\ldots 999.
;Related tasks
* [[Partition function P]]
| # Generate IPF triangle
# Nigel_Galloway: May 1st., 2013.
def g(n,g)
return 1 unless 1 < g and g < n-1
(2..g).inject(1){|res,q| res + (q > n-g ? 0 : g(n-g,q))}
end
(1..25).each {|n|
puts (1..n).map {|g| "%4s" % g(n,g)}.join
}
|
ABC problem | Ruby | You are given a collection of ABC blocks (maybe like the ones you had when you were a kid).
There are twenty blocks with two letters on each block.
A complete alphabet is guaranteed amongst all sides of the blocks.
The sample collection of blocks:
(B O)
(X K)
(D Q)
(C P)
(N A)
(G T)
(R E)
(T G)
(Q D)
(F S)
(J W)
(H U)
(V I)
(A N)
(O B)
(E R)
(F S)
(L Y)
(P C)
(Z M)
;Task:
Write a function that takes a string (word) and determines whether the word can be spelled with the given collection of blocks.
The rules are simple:
::# Once a letter on a block is used that block cannot be used again
::# The function should be case-insensitive
::# Show the output on this page for the following 7 words in the following example
;Example:
>>> can_make_word("A")
True
>>> can_make_word("BARK")
True
>>> can_make_word("BOOK")
False
>>> can_make_word("TREAT")
True
>>> can_make_word("COMMON")
False
>>> can_make_word("SQUAD")
True
>>> can_make_word("CONFUSE")
True
| words = %w(A BaRK BOoK tREaT COmMOn SqUAD CoNfuSE) << ""
words.each do |word|
blocks = "BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM"
res = word.each_char.all?{|c| blocks.sub!(/\w?#{c}\w?/i, "")} #regexps can be interpolated like strings
puts "#{word.inspect}: #{res}"
end
|
ASCII art diagram converter | Ruby | Given the RFC 1035 message diagram from Section 4.1.1 (Header section format) as a string:
http://www.ietf.org/rfc/rfc1035.txt
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| ID |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
|QR| Opcode |AA|TC|RD|RA| Z | RCODE |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| QDCOUNT |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| ANCOUNT |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| NSCOUNT |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| ARCOUNT |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
Where (every column of the table is 1 bit):
ID is 16 bits
QR = Query (0) or Response (1)
Opcode = Four bits defining kind of query:
0: a standard query (QUERY)
1: an inverse query (IQUERY)
2: a server status request (STATUS)
3-15: reserved for future use
AA = Authoritative Answer bit
TC = Truncation bit
RD = Recursion Desired bit
RA = Recursion Available bit
Z = Reserved
RCODE = Response code
QC = Question Count
ANC = Answer Count
AUC = Authority Count
ADC = Additional Count
Write a function, member function, class or template that accepts a similar multi-line string as input to define a data structure or something else able to decode or store a header with that specified bit structure.
If your language has macros, introspection, code generation, or powerful enough templates, then accept such string at compile-time to define the header data structure statically.
Such "Header" function or template should accept a table with 8, 16, 32 or 64 columns, and any number of rows. For simplicity the only allowed symbols to define the table are + - | (plus, minus, pipe), and whitespace. Lines of the input string composed just of whitespace should be ignored. Leading and trailing whitespace in the input string should be ignored, as well as before and after each table row. The box for each bit of the diagram takes four chars "+--+". The code should perform a little of validation of the input string, but for brevity a full validation is not required.
Bonus: perform a thoroughly validation of the input string.
| header = <<HEADER
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| ID |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
|QR| Opcode |AA|TC|RD|RA| Z | RCODE |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| QDCOUNT |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| ANCOUNT |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| NSCOUNT |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| ARCOUNT |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
HEADER
Item = Struct.new(:name, :bits, :range)
RE = /\| *\w+ */
i = 0
table = header.scan(RE).map{|m| Item.new( m.delete("^A-Za-z"), b = m.size/3, i...(i += b)) }
teststr = "78477bbf5496e12e1bf169a4"
padding = table.sum(&:bits)
binstr = teststr.hex.to_s(2).rjust(padding, "0")
table.each{|el| p el.values}; puts
table.each{|el| puts "%7s, %2d bits: %s" % [el.name, el.bits, binstr[el.range] ]}
|
Abbreviations, automatic | Ruby | The use of abbreviations (also sometimes called synonyms, nicknames, AKAs, or aliases) can be an
easy way to add flexibility when specifying or using commands, sub-commands, options, etc.
It would make a list of words easier to maintain (as words are added, changed, and/or deleted) if
the minimum abbreviation length of that list could be automatically (programmatically) determined.
For this task, use the list (below) of the days-of-the-week names that are expressed in about a hundred languages (note that there is a blank line in the list).
Sunday Monday Tuesday Wednesday Thursday Friday Saturday
Sondag Maandag Dinsdag Woensdag Donderdag Vrydag Saterdag
E_djele E_hene E_marte E_merkure E_enjte E_premte E_shtune
Ehud Segno Maksegno Erob Hamus Arbe Kedame
Al_Ahad Al_Ithinin Al_Tholatha'a Al_Arbia'a Al_Kamis Al_Gomia'a Al_Sabit
Guiragui Yergou_shapti Yerek_shapti Tchorek_shapti Hink_shapti Ourpat Shapat
domingu llunes martes miercoles xueves vienres sabadu
Bazar_gUnU Birinci_gUn Ckinci_gUn UcUncU_gUn DOrdUncU_gUn Bes,inci_gUn Altonco_gUn
Igande Astelehen Astearte Asteazken Ostegun Ostiral Larunbat
Robi_bar Shom_bar Mongal_bar Budhh_bar BRihashpati_bar Shukro_bar Shoni_bar
Nedjelja Ponedeljak Utorak Srijeda Cxetvrtak Petak Subota
Disul Dilun Dimeurzh Dimerc'her Diriaou Digwener Disadorn
nedelia ponedelnik vtornik sriada chetvartak petak sabota
sing_kei_yaht sing_kei_yat sing_kei_yee sing_kei_saam sing_kei_sie sing_kei_ng sing_kei_luk
Diumenge Dilluns Dimarts Dimecres Dijous Divendres Dissabte
Dzeenkk-eh Dzeehn_kk-ehreh Dzeehn_kk-ehreh_nah_kay_dzeeneh Tah_neesee_dzeehn_neh Deehn_ghee_dzee-neh Tl-oowey_tts-el_dehlee Dzeentt-ahzee
dy_Sul dy_Lun dy_Meurth dy_Mergher dy_You dy_Gwener dy_Sadorn
Dimanch Lendi Madi Mekredi Jedi Vandredi Samdi
nedjelja ponedjeljak utorak srijeda cxetvrtak petak subota
nede^le ponde^li utery str^eda c^tvrtek patek sobota
Sondee Mondee Tiisiday Walansedee TOOsedee Feraadee Satadee
s0ndag mandag tirsdag onsdag torsdag fredag l0rdag
zondag maandag dinsdag woensdag donderdag vrijdag zaterdag
Diman^co Lundo Mardo Merkredo ^Jaudo Vendredo Sabato
pUhapaev esmaspaev teisipaev kolmapaev neljapaev reede laupaev
Diu_prima Diu_sequima Diu_tritima Diu_quartima Diu_quintima Diu_sextima Diu_sabbata
sunnudagur manadagur tysdaguy mikudagur hosdagur friggjadagur leygardagur
Yek_Sham'beh Do_Sham'beh Seh_Sham'beh Cha'har_Sham'beh Panj_Sham'beh Jom'eh Sham'beh
sunnuntai maanantai tiistai keskiviiko torsktai perjantai lauantai
dimanche lundi mardi mercredi jeudi vendredi samedi
Snein Moandei Tiisdei Woansdei Tonersdei Freed Sneon
Domingo Segunda_feira Martes Mercores Joves Venres Sabado
k'vira orshabati samshabati otkhshabati khutshabati p'arask'evi shabati
Sonntag Montag Dienstag Mittwoch Donnerstag Freitag Samstag
Kiriaki' Defte'ra Tri'ti Teta'rti Pe'mpti Paraskebi' Sa'bato
ravivaar somvaar mangalvaar budhvaar guruvaar shukravaar shanivaar
popule po`akahi po`alua po`akolu po`aha po`alima po`aono
Yom_rishon Yom_sheni Yom_shlishi Yom_revi'i Yom_chamishi Yom_shishi Shabat
ravivara somavar mangalavar budhavara brahaspativar shukravara shanivar
vasarnap hetfo kedd szerda csutortok pentek szombat
Sunnudagur Manudagur +ridjudagur Midvikudagar Fimmtudagur FOstudagur Laugardagur
sundio lundio mardio merkurdio jovdio venerdio saturdio
Minggu Senin Selasa Rabu Kamis Jumat Sabtu
Dominica Lunedi Martedi Mercuridi Jovedi Venerdi Sabbato
De_Domhnaigh De_Luain De_Mairt De_Ceadaoin De_ardaoin De_hAoine De_Sathairn
domenica lunedi martedi mercoledi giovedi venerdi sabato
Nichiyou_bi Getzuyou_bi Kayou_bi Suiyou_bi Mokuyou_bi Kin'you_bi Doyou_bi
Il-yo-il Wol-yo-il Hwa-yo-il Su-yo-il Mok-yo-il Kum-yo-il To-yo-il
Dies_Dominica Dies_Lunae Dies_Martis Dies_Mercurii Dies_Iovis Dies_Veneris Dies_Saturni
sve-tdien pirmdien otrdien tresvdien ceturtdien piektdien sestdien
Sekmadienis Pirmadienis Antradienis Trec^iadienis Ketvirtadienis Penktadienis S^es^tadienis
Wangu Kazooba Walumbe Mukasa Kiwanuka Nnagawonye Wamunyi
xing-_qi-_ri xing-_qi-_yi-. xing-_qi-_er xing-_qi-_san-. xing-_qi-_si xing-_qi-_wuv. xing-_qi-_liu
Jedoonee Jelune Jemayrt Jecrean Jardaim Jeheiney Jesam
Jabot Manre Juje Wonje Taije Balaire Jarere
geminrongo minomishi martes mierkoles misheushi bernashi mishabaro
Ahad Isnin Selasa Rabu Khamis Jumaat Sabtu
sphndag mandag tirsdag onsdag torsdag fredag lphrdag
lo_dimenge lo_diluns lo_dimarc lo_dimercres lo_dijous lo_divendres lo_dissabte
djadomingo djaluna djamars djarason djaweps djabierna djasabra
Niedziela Poniedzial/ek Wtorek S,roda Czwartek Pia,tek Sobota
Domingo segunda-feire terca-feire quarta-feire quinta-feire sexta-feira sabado
Domingo Lunes martes Miercoles Jueves Viernes Sabado
Duminica Luni Mart'i Miercuri Joi Vineri Sambata
voskresenie ponedelnik vtornik sreda chetverg pyatnitsa subbota
Sunday Di-luain Di-mairt Di-ciadain Di-ardaoin Di-haoine Di-sathurne
nedjelja ponedjeljak utorak sreda cxetvrtak petak subota
Sontaha Mmantaha Labobedi Laboraro Labone Labohlano Moqebelo
Iridha- Sandhudha- Anga.haruwa-dha- Badha-dha- Brahaspa.thindha- Sikura-dha- Sena.sura-dha-
nedel^a pondelok utorok streda s^tvrtok piatok sobota
Nedelja Ponedeljek Torek Sreda Cxetrtek Petek Sobota
domingo lunes martes miercoles jueves viernes sabado
sonde mundey tude-wroko dride-wroko fode-wroko freyda Saturday
Jumapili Jumatatu Jumanne Jumatano Alhamisi Ijumaa Jumamosi
sondag mandag tisdag onsdag torsdag fredag lordag
Linggo Lunes Martes Miyerkoles Huwebes Biyernes Sabado
Le-pai-jit Pai-it Pai-ji Pai-san Pai-si Pai-gO. Pai-lak
wan-ar-tit wan-tjan wan-ang-kaan wan-phoet wan-pha-ru-hat-sa-boh-die wan-sook wan-sao
Tshipi Mosupologo Labobedi Laboraro Labone Labotlhano Matlhatso
Pazar Pazartesi Sali Car,samba Per,sembe Cuma Cumartesi
nedilya ponedilok vivtorok sereda chetver pyatnytsya subota
Chu?_Nha.t Thu*_Hai Thu*_Ba Thu*_Tu* Thu*_Na'm Thu*_Sau Thu*_Ba?y
dydd_Sul dyds_Llun dydd_Mawrth dyds_Mercher dydd_Iau dydd_Gwener dyds_Sadwrn
Dibeer Altine Talaata Allarba Al_xebes Aljuma Gaaw
iCawa uMvulo uLwesibini uLwesithathu uLuwesine uLwesihlanu uMgqibelo
zuntik montik dinstik mitvokh donershtik fraytik shabes
iSonto uMsombuluko uLwesibili uLwesithathu uLwesine uLwesihlanu uMgqibelo
Dies_Dominica Dies_Lunae Dies_Martis Dies_Mercurii Dies_Iovis Dies_Veneris Dies_Saturni
Bazar_gUnU Bazar_aertaesi Caers,aenbae_axs,amo Caers,aenbae_gUnU CUmae_axs,amo CUmae_gUnU CUmae_Senbae
Sun Moon Mars Mercury Jove Venus Saturn
zondag maandag dinsdag woensdag donderdag vrijdag zaterdag
KoseEraa GyoOraa BenEraa Kuoraa YOwaaraa FeEraa Memenaa
Sonntag Montag Dienstag Mittwoch Donnerstag Freitag Sonnabend
Domingo Luns Terza_feira Corta_feira Xoves Venres Sabado
Dies_Solis Dies_Lunae Dies_Martis Dies_Mercurii Dies_Iovis Dies_Veneris Dies_Sabbatum
xing-_qi-_tian xing-_qi-_yi-. xing-_qi-_er xing-_qi-_san-. xing-_qi-_si xing-_qi-_wuv. xing-_qi-_liu
djadomingu djaluna djamars djarason djaweps djabierne djasabra
Killachau Atichau Quoyllurchau Illapachau Chaskachau Kuychichau Intichau
''Caveat: The list (above) most surely contains errors (or, at the least, differences) of what the actual (or true) names for the days-of-the-week.''
To make this Rosetta Code task page as small as possible, if processing the complete list, read the days-of-the-week from a file (that is created from the above list).
Notes concerning the above list of words
::* each line has a list of days-of-the-week for a language, separated by at least one blank
::* the words on each line happen to be in order, from Sunday --> Saturday
::* most lines have words in mixed case and some have all manner of accented words and other characters
::* some words were translated to the nearest character that was available to ''code page'' '''437'''
::* the characters in the words are not restricted except that they may not have imbedded blanks
::* for this example, the use of an underscore ('''_''') was used to indicate a blank in a word
;Task:
::* The list of words (days of the week) needn't be verified/validated.
::* Write a function to find the (numeric) minimum length abbreviation for each line that would make abbreviations unique.
::* A blank line (or a null line) should return a null string.
::* Process and show the output for at least the first '''five''' lines of the file.
::* Show all output here.
| require "abbrev"
File.read("daynames.txt").each_line do |line|
next if line.strip.empty?
abbr = line.split.abbrev.invert
puts "Minimum size: #{abbr.values.max_by(&:size).size}", abbr.inspect, "\n"
end
|
Abbreviations, easy | Ruby | This task is an easier (to code) variant of the Rosetta Code task: [[Abbreviations, simple]].
For this task, the following ''command table'' will be used:
Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy
COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find
NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput
Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO
MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT
READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT
RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up
Notes concerning the above ''command table'':
::* it can be thought of as one long literal string (with blanks at end-of-lines)
::* it may have superfluous blanks
::* it may be in any case (lower/upper/mixed)
::* the order of the words in the ''command table'' must be preserved as shown
::* the user input(s) may be in any case (upper/lower/mixed)
::* commands will be restricted to the Latin alphabet (A --> Z, a --> z)
::* A valid abbreviation is a word that has:
:::* at least the minimum length of the number of capital letters of the word in the ''command table''
:::* compares equal (regardless of case) to the leading characters of the word in the ''command table''
:::* a length not longer than the word in the ''command table''
::::* '''ALT''', '''aLt''', '''ALTE''', and '''ALTER''' are all abbreviations of '''ALTer'''
::::* '''AL''', '''ALF''', '''ALTERS''', '''TER''', and '''A''' aren't valid abbreviations of '''ALTer'''
::::* The number of capital letters in '''ALTer''' indicates that any abbreviation for '''ALTer''' must be at least three letters
::::* Any word longer than five characters can't be an abbreviation for '''ALTer'''
::::* '''o''', '''ov''', '''oVe''', '''over''', '''overL''', '''overla''' are all acceptable abbreviations for '''Overlay'''
::* if there isn't any lowercase letters in the word in the ''command table'', then there isn't an abbreviation permitted
;Task:
::* The command table needn't be verified/validated.
::* Write a function to validate if the user "words" (given as input) are valid (in the ''command table'').
::* If the word is valid, then return the full uppercase version of that "word".
::* If the word isn't valid, then return the lowercase string: '''*error*''' (7 characters).
::* A blank input (or a null input) should return a null string.
::* Show all output here.
;An example test case to be used for this task:
For a user string of:
riG rePEAT copies put mo rest types fup. 6 poweRin
the computer program should return the string:
RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT
| #!/usr/bin/env ruby
cmd_table = File.read(ARGV[0]).split
user_str = File.read(ARGV[1]).split
user_str.each do |abbr|
candidate = cmd_table.find do |cmd|
cmd.count('A-Z') <= abbr.length && abbr.casecmp(cmd[0...abbr.length]).zero?
end
print candidate.nil? ? '*error*' : candidate.upcase
print ' '
end
puts
|
Abbreviations, simple | Ruby | The use of abbreviations (also sometimes called synonyms, nicknames, AKAs, or aliases) can be an
easy way to add flexibility when specifying or using commands, sub-commands, options, etc.
For this task, the following ''command table'' will be used:
add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3
compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate
3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2
forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load
locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2
msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3
refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left
2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1
Notes concerning the above ''command table'':
::* it can be thought of as one long literal string (with blanks at end-of-lines)
::* it may have superfluous blanks
::* it may be in any case (lower/upper/mixed)
::* the order of the words in the ''command table'' must be preserved as shown
::* the user input(s) may be in any case (upper/lower/mixed)
::* commands will be restricted to the Latin alphabet (A --> Z, a --> z)
::* a command is followed by an optional number, which indicates the minimum abbreviation
::* A valid abbreviation is a word that has:
:::* at least the minimum length of the word's minimum number in the ''command table''
:::* compares equal (regardless of case) to the leading characters of the word in the ''command table''
:::* a length not longer than the word in the ''command table''
::::* '''ALT''', '''aLt''', '''ALTE''', and '''ALTER''' are all abbreviations of '''ALTER 3'''
::::* '''AL''', '''ALF''', '''ALTERS''', '''TER''', and '''A''' aren't valid abbreviations of '''ALTER 3'''
::::* The '''3''' indicates that any abbreviation for '''ALTER''' must be at least three characters
::::* Any word longer than five characters can't be an abbreviation for '''ALTER'''
::::* '''o''', '''ov''', '''oVe''', '''over''', '''overL''', '''overla''' are all acceptable abbreviations for '''overlay 1'''
::* if there isn't a number after the command, then there isn't an abbreviation permitted
;Task:
::* The command table needn't be verified/validated.
::* Write a function to validate if the user "words" (given as input) are valid (in the ''command table'').
::* If the word is valid, then return the full uppercase version of that "word".
::* If the word isn't valid, then return the lowercase string: '''*error*''' (7 characters).
::* A blank input (or a null input) should return a null string.
::* Show all output here.
;An example test case to be used for this task:
For a user string of:
riG rePEAT copies put mo rest types fup. 6 poweRin
the computer program should return the string:
RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT
| str = "add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3
compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate
3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2
forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load
locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2
msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3
refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left
2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1"
RE = /(?<word1>[a-zA-Z]+)\s+(?<word2>[a-zA-Z]+)/
str = str.upcase
# add missing wordsizes
2.times{ str.gsub!(RE){ [ $~[:word1], $~[:word1].size, $~[:word2] ].join(" ")} }
table = Hash[*str.split].transform_values(&:to_i)
test = "riG rePEAT copies put mo rest types fup. 6 poweRin"
ar = test.split.map do |w|
(res = table.detect{|k,v| k.start_with?(w.upcase) && w.size >= v}) ? res[0] : "*error*"
end
puts ar.join(" ")
|
Abelian sandpile model/Identity | Ruby | Our sandpiles are based on a 3 by 3 rectangular grid giving nine areas that
contain a number from 0 to 3 inclusive. (The numbers are said to represent
grains of sand in each area of the sandpile).
E.g. s1 =
1 2 0
2 1 1
0 1 3
and s2 =
2 1 3
1 0 1
0 1 0
Addition on sandpiles is done by adding numbers in corresponding grid areas,
so for the above:
1 2 0 2 1 3 3 3 3
s1 + s2 = 2 1 1 + 1 0 1 = 3 1 2
0 1 3 0 1 0 0 2 3
If the addition would result in more than 3 "grains of sand" in any area then
those areas cause the whole sandpile to become "unstable" and the sandpile
areas are "toppled" in an "avalanche" until the "stable" result is obtained.
Any unstable area (with a number >= 4), is "toppled" by loosing one grain of
sand to each of its four horizontal or vertical neighbours. Grains are lost
at the edge of the grid, but otherwise increase the number in neighbouring
cells by one, whilst decreasing the count in the toppled cell by four in each
toppling.
A toppling may give an adjacent area more than four grains of sand leading to
a chain of topplings called an "avalanche".
E.g.
4 3 3 0 4 3 1 0 4 1 1 0 2 1 0
3 1 2 ==> 4 1 2 ==> 4 2 2 ==> 4 2 3 ==> 0 3 3
0 2 3 0 2 3 0 2 3 0 2 3 1 2 3
The final result is the stable sandpile on the right.
'''Note:''' The order in which cells are toppled does not affect the final result.
;Task:
* Create a class or datastructure and functions to represent and operate on sandpiles.
* Confirm the result of the avalanche of topplings shown above
* Confirm that s1 + s2 == s2 + s1 # Show the stable results
* If s3 is the sandpile with number 3 in every grid area, and s3_id is the following sandpile:
2 1 2
1 0 1
2 1 2
* Show that s3 + s3_id == s3
* Show that s3_id + s3_id == s3_id
Show confirming output here, with your examples.
;References:
* https://www.youtube.com/watch?v=1MtEUErz7Gg
* https://en.wikipedia.org/wiki/Abelian_sandpile_model
| class Sandpile
def initialize(ar) = @grid = ar
def to_a = @grid.dup
def + (other)
res = self.to_a.zip(other.to_a).map{|row1, row2| row1.zip(row2).map(&:sum) }
Sandpile.new(res)
end
def stable? = @grid.flatten.none?{|v| v > 3}
def avalanche
topple until stable?
self
end
def == (other) = self.avalanche.to_a == other.avalanche.to_a
def topple
a = @grid
a.each_index do |row|
a[row].each_index do |col|
next if a[row][col] < 4
a[row+1][col] += 1 unless row == a.size-1
a[row-1][col] += 1 if row > 0
a[row][col+1] += 1 unless col == a.size-1
a[row][col-1] += 1 if col > 0
a[row][col] -= 4
end
end
self
end
def to_s = "\n" + @grid.map {|row| row.join(" ") }.join("\n")
end
puts "Sandpile:"
puts demo = Sandpile.new( [[4,3,3], [3,1,2],[0,2,3]] )
puts "\nAfter the avalanche:"
puts demo.avalanche
puts "_" * 30,""
s1 = Sandpile.new([[1, 2, 0], [2, 1, 1], [0, 1, 3]] )
puts "s1: #{s1}"
s2 = Sandpile.new([[2, 1, 3], [1, 0, 1], [0, 1, 0]] )
puts "\ns2: #{s2}"
puts "\ns1 + s2 == s2 + s1: #{s1 + s2 == s2 + s1}"
puts "_" * 30,""
s3 = Sandpile.new([[3, 3, 3], [3, 3, 3], [3, 3, 3]] )
s3_id = Sandpile.new([[2, 1, 2], [1, 0, 1], [2, 1, 2]] )
puts "s3 + s3_id == s3: #{s3 + s3_id == s3}"
puts "s3_id + s3_id == s3_id: #{s3_id + s3_id == s3_id}"
|
Abundant odd numbers | Ruby | An Abundant number is a number '''n''' for which the ''sum of divisors'' '''s(n) > 2n''',
or, equivalently, the ''sum of proper divisors'' (or aliquot sum) '''s(n) > n'''.
;E.G.:
'''12''' is abundant, it has the proper divisors '''1,2,3,4 & 6''' which sum to '''16''' ( > '''12''' or '''n''');
or alternately, has the sigma sum of '''1,2,3,4,6 & 12''' which sum to '''28''' ( > '''24''' or '''2n''').
Abundant numbers are common, though '''even''' abundant numbers seem to be much more common than '''odd''' abundant numbers.
To make things more interesting, this task is specifically about finding ''odd abundant numbers''.
;Task
*Find and display here: at least the first 25 abundant odd numbers and either their proper divisor sum or sigma sum.
*Find and display here: the one thousandth abundant odd number and either its proper divisor sum or sigma sum.
*Find and display here: the first abundant odd number greater than one billion (109) and either its proper divisor sum or sigma sum.
;References:
:* OEIS:A005231: Odd abundant numbers (odd numbers n whose sum of divisors exceeds 2n)
:* American Journal of Mathematics, Vol. 35, No. 4 (Oct., 1913), pp. 413-422 - Finiteness of the Odd Perfect and Primitive Abundant Numbers with n Distinct Prime Factors (LE Dickson)
| require "prime"
class Integer
def proper_divisors
return [] if self == 1
primes = prime_division.flat_map{|prime, freq| [prime] * freq}
(1...primes.size).each_with_object([1]) do |n, res|
primes.combination(n).map{|combi| res << combi.inject(:*)}
end.flatten.uniq
end
end
def generator_odd_abundants(from=1)
from += 1 if from.even?
Enumerator.new do |y|
from.step(nil, 2) do |n|
sum = n.proper_divisors.sum
y << [n, sum] if sum > n
end
end
end
generator_odd_abundants.take(25).each{|n, sum| puts "#{n} with sum #{sum}" }
puts "\n%d with sum %#d" % generator_odd_abundants.take(1000).last
puts "\n%d with sum %#d" % generator_odd_abundants(1_000_000_000).next
|
Accumulator factory | Ruby | {{requires|Mutable State}}
A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed in so far to that accumulator (including the initial value passed when the accumulator was created).
;Rules:
The detailed rules are at http://paulgraham.com/accgensub.html and are reproduced here for simplicity (with additions in ''small italic text'').
:Before you submit an example, make sure the function
:# Takes a number n and returns a function (lets call it g), that takes a number i, and returns n incremented by the accumulation of i from every call of function g(i).Although these exact function and parameter names need not be used
:# Works for any numeric type-- i.e. can take both ints and floats and returns functions that can take both ints and floats. (It is not enough simply to convert all input to floats. An accumulator that has only seen integers must return integers.) ''(i.e., if the language doesn't allow for numeric polymorphism, you have to use overloading or something like that)''
:# Generates functions that return the sum of every number ever passed to them, not just the most recent. ''(This requires a piece of state to hold the accumulated value, which in turn means that pure functional languages can't be used for this task.)''
:# Returns a real function, meaning something that you can use wherever you could use a function you had defined in the ordinary way in the text of your program. ''(Follow your language's conventions here.)''
:# Doesn't store the accumulated value or the returned functions in a way that could cause them to be inadvertently modified by other code. ''(No global variables or other such things.)''
: E.g. if after the example, you added the following code (in a made-up language) ''where the factory function is called foo'':
:: x = foo(1);
x(5);
foo(3);
print x(2.3);
: It should print 8.3. ''(There is no need to print the form of the accumulator function returned by foo(3); it's not part of the task at all.)''
;Task:
Create a function that implements the described rules.
It need not handle any special error cases not described above. The simplest way to implement the task as described is typically to use a closure, providing the language supports them.
Where it is not possible to hold exactly to the constraints above, describe the deviations.
| require 'rational'
require 'complex'
y = accumulator(Rational(2, 3))
puts y[Rational(1, 2)] # 7/6
puts y[4] # 31/6
puts y[Complex(0, 1)] # 31/6+1i
t = accumulator(Time.utc(1999, 8, 7, 6, 5))
# (Ruby 1.8.6) (Ruby 1.9.2)
puts t[4] # Sat Aug 07 06:05:04 UTC 1999 1999-08-07 06:05:04 UTC
puts t[-12 * 60 * 60] # Fri Aug 06 18:05:04 UTC 1999 1999-08-06 18:05:04 UTC
require 'matrix'
m = accumulator(Matrix[[1, 2], [3, 4]])
puts m[Matrix[[5, 6], [7, 8]]] # Matrix[[6, 8], [10, 12]] |
Aliquot sequence classifications | Ruby from Python | An aliquot sequence of a positive integer K is defined recursively as the first member
being K and subsequent members being the sum of the [[Proper divisors]] of the previous term.
:* If the terms eventually reach 0 then the series for K is said to '''terminate'''.
:There are several classifications for non termination:
:* If the second term is K then all future terms are also K and so the sequence repeats from the first term with period 1 and K is called '''perfect'''.
:* If the third term ''would'' be repeating K then the sequence repeats with period 2 and K is called '''amicable'''.
:* If the Nth term ''would'' be repeating K for the first time, with N > 3 then the sequence repeats with period N - 1 and K is called '''sociable'''.
:Perfect, amicable and sociable numbers eventually repeat the original number K; there are other repetitions...
:* Some K have a sequence that eventually forms a periodic repetition of period 1 but of a number other than K, for example 95 which forms the sequence 95, 25, 6, 6, 6, ... such K are called '''aspiring'''.
:* K that have a sequence that eventually forms a periodic repetition of period >= 2 but of a number other than K, for example 562 which forms the sequence 562, 284, 220, 284, 220, ... such K are called '''cyclic'''.
:And finally:
:* Some K form aliquot sequences that are not known to be either terminating or periodic; these K are to be called '''non-terminating'''. For the purposes of this task, K is to be classed as non-terminating if it has not been otherwise classed after generating '''16''' terms or if any term of the sequence is greater than 2**47 = 140,737,488,355,328.
;Task:
# Create routine(s) to generate the aliquot sequence of a positive integer enough to classify it according to the classifications given above.
# Use it to display the classification and sequences of the numbers one to ten inclusive.
# Use it to show the classification and sequences of the following integers, in order:
:: 11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488, and optionally 15355717786080.
Show all output on this page.
;Related tasks:
* [[Abundant, deficient and perfect number classifications]]. (Classifications from only the first two members of the whole sequence).
* [[Proper divisors]]
* [[Amicable pairs]]
| def aliquot(n, maxlen=16, maxterm=2**47)
return "terminating", [0] if n == 0
s = []
while (s << n).size <= maxlen and n < maxterm
n = n.proper_divisors.inject(0, :+)
if s.include?(n)
case n
when s[0]
case s.size
when 1 then return "perfect", s
when 2 then return "amicable", s
else return "sociable of length #{s.size}", s
end
when s[-1] then return "aspiring", s
else return "cyclic back to #{n}", s
end
elsif n == 0 then return "terminating", s << 0
end
end
return "non-terminating", s
end
for n in 1..10
puts "%20s: %p" % aliquot(n)
end
puts
for n in [11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488, 15355717786080]
puts "%20s: %p" % aliquot(n)
end |
Amb | Ruby | Define and give an example of the Amb operator.
The Amb operator (short for "ambiguous") expresses nondeterminism. This doesn't refer to randomness (as in "nondeterministic universe") but is closely related to the term as it is used in automata theory ("non-deterministic finite automaton").
The Amb operator takes a variable number of expressions (or values if that's simpler in the language) and yields a correct one which will satisfy a constraint in some future computation, thereby avoiding failure.
Problems whose solution the Amb operator naturally expresses can be approached with other tools, such as explicit nested iterations over data sets, or with pattern matching. By contrast, the Amb operator appears integrated into the language. Invocations of Amb are not wrapped in any visible loops or other search patterns; they appear to be independent.
Essentially Amb(x, y, z) splits the computation into three possible futures: a future in which the value x is yielded, a future in which the value y is yielded and a future in which the value z is yielded. The future which leads to a successful subsequent computation is chosen. The other "parallel universes" somehow go away. Amb called with no arguments fails.
For simplicity, one of the domain values usable with Amb may denote failure, if that is convenient. For instance, it is convenient if a Boolean false denotes failure, so that Amb(false) fails, and thus constraints can be expressed using Boolean expressions like Amb(x * y == 8) which unless x and y add to four.
A pseudo-code program which satisfies this constraint might look like:
let x = Amb(1, 2, 3)
let y = Amb(7, 6, 4, 5)
Amb(x * y = 8)
print x, y
The output is 2 4 because Amb(1, 2, 3) correctly chooses the future in which x has value 2, Amb(7, 6, 4, 5) chooses 4 and consequently Amb(x * y = 8) produces a success.
Alternatively, failure could be represented using strictly Amb():
unless x * y = 8 do Amb()
Or else Amb could take the form of two operators or functions: one for producing values and one for enforcing constraints:
let x = Ambsel(1, 2, 3)
let y = Ambsel(4, 5, 6)
Ambassert(x * y = 8)
print x, y
where Ambassert behaves like Amb() if the Boolean expression is false, otherwise it allows the future computation to take place, without yielding any value.
The task is to somehow implement Amb, and demonstrate it with a program which chooses one word from each of the following four sets of character strings to generate a four-word sentence:
#"the" "that" "a"
#"frog" "elephant" "thing"
#"walked" "treaded" "grows"
#"slowly" "quickly"
The constraint to be satisfied is that the last character of each word (other than the last) is the same as the first character of its successor.
The only successful sentence is "that thing grows slowly"; other combinations do not satisfy the constraint and thus fail.
The goal of this task isn't to simply process the four lists of words with explicit, deterministic program flow such as nested iteration, to trivially demonstrate the correct output. The goal is to implement the Amb operator, or a facsimile thereof that is possible within the language limitations.
| require "continuation"
class Amb
class ExhaustedError < RuntimeError; end
def initialize
@fail = proc { fail ExhaustedError, "amb tree exhausted" }
end
def choose(*choices)
prev_fail = @fail
callcc { |sk|
choices.each { |choice|
callcc { |fk|
@fail = proc {
@fail = prev_fail
fk.call(:fail)
}
if choice.respond_to? :call
sk.call(choice.call)
else
sk.call(choice)
end
}
}
@fail.call
}
end
def failure
choose
end
def assert(cond)
failure unless cond
end
end
A = Amb.new
w1 = A.choose("the", "that", "a")
w2 = A.choose("frog", "elephant", "thing")
w3 = A.choose("walked", "treaded", "grows")
w4 = A.choose("slowly", "quickly")
A.choose() unless w1[-1] == w2[0]
A.choose() unless w2[-1] == w3[0]
A.choose() unless w3[-1] == w4[0]
puts w1, w2, w3, w4 |
Anagrams/Deranged anagrams | Ruby | Two or more words are said to be anagrams if they have the same characters, but in a different order.
By analogy with derangements we define a ''deranged anagram'' as two words with the same characters, but in which the same character does ''not'' appear in the same position in both words.
;Task
Use the word list at unixdict to find and display the longest deranged anagram.
;Related
* [[Permutations/Derangements]]
* Best shuffle
{{Related tasks/Word plays}}
| def deranged?(a, b)
a.chars.zip(b.chars).all? {|char_a, char_b| char_a != char_b}
end
def find_derangements(list)
list.combination(2) {|a,b| return a,b if deranged?(a,b)}
nil
end
require 'open-uri'
anagram = open('http://www.puzzlers.org/pub/wordlists/unixdict.txt') do |f|
f.read.split.group_by {|s| s.each_char.sort}
end
anagram = anagram.select{|k,list| list.size>1}.sort_by{|k,list| -k.size}
anagram.each do |k,list|
if derangements = find_derangements(list)
puts "Longest derangement anagram: #{derangements}"
break
end
end |
Angle difference between two bearings | Ruby from C++ | Finding the angle between two bearings is often confusing.[https://stackoverflow.com/questions/16180595/find-the-angle-between-two-bearings]
;Task:
Find the angle which is the result of the subtraction '''b2 - b1''', where '''b1''' and '''b2''' are the bearings.
Input bearings are expressed in the range '''-180''' to '''+180''' degrees.
The result is also expressed in the range '''-180''' to '''+180''' degrees.
Compute the angle for the following pairs:
* 20 degrees ('''b1''') and 45 degrees ('''b2''')
* -45 and 45
* -85 and 90
* -95 and 90
* -45 and 125
* -45 and 145
* 29.4803 and -88.6381
* -78.3251 and -159.036
;Optional extra:
Allow the input bearings to be any (finite) value.
;Test cases:
* -70099.74233810938 and 29840.67437876723
* -165313.6666297357 and 33693.9894517456
* 1174.8380510598456 and -154146.66490124757
* 60175.77306795546 and 42213.07192354373
| def getDifference(b1, b2)
r = (b2 - b1) % 360.0
# Ruby modulus has same sign as divisor, which is positive here,
# so no need to consider negative case
if r >= 180.0
r -= 360.0
end
return r
end
if __FILE__ == $PROGRAM_NAME
puts "Input in -180 to +180 range"
puts getDifference(20.0, 45.0)
puts getDifference(-45.0, 45.0)
puts getDifference(-85.0, 90.0)
puts getDifference(-95.0, 90.0)
puts getDifference(-45.0, 125.0)
puts getDifference(-45.0, 145.0)
puts getDifference(-45.0, 125.0)
puts getDifference(-45.0, 145.0)
puts getDifference(29.4803, -88.6381)
puts getDifference(-78.3251, -159.036)
puts "Input in wider range"
puts getDifference(-70099.74233810938, 29840.67437876723)
puts getDifference(-165313.6666297357, 33693.9894517456)
puts getDifference(1174.8380510598456, -154146.66490124757)
puts getDifference(60175.77306795546, 42213.07192354373)
end |
Anti-primes | Ruby | The anti-primes
(or highly composite numbers, sequence A002182 in the OEIS)
are the natural numbers with more factors than any smaller than itself.
;Task:
Generate and show here, the first twenty anti-primes.
;Related tasks:
:* [[Factors of an integer]]
:* [[Sieve of Eratosthenes]]
| require 'prime'
def num_divisors(n)
n.prime_division.inject(1){|prod, (_p,n)| prod *= (n + 1) }
end
anti_primes = Enumerator.new do |y| # y is the yielder
max = 0
y << 1 # yield 1
2.step(nil,2) do |candidate| # nil is taken as Infinity
num = num_divisors(candidate)
if num > max
y << candidate # yield the candidate
max = num
end
end
end
puts anti_primes.take(20).join(" ")
|
Apply a digital filter (direct form II transposed) | Ruby from C# | Digital filters are used to apply a mathematical operation to a sampled signal. One of the common formulations is the "direct form II transposed" which can represent both infinite impulse response (IIR) and finite impulse response (FIR) filters, as well as being more numerically stable than other forms. [https://ccrma.stanford.edu/~jos/fp/Transposed_Direct_Forms.html]
;Task:
Filter a signal using an order 3 low-pass Butterworth filter. The coefficients for the filter are a=[1.00000000, -2.77555756e-16, 3.33333333e-01, -1.85037171e-17] and b = [0.16666667, 0.5, 0.5, 0.16666667]
The signal that needs filtering is the following vector: [-0.917843918645, 0.141984778794, 1.20536903482, 0.190286794412, -0.662370894973, -1.00700480494, -0.404707073677 ,0.800482325044, 0.743500089861, 1.01090520172, 0.741527555207, 0.277841675195, 0.400833448236, -0.2085993586, -0.172842103641, -0.134316096293, 0.0259303398477, 0.490105989562, 0.549391221511, 0.9047198589]
;See also:
[Wikipedia on Butterworth filters]
| def filter(a,b,signal)
result = Array.new(signal.length(), 0.0)
for i in 0..signal.length()-1 do
tmp = 0.0
for j in 0 .. b.length()-1 do
if i - j < 0 then next end
tmp += b[j] * signal[i - j]
end
for j in 1 .. a.length()-1 do
if i - j < 0 then next end
tmp -= a[j] * result[i - j]
end
tmp /= a[0]
result[i] = tmp
end
return result
end
def main
a = [1.00000000, -2.77555756e-16, 3.33333333e-01, -1.85037171e-17]
b = [0.16666667, 0.5, 0.5, 0.16666667]
signal = [
-0.917843918645, 0.141984778794, 1.20536903482, 0.190286794412,
-0.662370894973, -1.00700480494, -0.404707073677, 0.800482325044,
0.743500089861, 1.01090520172, 0.741527555207, 0.277841675195,
0.400833448236, -0.2085993586, -0.172842103641, -0.134316096293,
0.0259303398477, 0.490105989562, 0.549391221511, 0.9047198589
]
result = filter(a,b,signal)
for i in 0 .. result.length() - 1 do
print "%11.8f" % [result[i]]
if (i + 1) % 5 == 0 then
print "\n"
else
print ", "
end
end
end
main() |
Approximate equality | Ruby | Sometimes, when testing whether the solution to a task (for example, here on Rosetta Code) is correct, the
difference in floating point calculations between different language implementations becomes significant.
For example, a difference between '''32''' bit and '''64''' bit floating point calculations may appear by
about the 8th significant digit in base 10 arithmetic.
;Task:
Create a function which returns true if two floating point numbers are approximately equal.
The function should allow for differences in the magnitude of numbers, so that, for example,
'''100000000000000.01''' may be approximately equal to '''100000000000000.011''',
even though '''100.01''' is not approximately equal to '''100.011'''.
If the language has such a feature in its standard library, this may be used instead of a custom function.
Show the function results with comparisons on the following pairs of values:
:# 100000000000000.01, 100000000000000.011 (note: should return ''true'')
:# 100.01, 100.011 (note: should return ''false'')
:# 10000000000000.001 / 10000.0, 1000000000.0000001000
:# 0.001, 0.0010000001
:# 0.000000000000000000000101, 0.0
:# sqrt(2) * sqrt(2), 2.0
:# -sqrt(2) * sqrt(2), -2.0
:# 3.14159265358979323846, 3.14159265358979324
Answers should be true for the first example and false in the second, so that just rounding the numbers to a fixed number of decimals should not be enough. Otherwise answers may vary and still be correct. See the Python code for one type of solution.
__TOC__
| require "bigdecimal"
testvalues = [[100000000000000.01, 100000000000000.011],
[100.01, 100.011],
[10000000000000.001 / 10000.0, 1000000000.0000001000],
[0.001, 0.0010000001],
[0.000000000000000000000101, 0.0],
[(2**0.5) * (2**0.5), 2.0],
[-(2**0.5) * (2**0.5), -2.0],
[BigDecimal("3.14159265358979323846"), 3.14159265358979324],
[Float::NAN, Float::NAN,],
[Float::INFINITY, Float::INFINITY],
]
class Numeric
def close_to?(num, tol = Float::EPSILON)
return true if self == num
return false if (self.to_f.nan? or num.to_f.nan?) # NaN is not even close to itself
return false if [self, num].count( Float::INFINITY) == 1 # Infinity is only close to itself
return false if [self, num].count(-Float::INFINITY) == 1
(self-num).abs <= tol * ([self.abs, num.abs].max)
end
end
testvalues.each do |a,b|
puts "#{a} #{a.close_to?(b) ? '≈' : '≉'} #{b}"
end
|
Arithmetic-geometric mean | Ruby | {{wikipedia|Arithmetic-geometric mean}}
;Task:
Write a function to compute the arithmetic-geometric mean of two numbers.
The arithmetic-geometric mean of two numbers can be (usefully) denoted as \mathrm{agm}(a,g), and is equal to the limit of the sequence:
: a_0 = a; \qquad g_0 = g
: a_{n+1} = \tfrac{1}{2}(a_n + g_n); \quad g_{n+1} = \sqrt{a_n g_n}.
Since the limit of a_n-g_n tends (rapidly) to zero with iterations, this is an efficient method.
Demonstrate the function by calculating:
:\mathrm{agm}(1,1/\sqrt{2})
;Also see:
* mathworld.wolfram.com/Arithmetic-Geometric Mean
| # The flt package (http://flt.rubyforge.org/) is useful for high-precision floating-point math.
# It lets us control 'context' of numbers, individually or collectively -- including precision
# (which adjusts the context's value of epsilon accordingly).
require 'flt'
include Flt
BinNum.Context.precision = 512 # default 53 (bits)
def agm(a,g)
new_a = BinNum a
new_g = BinNum g
while new_a - new_g > new_a.class.Context.epsilon do
old_g = new_g
new_g = (new_a * new_g).sqrt
new_a = (old_g + new_a) * 0.5
end
new_g
end
puts agm(1, 1 / BinNum(2).sqrt) |
Arithmetic-geometric mean/Calculate Pi | Ruby | Almkvist Berndt 1988 begins with an investigation of why the agm is such an efficient algorithm, and proves that it converges quadratically. This is an efficient method to calculate \pi.
With the same notations used in [[Arithmetic-geometric mean]], we can summarize the paper by writing:
\pi =
\frac{4\; \mathrm{agm}(1, 1/\sqrt{2})^2}
{1 - \sum\limits_{n=1}^{\infty} 2^{n+1}(a_n^2-g_n^2)}
This allows you to make the approximation, for any large '''N''':
\pi \approx
\frac{4\; a_N^2}
{1 - \sum\limits_{k=1}^N 2^{k+1}(a_k^2-g_k^2)}
The purpose of this task is to demonstrate how to use this approximation in order to compute a large number of decimals of \pi.
| # Calculate Pi using the Arithmetic Geometric Mean of 1 and 1/sqrt(2)
#
#
# Nigel_Galloway
# March 8th., 2012.
#
require 'flt'
Flt::BinNum.Context.precision = 8192
a = n = 1
g = 1 / Flt::BinNum(2).sqrt
z = 0.25
(0..17).each{
x = [(a + g) * 0.5, (a * g).sqrt]
var = x[0] - a
z -= var * var * n
n += n
a = x[0]
g = x[1]
}
puts a * a / z |
Arithmetic evaluation | Ruby | Create a program which parses and evaluates arithmetic expressions.
;Requirements:
* An abstract-syntax tree (AST) for the expression must be created from parsing the input.
* The AST must be used in evaluation, also, so the input may not be directly evaluated (e.g. by calling eval or a similar language feature.)
* The expression will be a string or list of symbols like "(1+3)*7".
* The four symbols + - * / must be supported as binary operators with conventional precedence rules.
* Precedence-control parentheses must also be supported.
;Note:
For those who don't remember, mathematical precedence is as follows:
* Parentheses
* Multiplication/Division (left to right)
* Addition/Subtraction (left to right)
;C.f:
* [[24 game Player]].
* [[Parsing/RPN calculator algorithm]].
* [[Parsing/RPN to infix conversion]].
| $op_priority = {"+" => 0, "-" => 0, "*" => 1, "/" => 1}
class TreeNode
OP_FUNCTION = {
"+" => lambda {|x, y| x + y},
"-" => lambda {|x, y| x - y},
"*" => lambda {|x, y| x * y},
"/" => lambda {|x, y| x / y}}
attr_accessor :info, :left, :right
def initialize(info)
@info = info
end
def leaf?
@left.nil? and @right.nil?
end
def to_s(order)
if leaf?
@info
else
left_s, right_s = @left.to_s(order), @right.to_s(order)
strs = case order
when :prefix then [@info, left_s, right_s]
when :infix then [left_s, @info, right_s]
when :postfix then [left_s, right_s, @info]
else []
end
"(" + strs.join(" ") + ")"
end
end
def eval
if !leaf? and operator?(@info)
OP_FUNCTION[@info].call(@left.eval, @right.eval)
else
@info.to_f
end
end
end
def tokenize(exp)
exp
.gsub('(', ' ( ')
.gsub(')', ' ) ')
.gsub('+', ' + ')
.gsub('-', ' - ')
.gsub('*', ' * ')
.gsub('/', ' / ')
.split(' ')
end
def operator?(token)
$op_priority.has_key?(token)
end
def pop_connect_push(op_stack, node_stack)
temp = op_stack.pop
temp.right = node_stack.pop
temp.left = node_stack.pop
node_stack.push(temp)
end
def infix_exp_to_tree(exp)
tokens = tokenize(exp)
op_stack, node_stack = [], []
tokens.each do |token|
if operator?(token)
# clear stack of higher priority operators
until (op_stack.empty? or
op_stack.last.info == "(" or
$op_priority[op_stack.last.info] < $op_priority[token])
pop_connect_push(op_stack, node_stack)
end
op_stack.push(TreeNode.new(token))
elsif token == "("
op_stack.push(TreeNode.new(token))
elsif token == ")"
while op_stack.last.info != "("
pop_connect_push(op_stack, node_stack)
end
# throw away the '('
op_stack.pop
else
node_stack.push(TreeNode.new(token))
end
end
until op_stack.empty?
pop_connect_push(op_stack, node_stack)
end
node_stack.last
end |
Ascending primes | Ruby | Generate and show all primes with strictly ascending decimal digits.
Aside: Try solving without peeking at existing solutions. I had a weird idea for generating
a prime sieve faster, which needless to say didn't pan out. The solution may be p(r)etty trivial
but generating them quickly is at least mildly interesting.
Tip: filtering all 7,027,260 primes below 123,456,789 probably won't kill you, but there is
at least one significantly better and much faster way, needing a mere 511 odd/prime tests.
;See also
;* OEIS:A052015 - Primes with distinct digits in ascending order
;Related:
*[[Primes with digits in nondecreasing order]] (infinite series allowing duplicate digits, whereas this isn't and doesn't)
*[[Pandigital prime]] (whereas this is the smallest, with gaps in the used digits being permitted)
| require 'prime'
digits = [9,8,7,6,5,4,3,2,1]
res = 1.upto(digits.size).flat_map do |n|
digits.combination(n).filter_map do |set|
candidate = set.join.to_i
candidate if candidate.prime?
end.reverse
end
puts res.join(",") |
Associative array/Merging | Ruby | Define two associative arrays, where one represents the following "base" data:
::::: {| class="wikitable"
|+
| '''Key''' || '''Value'''
|-
| "name" || "Rocket Skates"
|-
| "price" || 12.75
|-
| "color" || "yellow"
|}
And the other represents "update" data:
::::: {| class="wikitable"
|+
| '''Key''' || '''Value'''
|-
| "price" || 15.25
|-
| "color" || "red"
|-
| "year" || 1974
|}
Merge these into a new associative array that contains every key found in either of the source ones. Each key should map to the value in the second (update) table if that exists, or else to the value in the first (base) table. If possible, do this in a way that does not mutate the original two associative arrays. Obviously this should be done in a way that would work for any data, not just the specific data given here, but in this example the result should be:
::::: {| class="wikitable"
|+
| '''Key''' || '''Value'''
|-
| "name" || "Rocket Skates"
|-
| "price" || 15.25
|-
| "color" || "red"
|-
| "year" || 1974
|}
| base = {"name" => "Rocket Skates", "price" => 12.75, "color" => "yellow"}
update = {"price" => 15.25, "color" => "red", "year" => 1974}
result = base.merge(update)
p result |
Attractive numbers | Ruby | A number is an ''attractive number'' if the number of its prime factors (whether distinct or not) is also prime.
;Example:
The number '''20''', whose prime decomposition is '''2 x 2 x 5''', is an ''attractive number'' because the number of its prime factors ('''3''') is also prime.
;Task:
Show sequence items up to '''120'''.
;Reference:
:* The OEIS entry: A063989: Numbers with a prime number of prime divisors.
| require "prime"
p (1..120).select{|n| n.prime_division.sum(&:last).prime? }
|
Average loop length | Ruby | Let f be a uniformly-randomly chosen mapping from the numbers 1..N to the numbers 1..N (note: not necessarily a permutation of 1..N; the mapping could produce a number in more than one way or not at all). At some point, the sequence 1, f(1), f(f(1))... will contain a repetition, a number that occurring for the second time in the sequence.
;Task:
Write a program or a script that estimates, for each N, the average length until the first such repetition.
Also calculate this expected length using an analytical formula, and optionally compare the simulated result with the theoretical one.
This problem comes from the end of Donald Knuth's Christmas tree lecture 2011.
Example of expected output:
N average analytical (error)
=== ========= ============ =========
1 1.0000 1.0000 ( 0.00%)
2 1.4992 1.5000 ( 0.05%)
3 1.8784 1.8889 ( 0.56%)
4 2.2316 2.2188 ( 0.58%)
5 2.4982 2.5104 ( 0.49%)
6 2.7897 2.7747 ( 0.54%)
7 3.0153 3.0181 ( 0.09%)
8 3.2429 3.2450 ( 0.07%)
9 3.4536 3.4583 ( 0.14%)
10 3.6649 3.6602 ( 0.13%)
11 3.8091 3.8524 ( 1.12%)
12 3.9986 4.0361 ( 0.93%)
13 4.2074 4.2123 ( 0.12%)
14 4.3711 4.3820 ( 0.25%)
15 4.5275 4.5458 ( 0.40%)
16 4.6755 4.7043 ( 0.61%)
17 4.8877 4.8579 ( 0.61%)
18 4.9951 5.0071 ( 0.24%)
19 5.1312 5.1522 ( 0.41%)
20 5.2699 5.2936 ( 0.45%)
| class Integer
def factorial
self == 0 ? 1 : (1..self).inject(:*)
end
end
def rand_until_rep(n)
rands = {}
loop do
r = rand(1..n)
return rands.size if rands[r]
rands[r] = true
end
end
runs = 1_000_000
puts " N average exp. diff ",
"=== ======== ======== ==========="
(1..20).each do |n|
sum_of_runs = runs.times.inject(0){|sum, _| sum += rand_until_rep(n)}
avg = sum_of_runs / runs.to_f
analytical = (1..n).inject(0){|sum, i| sum += (n.factorial / (n**i).to_f / (n-i).factorial)}
puts "%3d %8.4f %8.4f (%8.4f%%)" % [n, avg, analytical, (avg/analytical - 1)*100]
end |
Averages/Mean angle | Ruby | {{Related tasks/Statistical measures}}
| require 'complex' # Superfluous in Ruby >= 2.0; complex is added to core.
def deg2rad(d)
d * Math::PI / 180
end
def rad2deg(r)
r * 180 / Math::PI
end
def mean_angle(deg)
rad2deg((deg.inject(0) {|z, d| z + Complex.polar(1, deg2rad(d))} / deg.length).arg)
end
[[350, 10], [90, 180, 270, 360], [10, 20, 30]].each {|angles|
puts "The mean angle of %p is: %f degrees" % [angles, mean_angle(angles)]
} |
Averages/Pythagorean means | Ruby 1.9+ | {{Related tasks/Statistical measures}}
| class Array
def arithmetic_mean
inject(0.0, :+) / length
end
def geometric_mean
inject(:*) ** (1.0 / length)
end
def harmonic_mean
length / inject(0.0) {|s, m| s + 1.0/m}
end
end
class Range
def method_missing(m, *args)
case m
when /_mean$/ then to_a.send(m)
else super
end
end
end
p a = (1..10).arithmetic_mean
p g = (1..10).geometric_mean
p h = (1..10).harmonic_mean
# is h < g < a ??
p g.between?(h, a) |
Averages/Root mean square | Ruby | Task
Compute the Root mean square of the numbers 1..10.
The ''root mean square'' is also known by its initials RMS (or rms), and as the '''quadratic mean'''.
The RMS is calculated as the mean of the squares of the numbers, square-rooted:
::: x_{\mathrm{rms}} = \sqrt {{{x_1}^2 + {x_2}^2 + \cdots + {x_n}^2} \over n}.
;See also
{{Related tasks/Statistical measures}}
| class Array
def quadratic_mean
Math.sqrt( self.inject(0.0) {|s, y| s + y*y} / self.length )
end
end
class Range
def quadratic_mean
self.to_a.quadratic_mean
end
end
(1..10).quadratic_mean # => 6.2048368229954285 |
Babbage problem | Ruby | Charles Babbage
Charles Babbage's analytical engine.
Charles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example:
{{quote
| What is the smallest positive integer whose square ends in the digits 269,696?
| Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, Electronic Computers, second edition, 1970, p. 125.
}}
He thought the answer might be 99,736, whose square is 9,947,269,696; but he couldn't be certain.
;Task
The task is to find out if Babbage had the right answer -- and to do so, as far as your language allows it, in code that Babbage himself would have been able to read and understand.
As Babbage evidently solved the task with pencil and paper, a similar efficient solution is preferred.
For these purposes, Charles Babbage may be taken to be an intelligent person, familiar with mathematics and with the idea of a computer; he has written the first drafts of simple computer programmes in tabular form. [Babbage Archive Series L].
;Motivation
The aim of the task is to write a program that is sufficiently clear and well-documented for such a person to be able to read it and be confident that it does indeed solve the specified problem.
| n = 0
n = n + 2 until (n*n).modulo(1000000) == 269696
print n
|
Balanced brackets | Ruby 1.9 | '''Task''':
* Generate a string with '''N''' opening brackets '''[''' and with '''N''' closing brackets ''']''', in some arbitrary order.
* Determine whether the generated string is ''balanced''; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest.
;Examples:
(empty) OK
[] OK
[][] OK
[[][]] OK
][ NOT OK
][][ NOT OK
[]][[] NOT OK
| re = /\A # beginning of string
(?<bb> # begin capture group <bb>
\[ # literal [
\g<bb>* # zero or more <bb>
\] # literal ]
)* # end group, zero or more such groups
\z/x # end of string
10.times do |i|
s = (%w{[ ]} * i).shuffle.join
puts (s =~ re ? " OK: " : "bad: ") + s
end
["[[]", "[]]", "a[ letters[-1] ].xyz[0]"].each do |s|
t = s.gsub(/[^\[\]]/, "")
puts (t =~ re ? " OK: " : "bad: ") + s
end |
Balanced ternary | Ruby | Balanced ternary is a way of representing numbers. Unlike the prevailing binary representation, a balanced ternary integer is in base 3, and each digit can have the values 1, 0, or -1.
;Examples:
Decimal 11 = 32 + 31 - 30, thus it can be written as "++-"
Decimal 6 = 32 - 31 + 0 x 30, thus it can be written as "+-0"
;Task:
Implement balanced ternary representation of integers with the following:
# Support arbitrarily large integers, both positive and negative;
# Provide ways to convert to and from text strings, using digits '+', '-' and '0' (unless you are already using strings to represent balanced ternary; but see requirement 5).
# Provide ways to convert to and from native integer type (unless, improbably, your platform's native integer type ''is'' balanced ternary). If your native integers can't support arbitrary length, overflows during conversion must be indicated.
# Provide ways to perform addition, negation and multiplication directly on balanced ternary integers; do ''not'' convert to native integers first.
# Make your implementation efficient, with a reasonable definition of "efficient" (and with a reasonable definition of "reasonable").
'''Test case''' With balanced ternaries ''a'' from string "+-0++0+", ''b'' from native integer -436, ''c'' "+-++-":
* write out ''a'', ''b'' and ''c'' in decimal notation;
* calculate ''a'' x (''b'' - ''c''), write out the result in both ternary and decimal notations.
'''Note:''' The pages floating point balanced ternary.
| class BalancedTernary
include Comparable
def initialize(str = "")
if str =~ /[^-+0]+/
raise ArgumentError, "invalid BalancedTernary number: #{str}"
end
@digits = trim0(str)
end
I2BT = {0 => ["0",0], 1 => ["+",0], 2 => ["-",1]}
def self.from_int(value)
n = value.to_i
digits = ""
while n != 0
quo, rem = n.divmod(3)
bt, carry = I2BT[rem]
digits = bt + digits
n = quo + carry
end
new(digits)
end
BT2I = {"-" => -1, "0" => 0, "+" => 1}
def to_int
@digits.chars.inject(0) do |sum, char|
sum = 3 * sum + BT2I[char]
end
end
alias :to_i :to_int
def to_s
@digits.dup # String is mutable
end
alias :inspect :to_s
def <=>(other)
to_i <=> other.to_i
end
ADDITION_TABLE = {
"---" => ["-","0"], "--0" => ["-","+"], "--+" => ["0","-"],
"-0-" => ["-","+"], "-00" => ["0","-"], "-0+" => ["0","0"],
"-+-" => ["0","-"], "-+0" => ["0","0"], "-++" => ["0","+"],
"0--" => ["-","+"], "0-0" => ["0","-"], "0-+" => ["0","0"],
"00-" => ["0","-"], "000" => ["0","0"], "00+" => ["0","+"],
"0+-" => ["0","0"], "0+0" => ["0","+"], "0++" => ["+","-"],
"+--" => ["0","-"], "+-0" => ["0","0"], "+-+" => ["0","+"],
"+0-" => ["0","0"], "+00" => ["0","+"], "+0+" => ["+","-"],
"++-" => ["0","+"], "++0" => ["+","-"], "+++" => ["+","0"],
}
def +(other)
maxl = [to_s.length, other.to_s.length].max
a = pad0_reverse(to_s, maxl)
b = pad0_reverse(other.to_s, maxl)
carry = "0"
sum = a.zip( b ).inject("") do |sum, (c1, c2)|
carry, digit = ADDITION_TABLE[carry + c1 + c2]
sum = digit + sum
end
self.class.new(carry + sum)
end
MULTIPLICATION_TABLE = {
"-" => "+0-",
"0" => "000",
"+" => "-0+",
}
def *(other)
product = self.class.new
other.to_s.each_char do |bdigit|
row = to_s.tr("-0+", MULTIPLICATION_TABLE[bdigit])
product += self.class.new(row)
product << 1
end
product >> 1
end
# negation
def -@()
self.class.new(@digits.tr('-+','+-'))
end
# subtraction
def -(other)
self + (-other)
end
# shift left
def <<(count)
@digits = trim0(@digits + "0"*count)
self
end
# shift right
def >>(count)
@digits[-count..-1] = "" if count > 0
@digits = trim0(@digits)
self
end
private
def trim0(str)
str = str.sub(/^0+/, "")
str = "0" if str.empty?
str
end
def pad0_reverse(str, len)
str.rjust(len, "0").reverse.chars
end
end
a = BalancedTernary.new("+-0++0+")
b = BalancedTernary.from_int(-436)
c = BalancedTernary.new("+-++-")
%w[a b c a*(b-c)].each do |exp|
val = eval(exp)
puts "%8s :%13s,%8d" % [exp, val, val.to_i]
end |
Base64 decode data | Ruby | See [[Base64 encode data]].
Now write a program that takes the output of the [[Base64 encode data]] task as input and regenerate the original file.
When working on the VBA implementation I found several 'solutions' on the net, including one from the software maker himself, that showed output with incorrect padding. Obviously with incorrect padding in the output you can not decode correctly to the original file again.
| require 'base64'
raku_example ='
VG8gZXJyIGlzIGh1bWFuLCBidXQgdG8gcmVhbGx5IGZvdWwgdGhpbmdzIHVwIHlvdSBuZWVkIGEgY2
9tcHV0ZXIuCiAgICAtLSBQYXVsIFIuIEVocmxpY2g=
'
puts Base64.decode64 raku_example |
Bell numbers | Ruby from D | Bell or exponential numbers are enumerations of the number of different ways to partition a set that has exactly '''n''' elements. Each element of the sequence '''Bn''' is the number of partitions of a set of size '''n''' where order of the elements and order of the partitions are non-significant. E.G.: '''{a b}''' is the same as '''{b a}''' and '''{a} {b}''' is the same as '''{b} {a}'''.
;So:
:'''B0 = 1''' trivially. There is only one way to partition a set with zero elements. '''{ }'''
:'''B1 = 1''' There is only one way to partition a set with one element. '''{a}'''
:'''B2 = 2''' Two elements may be partitioned in two ways. '''{a} {b}, {a b}'''
:'''B3 = 5''' Three elements may be partitioned in five ways '''{a} {b} {c}, {a b} {c}, {a} {b c}, {a c} {b}, {a b c}'''
: and so on.
A simple way to find the Bell numbers is construct a '''Bell triangle''', also known as an '''Aitken's array''' or '''Peirce triangle''', and read off the numbers in the first column of each row. There are other generating algorithms though, and you are free to choose the best / most appropriate for your case.
;Task:
Write a routine (function, generator, whatever) to generate the Bell number sequence and call the routine to show here, on this page at least the '''first 15''' and (if your language supports big Integers) '''50th''' elements of the sequence.
If you ''do'' use the Bell triangle method to generate the numbers, also show the '''first ten rows''' of the Bell triangle.
;See also:
:* '''OEIS:A000110 Bell or exponential numbers'''
:* '''OEIS:A011971 Aitken's array'''
| def bellTriangle(n)
tri = Array.new(n)
for i in 0 .. n - 1 do
tri[i] = Array.new(i)
for j in 0 .. i - 1 do
tri[i][j] = 0
end
end
tri[1][0] = 1
for i in 2 .. n - 1 do
tri[i][0] = tri[i - 1][i - 2]
for j in 1 .. i - 1 do
tri[i][j] = tri[i][j - 1] + tri[i - 1][j - 1]
end
end
return tri
end
def main
bt = bellTriangle(51)
puts "First fifteen and fiftieth Bell numbers:"
for i in 1 .. 15 do
puts "%2d: %d" % [i, bt[i][0]]
end
puts "50: %d" % [bt[50][0]]
puts
puts "The first ten rows of Bell's triangle:"
for i in 1 .. 10 do
puts bt[i].inspect
end
end
main() |
Benford's law | Ruby from Python | {{Wikipedia|Benford's_law}}
'''Benford's law''', also called the '''first-digit law''', refers to the frequency distribution of digits in many (but not all) real-life sources of data.
In this distribution, the number 1 occurs as the first digit about 30% of the time, while larger numbers occur in that position less frequently: 9 as the first digit less than 5% of the time. This distribution of first digits is the same as the widths of gridlines on a logarithmic scale.
Benford's law also concerns the expected distribution for digits beyond the first, which approach a uniform distribution.
This result has been found to apply to a wide variety of data sets, including electricity bills, street addresses, stock prices, population numbers, death rates, lengths of rivers, physical and mathematical constants, and processes described by power laws (which are very common in nature). It tends to be most accurate when values are distributed across multiple orders of magnitude.
A set of numbers is said to satisfy Benford's law if the leading digit d (d \in \{1, \ldots, 9\}) occurs with probability
:::: P(d) = \log_{10}(d+1)-\log_{10}(d) = \log_{10}\left(1+\frac{1}{d}\right)
For this task, write (a) routine(s) to calculate the distribution of first significant (non-zero) digits in a collection of numbers, then display the actual vs. expected distribution in the way most convenient for your language (table / graph / histogram / whatever).
Use the first 1000 numbers from the Fibonacci sequence as your data set. No need to show how the Fibonacci numbers are obtained.
You can generate them or load them from a file; whichever is easiest.
Display your actual vs expected distribution.
''For extra credit:'' Show the distribution for one other set of numbers from a page on Wikipedia. State which Wikipedia page it can be obtained from and what the set enumerates. Again, no need to display the actual list of numbers or the code to load them.
;See also:
* numberphile.com.
* A starting page on Wolfram Mathworld is {{Wolfram|Benfords|Law}}.
| EXPECTED = (1..9).map{|d| Math.log10(1+1.0/d)}
def fib(n)
a,b = 0,1
n.times.map{ret, a, b = a, b, a+b; ret}
end
# powers of 3 as a test sequence
def power_of_threes(n)
n.times.map{|k| 3**k}
end
def heads(s)
s.map{|a| a.to_s[0].to_i}
end
def show_dist(title, s)
s = heads(s)
c = Array.new(10, 0)
s.each{|x| c[x] += 1}
size = s.size.to_f
res = (1..9).map{|d| c[d]/size}
puts "\n %s Benfords deviation" % title
res.zip(EXPECTED).each.with_index(1) do |(r, e), i|
puts "%2d: %5.1f%% %5.1f%% %5.1f%%" % [i, r*100, e*100, (r - e).abs*100]
end
end
def random(n)
n.times.map{rand(1..n)}
end
show_dist("fibbed", fib(1000))
show_dist("threes", power_of_threes(1000))
# just to show that not all kind-of-random sets behave like that
show_dist("random", random(10000)) |
Best shuffle | Ruby from Raku | Shuffle the characters of a string in such a way that as many of the character values are in a different position as possible.
A shuffle that produces a randomized result among the best choices is to be preferred. A deterministic approach that produces the same sequence every time is acceptable as an alternative.
Display the result as follows:
original string, shuffled string, (score)
The score gives the number of positions whose character value did ''not'' change.
;Example:
tree, eetr, (0)
;Test cases:
abracadabra
seesaw
elk
grrrrrr
up
a
;Related tasks
* [[Anagrams/Deranged anagrams]]
* [[Permutations/Derangements]]
| def best_shuffle(s)
# Fill _pos_ with positions in the order
# that we want to fill them.
pos = []
# g["a"] = [2, 4] implies that s[2] == s[4] == "a"
g = s.length.times.group_by { |i| s[i] }
# k sorts letters from low to high count
k = g.sort_by { |k, v| v.length }.map { |k, v| k }
until g.empty?
k.each do |letter|
g[letter] or next
pos.push(g[letter].pop)
g[letter].empty? and g.delete letter
end
end
# Now fill in _new_ with _letters_ according to each position
# in _pos_, but skip ahead in _letters_ if we can avoid
# matching characters that way.
letters = s.dup
new = "?" * s.length
until letters.empty?
i, p = 0, pos.pop
i += 1 while letters[i] == s[p] and i < (letters.length - 1)
new[p] = letters.slice! i
end
score = new.chars.zip(s.chars).count { |c, d| c == d }
[new, score]
end
%w(abracadabra seesaw elk grrrrrr up a).each do |word|
puts "%s, %s, (%d)" % [word, *best_shuffle(word)]
end |
Bin given limits | Ruby | You are given a list of n ascending, unique numbers which are to form limits
for n+1 bins which count how many of a large set of input numbers fall in the
range of each bin.
(Assuming zero-based indexing)
bin[0] counts how many inputs are < limit[0]
bin[1] counts how many inputs are >= limit[0] and < limit[1]
..''
bin[n-1] counts how many inputs are >= limit[n-2] and < limit[n-1]
bin[n] counts how many inputs are >= limit[n-1]
;Task:
The task is to create a function that given the ascending limits and a stream/
list of numbers, will return the bins; together with another function that
given the same list of limits and the binning will ''print the limit of each bin
together with the count of items that fell in the range''.
Assume the numbers to bin are too large to practically sort.
;Task examples:
Part 1: Bin using the following limits the given input data
limits = [23, 37, 43, 53, 67, 83]
data = [95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47,
16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55]
Part 2: Bin using the following limits the given input data
limits = [14, 18, 249, 312, 389, 392, 513, 591, 634, 720]
data = [445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933,
416,589,930,373,202,253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306,
655,267,248,477,549,238, 62,678, 98,534,622,907,406,714,184,391,913, 42,560,247,
346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,945,733,507,916,123,
345,110,720,917,313,845,426, 9,457,628,410,723,354,895,881,953,677,137,397, 97,
854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157, 5,316,395,
787,942,456,242,759,898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692,
698,765,331,487,251,600,879,342,982,527,736,795,585, 40, 54,901,408,359,577,237,
605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791,
466, 23,707,467, 33,670,921,180,991,396,160,436,717,918, 8,374,101,684,727,749]
Show output here, on this page.
| Test = Struct.new(:limits, :data)
tests = Test.new( [23, 37, 43, 53, 67, 83],
[95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47,
16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55]),
Test.new( [14, 18, 249, 312, 389, 392, 513, 591, 634, 720],
[445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933,
416,589,930,373,202,253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306,
655,267,248,477,549,238, 62,678, 98,534,622,907,406,714,184,391,913, 42,560,247,
346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,945,733,507,916,123,
345,110,720,917,313,845,426, 9,457,628,410,723,354,895,881,953,677,137,397, 97,
854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157, 5,316,395,
787,942,456,242,759,898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692,
698,765,331,487,251,600,879,342,982,527,736,795,585, 40, 54,901,408,359,577,237,
605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791,
466, 23,707,467, 33,670,921,180,991,396,160,436,717,918, 8,374,101,684,727,749])
def bin(limits, data)
data.map{|d| limits.bsearch{|limit| limit > d} }.tally
end
def present_bins(limits, bins)
ranges = ([nil]+limits+[nil]).each_cons(2).map{|low, high| Range.new(low, high, true) }
ranges.each{|range| puts "#{range.to_s.ljust(12)} #{bins[range.end].to_i}"}
end
tests.each do |test|
present_bins(test.limits, bin(test.limits, test.data))
puts
end
|
Bioinformatics/Sequence mutation | Ruby | Given a string of characters A, C, G, and T representing a DNA sequence write a routine to mutate the sequence, (string) by:
# Choosing a random base position in the sequence.
# Mutate the sequence by doing one of either:
## '''S'''wap the base at that position by changing it to one of A, C, G, or T. (which has a chance of swapping the base for the same base)
## '''D'''elete the chosen base at the position.
## '''I'''nsert another base randomly chosen from A,C, G, or T into the sequence at that position.
# Randomly generate a test DNA sequence of at least 200 bases
# "Pretty print" the sequence and a count of its size, and the count of each base in the sequence
# Mutate the sequence ten times.
# "Pretty print" the sequence after all mutations, and a count of its size, and the count of each base in the sequence.
;Extra credit:
* Give more information on the individual mutations applied.
* Allow mutations to be weighted and/or chosen.
| class DNA_Seq
attr_accessor :seq
def initialize(bases: %i[A C G T] , size: 0)
@bases = bases
@seq = Array.new(size){ bases.sample }
end
def mutate(n = 10)
n.times{|n| method([:s, :d, :i].sample).call}
end
def to_s(n = 50)
just_size = @seq.size / n
([email protected]).step(n).map{|from| "#{from.to_s.rjust(just_size)} " + @seq[from, n].join}.join("\n") +
"\nTotal #{seq.size}: #{@seq.tally.sort.to_h.inspect}\n\n"
end
def s = @seq[rand_index]= @bases.sample
def d = @seq.delete_at(rand_index)
def i = @seq.insert(rand_index, @bases.sample )
alias :swap :s
alias :delete :d
alias :insert :i
private
def rand_index = rand( @seq.size )
end
puts test = DNA_Seq.new(size: 200)
test.mutate
puts test
test.delete
puts test
|
Bioinformatics/base count | Ruby | Given this string representing ordered DNA bases:
CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG
CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG
AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT
GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT
CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG
TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA
TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT
CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG
TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC
GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT
;Task:
:* "Pretty print" the sequence followed by a summary of the counts of each of the bases: ('''A''', '''C''', '''G''', and '''T''') in the sequence
:* print the total count of each base in the string.
| dna = <<DNA_STR
CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG
CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG
AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT
GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT
CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG
TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA
TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT
CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG
TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC
GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT
DNA_STR
chunk_size = 60
dna = dna.delete("\n")
size = dna.size
0.step(size, chunk_size) do |pos|
puts "#{pos.to_s.ljust(6)} #{dna[pos, chunk_size]}"
end
puts dna.chars.tally.sort.map{|ar| ar.join(" : ") }
puts "Total : #{dna.size}"
|
Biorhythms | Ruby | For a while in the late 70s, the pseudoscience of biorhythms was popular enough to rival astrology, with kiosks in malls that would give you your weekly printout. It was also a popular entry in "Things to Do with your Pocket Calculator" lists. You can read up on the history at Wikipedia, but the main takeaway is that unlike astrology, the math behind biorhythms is dead simple.
It's based on the number of days since your birth. The premise is that three cycles of unspecified provenance govern certain aspects of everyone's lives - specifically, how they're feeling physically, emotionally, and mentally. The best part is that not only do these cycles somehow have the same respective lengths for all humans of any age, gender, weight, genetic background, etc, but those lengths are an exact number of days. And the pattern is in each case a perfect sine curve. Absolutely miraculous!
To compute your biorhythmic profile for a given day, the first thing you need is the number of days between that day and your birth, so the answers in [[Days between dates]] are probably a good starting point. (Strictly speaking, the biorhythms start at 0 at the moment of your birth, so if you know time of day you can narrow things down further, but in general these operate at whole-day granularity.) Then take the residue of that day count modulo each of the the cycle lengths to calculate where the day falls on each of the three sinusoidal journeys.
The three cycles and their lengths are as follows:
:::{| class="wikitable"
! Cycle
! Length
|-
|Physical
| 23 days
|-
|Emotional
| 28 days
|-
|Mental
| 33 days
|}
The first half of each cycle is in "plus" territory, with a peak at the quarter-way point; the second half in "minus" territory, with a valley at the three-quarters mark. You can calculate a specific value between -1 and +1 for the ''k''th day of an ''n''-day cycle by computing '''sin( 2p''k'' / ''n'' )'''. The days where a cycle crosses the axis in either direction are called "critical" days, although with a cycle value of 0 they're also said to be the most neutral, which seems contradictory.
The task: write a subroutine, function, or program that will, given a birthdate and a target date, output the three biorhythmic values for the day. You may optionally include a text description of the position and the trend (e.g. "up and rising", "peak", "up but falling", "critical", "down and falling", "valley", "down but rising"), an indication of the date on which the next notable event (peak, valley, or crossing) falls, or even a graph of the cycles around the target date. Demonstrate the functionality for dates of your choice.
Example run of my Raku implementation:
raku br.raku 1943-03-09 1972-07-11
| require 'date'
CYCLES = {physical: 23, emotional: 28, mental: 33}
def biorhythms(date_of_birth, target_date = Date.today.to_s)
days_alive = Date.parse(target_date) - Date.parse(date_of_birth)
CYCLES.each do |name, num_days|
cycle_day = days_alive % num_days
state = case cycle_day
when 0, num_days/2 then "neutral"
when (1.. num_days/2) then "positive"
when (num_days/2+1..num_days) then "negative"
end
puts "%-10s: cycle day %2s, %s" % [name, cycle_day.to_i, state]
end
end
biorhythms("1943-03-09", "1972-07-11")
|
Bitcoin/address validation | Ruby | Write a program that takes a bitcoin address as argument,
and checks whether or not this address is valid.
A bitcoin address uses a base58 encoding, which uses an alphabet of the characters 0 .. 9, A ..Z, a .. z, but without the four characters:
:::* 0 zero
:::* O uppercase oh
:::* I uppercase eye
:::* l lowercase ell
With this encoding, a bitcoin address encodes 25 bytes:
* the first byte is the version number, which will be zero for this task ;
* the next twenty bytes are a [[RIPEMD-160]] digest, but you don't have to know that for this task: you can consider them a pure arbitrary data ;
* the last four bytes are a checksum check. They are the first four bytes of a double [[SHA-256]] digest of the previous 21 bytes.
To check the bitcoin address, you must read the first twenty-one bytes, compute the checksum, and check that it corresponds to the last four bytes.
The program can either return a boolean value or throw an exception when not valid.
You can use a digest library for [[SHA-256]].
;Example of a bitcoin address:
1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i
It doesn't belong to anyone and is part of the test suite of the bitcoin software.
You can change a few characters in this string and check that it'll fail the test.
| # Validate Bitcoin address
#
# Nigel_Galloway
# October 13th., 2014
require 'digest/sha2'
def convert g
i,e = '',[]
(0...g.length/2).each{|n| e[n] = g[n+=n]+g[n+1]; i+='H2'}
e.pack(i)
end
N = [0,1,2,3,4,5,6,7,8,nil,nil,nil,nil,nil,nil,nil,9,10,11,12,13,14,15,16,nil,17,18,19,20,21,nil,22,23,24,25,26,27,28,29,30,31,32,nil,nil,nil,nil,nil,nil,33,34,35,36,37,38,39,40,41,42,43,nil,44,45,46,47,48,49,50,51,52,53,54,55,56,57]
A = '1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62x'
g = A.bytes.inject(0){|g,n| g*58+N[n-49]}.to_s(16) # A small and interesting piece of code to do the decoding of base58-encoded data.
n = g.slice!(0..-9)
(n.length...42).each{n.insert(0,'0')}
puts "I think the checksum should be #{g}\nI calculate that it is #{Digest::SHA256.hexdigest(Digest::SHA256.digest(convert(n)))[0,8]}"
|
Bitcoin/public point to address | Ruby | elliptic curve public point into a short ASCII string. The purpose of this task is to perform such a conversion.
The encoding steps are:
* take the X and Y coordinates of the given public point, and concatenate them in order to have a 64 byte-longed string ;
* add one byte prefix equal to 4 (it is a convention for this way of encoding a public point) ;
* compute the [[SHA-256]] of this string ;
* compute the [[RIPEMD-160]] of this SHA-256 digest ;
* compute the checksum of the concatenation of the version number digit (a single zero byte) and this RIPEMD-160 digest, as described in [[bitcoin/address validation]] ;
* Base-58 encode (see below) the concatenation of the version number (zero in this case), the ripemd digest and the checksum
The base-58 encoding is based on an alphabet of alphanumeric characters (numbers, upper case and lower case, in that order) but without the four characters 0, O, l and I.
Here is an example public point:
X = 0x50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352
Y = 0x2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6
The corresponding address should be:
16UwLL9Risc3QfPqBUvKofHmBQ7wMtjvM
Nb. The leading '1' is not significant as 1 is zero in base-58. It is however often added to the bitcoin address for various reasons. There can actually be several of them. You can ignore this and output an address without the leading 1.
''Extra credit:'' add a verification procedure about the public point, making sure it belongs to the secp256k1 elliptic curve
| # Translate public point to Bitcoin address
#
# Nigel_Galloway
# October 12th., 2014
require 'digest/sha2'
def convert g
i,e = '',[]
(0...g.length/2).each{|n| e[n] = g[n+=n]+g[n+1]; i+='H2'}
e.pack(i)
end
X = '50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352'
Y = '2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6'
n = '00'+Digest::RMD160.hexdigest(Digest::SHA256.digest(convert('04'+X+Y)))
n+= Digest::SHA256.hexdigest(Digest::SHA256.digest(convert(n)))[0,8]
G = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
n,res = n.hex,''
while n > 0 do
n,ng = n.divmod(58)
res << G[ng]
end
puts res.reverse
|
Bitwise IO | Ruby 1.8.7 | The aim of this task is to write functions (or create a class if yourlanguage is Object Oriented and you prefer) for reading and writing sequences of
bits, most significant bit first. While the output of a asciiprint "STRING" is the ASCII byte sequence
"S", "T", "R", "I", "N", "G", the output of a "print" of the bits sequence
0101011101010 (13 bits) must be 0101011101010; real I/O is performed always
''quantized'' by byte (avoiding endianness issues and relying on underlying
buffering for performance), therefore you must obtain as output the bytes
0101 0111 0101 0'''000''' (bold bits are padding bits), i.e. in hexadecimal 57 50.
As test, you can implement a '''rough''' (e.g. don't care about error handling or
other issues) compression/decompression program for ASCII sequences
of bytes, i.e. bytes for which the most significant bit is always unused, so that you can write
seven bits instead of eight (each 8 bytes of input, we write 7 bytes of output).
These bit oriented I/O functions can be used to implement compressors and
decompressors; e.g. Dynamic and Static Huffman encodings use variable length
bits sequences, while LZW (see [[LZW compression]]) use fixed or variable ''words''
nine (or more) bits long.
* Limits in the maximum number of bits that can be written/read in a single read/write operation are allowed.
* Errors handling is not mandatory
| def crunch(ascii)
bitstring = ascii.bytes.collect {|b| "%07b" % b}.join
[bitstring].pack("B*")
end
def expand(binary)
bitstring = binary.unpack("B*")[0]
bitstring.scan(/[01]{7}/).collect {|b| b.to_i(2).chr}.join
end
original = "This is an ascii string that will be crunched, written, read and expanded."
puts "my ascii string is #{original.length} bytes"
filename = "crunched.out"
# write the compressed data
File.open(filename, "w") do |fh|
fh.binmode
fh.print crunch(original)
end
filesize = File.size(filename)
puts "the file containing the crunched text is #{filesize} bytes"
# read and expand
expanded = File.open(filename, "r") do |fh|
fh.binmode
expand(fh.read)
end
if original == expanded
puts "success"
else
puts "fail!"
end |
Box the compass | Ruby | Avast me hearties!
There be many a land lubber that knows naught of the pirate ways and gives direction by degree!
They know not how to box the compass!
;Task description:
# Create a function that takes a heading in degrees and returns the correct 32-point compass heading.
# Use the function to print and display a table of Index, Compass point, and Degree; rather like the corresponding columns from, the first table of the wikipedia article, but use only the following 33 headings as input:
:[0.0, 16.87, 16.88, 33.75, 50.62, 50.63, 67.5, 84.37, 84.38, 101.25, 118.12, 118.13, 135.0, 151.87, 151.88, 168.75, 185.62, 185.63, 202.5, 219.37, 219.38, 236.25, 253.12, 253.13, 270.0, 286.87, 286.88, 303.75, 320.62, 320.63, 337.5, 354.37, 354.38]. (They should give the same order of points but are spread throughout the ranges of acceptance).
;Notes;
* The headings and indices can be calculated from this pseudocode:
for i in 0..32 inclusive:
heading = i * 11.25
case i %3:
if 1: heading += 5.62; break
if 2: heading -= 5.62; break
end
index = ( i mod 32) + 1
* The column of indices can be thought of as an enumeration of the thirty two cardinal points (see talk page)..
| Headings = %w(north east south west north).each_cons(2).flat_map do |a, b|
[a,
"#{a} by #{b}",
"#{a}-#{a}#{b}",
"#{a}#{b} by #{a}",
"#{a}#{b}",
"#{a}#{b} by #{b}",
"#{b}-#{a}#{b}",
"#{b} by #{a}"]
end
Headings.prepend nil
def heading(degrees)
i = degrees.quo(360).*(32).round.%(32).+(1)
[i, Headings[i]]
end
# an array of angles, in degrees
angles = (0..32).map { |i| i * 11.25 + [0, 5.62, -5.62][i % 3] }
angles.each do |degrees|
index, name = heading degrees
printf "%2d %20s %6.2f\n", index, name.center(20), degrees
end |
Brazilian numbers | Ruby from C++ | Brazilian numbers are so called as they were first formally presented at the 1994 math Olympiad ''Olimpiada Iberoamericana de Matematica'' in Fortaleza, Brazil.
Brazilian numbers are defined as:
The set of positive integer numbers where each number '''N''' has at least one natural number '''B''' where '''1 < B < N-1''' where the representation of '''N''' in '''base B''' has all equal digits.
;E.G.:
:* '''1, 2 & 3''' can not be Brazilian; there is no base '''B''' that satisfies the condition '''1 < B < N-1'''.
:* '''4''' is not Brazilian; '''4''' in '''base 2''' is '''100'''. The digits are not all the same.
:* '''5''' is not Brazilian; '''5''' in '''base 2''' is '''101''', in '''base 3''' is '''12'''. There is no representation where the digits are the same.
:* '''6''' is not Brazilian; '''6''' in '''base 2''' is '''110''', in '''base 3''' is '''20''', in '''base 4''' is '''12'''. There is no representation where the digits are the same.
:* '''7''' ''is'' Brazilian; '''7''' in '''base 2''' is '''111'''. There is at least one representation where the digits are all the same.
:* '''8''' ''is'' Brazilian; '''8''' in '''base 3''' is '''22'''. There is at least one representation where the digits are all the same.
:* ''and so on...''
All even integers '''2P >= 8''' are Brazilian because '''2P = 2(P-1) + 2''', which is '''22''' in '''base P-1''' when '''P-1 > 2'''. That becomes true when '''P >= 4'''.
More common: for all all integers '''R''' and '''S''', where '''R > 1''' and also '''S-1 > R''', then '''R*S''' is Brazilian because '''R*S = R(S-1) + R''', which is '''RR''' in '''base S-1'''
The only problematic numbers are squares of primes, where R = S. Only 11^2 is brazilian to base 3.
All prime integers, that are brazilian, can only have the digit '''1'''. Otherwise one could factor out the digit, therefore it cannot be a prime number. Mostly in form of '''111''' to base Integer(sqrt(prime number)). Must be an odd count of '''1''' to stay odd like primes > 2
;Task:
Write a routine (function, whatever) to determine if a number is Brazilian and use the routine to show here, on this page;
:* the first '''20''' Brazilian numbers;
:* the first '''20 odd''' Brazilian numbers;
:* the first '''20 prime''' Brazilian numbers;
;See also:
:* '''OEIS:A125134 - Brazilian numbers'''
:* '''OEIS:A257521 - Odd Brazilian numbers'''
:* '''OEIS:A085104 - Prime Brazilian numbers'''
| def sameDigits(n,b)
f = n % b
while (n /= b) > 0 do
if n % b != f then
return false
end
end
return true
end
def isBrazilian(n)
if n < 7 then
return false
end
if n % 2 == 0 then
return true
end
for b in 2 .. n - 2 do
if sameDigits(n, b) then
return true
end
end
return false
end
def isPrime(n)
if n < 2 then
return false
end
if n % 2 == 0 then
return n == 2
end
if n % 3 == 0 then
return n == 3
end
d = 5
while d * d <= n do
if n % d == 0 then
return false
end
d = d + 2
if n % d == 0 then
return false
end
d = d + 4
end
return true
end
def main
for kind in ["", "odd ", "prime "] do
quiet = false
bigLim = 99999
limit = 20
puts "First %d %sBrazilian numbers:" % [limit, kind]
c = 0
n = 7
while c < bigLim do
if isBrazilian(n) then
if not quiet then
print "%d " % [n]
end
c = c + 1
if c == limit then
puts
puts
quiet = true
end
end
if quiet and kind != "" then
next
end
if kind == "" then
n = n + 1
elsif kind == "odd " then
n = n + 2
elsif kind == "prime " then
loop do
n = n + 2
if isPrime(n) then
break
end
end
else
raise "Unexpected"
end
end
if kind == "" then
puts "The %dth Brazillian number is: %d" % [bigLim + 1, n]
puts
end
end
end
main() |
Break OO privacy | Ruby | Show how to access private or protected members of a class in an object-oriented language from outside an instance of the class, without calling non-private or non-protected members of the class as a proxy.
The intent is to show how a debugger, serializer, or other meta-programming tool might access information that is barred by normal access methods to the object but can nevertheless be accessed from within the language by some provided escape hatch or reflection mechanism.
The intent is specifically not to demonstrate heroic measures such as peeking and poking raw memory.
Note that cheating on your type system is almost universally regarded
as unidiomatic at best, and poor programming practice at worst.
Nonetheless, if your language intentionally maintains a double-standard for OO privacy, here's where you can show it off.
| class Example
def initialize
@private_data = "nothing" # instance variables are always private
end
private
def hidden_method
"secret"
end
end
example = Example.new
p example.private_methods(false) # => [:hidden_method]
#p example.hidden_method # => NoMethodError: private method `name' called for #<Example:0x101308408>
p example.send(:hidden_method) # => "secret"
p example.instance_variables # => [:@private_data]
p example.instance_variable_get :@private_data # => "nothing"
p example.instance_variable_set :@private_data, 42 # => 42
p example.instance_variable_get :@private_data # => 42
|
Burrows–Wheeler transform | Ruby from C# | {{Wikipedia|Burrows-Wheeler_transform}}
The Burrows-Wheeler transform (BWT, also called block-sorting compression) rearranges a character string into runs of similar characters.
This is useful for compression, since it tends to be easy to compress a string that has runs of repeated characters by techniques such as move-to-front transform and run-length encoding.
More importantly, the transformation is reversible, without needing to store any additional data.
The BWT is thus a "free" method of improving the efficiency of text compression algorithms, costing only some extra computation.
Source: Burrows-Wheeler transform
| STX = "\u0002"
ETX = "\u0003"
def bwt(s)
for c in s.split('')
if c == STX or c == ETX then
raise ArgumentError.new("Input can't contain STX or ETX")
end
end
ss = ("%s%s%s" % [STX, s, ETX]).split('')
table = []
for i in 0 .. ss.length - 1
table.append(ss.join)
ss = ss.rotate(-1)
end
table = table.sort
return table.map{ |e| e[-1] }.join
end
def ibwt(r)
len = r.length
table = [""] * len
for i in 0 .. len - 1
for j in 0 .. len - 1
table[j] = r[j] + table[j]
end
table = table.sort
end
for row in table
if row[-1] == ETX then
return row[1 .. -2]
end
end
return ""
end
def makePrintable(s)
s = s.gsub(STX, "^")
return s.gsub(ETX, "|")
end
def main
tests = [
"banana",
"appellee",
"dogwood",
"TO BE OR NOT TO BE OR WANT TO BE OR NOT?",
"SIX.MIXED.PIXIES.SIFT.SIXTY.PIXIE.DUST.BOXES",
"\u0002ABC\u0003"
]
for test in tests
print makePrintable(test), "\n"
print " --> "
begin
t = bwt(test)
print makePrintable(t), "\n"
r = ibwt(t)
print " --> ", r, "\n\n"
rescue ArgumentError => e
print e.message, "\n"
print " -->\n\n"
end
end
end
main() |
CSV data manipulation | Ruby | CSV spreadsheet files are suitable for storing tabular data in a relatively portable way.
The CSV format is flexible but somewhat ill-defined.
For present purposes, authors may assume that the data fields contain no commas, backslashes, or quotation marks.
;Task:
Read a CSV file, change some values and save the changes back to a file.
For this task we will use the following CSV file:
C1,C2,C3,C4,C5
1,5,9,13,17
2,6,10,14,18
3,7,11,15,19
4,8,12,16,20
Suggestions
Show how to add a column, headed 'SUM', of the sums of the rows.
If possible, illustrate the use of built-in or standard functions, methods, or libraries, that handle generic CSV files.
| require 'csv'
# read:
ar = CSV.table("test.csv").to_a #table method assumes headers and converts numbers if possible.
# manipulate:
ar.first << "SUM"
ar[1..-1].each{|row| row << row.sum}
# write:
CSV.open("out.csv", 'w') do |csv|
ar.each{|line| csv << line}
end |
CSV to HTML translation | Ruby | Consider a simplified CSV format where all rows are separated by a newline
and all columns are separated by commas.
No commas are allowed as field data, but the data may contain
other characters and character sequences that would
normally be ''escaped'' when converted to HTML
;Task:
Create a function that takes a string representation of the CSV data
and returns a text string of an HTML table representing the CSV data.
Use the following data as the CSV text to convert, and show your output.
: Character,Speech
: The multitude,The messiah! Show us the messiah!
: Brians mother,Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!
: The multitude,Who are you?
: Brians mother,I'm his mother; that's who!
: The multitude,Behold his mother! Behold his mother!
;Extra credit:
''Optionally'' allow special formatting for the first row of the table as if it is the tables header row
(via preferably; CSS if you must).
| require 'cgi'
puts '<table summary="csv2html program output">'
def row2html str, wrap = "td"
"<tr>" +
str.split(",").map { |cell| "<#{wrap}>#{CGI.escapeHTML cell}</#{wrap}>" }.join +
"</tr>"
end
puts row2html gets.chomp, "th" if ARGV.delete "header"
while str = gets
puts row2html str.chomp
end
puts "</table>" |
Calculating the value of e | Ruby from C | Calculate the value of ''e''.
(''e'' is also known as ''Euler's number'' and ''Napier's constant''.)
See details: Calculating the value of e
| fact = 1
e = 2
e0 = 0
n = 2
until (e - e0).abs < Float::EPSILON do
e0 = e
fact *= n
n += 1
e += 1.0 / fact
end
puts e
|
Calkin-Wilf sequence | Ruby from Python | The '''Calkin-Wilf sequence''' contains every nonnegative rational number exactly once.
It can be calculated recursively as follows:
{{math|a1}} = {{math|1}}
{{math|an+1}} = {{math|1/(2an+1-an)}} for n > 1
;Task part 1:
* Show on this page terms 1 through 20 of the Calkin-Wilf sequence.
To avoid floating point error, you may want to use a rational number data type.
It is also possible, given a non-negative rational number, to determine where it appears in the sequence without calculating the sequence. The procedure is to get the continued fraction representation of the rational and use it as the run-length encoding of the binary representation of the term number, beginning from the end of the continued fraction.
It only works if the number of terms in the continued fraction is odd- use either of the two equivalent representations to achieve this:
{{math|[a0; a1, a2, ..., an]}} = {{math|[a0; a1, a2 ,..., an-1, 1]}}
;Example:
The fraction '''9/4''' has odd continued fraction representation {{math|2; 3, 1}}, giving a binary representation of '''100011''',
which means '''9/4''' appears as the '''35th''' term of the sequence.
;Task part 2:
* Find the position of the number '''83116''''''/''''''51639''' in the Calkin-Wilf sequence.
;See also:
* Wikipedia entry: Calkin-Wilf tree
* [[Continued fraction]]
* [[Continued fraction/Arithmetic/Construct from rational number]]
| cw = Enumerator.new do |y|
y << a = 1.to_r
loop { y << a = 1/(2*a.floor + 1 - a) }
end
def term_num(rat)
num, den, res, pwr, dig = rat.numerator, rat.denominator, 0, 0, 1
while den > 0
num, (digit, den) = den, num.divmod(den)
digit.times do
res |= dig << pwr
pwr += 1
end
dig ^= 1
end
res
end
puts cw.take(20).join(", ")
puts term_num (83116/51639r)
|
Call a function | Ruby | Demonstrate the different syntax and semantics provided for calling a function.
This may include:
:* Calling a function that requires no arguments
:* Calling a function with a fixed number of arguments
:* Calling a function with optional arguments
:* Calling a function with a variable number of arguments
:* Calling a function with named arguments
:* Using a function in statement context
:* Using a function in first-class context within an expression
:* Obtaining the return value of a function
:* Distinguishing built-in functions and user-defined functions
:* Distinguishing subroutines and functions
;* Stating whether arguments are passed by value or by reference
;* Is partial application possible and how
This task is ''not'' about defining functions.
| # return value substance
i = 3
p 1 + i #=> 4 1.+(i)
p i < 5 #=> true i.<(5)
p 2 ** i #=> 8 2.**(i)
p -i #=> -3 i.-@()
a = [1,2,3]
p a[0] #=> 1 a.[](0)
a[2] = "0" # a.[]=(2,"0")
p a << 5 #=> [1, 2, "0", 5] a.<<(5)
p a & [4,2] #=> [2] a.&([4,2])
p "abcde"[1..3] #=> "bcd" "abcde".[](1..3)
p "%2d %4s" % [1,"xyz"] #=> " 1 xyz" "%2d %4s".%([1,"xyz"]) |
Canonicalize CIDR | Ruby from Raku | Implement a function or program that, given a range of IPv4 addresses in CIDR notation (dotted-decimal/network-bits), will return/output the same range in canonical form.
That is, the IP address portion of the output CIDR block must not contain any set (1) bits in the host part of the address.
;Example:
Given '''87.70.141.1/22''', your code should output '''87.70.140.0/22'''
;Explanation:
An Internet Protocol version 4 address is a 32-bit value, conventionally represented as a number in base 256 using dotted-decimal notation, where each base-256 digit is given in decimal and the digits are separated by periods. Logically, this 32-bit value represents two components: the leftmost (most-significant) bits determine the network portion of the address, while the rightmost (least-significant) bits determine the host portion. Classless Internet Domain Routing block notation indicates where the boundary between these two components is for a given address by adding a slash followed by the number of bits in the network portion.
In general, CIDR blocks stand in for the entire set of IP addresses sharing the same network component, so it's common to see access control lists that specify individual IP addresses using /32 to indicate that only the one address is included. Software accepting this notation as input often expects it to be entered in canonical form, in which the host bits are all zeroes. But network admins sometimes skip this step and just enter the address of a specific host on the subnet with the network size, resulting in a non-canonical entry.
The example address, 87.70.141.1/22, represents binary 0101011101000110100011 / 0100000001, with the / indicating the network/host division. To canonicalize, clear all the bits to the right of the / and convert back to dotted decimal: 0101011101000110100011 / 0000000000 - 87.70.140.0.
;More examples for testing
36.18.154.103/12 - 36.16.0.0/12
62.62.197.11/29 - 62.62.197.8/29
67.137.119.181/4 - 64.0.0.0/4
161.214.74.21/24 - 161.214.74.0/24
184.232.176.184/18 - 184.232.128.0/18
| #!/usr/bin/env ruby
# canonicalize a CIDR block: make sure none of the host bits are set
if ARGV.length == 0 then
ARGV = $stdin.readlines.map(&:chomp)
end
ARGV.each do |cidr|
# dotted-decimal / bits in network part
dotted, size_str = cidr.split('/')
size = size_str.to_i
# get IP as binary string
binary = dotted.split('.').map { |o| "%08b" % o }.join
# Replace the host part with all zeroes
binary[size .. -1] = '0' * (32 - size)
# Convert back to dotted-decimal
canon = binary.chars.each_slice(8).map { |a| a.join.to_i(2) }.join('.')
# And output
puts "#{canon}/#{size}"
end |
Cantor set | Ruby | Draw a Cantor set.
See details at this Wikipedia webpage: Cantor set
| lines = 5
(0..lines).each do |exp|
seg_size = 3**(lines-exp-1)
chars = (3**exp).times.map{ |n| n.digits(3).any?(1) ? " " : "█"}
puts chars.map{ |c| c * seg_size }.join
end
|
Cartesian product of two or more lists | Ruby | Show one or more idiomatic ways of generating the Cartesian product of two arbitrary lists in your language.
Demonstrate that your function/method correctly returns:
::{1, 2} x {3, 4} = {(1, 3), (1, 4), (2, 3), (2, 4)}
and, in contrast:
::{3, 4} x {1, 2} = {(3, 1), (3, 2), (4, 1), (4, 2)}
Also demonstrate, using your function/method, that the product of an empty list with any other list is empty.
:: {1, 2} x {} = {}
:: {} x {1, 2} = {}
For extra credit, show or write a function returning the n-ary product of an arbitrary number of lists, each of arbitrary length. Your function might, for example, accept a single argument which is itself a list of lists, and return the n-ary product of those lists.
Use your n-ary Cartesian product function to show the following products:
:: {1776, 1789} x {7, 12} x {4, 14, 23} x {0, 1}
:: {1, 2, 3} x {30} x {500, 100}
:: {1, 2, 3} x {} x {500, 100}
| p [1, 2].product([3, 4])
p [3, 4].product([1, 2])
p [1, 2].product([])
p [].product([1, 2])
p [1776, 1789].product([7, 12], [4, 14, 23], [0, 1])
p [1, 2, 3].product([30], [500, 100])
p [1, 2, 3].product([], [500, 100])
|
Casting out nines | Ruby from C | Task (in three parts):
;Part 1
Write a procedure (say \mathit{co9}(x)) which implements Casting Out Nines as described by returning the checksum for x. Demonstrate the procedure using the examples given there, or others you may consider lucky.
Note that this function does nothing more than calculate the least positive residue, modulo 9. Many of the solutions omit Part 1 for this reason. Many languages have a modulo operator, of which this is a trivial application.
With that understanding, solutions to Part 1, if given, are encouraged to follow the naive pencil-and-paper or mental arithmetic of repeated digit addition understood to be "casting out nines", or some approach other than just reducing modulo 9 using a built-in operator. Solutions for part 2 and 3 are not required to make use of the function presented in part 1.
;Part 2
Notwithstanding past Intel microcode errors, checking computer calculations like this would not be sensible. To find a computer use for your procedure:
: Consider the statement "318682 is 101558 + 217124 and squared is 101558217124" (see: [[Kaprekar numbers#Casting Out Nines (fast)]]).
: note that 318682 has the same checksum as (101558 + 217124);
: note that 101558217124 has the same checksum as (101558 + 217124) because for a Kaprekar they are made up of the same digits (sometimes with extra zeroes);
: note that this implies that for Kaprekar numbers the checksum of k equals the checksum of k^2.
Demonstrate that your procedure can be used to generate or filter a range of numbers with the property \mathit{co9}(k) = \mathit{co9}(k^2) and show that this subset is a small proportion of the range and contains all the Kaprekar in the range.
;Part 3
Considering this MathWorld page, produce a efficient algorithm based on the more mathematical treatment of Casting Out Nines, and realizing:
: \mathit{co9}(x) is the residual of x mod 9;
: the procedure can be extended to bases other than 9.
Demonstrate your algorithm by generating or filtering a range of numbers with the property k%(\mathit{Base}-1) == (k^2)%(\mathit{Base}-1) and show that this subset is a small proportion of the range and contains all the Kaprekar in the range.
;related tasks
* [[First perfect square in base N with N unique digits]]
* [[Kaprekar numbers]]
| N = 2
base = 10
c1 = 0
c2 = 0
for k in 1 .. (base ** N) - 1
c1 = c1 + 1
if k % (base - 1) == (k * k) % (base - 1) then
c2 = c2 + 1
print "%d " % [k]
end
end
puts
print "Trying %d numbers instead of %d numbers saves %f%%" % [c2, c1, 100.0 - 100.0 * c2 / c1] |
Catalan numbers/Pascal's triangle | Ruby | Print out the first '''15''' Catalan numbers by extracting them from Pascal's triangle.
;See:
* Catalan Numbers and the Pascal Triangle. This method enables calculation of Catalan Numbers using only addition and subtraction.
* Catalan's Triangle for a Number Triangle that generates Catalan Numbers using only addition.
* Sequence A000108 on OEIS has a lot of information on Catalan Numbers.
;Related Tasks:
[[Pascal's triangle]]
| def catalan(num)
t = [0, 1] #grows as needed
(1..num).map do |i|
i.downto(1){|j| t[j] += t[j-1]}
t[i+1] = t[i]
(i+1).downto(1) {|j| t[j] += t[j-1]}
t[i+1] - t[i]
end
end
p catalan(15) |
Catamorphism | Ruby | ''Reduce'' is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value.
;Task:
Show how ''reduce'' (or ''foldl'' or ''foldr'' etc), work (or would be implemented) in your language.
;See also:
* Wikipedia article: Fold
* Wikipedia article: Catamorphism
| p row = [1]
10.times{p row = row.each_cons(2).inject([1,1]){|ar,(a,b)| ar.insert(-2, a+b)} }
# [1]
# [1, 1]
# [1, 2, 1]
# [1, 3, 3, 1]
# [1, 4, 6, 4, 1]
# [1, 5, 10, 10, 5, 1]
# [1, 6, 15, 20, 15, 6, 1]
# etc
|
Chaocipher | Ruby | Description:
The Chaocipher was invented by J.F.Byrne in 1918 and, although simple by modern cryptographic standards, does not appear to have been broken until the algorithm was finally disclosed by his family in 2010.
The algorithm is described in this paper by M.Rubin in 2010 and there is a C# implementation here.
;Task:
Code the algorithm in your language and to test that it works with the plaintext 'WELLDONEISBETTERTHANWELLSAID' used in the paper itself.
| txt = "WELLDONEISBETTERTHANWELLSAID"
@left = "HXUCZVAMDSLKPEFJRIGTWOBNYQ".chars
@right = "PTLNBQDEOYSFAVZKGJRIHWXUMC".chars
def encrypt(char)
coded_char = @left[@right.index(char)]
@left.rotate!(@left.index(coded_char))
part = @left.slice!(1,13).rotate
@left.insert(1, *part)
@right.rotate!(@right.index(char)+1)
part = @right.slice!(2,12).rotate
@right.insert(2, *part)
@left[0]
end
puts txt.each_char.map{|c| encrypt(c) }.join
|
Check input device is a terminal | Ruby | Demonstrate how to check whether the input device is a terminal or not.
;Related task:
* [[Check output device is a terminal]]
| File.new("testfile").isatty #=> false
File.new("/dev/tty").isatty #=> true |
Check output device is a terminal | Ruby | Demonstrate how to check whether the output device is a terminal or not.
;Related task:
* [[Check input device is a terminal]]
| f = File.open("test.txt")
p f.isatty # => false
p STDOUT.isatty # => true
|
Cheryl's birthday | Ruby from C# | Albert and Bernard just became friends with Cheryl, and they want to know when her birthday is.
Cheryl gave them a list of ten possible dates:
May 15, May 16, May 19
June 17, June 18
July 14, July 16
August 14, August 15, August 17
Cheryl then tells Albert the ''month'' of birth, and Bernard the ''day'' (of the month) of birth.
1) Albert: I don't know when Cheryl's birthday is, but I know that Bernard does not know too.
2) Bernard: At first I don't know when Cheryl's birthday is, but I know now.
3) Albert: Then I also know when Cheryl's birthday is.
;Task
Write a computer program to deduce, by successive elimination, Cheryl's birthday.
;Related task:
* [[Sum and Product Puzzle]]
;References
* Wikipedia article of the same name.
* Tuple Relational Calculus
| dates = [
["May", 15],
["May", 16],
["May", 19],
["June", 17],
["June", 18],
["July", 14],
["July", 16],
["August", 14],
["August", 15],
["August", 17],
]
print dates.length, " remaining\n"
# the month cannot have a unique day
uniqueMonths = dates.group_by { |m,d| d }
.select { |k,v| v.size == 1 }
.map { |k,v| v.flatten }
.map { |m,d| m }
dates.delete_if { |m,d| uniqueMonths.include? m }
print dates.length, " remaining\n"
# the day must be unique
dates = dates .group_by { |m,d| d }
.select { |k,v| v.size == 1 }
.map { |k,v| v.flatten }
print dates.length, " remaining\n"
# the month must now be unique
dates = dates .group_by { |m,d| m }
.select { |k,v| v.size == 1 }
.map { |k,v| v }
.flatten
print dates |
Chinese remainder theorem | Ruby | Suppose n_1, n_2, \ldots, n_k are positive [[integer]]s that are pairwise co-prime.
Then, for any given sequence of integers a_1, a_2, \dots, a_k, there exists an integer x solving the following system of simultaneous congruences:
::: \begin{align}
x &\equiv a_1 \pmod{n_1} \\
x &\equiv a_2 \pmod{n_2} \\
&{}\ \ \vdots \\
x &\equiv a_k \pmod{n_k}
\end{align}
Furthermore, all solutions x of this system are congruent modulo the product, N=n_1n_2\ldots n_k.
;Task:
Write a program to solve a system of linear congruences by applying the Chinese Remainder Theorem.
If the system of equations cannot be solved, your program must somehow indicate this.
(It may throw an exception or return a special false value.)
Since there are infinitely many solutions, the program should return the unique solution s where 0 \leq s \leq n_1n_2\ldots n_k.
''Show the functionality of this program'' by printing the result such that the n's are [3,5,7] and the a's are [2,3,2].
'''Algorithm''': The following algorithm only applies if the n_i's are pairwise co-prime.
Suppose, as above, that a solution is required for the system of congruences:
::: x \equiv a_i \pmod{n_i} \quad\mathrm{for}\; i = 1, \ldots, k
Again, to begin, the product N = n_1n_2 \ldots n_k is defined.
Then a solution x can be found as follows:
For each i, the integers n_i and N/n_i are co-prime.
Using the Extended Euclidean algorithm, we can find integers r_i and s_i such that r_i n_i + s_i N/n_i = 1.
Then, one solution to the system of simultaneous congruences is:
::: x = \sum_{i=1}^k a_i s_i N/n_i
and the minimal solution,
::: x \pmod{N}.
| def extended_gcd(a, b)
last_remainder, remainder = a.abs, b.abs
x, last_x = 0, 1
while remainder != 0
last_remainder, (quotient, remainder) = remainder, last_remainder.divmod(remainder)
x, last_x = last_x - quotient*x, x
end
return last_remainder, last_x * (a < 0 ? -1 : 1)
end
def invmod(e, et)
g, x = extended_gcd(e, et)
if g != 1
raise 'Multiplicative inverse modulo does not exist!'
end
x % et
end
def chinese_remainder(mods, remainders)
max = mods.inject( :* ) # product of all moduli
series = remainders.zip(mods).map{ |r,m| (r * max * invmod(max/m, m) / m) }
series.inject( :+ ) % max
end
p chinese_remainder([3,5,7], [2,3,2]) #=> 23
p chinese_remainder([17353461355013928499, 3882485124428619605195281, 13563122655762143587], [7631415079307304117, 1248561880341424820456626, 2756437267211517231]) #=> 937307771161836294247413550632295202816
p chinese_remainder([10,4,9], [11,22,19]) #=> nil
|
Chinese zodiac | Ruby | Determine the Chinese zodiac sign and related associations for a given year.
Traditionally, the Chinese have counted years using two lists of labels, one of length 10 (the "celestial stems") and one of length 12 (the "terrestrial branches"). The labels do not really have any meaning outside their positions in the two lists; they're simply a traditional enumeration device, used much as Westerners use letters and numbers. They were historically used for months and days as well as years, and the stems are still sometimes used for school grades.
Years cycle through both lists concurrently, so that both stem and branch advance each year; if we used Roman letters for the stems and numbers for the branches, consecutive years would be labeled A1, B2, C3, etc. Since the two lists are different lengths, they cycle back to their beginning at different points: after J10 we get A11, and then after B12 we get C1. The result is a repeating 60-year pattern within which each pair of names occurs only once.
Mapping the branches to twelve traditional animal deities results in the well-known "Chinese zodiac", assigning each year to a given animal. For example, Sunday, January 22, 2023 CE (in the common Gregorian calendar) began the lunisolar Year of the Rabbit.
The celestial stems do not have a one-to-one mapping like that of the branches to animals; however, the five pairs of consecutive stems are each associated with one of the five traditional Chinese elements (Wood, Fire, Earth, Metal, and Water). Further, one of the two years within each element is assigned to yin, the other to yang.
Thus, the Chinese year beginning in 2023 CE is also the yin year of Water. Since 12 is an even number, the association between animals and yin/yang doesn't change; consecutive Years of the Rabbit will cycle through the five elements, but will always be yin.
;Task: Create a subroutine or program that will return or output the animal, yin/yang association, and element for the lunisolar year that begins in a given CE year.
You may optionally provide more information in the form of the year's numerical position within the 60-year cycle and/or its actual Chinese stem-branch name (in Han characters or Pinyin transliteration).
;Requisite information:
* The animal cycle runs in this order: Rat, Ox, Tiger, Rabbit, Dragon, Snake, Horse, Goat, Monkey, Rooster, Dog, Pig.
* The element cycle runs in this order: Wood, Fire, Earth, Metal, Water.
* Each element gets two consecutive years; a yang followed by a yin.
* The current 60-year cycle began in 1984; any multiple of 60 years from that point may be used to reckon from.
Thus, year 1 of a cycle is the year of the Wood Rat (yang), year 2 the Wood Ox (yin), and year 3 the Fire Tiger (yang). The year 2023 - which, as already noted, is the year of the Water Rabbit (yin) - is the 40th year of the current cycle.
;Information for optional task:
* The ten celestial stems are '''Jia ''' ''jia'', '''Yi ''' ''yi'', '''Bing ''' ''bing'', '''Ding ''' ''ding'', '''Wu ''' ''wu'', '''Ji ''' ''ji'', '''Geng ''' ''geng'', '''Xin ''' ''xin'', '''Ren ''' ''ren'', and '''Gui ''' ''gui''. With the ASCII version of Pinyin tones, the names are written "jia3", "yi3", "bing3", "ding1", "wu4", "ji3", "geng1", "xin1", "ren2", and "gui3".
* The twelve terrestrial branches are '''Zi ''' ''zi'', '''Chou ''' ''chou'', '''Yin ''' ''yin'', '''Mao ''' ''mao'', '''Chen ''' ''chen'', '''Si ''' ''si'', '''Wu ''' ''wu'', '''Wei ''' ''wei'', '''Shen ''' ''shen'', '''You ''' ''you'', '''Xu ''' ''xu'', '''Hai ''' ''hai''. In ASCII Pinyin, those are "zi3", "chou3", "yin2", "mao3", "chen2", "si4", "wu3", "wei4", "shen1", "you3", "xu1", and "hai4".
Therefore 1984 was '''Jia Zi ''' (''jia-zi'', or jia3-zi3). 2023 is '''Gui Mao ''' (''gui-mao'' or gui3-mao3).
| # encoding: utf-8
pinyin = {
'甲' => 'jiă',
'乙' => 'yĭ',
'丙' => 'bĭng',
'丁' => 'dīng',
'戊' => 'wù',
'己' => 'jĭ',
'庚' => 'gēng',
'辛' => 'xīn',
'壬' => 'rén',
'癸' => 'gŭi',
'子' => 'zĭ',
'丑' => 'chŏu',
'寅' => 'yín',
'卯' => 'măo',
'辰' => 'chén',
'巳' => 'sì',
'午' => 'wŭ',
'未' => 'wèi',
'申' => 'shēn',
'酉' => 'yŏu',
'戌' => 'xū',
'亥' => 'hài'
}
celestial = %w(甲 乙 丙 丁 戊 己 庚 辛 壬 癸)
terrestrial = %w(子 丑 寅 卯 辰 巳 午 未 申 酉 戌 亥)
animals = %w(Rat Ox Tiger Rabbit Dragon Snake
Horse Goat Monkey Rooster Dog Pig)
elements = %w(Wood Fire Earth Metal Water)
aspects = %w(yang yin)
BASE = 4
args = if !ARGV.empty?
ARGV
else
[Time.new.year]
end
args.each do |arg|
ce_year = Integer(arg)
print "#{ce_year}: " if ARGV.length > 1
cycle_year = ce_year - BASE
stem_number = cycle_year % 10
stem_han = celestial[stem_number]
stem_pinyin = pinyin[stem_han]
element_number = stem_number / 2
element = elements[element_number]
branch_number = cycle_year % 12
branch_han = terrestrial[branch_number]
branch_pinyin = pinyin[branch_han]
animal = animals[branch_number]
aspect_number = cycle_year % 2
aspect = aspects[aspect_number]
index = cycle_year % 60 + 1
print stem_han, branch_han
puts " (#{stem_pinyin}-#{branch_pinyin}, #{element} #{animal}; #{aspect} - year #{index} of the cycle)"
end |
Church numerals | Ruby from Raku | In the Church encoding of natural numbers, the number N is encoded by a function that applies its first argument N times to its second argument.
* '''Church zero''' always returns the identity function, regardless of its first argument. In other words, the first argument is not applied to the second argument at all.
* '''Church one''' applies its first argument f just once to its second argument x, yielding '''f(x)'''
* '''Church two''' applies its first argument f twice to its second argument x, yielding '''f(f(x))'''
* and each successive Church numeral applies its first argument one additional time to its second argument, '''f(f(f(x)))''', '''f(f(f(f(x))))''' ... The Church numeral 4, for example, returns a quadruple composition of the function supplied as its first argument.
Arithmetic operations on natural numbers can be similarly represented as functions on Church numerals.
In your language define:
* Church Zero,
* a Church successor function (a function on a Church numeral which returns the next Church numeral in the series),
* functions for Addition, Multiplication and Exponentiation over Church numerals,
* a function to convert integers to corresponding Church numerals,
* and a function to convert Church numerals to corresponding integers.
You should:
* Derive Church numerals three and four in terms of Church zero and a Church successor function.
* use Church numeral arithmetic to obtain the the sum and the product of Church 3 and Church 4,
* similarly obtain 4^3 and 3^4 in terms of Church numerals, using a Church numeral exponentiation function,
* convert each result back to an integer, and return it or print it to the console.
| def zero(f)
return lambda {|x| x}
end
Zero = lambda { |f| zero(f) }
def succ(n)
return lambda { |f| lambda { |x| f.(n.(f).(x)) } }
end
Three = succ(succ(succ(Zero)))
def add(n, m)
return lambda { |f| lambda { |x| m.(f).(n.(f).(x)) } }
end
def mult(n, m)
return lambda { |f| lambda { |x| m.(n.(f)).(x) } }
end
def power(b, e)
return e.(b)
end
def int_from_couch(f)
countup = lambda { |i| i+1 }
f.(countup).(0)
end
def couch_from_int(x)
countdown = lambda { |i|
case i
when 0 then Zero
else succ(countdown.(i-1))
end
}
countdown.(x)
end
Four = couch_from_int(4)
puts [ add(Three, Four),
mult(Three, Four),
power(Three, Four),
power(Four, Three) ].map {|f| int_from_couch(f) }
|
Circles of given radius through two points | Ruby from Python | 2 circles with a given radius through 2 points in 2D space.
Given two points on a plane and a radius, usually two circles of given radius can be drawn through the points.
;Exceptions:
# r==0.0 should be treated as never describing circles (except in the case where the points are coincident).
# If the points are coincident then an infinite number of circles with the point on their circumference can be drawn, unless r==0.0 as well which then collapses the circles to a point.
# If the points form a diameter then return two identical circles ''or'' return a single circle, according to which is the most natural mechanism for the implementation language.
# If the points are too far apart then no circles can be drawn.
;Task detail:
* Write a function/subroutine/method/... that takes two points and a radius and returns the two circles through those points, ''or some indication of special cases where two, possibly equal, circles cannot be returned''.
* Show here the output for the following inputs:
p1 p2 r
0.1234, 0.9876 0.8765, 0.2345 2.0
0.0000, 2.0000 0.0000, 0.0000 1.0
0.1234, 0.9876 0.1234, 0.9876 2.0
0.1234, 0.9876 0.8765, 0.2345 0.5
0.1234, 0.9876 0.1234, 0.9876 0.0
;Related task:
* [[Total circles area]].
;See also:
* Finding the Center of a Circle from 2 Points and Radius from Math forum @ Drexel
| Pt = Struct.new(:x, :y)
Circle = Struct.new(:x, :y, :r)
def circles_from(pt1, pt2, r)
raise ArgumentError, "Infinite number of circles, points coincide." if pt1 == pt2 && r > 0
# handle single point and r == 0
return [Circle.new(pt1.x, pt1.y, r)] if pt1 == pt2 && r == 0
dx, dy = pt2.x - pt1.x, pt2.y - pt1.y
# distance between points
q = Math.hypot(dx, dy)
# Also catches pt1 != pt2 && r == 0
raise ArgumentError, "Distance of points > diameter." if q > 2.0*r
# halfway point
x3, y3 = (pt1.x + pt2.x)/2.0, (pt1.y + pt2.y)/2.0
d = (r**2 - (q/2)**2)**0.5
[Circle.new(x3 - d*dy/q, y3 + d*dx/q, r),
Circle.new(x3 + d*dy/q, y3 - d*dx/q, r)].uniq
end
# Demo:
ar = [[Pt.new(0.1234, 0.9876), Pt.new(0.8765, 0.2345), 2.0],
[Pt.new(0.0000, 2.0000), Pt.new(0.0000, 0.0000), 1.0],
[Pt.new(0.1234, 0.9876), Pt.new(0.1234, 0.9876), 2.0],
[Pt.new(0.1234, 0.9876), Pt.new(0.8765, 0.2345), 0.5],
[Pt.new(0.1234, 0.9876), Pt.new(0.1234, 0.9876), 0.0]]
ar.each do |p1, p2, r|
print "Given points:\n #{p1.values},\n #{p2.values}\n and radius #{r}\n"
begin
circles = circles_from(p1, p2, r)
puts "You can construct the following circles:"
circles.each{|c| puts " #{c}"}
rescue ArgumentError => e
puts e
end
puts
end |
Cistercian numerals | Ruby from Lua | Cistercian numerals were used across Europe by Cistercian monks during the Late Medieval Period as an alternative to Roman numerals. They were used to represent base 10 integers from '''0''' to '''9999'''.
;How they work
All Cistercian numerals begin with a vertical line segment, which by itself represents the number '''0'''. Then, glyphs representing the digits '''1''' through '''9''' are optionally added to the four quadrants surrounding the vertical line segment. These glyphs are drawn with vertical and horizontal symmetry about the initial line segment. Each quadrant corresponds to a digit place in the number:
:* The '''upper-right''' quadrant represents the '''ones''' place.
:* The '''upper-left''' quadrant represents the '''tens''' place.
:* The '''lower-right''' quadrant represents the '''hundreds''' place.
:* The '''lower-left''' quadrant represents the '''thousands''' place.
Please consult the following image for examples of Cistercian numerals showing each glyph: [https://upload.wikimedia.org/wikipedia/commons/6/67/Cistercian_digits_%28vertical%29.svg]
;Task
:* Write a function/procedure/routine to display any given Cistercian numeral. This could be done by drawing to the display, creating an image, or even as text (as long as it is a reasonable facsimile).
:* Use the routine to show the following Cistercian numerals:
::* 0
::* 1
::* 20
::* 300
::* 4000
::* 5555
::* 6789
::* And a number of your choice!
;Notes
Due to the inability to upload images to Rosetta Code as of this task's creation, showing output here on this page is not required. However, it is welcomed -- especially for text output.
;See also
:* '''Numberphile - The Forgotten Number System'''
:* '''dcode.fr - Online Cistercian numeral converter'''
| def initN
n = Array.new(15){Array.new(11, ' ')}
for i in 1..15
n[i - 1][5] = 'x'
end
return n
end
def horiz(n, c1, c2, r)
for c in c1..c2
n[r][c] = 'x'
end
end
def verti(n, r1, r2, c)
for r in r1..r2
n[r][c] = 'x'
end
end
def diagd(n, c1, c2, r)
for c in c1..c2
n[r+c-c1][c] = 'x'
end
end
def diagu(n, c1, c2, r)
for c in c1..c2
n[r-c+c1][c] = 'x'
end
end
def initDraw
draw = []
draw[1] = lambda do |n| horiz(n, 6, 10, 0) end
draw[2] = lambda do |n| horiz(n, 6, 10, 4) end
draw[3] = lambda do |n| diagd(n, 6, 10, 0) end
draw[4] = lambda do |n| diagu(n, 6, 10, 4) end
draw[5] = lambda do |n|
draw[1].call(n)
draw[4].call(n)
end
draw[6] = lambda do |n| verti(n, 0, 4, 10) end
draw[7] = lambda do |n|
draw[1].call(n)
draw[6].call(n)
end
draw[8] = lambda do |n|
draw[2].call(n)
draw[6].call(n)
end
draw[9] = lambda do |n|
draw[1].call(n)
draw[8].call(n)
end
draw[10] = lambda do |n| horiz(n, 0, 4, 0) end
draw[20] = lambda do |n| horiz(n, 0, 4, 4) end
draw[30] = lambda do |n| diagu(n, 0, 4, 4) end
draw[40] = lambda do |n| diagd(n, 0, 4, 0) end
draw[50] = lambda do |n|
draw[10].call(n)
draw[40].call(n)
end
draw[60] = lambda do |n| verti(n, 0, 4, 0) end
draw[70] = lambda do |n|
draw[10].call(n)
draw[60].call(n)
end
draw[80] = lambda do |n|
draw[20].call(n)
draw[60].call(n)
end
draw[90] = lambda do |n|
draw[10].call(n)
draw[80].call(n)
end
draw[100] = lambda do |n| horiz(n, 6, 10, 14) end
draw[200] = lambda do |n| horiz(n, 6, 10, 10) end
draw[300] = lambda do |n| diagu(n, 6, 10, 14) end
draw[400] = lambda do |n| diagd(n, 6, 10, 10) end
draw[500] = lambda do |n|
draw[100].call(n)
draw[400].call(n)
end
draw[600] = lambda do |n| verti(n, 10, 14, 10) end
draw[700] = lambda do |n|
draw[100].call(n)
draw[600].call(n)
end
draw[800] = lambda do |n|
draw[200].call(n)
draw[600].call(n)
end
draw[900] = lambda do |n|
draw[100].call(n)
draw[800].call(n)
end
draw[1000] = lambda do |n| horiz(n, 0, 4, 14) end
draw[2000] = lambda do |n| horiz(n, 0, 4, 10) end
draw[3000] = lambda do |n| diagd(n, 0, 4, 10) end
draw[4000] = lambda do |n| diagu(n, 0, 4, 14) end
draw[5000] = lambda do |n|
draw[1000].call(n)
draw[4000].call(n)
end
draw[6000] = lambda do |n| verti(n, 10, 14, 0) end
draw[7000] = lambda do |n|
draw[1000].call(n)
draw[6000].call(n)
end
draw[8000] = lambda do |n|
draw[2000].call(n)
draw[6000].call(n)
end
draw[9000] = lambda do |n|
draw[1000].call(n)
draw[8000].call(n)
end
return draw
end
def printNumeral(n)
for a in n
for b in a
print b
end
print "\n"
end
print "\n"
end
draw = initDraw()
for number in [0, 1, 20, 300, 4000, 5555, 6789, 9999]
n = initN()
print number, ":\n"
thousands = (number / 1000).floor
number = number % 1000
hundreds = (number / 100).floor
number = number % 100
tens = (number / 10).floor
ones = number % 10
if thousands > 0 then
draw[thousands * 1000].call(n)
end
if hundreds > 0 then
draw[hundreds * 100].call(n)
end
if tens > 0 then
draw[tens * 10].call(n)
end
if ones > 0 then
draw[ones].call(n)
end
printNumeral(n)
end |
Closures/Value capture | Ruby | Create a list of ten functions, in the simplest manner possible (anonymous functions are encouraged), such that the function at index '' i '' (you may choose to start '' i '' from either '''0''' or '''1'''), when run, should return the square of the index, that is, '' i '' 2.
Display the result of running any but the last function, to demonstrate that the function indeed remembers its value.
;Goal:
Demonstrate how to create a series of independent closures based on the same template but maintain separate copies of the variable closed over.
In imperative languages, one would generally use a loop with a mutable counter variable.
For each function to maintain the correct number, it has to capture the ''value'' of the variable at the time it was created, rather than just a reference to the variable, which would have a different value by the time the function was run.
See also: [[Multiple distinct objects]]
| procs = Array.new(10){|i| ->{i*i} } # -> creates a lambda
p procs[7].call # => 49 |
Colorful numbers | Ruby | A '''colorful number''' is a non-negative base 10 integer where the product of every sub group of consecutive digits is unique.
;E.G.
24753 is a colorful number. 2, 4, 7, 5, 3, (2x4)8, (4x7)28, (7x5)35, (5x3)15, (2x4x7)56, (4x7x5)140, (7x5x3)105, (2x4x7x5)280, (4x7x5x3)420, (2x4x7x5x3)840
Every product is unique.
2346 is '''not''' a colorful number. 2, 3, 4, '''6''', (2x3)'''6''', (3x4)12, (4x6)24, (2x3x4)48, (3x4x6)72, (2x3x4x6)144
The product '''6''' is repeated.
Single digit numbers '''are''' considered to be colorful. A colorful number larger than 9 cannot contain a repeated digit, the digit 0 or the digit 1. As a consequence, there is a firm upper limit for colorful numbers; no colorful number can have more than 8 digits.
;Task
* Write a routine (subroutine, function, procedure, whatever it may be called in your language) to test if a number is a colorful number or not.
* Use that routine to find all of the colorful numbers less than 100.
* Use that routine to find the largest possible colorful number.
;Stretch
* Find and display the count of colorful numbers in each order of magnitude.
* Find and show the total count of '''all''' colorful numbers.
''Colorful numbers have no real number theory application. They are more a recreational math puzzle than a useful tool.''
| def colorful?(ar)
products = []
(1..ar.size).all? do |chunk_size|
ar.each_cons(chunk_size) do |chunk|
product = chunk.inject(&:*)
return false if products.include?(product)
products << product
end
end
end
below100 = (0..100).select{|n| colorful?(n.digits)}
puts "The colorful numbers less than 100 are:", below100.join(" "), ""
puts "Largest colorful number: #{(98765432.downto(1).detect{|n| colorful?(n.digits) })}", ""
total = 0
(1..8).each do |numdigs|
digits = (numdigs == 1 ? (0..9).to_a : (2..9).to_a)
count = digits.permutation(numdigs).count{|perm| colorful?(perm)}
puts "#{numdigs} digit colorful numbers count: #{count}"
total += count
end
puts "\nTotal colorful numbers: #{total}"
|
Comma quibbling | Ruby from Raku | Comma quibbling is a task originally set by Eric Lippert in his blog.
;Task:
Write a function to generate a string output which is the concatenation of input words from a list/sequence where:
# An input of no words produces the output string of just the two brace characters "{}".
# An input of just one word, e.g. ["ABC"], produces the output string of the word inside the two braces, e.g. "{ABC}".
# An input of two words, e.g. ["ABC", "DEF"], produces the output string of the two words inside the two braces with the words separated by the string " and ", e.g. "{ABC and DEF}".
# An input of three or more words, e.g. ["ABC", "DEF", "G", "H"], produces the output string of all but the last word separated by ", " with the last word separated by " and " and all within braces; e.g. "{ABC, DEF, G and H}".
Test your function with the following series of inputs showing your output here on this page:
* [] # (No input words).
* ["ABC"]
* ["ABC", "DEF"]
* ["ABC", "DEF", "G", "H"]
Note: Assume words are non-empty strings of uppercase characters for this task.
| def comma_quibbling(a)
%w<{ }>.join(a.length < 2 ? a.first :
"#{a[0..-2].join(', ')} and #{a[-1]}")
end
[[], %w<ABC>, %w<ABC DEF>, %w<ABC DEF G H>].each do |a|
puts comma_quibbling(a)
end |
Compare a list of strings | Ruby | Given a list of arbitrarily many strings, show how to:
* test if they are all lexically '''equal'''
* test if every string is lexically '''less than''' the one after it ''(i.e. whether the list is in strict ascending order)''
Each of those two tests should result in a single true or false value, which could be used as the condition of an if statement or similar.
If the input list has less than two elements, the tests should always return true.
There is ''no'' need to provide a complete program and output.
Assume that the strings are already stored in an array/list/sequence/tuple variable (whatever is most idiomatic) with the name strings, and just show the expressions for performing those two tests on it (plus of course any includes and custom functions etc. that it needs), with as little distractions as possible.
Try to write your solution in a way that does not modify the original list, but if it does then please add a note to make that clear to readers.
If you need further guidance/clarification, see [[#Perl]] and [[#Python]] for solutions that use implicit short-circuiting loops, and [[#Raku]] for a solution that gets away with simply using a built-in language feature.
| strings.all?{|str| str == strings.first} # all equal?
strings.each_cons(2).all?{|str1, str2| str1 < str2} # ascending? |
Composite numbers k with no single digit factors whose factors are all substrings of k | Ruby | Find the composite numbers '''k''' in base 10, that have no single digit prime factors and whose prime factors are all a substring of '''k'''.
;Task
* Find and show here, on this page, the first ten elements of the sequence.
;Stretch
* Find and show the next ten elements.
| require 'prime'
generator2357 = Enumerator.new do |y|
gen23 = Prime::Generator23.new
gen23.each {|n| y << n unless (n%5 == 0 || n%7 == 0) }
end
res = generator2357.lazy.select do |n|
primes, exp = n.prime_division.transpose
next if exp.sum < 2 #exclude primes
s = n.to_s
primes.all?{|pr| s.match?(-pr.to_s) }
end
res.take(10).each{|n| puts n} |
Conjugate transpose | Ruby 2.0 | Suppose that a conjugate transpose of M is a matrix M^H containing the [[complex conjugate]]s of the [[matrix transposition]] of M.
::: (M^H)_{ji} = \overline{M_{ij}}
This means that row j, column i of the conjugate transpose equals the
complex conjugate of row i, column j of the original matrix.
In the next list, M must also be a square matrix.
* A Hermitian matrix equals its own conjugate transpose: M^H = M.
* A multiplication with its conjugate transpose: M^HM = MM^H.
* A iff M^HM = I_n and iff MM^H = I_n, where I_n is the identity matrix.
;Task:
Given some matrix of complex numbers, find its conjugate transpose.
Also determine if the matrix is a:
::* Hermitian matrix,
::* normal matrix, or
::* unitary matrix.
;See also:
* MathWorld entry: conjugate transpose
* MathWorld entry: Hermitian matrix
* MathWorld entry: normal matrix
* MathWorld entry: unitary matrix
| require 'matrix'
# Start with some matrix.
i = Complex::I
matrix = Matrix[[i, 0, 0],
[0, i, 0],
[0, 0, i]]
# Find the conjugate transpose.
# Matrix#conjugate appeared in Ruby 1.9.2.
conjt = matrix.conj.t # aliases for matrix.conjugate.tranpose
print 'conjugate tranpose: '; puts conjt
if matrix.square?
# These predicates appeared in Ruby 1.9.3.
print 'Hermitian? '; puts matrix.hermitian?
print ' normal? '; puts matrix.normal?
print ' unitary? '; puts matrix.unitary?
else
# Matrix is not square. These predicates would
# raise ExceptionForMatrix::ErrDimensionMismatch.
print 'Hermitian? false'
print ' normal? false'
print ' unitary? false'
end |
Continued fraction | Ruby | A number may be represented as a continued fraction (see Mathworld for more information) as follows:
:a_0 + \cfrac{b_1}{a_1 + \cfrac{b_2}{a_2 + \cfrac{b_3}{a_3 + \ddots}}}
The task is to write a program which generates such a number and prints a real representation of it. The code should be tested by calculating and printing the square root of 2, Napier's Constant, and Pi, using the following coefficients:
For the square root of 2, use a_0 = 1 then a_N = 2. b_N is always 1.
:\sqrt{2} = 1 + \cfrac{1}{2 + \cfrac{1}{2 + \cfrac{1}{2 + \ddots}}}
For Napier's Constant, use a_0 = 2, then a_N = N. b_1 = 1 then b_N = N-1.
:e = 2 + \cfrac{1}{1 + \cfrac{1}{2 + \cfrac{2}{3 + \cfrac{3}{4 + \ddots}}}}
For Pi, use a_0 = 3 then a_N = 6. b_N = (2N-1)^2.
:\pi = 3 + \cfrac{1}{6 + \cfrac{9}{6 + \cfrac{25}{6 + \ddots}}}
;See also:
:* [[Continued fraction/Arithmetic]] for tasks that do arithmetic over continued fractions.
| require 'bigdecimal'
# square root of 2
sqrt2 = Object.new
def sqrt2.a(n); n == 1 ? 1 : 2; end
def sqrt2.b(n); 1; end
# Napier's constant
napier = Object.new
def napier.a(n); n == 1 ? 2 : n - 1; end
def napier.b(n); n == 1 ? 1 : n - 1; end
pi = Object.new
def pi.a(n); n == 1 ? 3 : 6; end
def pi.b(n); (2*n - 1)**2; end
# Estimates the value of a continued fraction _cfrac_, to _prec_
# decimal digits of precision. Returns a BigDecimal. _cfrac_ must
# respond to _cfrac.a(n)_ and _cfrac.b(n)_ for integer _n_ >= 1.
def estimate(cfrac, prec)
last_result = nil
terms = prec
loop do
# Estimate continued fraction for _n_ from 1 to _terms_.
result = cfrac.a(terms)
(terms - 1).downto(1) do |n|
a = BigDecimal cfrac.a(n)
b = BigDecimal cfrac.b(n)
digits = [b.div(result, 1).exponent + prec, 1].max
result = a + b.div(result, digits)
end
result = result.round(prec)
if result == last_result
return result
else
# Double _terms_ and try again.
last_result = result
terms *= 2
end
end
end
puts estimate(sqrt2, 50).to_s('F')
puts estimate(napier, 50).to_s('F')
puts estimate(pi, 10).to_s('F') |
Continued fraction/Arithmetic/Construct from rational number | Ruby | To understand this task in context please see [[Continued fraction arithmetic]]
The purpose of this task is to write a function \mathit{r2cf}(\mathrm{int} N_1, \mathrm{int} N_2), or \mathit{r2cf}(\mathrm{Fraction} N), which will output a continued fraction assuming:
:N_1 is the numerator
:N_2 is the denominator
The function should output its results one digit at a time each time it is called, in a manner sometimes described as lazy evaluation.
To achieve this it must determine: the integer part; and remainder part, of N_1 divided by N_2. It then sets N_1 to N_2 and N_2 to the determined remainder part. It then outputs the determined integer part. It does this until \mathrm{abs}(N_2) is zero.
Demonstrate the function by outputing the continued fraction for:
: 1/2
: 3
: 23/8
: 13/11
: 22/7
: -151/77
\sqrt 2 should approach [1; 2, 2, 2, 2, \ldots] try ever closer rational approximations until boredom gets the better of you:
: 14142,10000
: 141421,100000
: 1414214,1000000
: 14142136,10000000
Try :
: 31,10
: 314,100
: 3142,1000
: 31428,10000
: 314285,100000
: 3142857,1000000
: 31428571,10000000
: 314285714,100000000
Observe how this rational number behaves differently to \sqrt 2 and convince yourself that, in the same way as 3.7 may be represented as 3.70 when an extra decimal place is required, [3;7] may be represented as [3;7,\infty] when an extra term is required.
| [[1,2], [3,1], [23,8], [13,11], [22,7], [-151,77]].each do |n1,n2|
print "%10s : " % "#{n1} / #{n2}"
r2cf(n1,n2) {|n| print "#{n} "}
puts
end |
Continued fraction/Arithmetic/G(matrix ng, continued fraction n) | Ruby | This task investigates mathmatical operations that can be performed on a single continued fraction. This requires only a baby version of NG:
: \begin{bmatrix}
a_1 & a \\
b_1 & b
\end{bmatrix}
I may perform perform the following operations:
:Input the next term of N1
:Output a term of the continued fraction resulting from the operation.
I output a term if the integer parts of \frac{a}{b} and \frac{a_1}{b_1} are equal. Otherwise I input a term from N. If I need a term from N but N has no more terms I inject \infty.
When I input a term t my internal state: \begin{bmatrix}
a_1 & a \\
b_1 & b
\end{bmatrix} is transposed thus \begin{bmatrix} a + a_1 * t & a_1 \\
b + b_1 * t & b_1
\end{bmatrix}
When I output a term t my internal state: \begin{bmatrix}
a_1 & a \\
b_1 & b
\end{bmatrix} is transposed thus \begin{bmatrix} b_1 & b \\
a_1 - b_1 * t & a - b * t
\end{bmatrix}
When I need a term t but there are no more my internal state: \begin{bmatrix}
a_1 & a \\
b_1 & b
\end{bmatrix} is transposed thus \begin{bmatrix} a_1 & a_1 \\
b_1 & b_1
\end{bmatrix}
I am done when b1 and b are zero.
Demonstrate your solution by calculating:
:[1;5,2] + 1/2
:[3;7] + 1/2
:[3;7] divided by 4
Using a generator for \sqrt{2} (e.g., from [[Continued fraction]]) calculate \frac{1}{\sqrt{2}}. You are now at the starting line for using Continued Fractions to implement [[Arithmetic-geometric mean]] without ulps and epsilons.
The first step in implementing [[Arithmetic-geometric mean]] is to calculate \frac{1 + \frac{1}{\sqrt{2}}}{2} do this now to cross the starting line and begin the race.
| # I define a class to implement baby NG
class NG
def initialize(a1, a, b1, b)
@a1, @a, @b1, @b = a1, a, b1, b
end
def ingress(n)
@a, @a1 = @a1, @a + @a1 * n
@b, @b1 = @b1, @b + @b1 * n
end
def needterm?
return true if @b == 0 or @b1 == 0
return true unless @a/@b == @a1/@b1
false
end
def egress
n = @a / @b
@a, @b = @b, @a - @b * n
@a1, @b1 = @b1, @a1 - @b1 * n
n
end
def egress_done
@a, @b = @a1, @b1 if needterm?
egress
end
def done?
@b == 0 and @b1 == 0
end
end |
Subsets and Splits