September 2017 Update

This commit is contained in:
Ingy döt Net 2017-09-23 10:01:46 +02:00
parent bba7bfd280
commit ba8067c3b7
14570 changed files with 153136 additions and 63871 deletions

View file

@ -0,0 +1,41 @@
begin
% prints a Floyd's Triangle with n lines %
procedure floydsTriangle ( integer value n ) ;
begin
% the triangle should be left aligned with the individual numbers %
% right-aligned with only one space before the number in the final %
% row %
% calculate the highest number that will be printed %
% ( the sum of the integeregers 1, 2, ... n ) %
integer array widths( 1 :: n );
integer maxNumber, number;
maxNumber := ( n * ( n + 1 ) ) div 2;
% determine the widths required to print the numbers of the final row %
number := maxNumber;
for col := n step -1 until 1 do begin
integer v, w;
w := 0;
v := number;
number := number - 1;
while v > 0 do begin
w := w + 1;
v := v div 10
end while_v_gt_0 ;
widths( col ) := w
end for_col;
% print the triangle %
number := 0;
for row := 1 until n do begin
for col := 1 until row do begin
number := number + 1;
writeon( i_w := widths( col ), s_w := 0, " ", number )
end for_col ;
write()
end for_row
end; % floyds triangle %
floydsTriangle( 5 );
write();
floydsTriangle( 14 )
end.

View file

@ -1,23 +1,12 @@
with Ada.Text_IO, Ada.Integer_Text_IO, Ada.Command_Line;
procedure Floyd_Triangle is
Rows: constant Positive := Integer'Value(Ada.Command_Line.Argument(1));
Current: Positive := 1;
Width: array(1 .. Rows) of Positive;
rows : constant Natural := Natural'Value(Ada.Command_Line.Argument(1));
begin
-- compute the width for the different columns
for I in Width'Range loop
Width(I) := Integer'Image(I + (Rows * (Rows-1))/2)'Length;
end loop;
-- output the triangle
for Line in 1 .. Rows loop
for Column in 1 .. Line loop
Ada.Integer_Text_IO.Put(Current, Width => Width(Column));
Current := Current + 1;
end loop;
Ada.Text_IO.New_Line;
end loop;
for r in 1..rows loop
for i in 1..r loop
Ada.Integer_Text_IO.put (r*(r-1)/2+i, Width=> Natural'Image(rows*(rows-1)/2+i)'Length);
end loop;
Ada.Text_IO.New_Line;
end loop;
end Floyd_Triangle;

View file

@ -0,0 +1,276 @@
-- FLOYDs TRIANGLE -----------------------------------------------------------
-- floyd :: Int -> [[Int]]
on floyd(n)
script floydRow
on |λ|(start, row)
{start + row + 1, enumFromTo(start, start + row)}
end |λ|
end script
snd(mapAccumL(floydRow, 1, enumFromTo(0, n - 1)))
end floyd
-- showFloyd :: [[Int]] -> String
on showFloyd(xss)
set ws to map(compose({my succ, my |length|, my show}), |last|(xss))
script aligned
on |λ|(xs)
script pad
on |λ|(w, x)
justifyRight(w, space, show(x))
end |λ|
end script
concat(zipWith(pad, ws, xs))
end |λ|
end script
unlines(map(aligned, xss))
end showFloyd
-- TEST ----------------------------------------------------------------------
on run
script test
on |λ|(n)
showFloyd(floyd(n)) & linefeed
end |λ|
end script
unlines(map(test, {5, 14}))
end run
-- GENERIC FUNCTIONS ---------------------------------------------------------
-- compose :: [(a -> a)] -> (a -> a)
on compose(fs)
script
on |λ|(x)
script
on |λ|(f, a)
mReturn(f)'s |λ|(a)
end |λ|
end script
foldr(result, x, fs)
end |λ|
end script
end compose
-- concat :: [[a]] -> [a] | [String] -> String
on concat(xs)
if length of xs > 0 and class of (item 1 of xs) is string then
set acc to ""
else
set acc to {}
end if
repeat with i from 1 to length of xs
set acc to acc & item i of xs
end repeat
acc
end concat
-- enumFromTo :: Int -> Int -> [Int]
on enumFromTo(m, n)
if n < m then
set d to -1
else
set d to 1
end if
set lst to {}
repeat with i from m to n by d
set end of lst to i
end repeat
return lst
end enumFromTo
-- foldl :: (a -> b -> a) -> a -> [b] -> a
on foldl(f, startValue, xs)
tell mReturn(f)
set v to startValue
set lng to length of xs
repeat with i from 1 to lng
set v to |λ|(v, item i of xs, i, xs)
end repeat
return v
end tell
end foldl
-- foldr :: (b -> a -> a) -> a -> [b] -> a
on foldr(f, startValue, xs)
tell mReturn(f)
set v to startValue
set lng to length of xs
repeat with i from lng to 1 by -1
set v to |λ|(item i of xs, v, i, xs)
end repeat
return v
end tell
end foldr
-- intercalate :: Text -> [Text] -> Text
on intercalate(strText, lstText)
set {dlm, my text item delimiters} to {my text item delimiters, strText}
set strJoined to lstText as text
set my text item delimiters to dlm
return strJoined
end intercalate
-- justifyRight :: Int -> Char -> Text -> Text
on justifyRight(n, cFiller, strText)
if n > length of strText then
text -n thru -1 of ((replicate(n, cFiller) as text) & strText)
else
strText
end if
end justifyRight
-- last :: [a] -> a
on |last|(xs)
if length of xs > 0 then
item -1 of xs
else
missing value
end if
end |last|
-- length :: [a] -> Int
on |length|(xs)
length of xs
end |length|
-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
tell mReturn(f)
set lng to length of xs
set lst to {}
repeat with i from 1 to lng
set end of lst to |λ|(item i of xs, i, xs)
end repeat
return lst
end tell
end map
-- 'The mapAccumL function behaves like a combination of map and foldl;
-- it applies a function to each element of a list, passing an
-- accumulating parameter from left to right, and returning a final
-- value of this accumulator together with the new list.' (see Hoogle)
-- mapAccumL :: (acc -> x -> (acc, y)) -> acc -> [x] -> (acc, [y])
on mapAccumL(f, acc, xs)
script
on |λ|(a, x)
tell mReturn(f) to set pair to |λ|(item 1 of a, x)
[item 1 of pair, (item 2 of a) & {item 2 of pair}]
end |λ|
end script
foldl(result, [acc, []], xs)
end mapAccumL
-- min :: Ord a => a -> a -> a
on min(x, y)
if y < x then
y
else
x
end if
end min
-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: Handler -> Script
on mReturn(f)
if class of f is script then
f
else
script
property |λ| : f
end script
end if
end mReturn
-- Egyptian multiplication - progressively doubling a list, appending
-- stages of doubling to an accumulator where needed for binary
-- assembly of a target length
-- replicate :: Int -> a -> [a]
on replicate(n, a)
set out to {}
if n < 1 then return out
set dbl to {a}
repeat while (n > 1)
if (n mod 2) > 0 then set out to out & dbl
set n to (n div 2)
set dbl to (dbl & dbl)
end repeat
return out & dbl
end replicate
-- snd :: (a, b) -> b
on snd(xs)
if class of xs is list and length of xs > 1 then
item 2 of xs
else
missing value
end if
end snd
-- show :: a -> String
on show(e)
set c to class of e
if c = list then
script serialized
on |λ|(v)
show(v)
end |λ|
end script
"{" & intercalate(", ", map(serialized, e)) & "}"
else if c = record then
script showField
on |λ|(kv)
set {k, v} to kv
k & ":" & show(v)
end |λ|
end script
"{" & intercalate(", ", ¬
map(showField, zip(allKeys(e), allValues(e)))) & "}"
else if c = date then
("date \"" & e as text) & "\""
else if c = text then
"\"" & e & "\""
else
try
e as text
on error
("«" & c as text) & "»"
end try
end if
end show
-- succ :: Int -> Int
on succ(x)
x + 1
end succ
-- unlines :: [String] -> String
on unlines(xs)
intercalate(linefeed, xs)
end unlines
-- zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
on zipWith(f, xs, ys)
set lng to min(length of xs, length of ys)
set lst to {}
tell mReturn(f)
repeat with i from 1 to lng
set end of lst to |λ|(item i of xs, item i of ys)
end repeat
return lst
end tell
end zipWith

View file

@ -0,0 +1,52 @@
@echo off
call:floyd 5
echo.
call:floyd 14
pause>nul
exit /b
:floyd
setlocal enabledelayedexpansion
set iterations=%1
set startn=1
set endn=1
for /l %%i in (1,1,%iterations%) do (
for /l %%j in (!startn!,1,!endn!) do (
set lastnum=%%j
set /a startn=%%j+1
)
set /a endn=!startn!+%%i
)
call:getlength %startn%
set digits=%errorlevel%
set startn=1
set endn=1
for /l %%i in (1,1,%iterations%) do (
set "line="
for /l %%j in (!startn!,1,!endn!) do (
set "space="
call:getlength %%j
set /a sparespace=%digits%-!errorlevel!
for /l %%k in (0,1,!sparespace!) do set "space=!space! "
set line=!line!!space!%%j
set /a startn=%%j+1
)
echo !line!
set /a endn=!startn!+%%i
)
exit /b
:getlength
setlocal enabledelayedexpansion
set offset=0
set string=%1
:floydloop
if "!string:~%offset%,1!"=="" endlocal && exit /b %offset%
set /a offset+=1
goto floydloop

View file

@ -0,0 +1,17 @@
(defn TriangleList [n]
(let [l (map inc (range))]
(loop [l l x 1 nl []]
(if (= n (count nl))
nl
(recur (drop x l) (inc x) (conj nl (take x l)))))))
(defn TrianglePrint [n]
(let [t (TriangleList n)
m (count (str (last (last t))))
f (map #(map str %) t)
l (map #(map (fn [x] (if (> m (count x))
(str (apply str (take (- m (count x))
(repeat " "))) x)
x)) %) f)
e (map #(map (fn [x] (str " " x)) %) l)]
(map #(println (apply str %)) e)))

View file

@ -0,0 +1,25 @@
Public Sub Main()
Dim siCount, siNo, siCounter As Short
Dim siLine As Short = 1
Dim siInput As Short[] = [5, 14]
For siCount = 0 To siInput.Max
Print "Floyd's triangle to " & siInput[siCount] & " lines"
Do
Inc siNo
Inc siCounter
Print Format(siNo, "####");
If siLine = siCounter Then
Print
Inc siLine
siCounter = 0
End If
If siLine - 1 = siInput[siCount] Then Break
Loop
siLine = 1
siCounter = 0
siNo = 0
Print
Next
End

View file

@ -1,12 +1,17 @@
import Data.List
import Control.Monad
import Control.Arrow
import Control.Monad (liftM2)
floydTriangle =
liftM2
(zipWith (liftM2 (.) enumFromTo ((pred .) . (+))))
(scanl (+) 1)
id
[1 ..]
alignR :: Int -> Integer -> String
alignR n = (\s -> replicate (n - length s) ' ' ++ s). show
alignR n = (\s -> replicate (n - length s) ' ' ++ s) . show
floydTriangle = liftM2 (zipWith (liftM2 (.) enumFromTo ((pred.). (+)))) (scanl (+) 1) id [1..]
formatFT n = mapM_ (putStrLn. unwords. zipWith alignR ws) t where
t = take n floydTriangle
ws = map (length. show) $ last t
formatFT :: Int -> IO ()
formatFT n = mapM_ (putStrLn . unwords . zipWith alignR ws) t
where
t = take n floydTriangle
ws = map (length . show) $ last t

View file

@ -0,0 +1,21 @@
import Data.List (mapAccumL)
floyd :: Int -> [[Int]]
floyd n =
snd $
mapAccumL
(\start row -> (start + succ row, [start .. start + row]))
1
[0 .. pred n]
-- TEST -----------------------------------------------------------------------
showFloyd :: [[Int]] -> String
showFloyd xs =
let padRight n = length >>= (<$> mappend (replicate n ' ')) . drop
in unlines $
(concat .
zipWith ((. show) . padRight) ((succ . length . show) <$> last xs)) <$>
xs
main :: IO ()
main = mapM_ putStrLn $ (showFloyd . floyd) <$> [5, 14]

View file

@ -1,78 +1,121 @@
// Floyd triangles of 5 and 14 rows
// right-aligned monospaced columns (nMargin allows for extra spacing)
// () --> s
function main() {
// minimum space between numbers - adjust for visual preference
var nMargin = 1;
(function () {
'use strict';
// Formatted strings for Floyd's triangles of 5 and 14 rows
return (function (lstN) {
return lstN.map(function (nFloydRows) {
var lstRows = floydIntegerLists(nFloydRows),
iLast = nFloydRows - 1;
// FLOYD's TRIANGLE -------------------------------------------------------
return colsSpacedRight(
lstRows,
// Minimum space required per number cell
// nMargin more than the width of the final number
lstRows[iLast][iLast].toString().length + nMargin
)
}).join('\n\n');
})([5, 14]);
}
// floyd :: Int -> [[Int]]
function floyd(n) {
return snd(mapAccumL(function (start, row) {
return [start + row + 1, enumFromTo(start, start + row)];
}, 1, enumFromTo(0, n - 1)));
};
// n Floyd's triangle rows
// n --> [[n]]
function floydIntegerLists(nRows) {
// showFloyd :: [[Int]] -> String
function showFloyd(xss) {
var ws = map(compose([succ, length, show]), last(xss));
return unlines(map(function (xs) {
return concat(zipWith(function (w, x) {
return justifyRight(w, ' ', show(x));
}, ws, xs));
}, xss));
};
// Full integer list folded into list of rows
// [n] --> [[n]]
return (function triangleNumbers(lstInt, startWidth) {
var n = startWidth || 1;
return n > lstInt.length ? [] : [lstInt.slice(0, n)].concat(
triangleNumbers(lstInt.slice(n), n + 1)
)
})(
range(
1,
Math.floor(
(nRows * nRows) / 2
) + Math.ceil(
nRows / 2
)
)
);
}
// GENERIC FUNCTIONS ------------------------------------------------------
// list of list of numbers --> lines of fixed right-aligned col width
// [[n]] --> s
function colsSpacedRight(lstLines, nColWidth) {
return lstLines.reduce(
function (s, line) {
return s + line.map(function (n) {
return rightAligned(n, nColWidth)
}).join('') + '\n';
}, ''
)
}
// compose :: [(a -> a)] -> (a -> a)
function compose(fs) {
return function (x) {
return fs.reduceRight(function (a, f) {
return f(a);
}, x);
};
};
// range(1, 20) --> [1..20]
function range(m, n) {
return Array.apply(null, Array(n - m + 1)).map(
function (x, i) {
// concat :: [[a]] -> [a] | [String] -> String
function concat(xs) {
if (xs.length > 0) {
var unit = typeof xs[0] === 'string' ? '' : [];
return unit.concat.apply(unit, xs);
} else return [];
};
// enumFromTo :: Int -> Int -> [Int]
function enumFromTo(m, n) {
return Array.from({
length: Math.floor(n - m) + 1
}, function (_, i) {
return m + i;
}
);
}
});
};
// Integer as right-padded string of given width
// n --> n --> s
function rightAligned(n, width) {
var strN = n.toString();
return Array(width - strN.length + 1).join(' ') + strN;
}
// justifyRight :: Int -> Char -> Text -> Text
function justifyRight(n, cFiller, strText) {
return n > strText.length ? (cFiller.repeat(n) + strText)
.slice(-n) : strText;
};
console.log( // if the context is a browser
main()
);
// last :: [a] -> a
function last(xs) {
return xs.length ? xs.slice(-1)[0] : undefined;
};
// length :: [a] -> Int
function length(xs) {
return xs.length;
};
// map :: (a -> b) -> [a] -> [b]
function map(f, xs) {
return xs.map(f);
};
// 'The mapAccumL function behaves like a combination of map and foldl;
// it applies a function to each element of a list, passing an accumulating
// parameter from left to right, and returning a final value of this
// accumulator together with the new list.' (See hoogle )
// mapAccumL :: (acc -> x -> (acc, y)) -> acc -> [x] -> (acc, [y])
function mapAccumL(f, acc, xs) {
return xs.reduce(function (a, x) {
var pair = f(a[0], x);
return [pair[0], a[1].concat([pair[1]])];
}, [acc, []]);
};
// show ::
// (a -> String) f, Num n =>
// a -> maybe f -> maybe n -> String
var show = JSON.stringify;
// snd :: (a, b) -> b
function snd(tpl) {
return Array.isArray(tpl) ? tpl[1] : undefined;
};
// succ :: Int -> Int
function succ(x) {
return x + 1;
};
// unlines :: [String] -> String
function unlines(xs) {
return xs.join('\n');
};
// zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
function zipWith(f, xs, ys) {
var ny = ys.length;
return (xs.length <= ny ? xs : xs.slice(0, ny))
.map(function (x, i) {
return f(x, ys[i]);
});
};
// TEST ( n=5 and n=14 rows ) ---------------------------------------------
return unlines(map(function (n) {
return showFloyd(floyd(n)) + '\n';
}, [5, 14]));
})();

View file

@ -1,36 +1,97 @@
#!/usr/bin/env js
(() => {
'use strict';
function main() {
print('Floyd 5:');
floyd(5);
print('\nFloyd 14:');
floyd(14);
}
// FLOYD's TRIANGLE -------------------------------------------------------
// floyd :: Int -> [[Int]]
const floyd = n => snd(mapAccumL(
(start, row) => [start + row + 1, enumFromTo(start, start + row)],
1, enumFromTo(0, n - 1)
));
// showFloyd :: [[Int]] -> String
const showFloyd = xss => {
const ws = map(compose([succ, length, show]), last(xss));
return unlines(
map(xs => concat(zipWith(
(w, x) => justifyRight(w, ' ', show(x)), ws, xs
)),
xss
)
);
};
// GENERIC FUNCTIONS ------------------------------------------------------
// compose :: [(a -> a)] -> (a -> a)
const compose = fs => x => fs.reduceRight((a, f) => f(a), x);
// concat :: [[a]] -> [a] | [String] -> String
const concat = xs => {
if (xs.length > 0) {
const unit = typeof xs[0] === 'string' ? '' : [];
return unit.concat.apply(unit, xs);
} else return [];
};
// enumFromTo :: Int -> Int -> [Int]
const enumFromTo = (m, n) =>
Array.from({
length: Math.floor(n - m) + 1
}, (_, i) => m + i);
// justifyRight :: Int -> Char -> Text -> Text
const justifyRight = (n, cFiller, strText) =>
n > strText.length ? (
(cFiller.repeat(n) + strText)
.slice(-n)
) : strText;
// last :: [a] -> a
const last = xs => xs.length ? xs.slice(-1)[0] : undefined;
// length :: [a] -> Int
const length = xs => xs.length;
// map :: (a -> b) -> [a] -> [b]
const map = (f, xs) => xs.map(f)
// 'The mapAccumL function behaves like a combination of map and foldl;
// it applies a function to each element of a list, passing an accumulating
// parameter from left to right, and returning a final value of this
// accumulator together with the new list.' (See hoogle )
// mapAccumL :: (acc -> x -> (acc, y)) -> acc -> [x] -> (acc, [y])
const mapAccumL = (f, acc, xs) =>
xs.reduce((a, x) => {
const pair = f(a[0], x);
return [pair[0], a[1].concat([pair[1]])];
}, [acc, []]);
// show ::
// (a -> String) f, Num n =>
// a -> maybe f -> maybe n -> String
const show = JSON.stringify;
// snd :: (a, b) -> b
const snd = tpl => Array.isArray(tpl) ? tpl[1] : undefined;
// succ :: Int -> Int
const succ = x => x + 1
// unlines :: [String] -> String
const unlines = xs => xs.join('\n');
function padLeft(s, w) {
for (s = String(s); s.length < w; s = ' ' + s);
return s;
}
// zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
const zipWith = (f, xs, ys) => {
const ny = ys.length;
return (xs.length <= ny ? xs : xs.slice(0, ny))
.map((x, i) => f(x, ys[i]));
};
// TEST ( n=5 and n=14 rows ) ---------------------------------------------
function floyd(nRows) {
var lowerLeft = nRows * (nRows - 1) / 2 + 1;
var lowerRight = nRows * (nRows + 1) / 2;
var colWidths = [];
for (var col = lowerLeft; col <= lowerRight; col++) {
colWidths.push(String(col).length);
}
var num = 1;
for (var row = 0; row < nRows; row++) {
var line = [];
for (var col = 0; col <= row; col++, num++) {
line.push(padLeft(num, colWidths[col]));
}
print(line.join(' '));
}
}
main();
return unlines(map(n => showFloyd(floyd(n)) + '\n', [5, 14]))
})();

View file

@ -0,0 +1,36 @@
#!/usr/bin/env js
function main() {
print('Floyd 5:');
floyd(5);
print('\nFloyd 14:');
floyd(14);
}
function padLeft(s, w) {
for (s = String(s); s.length < w; s = ' ' + s);
return s;
}
function floyd(nRows) {
var lowerLeft = nRows * (nRows - 1) / 2 + 1;
var lowerRight = nRows * (nRows + 1) / 2;
var colWidths = [];
for (var col = lowerLeft; col <= lowerRight; col++) {
colWidths.push(String(col).length);
}
var num = 1;
for (var row = 0; row < nRows; row++) {
var line = [];
for (var col = 0; col <= row; col++, num++) {
line.push(padLeft(num, colWidths[col]));
}
print(line.join(' '));
}
}
main();

View file

@ -1,7 +1,6 @@
function floyds_triangle(n)
width = 1+floor(log10(nr*(nr+1)/2));
for k=1:n,
fprintf(stdout,' %*i',[width(ones(1,k));k*(k-1)/2+1:k*(k+1)/2]);
fprintf(stdout,'\n');
end;
s = 1;
for k = 1 : n
disp(s : s + k - 1)
s = s + k;
end

View file

@ -0,0 +1,17 @@
procedure Floyds_triangle(integer n)
sequence widths = repeat(0,n)
integer k = (n * (n-1))/2
for i=1 to n do
widths[i] = sprintf("%%%dd",length(sprintf("%d",i+k))+1)
end for
k = 1
for i=1 to n do
for j=1 to i do
printf(1,widths[j],k)
k += 1
end for
printf(1,"\n")
end for
end procedure
Floyds_triangle(5)
Floyds_triangle(14)

View file

@ -1,12 +1,11 @@
/*REXX program constructs & displays Floyd's triangle for any number of specified rows.*/
parse arg rows .; if rows=='' then rows=5 /*Not specified? Then use the default.*/
mx=rows * (rows+1) % 2 /*calculate maximum value of any value.*/
say 'displaying a ' rows " row Floyd's triangle:" /*show header for the triangle.*/
parse arg N .; if N=='' | N=="," then N=5 /*Not specified? Then use the default.*/
mx=N * (N+1) % 2 - N /*calculate maximum value of any value.*/
say 'displaying a ' N " row Floyd's triangle:" /*show the header for Floyd's triangle.*/
say
#=1; do r=1 for rows; i=0; _= /*construct Floyd's triangle row by row*/
do #=# for r; i=i+1 /*start to construct a row of triangle.*/
_=_ right(#, length(mx-rows+i)) /*build a row of the Floyd's triangle. */
#=1; do r=1 for N; i=0; _= /*construct Floyd's triangle row by row*/
do #=# for r; i=i+1 /*start to construct a row of triangle.*/
_=_ right(#, length( mx+i ) ) /*build a row of the Floyd's triangle. */
end /*#*/
say substr(_,2) /*remove 1st leading blank in the line,*/
end /*r*/ /* [↑] introduced by first abutment. */
/*stick a fork in it, we're all done. */
say substr(_, 2) /*remove 1st leading blank in the line.*/
end /*r*/ /*stick a fork in it, we're all done. */

View file

@ -1,12 +1,11 @@
/*REXX program constructs & displays Floyd's triangle for any number of rows in base 16.*/
parse arg rows .; if rows=='' then rows=6 /*Not specified? Then use the default.*/
mx=rows * (rows+1) % 2 /*calculate maximum value of any value.*/
say 'displaying a ' rows " row Floyd's triangle in base 16:"; say /*show triangle hdr*/
#=1
do r=1 for rows; i=0; _= /*construct Floyd's triangle row by row*/
do #=# for r; i=i+1 /*start to construct a row of triangle.*/
_=_ right(d2x(#),length(d2x(mx-rows+i))) /*build a row of the Floyd's triangle. */
end /*#*/
say substr(_,2) /*remove 1st leading blank in the line,*/
end /*r*/ /* [↑] introduced by first abutment. */
/*stick a fork in it, we're all done. */
parse arg N .; if N=='' | N=="," then N=6 /*Not specified? Then use the default.*/
mx=N * (N+1) % 2 - N /*calculate maximum value of any value.*/
say 'displaying a ' N " row Floyd's triangle in base 16:" /*show triangle header.*/
say
#=1; do r=1 for N; i=0; _= /*construct Floyd's triangle row by row*/
do #=# for r; i=i+1 /*start to construct a row of triangle.*/
_=_ right( d2x(#), length( d2x(mx+i))) /*build a row of the Floyd's triangle. */
end /*#*/
say substr(_, 2) /*remove 1st leading blank in the line.*/
end /*r*/ /*stick a fork in it, we're all done. */

View file

@ -1,50 +1,50 @@
/*REXX program constructs/shows Floyd's triangle for any number of rows in any base ≤90.*/
parse arg rows radx . /*obtain optional arguments from the CL*/
if rows=='' | rows=="," then rows= 5 /*Not specified? Then use the default.*/
parse arg N radx . /*obtain optional arguments from the CL*/
if N=='' | N=="," then N= 5 /*Not specified? Then use the default.*/
if radx=='' | radx=="," then radx=10 /* " " " " " " */
mx=rows * (rows+1) % 2 /*calculate maximum value of any value.*/
say 'displaying a ' rows " row Floyd's triangle in base" radx':'; say /*display hdr*/
#=1
do r=1 for rows; i=0; _= /*construct Floyd's triangle row by row*/
mx=N * (N+1) % 2 - N /*calculate maximum value of any value.*/
say 'displaying a ' N " row Floyd's triangle in base" radx':' /*display the header.*/
say
#=1; do r=1 for N; i=0; _= /*construct Floyd's triangle row by row*/
do #=# for r; i=i+1 /*start to construct a row of triangle.*/
_=_ right(base(#, radx), length(base(mx-rows+i, radx))) /*build triangle row*/
_=_ right(base(#, radx), length( base(mx+i, radx) ) ) /*build triangle row.*/
end /*#*/
say substr(_,2) /*remove 1st leading blank in the line,*/
say substr(_, 2) /*remove 1st leading blank in the line,*/
end /*r*/ /* [↑] introduced by first abutment. */
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
base: procedure; parse arg x 1 ox,toB,inB /*obtain number, toBase, inBase. */
@abc='abcdefghijklmnopqrstuvwxyz' /*lowercase Latin alphabet. */
@abcU=@abc; upper @abcU /*go whole hog and extend 'em. */
@@@='0123456789'@abc || @abcU /*prefix 'em with numeric digits.*/
@abc= 'abcdefghijklmnopqrstuvwxyz' /*lowercase Latin alphabet. */
@abcU=@abc; upper @abcU /*go whole hog and extend 'em. */
@@@= '0123456789'@abc || @abcU /*prefix 'em with numeric digits.*/
@@@=@@@'<>[]{}()?~!@#$%^&*_=|\/;:¢¬' /*add some special chars as well.*/
/*handles up to base 90, all chars must be viewable.*/
numeric digits 1000 /*what the hey, support gihugeics*/
/* [↑] handles up to base 90, all chars must be viewable.*/
numeric digits 3000 /*what the hey, support gihugeics*/
mxB=length(@@@) /*max base (radix) supported here*/
if toB=='' | toB=="," then toB=10 /*if skipped, assume default (10)*/
if inB=='' | inB=="," then inB=10 /* " " " " " */
if inB<2 | inb>mxB then call erb 'inBase',inB /*invalid/illegal arg: inBase. */
if toB<2 | tob>mxB then call erb 'toBase',toB /* " " " toBase. */
if x=='' then call erm /* " " " number. */
sigX=left(x,1)
if pos(sigX,'-+')\==0 then x=substr(x,2) /*X number has a leading sign? */
else sigX= /* ··· no leading sign.*/
#=0; do j=1 for length(x) /*convert X, base inB ──► base 10*/
_=substr(x, j, 1) /*pick off a numeral from X. */
sigX=left(x, 1) /*obtain a possible leading sign.*/
if pos(sigX, '-+')\==0 then x=substr(x, 2) /*X number has a leading sign? */
else sigX= /* ··· no leading sign.*/
#=0
do j=1 for length(x); _=substr(x, j, 1) /*convert X, base inB ──► base 10*/
v=pos(_, @@@) /*get the value of this "digit". */
if v==0 | v>inB then call erd x,j,inB /*is this an illegal "numeral" ? */
#=#*inB+v-1 /*construct new num, dig by dig. */
#=# * inB + v - 1 /*construct new num, dig by dig. */
end /*j*/
y=
do while # >= toB /*convert #, base 10 ──► base toB*/
y=substr(@@@, (#//toB)+1, 1)y /*construct the number for output*/
#=#%toB /* ··· and whittle # down also.*/
y=substr(@@@, (# // toB) + 1, 1)y /*construct the number for output*/
#=# % toB /* ··· and whittle # down also.*/
end /*while*/
y=sigX || substr(@@@, #+1, 1)y /*prepend the sign if it existed.*/
return y /*return the number in base toB.*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
erb: call ser 'illegal' arg(2) "base:" arg(1) "must be in range: 2──►" mxB
erd: call ser 'illegal "digit" in' x":" _
/*──────────────────────────────────────────────────────────────────────────────────────*/
erb: call ser 'illegal' arg(2) "base: " arg(1) "must be in range: 2──► " mxB
erd: call ser 'illegal "digit" in' x":" _
erm: call ser 'no argument specified.'
ser: say; say '*** error! ***'; say arg(1); say; exit 13
ser: say; say '***error***'; say arg(1); say; exit 13

View file

@ -0,0 +1,15 @@
floyd(5)
floyd(14)
floyd(n)=
k = 0
> r, 1..n
s = ""
> j, 1..r
k += 1
f = ">"+#.upper(#.log10((n-1)*n/2+j+1)+1)+">"
s += #.str(k,f)
<
#.output(s)
<
.

View file

@ -1,10 +1,10 @@
func floyd(rows, n=1) {
var max = Math.range_sum(1, rows);
var widths = (max-rows .. max-1 -> map{(.+n).to_s.len});
var max = Math.range_sum(1, rows)
var widths = (max-rows .. max-1 -> map{.+n->to_s.len})
{ |r|
say %'#{1..r -> map{|i| "%#{widths[i-1]}d" % n++}.join(" ")}';
} * rows;
say %'#{1..r -> map{|i| "%#{widths[i-1]}d" % n++}.join(" ")}'
} << 1..rows
}
floyd(5); # or: floyd(5, 88);
floyd(14); # or: floyd(14, 900);
floyd(5) # or: floyd(5, 88)
floyd(14) # or: floyd(14, 900)

View file

@ -0,0 +1,24 @@
Option Explicit
Dim o As String
Sub floyd(L As Integer)
Dim r, c, m, n As Integer
n = L * (L - 1) / 2
m = 1
For r = 1 To L
o = o & vbCrLf
For c = 1 To r
o = o & Space(Len(CStr(n + c)) - Len(CStr(m))) & m & " "
m = m + 1
Next
Next
End Sub
Sub triangle()
o = "5 lines"
Call floyd(5)
o = o & vbCrLf & "14 lines"
Call floyd(14)
With Selection
.Font.Name = "Courier New"
.TypeText Text:=o
End With
End Sub

View file

@ -0,0 +1,22 @@
5 lines
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
14 lines
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31 32 33 34 35 36
37 38 39 40 41 42 43 44 45
46 47 48 49 50 51 52 53 54 55
56 57 58 59 60 61 62 63 64 65 66
67 68 69 70 71 72 73 74 75 76 77 78
79 80 81 82 83 84 85 86 87 88 89 90 91
92 93 94 95 96 97 98 99 100 101 102 103 104 105

View file

@ -0,0 +1,11 @@
fcn lcNum(row){(row*(row+1)/2+1)} // lazy caterer's sequence
fcn floydsTriangle(rows){
fmt:=[lcNum(rows-1)..lcNum(rows)-1].pump(String,fcn(n){
String("%",n.toString().len(),"d ")}); // eg "%2d %2d %3d %3d"
foreach row in (rows){
ns:=[lcNum(row)..lcNum(row+1)-1].walk(); // eg L(4.5,6)
fmt[0,ns.len()*4].fmt(ns.xplode()).println(); // eg "%2d %2d %2d ".fmt(4,5,6)
}
}
floydsTriangle(5); println();
floydsTriangle(14);