task_url stringlengths 30 116 | task_name stringlengths 2 86 | task_description stringlengths 0 14.4k | language_url stringlengths 2 53 | language_name stringlengths 1 52 | code stringlengths 0 61.9k |
|---|---|---|---|---|---|
http://rosettacode.org/wiki/OpenWebNet_password | OpenWebNet password | Calculate the password requested by ethernet gateways from the Legrand / Bticino MyHome OpenWebNet home automation system when the user's ip address is not in the gateway's whitelist
Note: Factory default password is '12345'. Changing it is highly recommended !
conversation goes as follows
← *#*1##
→ *99*0##
← *#603356072##
at which point a password should be sent back, calculated from the "password open" that is set in the gateway, and the nonce that was just sent
→ *#25280520##
← *#*1## | #Wren | Wren | import "/fmt" for Fmt
var ownCalcPass = Fn.new { |password, nonce|
var start = true
var num1 = 0
var num2 = 0
var pwd = Num.fromString(password)
for (c in nonce) {
if (c != "0") {
if (start) num2 = pwd
start = false
}
if (c == "1") {
num1 = (num2 & 0xFFFFFF80) >> 7
num2 = num2 << 25
} else if (c == "2") {
num1 = (num2 & 0xFFFFFFF0) >> 4
num2 = num2 << 28
} else if (c == "3") {
num1 = (num2 & 0xFFFFFFF8) >> 3
num2 = num2 << 29
} else if (c == "4") {
num1 = num2 << 1
num2 = num2 >> 31
} else if (c == "5") {
num1 = num2 << 5
num2 = num2 >> 27
} else if (c == "6") {
num1 = num2 << 12
num2 = num2 >> 20
} else if (c == "7") {
var num3 = num2 & 0x0000FF00
var num4 = ((num2 & 0x000000FF) << 24) | ((num2 & 0x00FF0000) >> 16)
num1 = num3 | num4
num2 = (num2 & 0xFF000000) >> 8
} else if (c == "8") {
num1 = (num2&0x0000FFFF)<<16 | (num2 >> 24)
num2 = (num2 & 0x00FF0000) >> 8
} else if (c == "9") {
num1 = ~num2
} else {
num1 = num2
}
num1 = num1 & 0xFFFFFFFF
num2 = num2 & 0xFFFFFFFF
if (c != "0" && c != "9") num1 = num1 | num2
num2 = num1
}
return num1
}
var testPasswordCalc = Fn.new { |password, nonce, expected|
var res = ownCalcPass.call(password, nonce)
var m = Fmt.swrite("$s $s $-10d $-10d", password, nonce, res, expected)
if (res == expected) {
System.print("PASS %(m)")
} else {
System.print("FAIL %(m)")
}
}
testPasswordCalc.call("12345", "603356072", 25280520)
testPasswordCalc.call("12345", "410501656", 119537670)
testPasswordCalc.call("12345", "630292165", 4269684735) |
http://rosettacode.org/wiki/Old_Russian_measure_of_length | Old Russian measure of length | Task
Write a program to perform a conversion of the old Russian measures of length to the metric system (and vice versa).
It is an example of a linear transformation of several variables.
The program should accept a single value in a selected unit of measurement, and convert and return it to the other units:
vershoks, arshins, sazhens, versts, meters, centimeters and kilometers.
Also see
Old Russian measure of length
| #BBC_BASIC | BBC BASIC | REM >oldrussian
@% = &90E
PROColdrus(1, "meter")
PRINT
PROColdrus(10, "arshin")
END
:
DEF PROColdrus(length, unit$)
LOCAL units$(), values(), unit%, i%
DIM units$(12)
DIM values(12)
units$() = "kilometer", "meter", "centimeter", "milia", "versta", "sazhen", "arshin", "fut", "piad", "vershok", "diuym", "liniya", "tochka"
values() = 1000, 1, 0.01, 7467.6, 1066.8, 2.1336, 0.7112, 0.3048, 0.1778, 0.04445, 0.0254, 0.00254, 0.000254
unit% = -1
FOR i% = 0 TO 12
IF units$(i%) = unit$ THEN unit% = i%
NEXT
IF unit% = -1 THEN
PRINT "Unknown unit '"; unit$; "'"
ELSE
PRINT; length; " "; unit$; " ="
FOR i% = 0 TO 12
IF i% <> unit% THEN PRINT length / values(i%) * values(unit%); " "; units$(i%)
NEXT
ENDIF
ENDPROC |
http://rosettacode.org/wiki/Old_Russian_measure_of_length | Old Russian measure of length | Task
Write a program to perform a conversion of the old Russian measures of length to the metric system (and vice versa).
It is an example of a linear transformation of several variables.
The program should accept a single value in a selected unit of measurement, and convert and return it to the other units:
vershoks, arshins, sazhens, versts, meters, centimeters and kilometers.
Also see
Old Russian measure of length
| #C | C |
#include<string.h>
#include<stdlib.h>
#include<ctype.h>
#include<stdio.h>
#define UNITS_LENGTH 13
int main(int argC,char* argV[])
{
int i,reference;
char *units[UNITS_LENGTH] = {"kilometer","meter","centimeter","tochka","liniya","diuym","vershok","piad","fut","arshin","sazhen","versta","milia"};
double factor, values[UNITS_LENGTH] = {1000.0,1.0,0.01,0.000254,0.00254,0.0254,0.04445,0.1778,0.3048,0.7112,2.1336,1066.8,7467.6};
if(argC!=3)
printf("Usage : %s followed by length as <value> <unit>");
else{
for(i=0;argV[2][i]!=00;i++)
argV[2][i] = tolower(argV[2][i]);
for(i=0;i<UNITS_LENGTH;i++){
if(strstr(argV[2],units[i])!=NULL){
reference = i;
factor = atof(argV[1])*values[i];
break;
}
}
printf("%s %s is equal in length to : \n",argV[1],argV[2]);
for(i=0;i<UNITS_LENGTH;i++){
if(i!=reference)
printf("\n%lf %s",factor/values[i],units[i]);
}
}
return 0;
}
|
http://rosettacode.org/wiki/OpenGL | OpenGL |
Task
Display a smooth shaded triangle with OpenGL.
Triangle created using C example compiled with GCC 4.1.2 and freeglut3.
| #Delphi | Delphi |
program OpenGLTriangle;
{$APPTYPE CONSOLE}
uses
System.Classes,
Sample.App,
Winapi.OpenGL,
System.UITypes;
type
TTriangleApp = class(TApplication)
public
procedure Initialize; override;
procedure Update(const ADeltaTimeSec, ATotalTimeSec: Double); override;
procedure Shutdown; override;
procedure KeyDown(const AKey: Integer; const AShift: TShiftState); override;
end;
{ TTriangleApp }
procedure TTriangleApp.Initialize;
begin
inherited;
glViewport(0, 0, width, height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(-30.0, 30.0, -30.0, 30.0, -30.0, 30.0);
glMatrixMode(GL_MODELVIEW);
end;
procedure TTriangleApp.KeyDown(const AKey: Integer; const AShift: TShiftState);
begin
inherited;
if (AKey = vkEscape) then
Terminate;
end;
procedure TTriangleApp.Shutdown;
begin
inherited;
// Writeln('App is Shutdown');
end;
procedure TTriangleApp.Update(const ADeltaTimeSec, ATotalTimeSec: Double);
begin
inherited;
glClearColor(0.3, 0.3, 0.3, 0.0);
glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT);
glShadeModel(GL_SMOOTH);
glLoadIdentity();
glTranslatef(-15.0, -15.0, 0.0);
glBegin(GL_TRIANGLES);
glColor3f(1.0, 0.0, 0.0);
glVertex2f(0.0, 0.0);
glColor3f(0.0, 1.0, 0.0);
glVertex2f(30.0, 0.0);
glColor3f(0.0, 0.0, 1.0);
glVertex2f(0.0, 30.0);
glEnd();
glFlush();
end;
begin
RunApp(TTriangleApp, 640, 480, 'OpenGL Triangle');
end. |
http://rosettacode.org/wiki/One_of_n_lines_in_a_file | One of n lines in a file | A method of choosing a line randomly from a file:
Without reading the file more than once
When substantial parts of the file cannot be held in memory
Without knowing how many lines are in the file
Is to:
keep the first line of the file as a possible choice, then
Read the second line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/2.
Read the third line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/3.
...
Read the Nth line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/N
Return the computed possible choice when no further lines exist in the file.
Task
Create a function/method/routine called one_of_n that given n, the number of actual lines in a file, follows the algorithm above to return an integer - the line number of the line chosen from the file.
The number returned can vary, randomly, in each run.
Use one_of_n in a simulation to find what woud be the chosen line of a 10 line file simulated 1,000,000 times.
Print and show how many times each of the 10 lines is chosen as a rough measure of how well the algorithm works.
Note: You may choose a smaller number of repetitions if necessary, but mention this up-front.
Note: This is a specific version of a Reservoir Sampling algorithm: https://en.wikipedia.org/wiki/Reservoir_sampling
| #Batch_File | Batch File |
@echo off
for /l %%i in (1,1,10000) do call one_of_n
:: To show progress add to the FOR loop code block -
:: title %%i
for /l %%i in (1,1,10) do (
for /f "usebackq tokens=1,2 delims=:" %%j in (`find /c "%%i" output.txt`) do echo Line %%i =%%k
)
del output.txt
pause>nul
|
http://rosettacode.org/wiki/One_of_n_lines_in_a_file | One of n lines in a file | A method of choosing a line randomly from a file:
Without reading the file more than once
When substantial parts of the file cannot be held in memory
Without knowing how many lines are in the file
Is to:
keep the first line of the file as a possible choice, then
Read the second line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/2.
Read the third line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/3.
...
Read the Nth line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/N
Return the computed possible choice when no further lines exist in the file.
Task
Create a function/method/routine called one_of_n that given n, the number of actual lines in a file, follows the algorithm above to return an integer - the line number of the line chosen from the file.
The number returned can vary, randomly, in each run.
Use one_of_n in a simulation to find what woud be the chosen line of a 10 line file simulated 1,000,000 times.
Print and show how many times each of the 10 lines is chosen as a rough measure of how well the algorithm works.
Note: You may choose a smaller number of repetitions if necessary, but mention this up-front.
Note: This is a specific version of a Reservoir Sampling algorithm: https://en.wikipedia.org/wiki/Reservoir_sampling
| #BBC_BASIC | BBC BASIC | @% = 7 : REM Column width
DIM cnt%(10)
FOR test% = 1 TO 1000000
cnt%(FNone_of_n(10)) += 1
NEXT
FOR i% = 1 TO 10
PRINT cnt%(i%);
NEXT
PRINT
END
DEF FNone_of_n(n%)
LOCAL i%, l%
FOR i% = 1 TO n%
IF RND(1) <= 1/i% l% = i%
NEXT
= l% |
http://rosettacode.org/wiki/P-value_correction | P-value correction | Given a list of p-values, adjust the p-values for multiple comparisons. This is done in order to control the false positive, or Type 1 error rate.
This is also known as the "false discovery rate" (FDR). After adjustment, the p-values will be higher but still inside [0,1].
The adjusted p-values are sometimes called "q-values".
Task
Given one list of p-values, return the p-values correcting for multiple comparisons
p = {4.533744e-01, 7.296024e-01, 9.936026e-02, 9.079658e-02, 1.801962e-01,
8.752257e-01, 2.922222e-01, 9.115421e-01, 4.355806e-01, 5.324867e-01,
4.926798e-01, 5.802978e-01, 3.485442e-01, 7.883130e-01, 2.729308e-01,
8.502518e-01, 4.268138e-01, 6.442008e-01, 3.030266e-01, 5.001555e-02,
3.194810e-01, 7.892933e-01, 9.991834e-01, 1.745691e-01, 9.037516e-01,
1.198578e-01, 3.966083e-01, 1.403837e-02, 7.328671e-01, 6.793476e-02,
4.040730e-03, 3.033349e-04, 1.125147e-02, 2.375072e-02, 5.818542e-04,
3.075482e-04, 8.251272e-03, 1.356534e-03, 1.360696e-02, 3.764588e-04,
1.801145e-05, 2.504456e-07, 3.310253e-02, 9.427839e-03, 8.791153e-04,
2.177831e-04, 9.693054e-04, 6.610250e-05, 2.900813e-02, 5.735490e-03}
There are several methods to do this, see:
Yoav Benjamini, Yosef Hochberg "Controlling the False Discovery Rate: A Practical and Powerful Approach to Multiple Testing", Journal of the Royal Statistical Society. Series B, Vol. 57, No. 1 (1995), pp. 289-300, JSTOR:2346101
Yoav Benjamini, Daniel Yekutieli, "The control of the false discovery rate in multiple testing under dependency", Ann. Statist., Vol. 29, No. 4 (2001), pp. 1165-1188, DOI:10.1214/aos/1013699998 JSTOR:2674075
Sture Holm, "A Simple Sequentially Rejective Multiple Test Procedure", Scandinavian Journal of Statistics, Vol. 6, No. 2 (1979), pp. 65-70, JSTOR:4615733
Yosef Hochberg, "A sharper Bonferroni procedure for multiple tests of significance", Biometrika, Vol. 75, No. 4 (1988), pp 800–802, DOI:10.1093/biomet/75.4.800 JSTOR:2336325
Gerhard Hommel, "A stagewise rejective multiple test procedure based on a modified Bonferroni test", Biometrika, Vol. 75, No. 2 (1988), pp 383–386, DOI:10.1093/biomet/75.2.383 JSTOR:2336190
Each method has its own advantages and disadvantages.
| #Ruby | Ruby | def pmin(array)
x = 1
pmin_array = []
array.each_index do |i|
pmin_array[i] = [array[i], x].min
abort if pmin_array[i] > 1
end
pmin_array
end
def cummin(array)
cumulative_min = array[0]
arr_cummin = []
array.each do |p|
cumulative_min = [p, cumulative_min].min
arr_cummin.push(cumulative_min)
end
arr_cummin
end
def cummax(array)
cumulative_max = array[0]
arr_cummax = []
array.each do |p|
cumulative_max = [p, cumulative_max].max
arr_cummax.push(cumulative_max)
end
arr_cummax
end
# decreasing variable is optional
def order(array, decreasing = false)
if decreasing == false
array.sort.map { |n| array.index(n) }
else
array.sort.map { |n| array.index(n) }.reverse
end
end
def p_adjust(arr_pvalues, method = 'Holm')
lp = arr_pvalues.size
n = lp
if method.casecmp('hochberg').zero?
arr_o = order(arr_pvalues, true)
arr_cummin_input = []
(0..n).each do |index|
arr_cummin_input[index] = (index + 1) * arr_pvalues[arr_o[index].to_i]
end
arr_cummin = cummin(arr_cummin_input)
arr_pmin = pmin(arr_cummin)
arr_ro = order(arr_o)
return arr_pmin.values_at(*arr_ro)
elsif method.casecmp('bh').zero? || method.casecmp('benjamini-hochberg').zero?
arr_o = order(arr_pvalues, true)
arr_cummin_input = []
(0..(n - 1)).each do |i|
arr_cummin_input[i] = (n / (n - i).to_f) * arr_pvalues[arr_o[i]]
end
arr_ro = order(arr_o)
arr_cummin = cummin(arr_cummin_input)
arr_pmin = pmin(arr_cummin)
return arr_pmin.values_at(*arr_ro)
elsif method.casecmp('by').zero? || method.casecmp('benjamini-yekutieli').zero?
q = 0.0
arr_o = order(arr_pvalues, true)
arr_ro = order(arr_o)
(1..n).each do |index|
q += 1.0 / index
end
arr_cummin_input = []
(0..(n - 1)).each do |i|
arr_cummin_input[i] = q * (n / (n - i).to_f) * arr_pvalues[arr_o[i]]
end
arr_cummin = cummin(arr_cummin_input)
arr_pmin = pmin(arr_cummin)
return arr_pmin.values_at(*arr_ro)
elsif method.casecmp('bonferroni').zero?
arr_qvalues = []
(0..(n - 1)).each do |i|
q = arr_pvalues[i] * n
if (q >= 0) && (q < 1)
arr_qvalues[i] = q
elsif q >= 1
arr_qvalues[i] = 1.0
else
puts "Falied to get Bonferroni adjusted p for #{arr_pvalues[i]}"
end
end
return arr_qvalues
elsif method.casecmp('holm').zero?
o = order(arr_pvalues)
cummax_input = []
(0..(n - 1)).each do |index|
cummax_input[index] = (n - index) * arr_pvalues[o[index]]
end
ro = order(o)
arr_cummax = cummax(cummax_input)
arr_pmin = pmin(arr_cummax)
return arr_pmin.values_at(*ro)
elsif method.casecmp('hommel').zero?
o = order(arr_pvalues)
arr_p = arr_pvalues.values_at(*o)
ro = order(o)
q = []
pa = []
min = n * arr_p[0]
(0..(n - 1)).each do |index|
temp = n * arr_p[index] / (index + 1)
min = [min, temp].min
end
(0..(n - 1)).each do |index|
pa[index] = min
q[index] = min
end
j = n - 1
while j >= 2
ij = Array 0..(n - j)
i2_length = j - 1
i2 = []
(0..(i2_length - 1)).each do |i|
i2[i] = n - j + 2 + i - 1 # R's indices are 1-based, C's are 0-based
end
q1 = j * arr_p[i2[0]] / 2.0
(1..(i2_length - 1)).each do |i|
temp_q1 = j * arr_p[i2[i]] / (2 + i)
q1 = [temp_q1, q1].min
end
(0..(n - j)).each do |i|
tmp = j * arr_p[ij[i]]
q[ij[i]] = [tmp, q1].min
end
(0..(i2_length - 1)).each do |i|
q[i2[i]] = q[n - j]
end
(0..(n - 1)).each do |i|
pa[i] = q[i] if pa[i] < q[i]
end
j -= 1
end
return pa.values_at(*ro)
else
puts "#{method} isn't accepted."
abort
end
end
pvalues =
[4.533744e-01, 7.296024e-01, 9.936026e-02, 9.079658e-02,
1.801962e-01, 8.752257e-01, 2.922222e-01, 9.115421e-01,
4.355806e-01, 5.324867e-01, 4.926798e-01, 5.802978e-01,
3.485442e-01, 7.883130e-01, 2.729308e-01, 8.502518e-01,
4.268138e-01, 6.442008e-01, 3.030266e-01, 5.001555e-02,
3.194810e-01, 7.892933e-01, 9.991834e-01, 1.745691e-01,
9.037516e-01, 1.198578e-01, 3.966083e-01, 1.403837e-02,
7.328671e-01, 6.793476e-02, 4.040730e-03, 3.033349e-04,
1.125147e-02, 2.375072e-02, 5.818542e-04, 3.075482e-04,
8.251272e-03, 1.356534e-03, 1.360696e-02, 3.764588e-04,
1.801145e-05, 2.504456e-07, 3.310253e-02, 9.427839e-03,
8.791153e-04, 2.177831e-04, 9.693054e-04, 6.610250e-05,
2.900813e-02, 5.735490e-03]
correct_answers = {
'Benjamini-Hochberg' => [6.126681e-01, 8.521710e-01, 1.987205e-01,
1.891595e-01, 3.217789e-01, 9.301450e-01,
4.870370e-01, 9.301450e-01, 6.049731e-01,
6.826753e-01, 6.482629e-01, 7.253722e-01,
5.280973e-01, 8.769926e-01, 4.705703e-01,
9.241867e-01, 6.049731e-01, 7.856107e-01,
4.887526e-01, 1.136717e-01, 4.991891e-01,
8.769926e-01, 9.991834e-01, 3.217789e-01,
9.301450e-01, 2.304958e-01, 5.832475e-01,
3.899547e-02, 8.521710e-01, 1.476843e-01,
1.683638e-02, 2.562902e-03, 3.516084e-02,
6.250189e-02, 3.636589e-03, 2.562902e-03,
2.946883e-02, 6.166064e-03, 3.899547e-02,
2.688991e-03, 4.502862e-04, 1.252228e-05,
7.881555e-02, 3.142613e-02, 4.846527e-03,
2.562902e-03, 4.846527e-03, 1.101708e-03,
7.252032e-02, 2.205958e-02],
'Benjamini-Yekutieli' => [1.000000e+00, 1.000000e+00, 8.940844e-01,
8.510676e-01, 1.000000e+00, 1.000000e+00,
1.000000e+00, 1.000000e+00, 1.000000e+00,
1.000000e+00, 1.000000e+00, 1.000000e+00,
1.000000e+00, 1.000000e+00, 1.000000e+00,
1.000000e+00, 1.000000e+00, 1.000000e+00,
1.000000e+00, 5.114323e-01, 1.000000e+00,
1.000000e+00, 1.000000e+00, 1.000000e+00,
1.000000e+00, 1.000000e+00, 1.000000e+00,
1.754486e-01, 1.000000e+00, 6.644618e-01,
7.575031e-02, 1.153102e-02, 1.581959e-01,
2.812089e-01, 1.636176e-02, 1.153102e-02,
1.325863e-01, 2.774239e-02, 1.754486e-01,
1.209832e-02, 2.025930e-03, 5.634031e-05,
3.546073e-01, 1.413926e-01, 2.180552e-02,
1.153102e-02, 2.180552e-02, 4.956812e-03,
3.262838e-01, 9.925057e-02],
'Bonferroni' => [1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00,
1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00,
1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00,
1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00,
1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00,
1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00,
1.000000e+00, 1.000000e+00, 1.000000e+00, 7.019185e-01,
1.000000e+00, 1.000000e+00, 2.020365e-01, 1.516674e-02,
5.625735e-01, 1.000000e+00, 2.909271e-02, 1.537741e-02,
4.125636e-01, 6.782670e-02, 6.803480e-01, 1.882294e-02,
9.005725e-04, 1.252228e-05, 1.000000e+00, 4.713920e-01,
4.395577e-02, 1.088915e-02, 4.846527e-02, 3.305125e-03,
1.000000e+00, 2.867745e-01],
'Hochberg' => [9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01,
9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01,
9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01,
9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01,
9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01,
9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01,
9.991834e-01, 9.991834e-01, 9.991834e-01, 4.632662e-01,
9.991834e-01, 9.991834e-01, 1.575885e-01, 1.383967e-02,
3.938014e-01, 7.600230e-01, 2.501973e-02, 1.383967e-02,
3.052971e-01, 5.426136e-02, 4.626366e-01, 1.656419e-02,
8.825610e-04, 1.252228e-05, 9.930759e-01, 3.394022e-01,
3.692284e-02, 1.023581e-02, 3.974152e-02, 3.172920e-03,
8.992520e-01, 2.179486e-01],
'Holm' => [1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00,
1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00,
1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00,
1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00,
1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00,
1.000000e+00, 1.000000e+00, 1.000000e+00, 1.000000e+00,
1.000000e+00, 1.000000e+00, 1.000000e+00, 4.632662e-01,
1.000000e+00, 1.000000e+00, 1.575885e-01, 1.395341e-02,
3.938014e-01, 7.600230e-01, 2.501973e-02, 1.395341e-02,
3.052971e-01, 5.426136e-02, 4.626366e-01, 1.656419e-02,
8.825610e-04, 1.252228e-05, 9.930759e-01, 3.394022e-01,
3.692284e-02, 1.023581e-02, 3.974152e-02, 3.172920e-03,
8.992520e-01, 2.179486e-01],
'Hommel' => [9.991834e-01, 9.991834e-01, 9.991834e-01, 9.987624e-01,
9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01,
9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01,
9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01,
9.991834e-01, 9.991834e-01, 9.991834e-01, 9.595180e-01,
9.991834e-01, 9.991834e-01, 9.991834e-01, 9.991834e-01,
9.991834e-01, 9.991834e-01, 9.991834e-01, 4.351895e-01,
9.991834e-01, 9.766522e-01, 1.414256e-01, 1.304340e-02,
3.530937e-01, 6.887709e-01, 2.385602e-02, 1.322457e-02,
2.722920e-01, 5.426136e-02, 4.218158e-01, 1.581127e-02,
8.825610e-04, 1.252228e-05, 8.743649e-01, 3.016908e-01,
3.516461e-02, 9.582456e-03, 3.877222e-02, 3.172920e-03,
8.122276e-01, 1.950067e-01]
}
# correct_answers.each do |method, answers|
methods = ['Benjamini-Yekutieli', 'Benjamini-Hochberg', 'Hochberg',
'Bonferroni', 'Holm', 'Hommel']
methods.each do |method|
puts method
error = 0.0
arr_q = p_adjust(pvalues, method)
arr_q.each_index do |p|
error += (correct_answers[method][p] - arr_q[p])
end
puts "total error for #{method} = #{error}"
end
|
http://rosettacode.org/wiki/Order_disjoint_list_items | Order disjoint list items |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Given M as a list of items and another list N of items chosen from M, create M' as a list with the first occurrences of items from N sorted to be in one of the set of indices of their original occurrence in M but in the order given by their order in N.
That is, items in N are taken from M without replacement, then the corresponding positions in M' are filled by successive items from N.
For example
if M is 'the cat sat on the mat'
And N is 'mat cat'
Then the result M' is 'the mat sat on the cat'.
The words not in N are left in their original positions.
If there are duplications then only the first instances in M up to as many as are mentioned in N are potentially re-ordered.
For example
M = 'A B C A B C A B C'
N = 'C A C A'
Is ordered as:
M' = 'C B A C B A A B C'
Show the output, here, for at least the following inputs:
Data M: 'the cat sat on the mat' Order N: 'mat cat'
Data M: 'the cat sat on the mat' Order N: 'cat mat'
Data M: 'A B C A B C A B C' Order N: 'C A C A'
Data M: 'A B C A B D A B E' Order N: 'E A D A'
Data M: 'A B' Order N: 'B'
Data M: 'A B' Order N: 'B A'
Data M: 'A B B A' Order N: 'B A'
Cf
Sort disjoint sublist
| #Lua | Lua | -- Split str on any space characters and return as a table
function split (str)
local t = {}
for word in str:gmatch("%S+") do table.insert(t, word) end
return t
end
-- Order disjoint list items
function orderList (dataStr, orderStr)
local data, order = split(dataStr), split(orderStr)
for orderPos, orderWord in pairs(order) do
for dataPos, dataWord in pairs(data) do
if dataWord == orderWord then
data[dataPos] = false
break
end
end
end
local orderPos = 1
for dataPos, dataWord in pairs(data) do
if not dataWord then
data[dataPos] = order[orderPos]
orderPos = orderPos + 1
if orderPos > #order then return data end
end
end
return data
end
-- Main procedure
local testCases = {
{'the cat sat on the mat', 'mat cat'},
{'the cat sat on the mat', 'cat mat'},
{'A B C A B C A B C' , 'C A C A'},
{'A B C A B D A B E' , 'E A D A'},
{'A B' , 'B'},
{'A B' , 'B A'},
{'A B B A' , 'B A'}
}
for _, example in pairs(testCases) do
print(table.concat(orderList(unpack(example)), " "))
end |
http://rosettacode.org/wiki/Optional_parameters | Optional parameters | Task
Define a function/method/subroutine which sorts a sequence ("table") of sequences ("rows") of strings ("cells"), by one of the strings. Besides the input to be sorted, it shall have the following optional parameters:
ordering
A function specifying the ordering of strings; lexicographic by default.
column
An integer specifying which string of each row to compare; the first by default.
reverse
Reverses the ordering.
This task should be considered to include both positional and named optional parameters, as well as overloading on argument count as in Java or selector name as in Smalltalk, or, in the extreme, using different function names. Provide these variations of sorting in whatever way is most natural to your language. If the language supports both methods naturally, you are encouraged to describe both.
Do not implement a sorting algorithm; this task is about the interface. If you can't use a built-in sort routine, just omit the implementation (with a comment).
See also:
Named Arguments
| #FreeBASIC | FreeBASIC | Function power(n As Integer, p As Integer = 2) As Double
Return n ^ p
End Function
Print power(2) ' muestra 4
Print power(2, 3) ' muestra 8
Sleep |
http://rosettacode.org/wiki/Order_two_numerical_lists | Order two numerical lists | sorting
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Write a function that orders two lists or arrays filled with numbers.
The function should accept two lists as arguments and return true if the first list should be ordered before the second, and false otherwise.
The order is determined by lexicographic order: Comparing the first element of each list.
If the first elements are equal, then the second elements should be compared, and so on, until one of the list has no more elements.
If the first list runs out of elements the result is true.
If the second list or both run out of elements the result is false.
Note: further clarification of lexicographical ordering is expounded on the talk page here and here.
| #D | D | void main() {
assert([1,2,1,3,2] >= [1,2,0,4,4,0,0,0]);
} |
http://rosettacode.org/wiki/Pascal%27s_triangle | Pascal's triangle | Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere.
Its first few rows look like this:
1
1 1
1 2 1
1 3 3 1
where each element of each row is either 1 or the sum of the two elements right above it.
For example, the next row of the triangle would be:
1 (since the first element of each row doesn't have two elements above it)
4 (1 + 3)
6 (3 + 3)
4 (3 + 1)
1 (since the last element of each row doesn't have two elements above it)
So the triangle now looks like this:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
Each row n (starting with row 0 at the top) shows the coefficients of the binomial expansion of (x + y)n.
Task
Write a function that prints out the first n rows of the triangle (with f(1) yielding the row consisting of only the element 1).
This can be done either by summing elements from the previous rows or using a binary coefficient or combination function.
Behavior for n ≤ 0 does not need to be uniform, but should be noted.
See also
Evaluate binomial coefficients
| #VBA | VBA | Option Base 1
Private Sub pascal_triangle(n As Integer)
Dim odd() As String
Dim eve() As String
ReDim odd(1)
ReDim eve(2)
odd(1) = " 1"
For i = 1 To n
If i Mod 2 = 1 Then
Debug.Print String$(2 * n - 2 * i, " ") & Join(odd, " ")
eve(1) = " 1"
ReDim Preserve eve(i + 1)
For j = 2 To i
eve(j) = Format(CStr(Val(odd(j - 1)) + Val(odd(j))), "@@@")
Next j
eve(i + 1) = " 1"
Else
Debug.Print String$(2 * n - 2 * i, " ") & Join(eve, " ")
odd(1) = " 1"
ReDim Preserve odd(i + 1)
For j = 2 To i
odd(j) = Format(CStr(Val(eve(j - 1)) + Val(eve(j))), "@@@")
Next j
odd(i + 1) = " 1"
End If
Next i
End Sub
Public Sub main()
pascal_triangle 13
End Sub |
http://rosettacode.org/wiki/Operator_precedence | Operator precedence |
This page uses content from Wikipedia. The original article was at Operators in C and C++. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Provide a list of precedence and associativity of all the operators and constructs that the language utilizes in descending order of precedence such that an operator which is listed on some row will be evaluated prior to any operator that is listed on a row further below it.
Operators that are in the same cell (there may be several rows of operators listed in a cell) are evaluated with the same level of precedence, in the given direction.
State whether arguments are passed by value or by reference.
| #Nim | Nim | q)3*2+1
9
q)(3*2)+1 / Brackets give the usual order of precedence
7
q)x:5
q)(x+5; x:20; x-5)
25 20 0 |
http://rosettacode.org/wiki/Operator_precedence | Operator precedence |
This page uses content from Wikipedia. The original article was at Operators in C and C++. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Provide a list of precedence and associativity of all the operators and constructs that the language utilizes in descending order of precedence such that an operator which is listed on some row will be evaluated prior to any operator that is listed on a row further below it.
Operators that are in the same cell (there may be several rows of operators listed in a cell) are evaluated with the same level of precedence, in the given direction.
State whether arguments are passed by value or by reference.
| #OCaml | OCaml | q)3*2+1
9
q)(3*2)+1 / Brackets give the usual order of precedence
7
q)x:5
q)(x+5; x:20; x-5)
25 20 0 |
http://rosettacode.org/wiki/Ordered_words | Ordered words | An ordered word is a word in which the letters appear in alphabetic order.
Examples include abbey and dirt.
Task[edit]
Find and display all the ordered words in the dictionary unixdict.txt that have the longest word length.
(Examples that access the dictionary file locally assume that you have downloaded this file yourself.)
The display needs to be shown on this page.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Factor | Factor |
USING: grouping http.client io io.encodings.utf8 io.files
io.files.temp kernel math memoize sequences sequences.extras
unicode.case urls ;
IN: rosetta-code.ordered-words
MEMO: word-list ( -- seq )
"unixdict.txt" temp-file dup exists? [
URL" http://puzzlers.org/pub/wordlists/unixdict.txt"
over download-to
] unless utf8 file-lines ;
: ordered-word? ( word -- ? )
>lower [ <= ] monotonic? ;
: ordered-words-main ( -- )
word-list [ ordered-word? ] filter
all-longest [ print ] each ;
|
http://rosettacode.org/wiki/Palindrome_detection | Palindrome detection | A palindrome is a phrase which reads the same backward and forward.
Task[edit]
Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes)
is a palindrome.
For extra credit:
Support Unicode characters.
Write a second function (possibly as a wrapper to the first) which detects inexact palindromes, i.e. phrases that are palindromes if white-space and punctuation is ignored and case-insensitive comparison is used.
Hints
It might be useful for this task to know how to reverse a string.
This task's entries might also form the subjects of the task Test a function.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Oforth | Oforth | String method: isPalindrome self reverse self == ; |
http://rosettacode.org/wiki/One-time_pad | One-time pad | Implement a One-time pad, for encrypting and decrypting messages.
To keep it simple, we will be using letters only.
Sub-Tasks
Generate the data for a One-time pad (user needs to specify a filename and length)
The important part is to get "true random" numbers, e.g. from /dev/random
encryption / decryption ( basically the same operation, much like Rot-13 )
For this step, much of Vigenère cipher could be reused,
with the key to be read from the file containing the One-time pad.
optional: management of One-time pads: list, mark as used, delete, etc.
Somehow, the users needs to keep track which pad to use for which partner.
To support the management of pad-files:
Such files have a file-extension ".1tp"
Lines starting with "#" may contain arbitary meta-data (i.e. comments)
Lines starting with "-" count as "used"
Whitespace within the otp-data is ignored
For example, here is the data from Wikipedia:
# Example data - Wikipedia - 2014-11-13
-ZDXWWW EJKAWO FECIFE WSNZIP PXPKIY URMZHI JZTLBC YLGDYJ
-HTSVTV RRYYEG EXNCGA GGQVRF FHZCIB EWLGGR BZXQDQ DGGIAK
YHJYEQ TDLCQT HZBSIZ IRZDYS RBYJFZ AIRCWI UCVXTW YKPQMK
CKHVEX VXYVCS WOGAAZ OUVVON GCNEVR LMBLYB SBDCDC PCGVJX
QXAUIP PXZQIJ JIUWYH COVWMJ UZOJHL DWHPER UBSRUJ HGAAPR
CRWVHI FRNTQW AJVWRT ACAKRD OZKIIB VIQGBK IJCWHF GTTSSE
EXFIPJ KICASQ IOUQTP ZSGXGH YTYCTI BAZSTN JKMFXI RERYWE
See also
one time pad encryption in Python
snapfractalpop - One-Time-Pad Command-Line-Utility (C).
Crypt-OTP-2.00 on CPAN (Perl)
| #Racket | Racket | sub MAIN {
put "Generate data for one time pad encryption.\n" ~
"File will have .1tp extension.";
my $fn;
loop {
$fn = prompt 'Filename for one time pad data: ';
if $fn !~~ /'.1tp' $/ { $fn ~= '.1tp' }
if $fn.IO.e {
my $ow = prompt "$fn aready exists, over-write? y/[n] ";
last if $ow ~~ m:i/'y'/;
redo;
}
last;
}
put 'Each line will contain 48 characters of encyption data.';
my $lines = prompt 'How many lines of data to generate? [1000] ';
$lines ||= 1000;
generate($fn, $lines);
say "One-time-pad data saved to: ", $fn.IO.absolute;
sub generate ( $fn, $lines) {
use Crypt::Random;
$fn.IO.spurt: "# one-time-pad encryption data\n" ~
((sprintf(" %s %s %s %s %s %s %s %s\n",
((('A'..'Z')[crypt_random_uniform(26)] xx 6).join) xx 8))
xx $lines).join;
}
} |
http://rosettacode.org/wiki/One-dimensional_cellular_automata | One-dimensional cellular automata | Assume an array of cells with an initial distribution of live and dead cells,
and imaginary cells off the end of the array having fixed values.
Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the current generation.
If, in the following table, a live cell is represented by 1 and a dead cell by 0 then to generate the value of the cell at a particular index in the array of cellular values you use the following table:
000 -> 0 #
001 -> 0 #
010 -> 0 # Dies without enough neighbours
011 -> 1 # Needs one neighbour to survive
100 -> 0 #
101 -> 1 # Two neighbours giving birth
110 -> 1 # Needs one neighbour to survive
111 -> 0 # Starved to death.
| #11l | 11l | V gen = ‘_###_##_#_#_#_#__#__’.map(ch -> Int(ch == ‘#’))
L(n) 10
print(gen.map(cell -> (I cell != 0 {‘#’} E ‘_’)).join(‘’))
gen = [0] [+] gen [+] [0]
gen = (0 .< gen.len - 2).map(m -> Int(sum(:gen[m .+ 3]) == 2)) |
http://rosettacode.org/wiki/Old_lady_swallowed_a_fly | Old lady swallowed a fly | Task
Present a program which emits the lyrics to the song I Knew an Old Lady Who Swallowed a Fly, taking advantage of the repetitive structure of the song's lyrics.
This song has multiple versions with slightly different lyrics, so all these programs might not emit identical output.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #11l | 11l | V animals = [
(‘fly’, ‘I don't know why she swallowed a fly, perhaps she'll die.’),
(‘spider’, ‘It wiggled and jiggled and tickled inside her.’),
(‘bird’, ‘How absurd, to swallow a bird.’),
(‘cat’, ‘Imagine that, she swallowed a cat.’),
(‘dog’, ‘What a hog, to swallow a dog.’),
(‘goat’, ‘She just opened her throat and swallowed a goat.’),
(‘cow’, ‘I don't know how she swallowed a cow.’),
(‘horse’, ‘She's dead, of course.’)]
L(animal_lyric) animals
V i = L.index
V (animal, lyric) = animal_lyric
print("There was an old lady who swallowed a #..\n#.".format(animal, lyric))
I animal == ‘horse’
L.break
L(predator, prey) zip(animals[(i .< 0).step(-1)], animals[(i - 1 ..).step(-1)])
print("\tShe swallowed the #. to catch the #.".format(predator[0], prey[0]))
I animal != ‘fly’
print(animals[0][1])
print() |
http://rosettacode.org/wiki/Numerical_and_alphabetical_suffixes | Numerical and alphabetical suffixes | This task is about expressing numbers with an attached (abutted) suffix multiplier(s), the suffix(es) could be:
an alphabetic (named) multiplier which could be abbreviated
metric multiplier(s) which can be specified multiple times
"binary" multiplier(s) which can be specified multiple times
explanation marks (!) which indicate a factorial or multifactorial
The (decimal) numbers can be expressed generally as:
{±} {digits} {.} {digits}
────── or ──────
{±} {digits} {.} {digits} {E or e} {±} {digits}
where:
numbers won't have embedded blanks (contrary to the expaciated examples above where whitespace was used for readability)
this task will only be dealing with decimal numbers, both in the mantissa and exponent
± indicates an optional plus or minus sign (+ or -)
digits are the decimal digits (0 ──► 9)
the digits can have comma(s) interjected to separate the periods (thousands) such as: 12,467,000
. is the decimal point, sometimes also called a dot
e or E denotes the use of decimal exponentiation (a number multiplied by raising ten to some power)
This isn't a pure or perfect definition of the way we express decimal numbers, but it should convey the intent for this task.
The use of the word periods (thousands) is not meant to confuse, that word (as used above) is what the comma separates;
the groups of decimal digits are called periods, and in almost all cases, are groups of three decimal digits.
If an e or E is specified, there must be a legal number expressed before it, and there must be a legal (exponent) expressed after it.
Also, there must be some digits expressed in all cases, not just a sign and/or decimal point.
Superfluous signs, decimal points, exponent numbers, and zeros need not be preserved.
I.E.:
+7 007 7.00 7E-0 7E000 70e-1 could all be expressed as 7
All numbers to be "expanded" can be assumed to be valid and there won't be a requirement to verify their validity.
Abbreviated alphabetic suffixes to be supported (where the capital letters signify the minimum abbreation that can be used)
PAIRs multiply the number by 2 (as in pairs of shoes or pants)
SCOres multiply the number by 20 (as 3score would be 60)
DOZens multiply the number by 12
GRoss multiply the number by 144 (twelve dozen)
GREATGRoss multiply the number by 1,728 (a dozen gross)
GOOGOLs multiply the number by 10^100 (ten raised to the 100&sup>th</sup> power)
Note that the plurals are supported, even though they're usually used when expressing exact numbers (She has 2 dozen eggs, and dozens of quavas)
Metric suffixes to be supported (whether or not they're officially sanctioned)
K multiply the number by 10^3 kilo (1,000)
M multiply the number by 10^6 mega (1,000,000)
G multiply the number by 10^9 giga (1,000,000,000)
T multiply the number by 10^12 tera (1,000,000,000,000)
P multiply the number by 10^15 peta (1,000,000,000,000,000)
E multiply the number by 10^18 exa (1,000,000,000,000,000,000)
Z multiply the number by 10^21 zetta (1,000,000,000,000,000,000,000)
Y multiply the number by 10^24 yotta (1,000,000,000,000,000,000,000,000)
X multiply the number by 10^27 xenta (1,000,000,000,000,000,000,000,000,000)
W multiply the number by 10^30 wekta (1,000,000,000,000,000,000,000,000,000,000)
V multiply the number by 10^33 vendeka (1,000,000,000,000,000,000,000,000,000,000,000)
U multiply the number by 10^36 udekta (1,000,000,000,000,000,000,000,000,000,000,000,000)
Binary suffixes to be supported (whether or not they're officially sanctioned)
Ki multiply the number by 2^10 kibi (1,024)
Mi multiply the number by 2^20 mebi (1,048,576)
Gi multiply the number by 2^30 gibi (1,073,741,824)
Ti multiply the number by 2^40 tebi (1,099,571,627,776)
Pi multiply the number by 2^50 pebi (1,125,899,906,884,629)
Ei multiply the number by 2^60 exbi (1,152,921,504,606,846,976)
Zi multiply the number by 2^70 zeb1 (1,180,591,620,717,411,303,424)
Yi multiply the number by 2^80 yobi (1,208,925,819,614,629,174,706,176)
Xi multiply the number by 2^90 xebi (1,237,940,039,285,380,274,899,124,224)
Wi multiply the number by 2^100 webi (1,267,650,600,228,229,401,496,703,205,376)
Vi multiply the number by 2^110 vebi (1,298,074,214,633,706,907,132,624,082,305,024)
Ui multiply the number by 2^120 uebi (1,329,227,995,784,915,872,903,807,060,280,344,576)
All of the metric and binary suffixes can be expressed in lowercase, uppercase, or mixed case.
All of the metric and binary suffixes can be stacked (expressed multiple times), and also be intermixed:
I.E.: 123k 123K 123GKi 12.3GiGG 12.3e-7T .78E100e
Factorial suffixes to be supported
! compute the (regular) factorial product: 5! is 5 × 4 × 3 × 2 × 1 = 120
!! compute the double factorial product: 8! is 8 × 6 × 4 × 2 = 384
!!! compute the triple factorial product: 8! is 8 × 5 × 2 = 80
!!!! compute the quadruple factorial product: 8! is 8 × 4 = 32
!!!!! compute the quintuple factorial product: 8! is 8 × 3 = 24
··· the number of factorial symbols that can be specified is to be unlimited (as per what can be entered/typed) ···
Factorial suffixes aren't, of course, the usual type of multipliers, but are used here in a similar vein.
Multifactorials aren't to be confused with super─factorials where (4!)! would be (24)!.
Task
Using the test cases (below), show the "expanded" numbers here, on this page.
For each list, show the input on one line, and also show the output on one line.
When showing the input line, keep the spaces (whitespace) and case (capitalizations) as is.
For each result (list) displayed on one line, separate each number with two blanks.
Add commas to the output numbers were appropriate.
Test cases
2greatGRo 24Gros 288Doz 1,728pairs 172.8SCOre
1,567 +1.567k 0.1567e-2m
25.123kK 25.123m 2.5123e-00002G
25.123kiKI 25.123Mi 2.5123e-00002Gi +.25123E-7Ei
-.25123e-34Vikki 2e-77gooGols
9! 9!! 9!!! 9!!!! 9!!!!! 9!!!!!! 9!!!!!!! 9!!!!!!!! 9!!!!!!!!!
where the last number for the factorials has nine factorial symbols (!) after the 9
Related tasks
Multifactorial (which has a clearer and more succinct definition of multifactorials.)
Factorial
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Factor | Factor | USING: combinators combinators.short-circuit formatting fry
grouping grouping.extras kernel literals math math.functions
math.parser math.ranges qw regexp sequences sequences.deep
sequences.extras sets splitting unicode ;
IN: rosetta-code.numerical-suffixes
CONSTANT: test-cases {
qw{ 2greatGRo 24Gros 288Doz 1,728pairs 172.8SCOre }
qw{ 1,567 +1.567k 0.1567e-2m }
qw{ 25.123kK 25.123m 2.5123e-00002G }
qw{ 25.123kiKI 25.123Mi 2.5123e-00002Gi +.25123E-7Ei }
qw{ -.25123e-34Vikki 2e-77gooGols }
qw{
9! 9!! 9!!! 9!!!! 9!!!!! 9!!!!!! 9!!!!!!! 9!!!!!!!!
9!!!!!!!!!
}
}
CONSTANT: alpha {
{ "PAIRs" 2 } { "DOZens" 12 } { "SCOres" 20 }
{ "GRoss" 144 } { "GREATGRoss" 1,728 }
${ "GOOGOLs" 10 100 ^ }
}
CONSTANT: metric qw{ K M G T P E Z Y X W V U }
! Multifactorial
: m! ( n degree -- m ) neg 1 swap <range> product ;
! Separate a number from its suffix(es).
! e.g. "+1.567k" -> 1.567 "k"
: num/suffix ( str -- n suffix(es) )
dup <head-clumps> <reversed> { } like "" map-like
[ string>number ] map [ ] find [ tail* ] dip swap ;
! Checks whether str1 is an abbreviation of str2.
! e.g. "greatGRo" "GREATGRoss" -> t
: abbrev? ( str1 str2 -- ? )
{
[ [ >upper ] [ [ LETTER? ] take-while head? ] bi* ]
[ [ length ] bi@ <= ]
} 2&& ;
! Convert an alpha suffix to its multiplication function.
! e.g. "Doz" -> [ 12 * ]
: alpha>quot ( str -- quot )
[ alpha ] dip '[ first _ swap abbrev? ] find nip second
[ * ] curry ;
! Split a suffix composed of metric and binary suffixes into its
! constituent parts. e.g. "Vikki" -> { "Vi" "k" "ki" }
: split-compound ( str -- seq )
R/ (.i|.)/i all-matching-subseqs ;
! Convert a metric or binary suffix to its multiplication
! function. e.g. "k" -> [ 10 3 ^ * ]
: suffix>quot ( str -- quot )
dup [ [ 0 1 ] dip subseq >upper metric index 1 + ] dip
length 1 = [ 3 * '[ 10 _ ^ * ] ] [ 10 * '[ 2 _ ^ * ] ] if ;
! Apply suffix>quot to each member of a sequence.
! e.g. { "Vi" "k" "ki" } ->
! [ [ 2 110 ^ * ] [ 10 3 ^ * ] [ 2 10 ^ * ] ]
: map-suffix ( seq -- seq' ) [ suffix>quot ] [ ] map-as ;
! Tests whether a string is composed of metric and/or binary
! suffixes. e.g. "Vikki" -> t
: compound? ( str -- ? )
>upper metric concat "I" append without empty? ;
! Convert a float to an integer if it is numerically equivalent
! to an integer. e.g. 1.0 -> 1, 1.23 -> 1.23
: ?f>i ( x -- y/n )
dup >integer 2dup [ number= ] 2dip swap ? ;
! Convert a suffix string to a function that performs the
! calculations required by the suffix.
! e.g. "!!!" -> [ 3 m! ], "kiKI" -> [ 2 10 ^ * 2 10 ^ * ]
: parse-suffix ( str -- quot )
{
{ [ dup empty? ] [ drop [ ] ] }
{ [ dup first CHAR: ! = ] [ length [ m! ] curry ] }
{ [ dup compound? ] [ split-compound map-suffix ] }
[ alpha>quot ]
} cond flatten ;
GENERIC: commas ( n -- str )
! Add commas to an integer in triplets.
! e.g. 1567 -> "1,567"
M: integer commas number>string <reversed> 3 group
[ "," append ] map concat reverse rest ;
! Add commas to a float in triplets.
! e.g. 1567.12345 -> "1,567.12345"
M: float commas number>string "." split first2
[ string>number commas ] dip "." glue ;
! Parse any number with any numerical or alphabetical suffix.
! e.g. "288Doz" -> "3,456", "9!!" -> "945"
: parse-alpha ( str -- str' )
num/suffix parse-suffix curry call( -- x ) ?f>i commas ;
: main ( -- )
test-cases [
dup [ parse-alpha ] map
"Numbers: %[%s, %]\n Result: %[%s, %]\n\n" printf
] each ;
MAIN: main |
http://rosettacode.org/wiki/Old_Russian_measure_of_length | Old Russian measure of length | Task
Write a program to perform a conversion of the old Russian measures of length to the metric system (and vice versa).
It is an example of a linear transformation of several variables.
The program should accept a single value in a selected unit of measurement, and convert and return it to the other units:
vershoks, arshins, sazhens, versts, meters, centimeters and kilometers.
Also see
Old Russian measure of length
| #C.2B.2B | C++ |
#include <iostream>
#include <iomanip>
//-------------------------------------------------------------------------------------------
using namespace std;
//-------------------------------------------------------------------------------------------
class ormConverter
{
public:
ormConverter() : AR( 0.7112f ), CE( 0.01f ), DI( 0.0254f ), FU( 0.3048f ), KI( 1000.0f ), LI( 0.00254f ), ME( 1.0f ),
MI( 7467.6f ), PI( 0.1778f ), SA( 2.1336f ), TO( 0.000254f ), VE( 0.04445f ), VR( 1066.8f ) {}
void convert( char c, float l )
{
system( "cls" );
cout << endl << l;
switch( c )
{
case 'A': cout << " Arshin to:"; l *= AR; break;
case 'C': cout << " Centimeter to:"; l *= CE; break;
case 'D': cout << " Diuym to:"; l *= DI; break;
case 'F': cout << " Fut to:"; l *= FU; break;
case 'K': cout << " Kilometer to:"; l *= KI; break;
case 'L': cout << " Liniya to:"; l *= LI; break;
case 'M': cout << " Meter to:"; l *= ME; break;
case 'I': cout << " Milia to:"; l *= MI; break;
case 'P': cout << " Piad to:"; l *= PI; break;
case 'S': cout << " Sazhen to:"; l *= SA; break;
case 'T': cout << " Tochka to:"; l *= TO; break;
case 'V': cout << " Vershok to:"; l *= VE; break;
case 'E': cout << " Versta to:"; l *= VR;
}
float ar = l / AR, ce = l / CE, di = l / DI, fu = l / FU, ki = l / KI, li = l / LI, me = l / ME,
mi = l / MI, pi = l / PI, sa = l / SA, to = l / TO, ve = l / VE, vr = l / VR;
cout << left << endl << "=================" << endl
<< setw( 12 ) << "Arshin:" << ar << endl << setw( 12 ) << "Centimeter:" << ce << endl
<< setw( 12 ) << "Diuym:" << di << endl << setw( 12 ) << "Fut:" << fu << endl
<< setw( 12 ) << "Kilometer:" << ki << endl << setw( 12 ) << "Liniya:" << li << endl
<< setw( 12 ) << "Meter:" << me << endl << setw( 12 ) << "Milia:" << mi << endl
<< setw( 12 ) << "Piad:" << pi << endl << setw( 12 ) << "Sazhen:" << sa << endl
<< setw( 12 ) << "Tochka:" << to << endl << setw( 12 ) << "Vershok:" << ve << endl
<< setw( 12 ) << "Versta:" << vr << endl << endl << endl;
}
private:
const float AR, CE, DI, FU, KI, LI, ME, MI, PI, SA, TO, VE, VR;
};
//-------------------------------------------------------------------------------------------
int _tmain(int argc, _TCHAR* argv[])
{
ormConverter c;
char s; float l;
while( true )
{
cout << "What unit:\n(A)rshin, (C)entimeter, (D)iuym, (F)ut\n(K)ilometer, (L)iniya, (M)eter, m(I)lia, (P)iad\n(S)azhen, (T)ochka, (V)ershok, v(E)rsta, (Q)uit\n";
cin >> s; if( s & 32 ) s ^= 32; if( s == 'Q' ) return 0;
cout << "Length (0 to Quit): "; cin >> l; if( l == 0 ) return 0;
c.convert( s, l ); system( "pause" ); system( "cls" );
}
return 0;
}
//-------------------------------------------------------------------------------------------
|
http://rosettacode.org/wiki/OpenGL | OpenGL |
Task
Display a smooth shaded triangle with OpenGL.
Triangle created using C example compiled with GCC 4.1.2 and freeglut3.
| #eC | eC | #include <GL/gl.h>
import "ecere"
class GLTriangle : Window
{
text = "Triangle";
displayDriver = "OpenGL";
background = activeBorder;
nativeDecorations = true;
borderStyle = sizable;
hasMaximize = true, hasMinimize = true, hasClose = true;
size = { 640, 480 };
void OnRedraw(Surface surface)
{
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(-30, 30, -30, 30, -30, 30);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glTranslatef(-15, -15, 0);
glShadeModel(GL_SMOOTH);
glBegin(GL_TRIANGLES);
glColor3f(1, 0, 0);
glVertex2f(0, 0);
glColor3f(0, 1, 0);
glVertex2f(30, 0);
glColor3f(0, 0, 1);
glVertex2f(0, 30);
glEnd();
}
}
GLTriangle window {}; |
http://rosettacode.org/wiki/One_of_n_lines_in_a_file | One of n lines in a file | A method of choosing a line randomly from a file:
Without reading the file more than once
When substantial parts of the file cannot be held in memory
Without knowing how many lines are in the file
Is to:
keep the first line of the file as a possible choice, then
Read the second line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/2.
Read the third line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/3.
...
Read the Nth line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/N
Return the computed possible choice when no further lines exist in the file.
Task
Create a function/method/routine called one_of_n that given n, the number of actual lines in a file, follows the algorithm above to return an integer - the line number of the line chosen from the file.
The number returned can vary, randomly, in each run.
Use one_of_n in a simulation to find what woud be the chosen line of a 10 line file simulated 1,000,000 times.
Print and show how many times each of the 10 lines is chosen as a rough measure of how well the algorithm works.
Note: You may choose a smaller number of repetitions if necessary, but mention this up-front.
Note: This is a specific version of a Reservoir Sampling algorithm: https://en.wikipedia.org/wiki/Reservoir_sampling
| #C | C | #include <stdio.h>
#include <stdlib.h>
inline int irand(int n)
{
int r, randmax = RAND_MAX/n * n;
while ((r = rand()) >= randmax);
return r / (randmax / n);
}
inline int one_of_n(int n)
{
int i, r = 0;
for (i = 1; i < n; i++) if (!irand(i + 1)) r = i;
return r;
}
int main(void)
{
int i, r[10] = {0};
for (i = 0; i < 1000000; i++, r[one_of_n(10)]++);
for (i = 0; i < 10; i++)
printf("%d%c", r[i], i == 9 ? '\n':' ');
return 0;
} |
http://rosettacode.org/wiki/P-value_correction | P-value correction | Given a list of p-values, adjust the p-values for multiple comparisons. This is done in order to control the false positive, or Type 1 error rate.
This is also known as the "false discovery rate" (FDR). After adjustment, the p-values will be higher but still inside [0,1].
The adjusted p-values are sometimes called "q-values".
Task
Given one list of p-values, return the p-values correcting for multiple comparisons
p = {4.533744e-01, 7.296024e-01, 9.936026e-02, 9.079658e-02, 1.801962e-01,
8.752257e-01, 2.922222e-01, 9.115421e-01, 4.355806e-01, 5.324867e-01,
4.926798e-01, 5.802978e-01, 3.485442e-01, 7.883130e-01, 2.729308e-01,
8.502518e-01, 4.268138e-01, 6.442008e-01, 3.030266e-01, 5.001555e-02,
3.194810e-01, 7.892933e-01, 9.991834e-01, 1.745691e-01, 9.037516e-01,
1.198578e-01, 3.966083e-01, 1.403837e-02, 7.328671e-01, 6.793476e-02,
4.040730e-03, 3.033349e-04, 1.125147e-02, 2.375072e-02, 5.818542e-04,
3.075482e-04, 8.251272e-03, 1.356534e-03, 1.360696e-02, 3.764588e-04,
1.801145e-05, 2.504456e-07, 3.310253e-02, 9.427839e-03, 8.791153e-04,
2.177831e-04, 9.693054e-04, 6.610250e-05, 2.900813e-02, 5.735490e-03}
There are several methods to do this, see:
Yoav Benjamini, Yosef Hochberg "Controlling the False Discovery Rate: A Practical and Powerful Approach to Multiple Testing", Journal of the Royal Statistical Society. Series B, Vol. 57, No. 1 (1995), pp. 289-300, JSTOR:2346101
Yoav Benjamini, Daniel Yekutieli, "The control of the false discovery rate in multiple testing under dependency", Ann. Statist., Vol. 29, No. 4 (2001), pp. 1165-1188, DOI:10.1214/aos/1013699998 JSTOR:2674075
Sture Holm, "A Simple Sequentially Rejective Multiple Test Procedure", Scandinavian Journal of Statistics, Vol. 6, No. 2 (1979), pp. 65-70, JSTOR:4615733
Yosef Hochberg, "A sharper Bonferroni procedure for multiple tests of significance", Biometrika, Vol. 75, No. 4 (1988), pp 800–802, DOI:10.1093/biomet/75.4.800 JSTOR:2336325
Gerhard Hommel, "A stagewise rejective multiple test procedure based on a modified Bonferroni test", Biometrika, Vol. 75, No. 2 (1988), pp 383–386, DOI:10.1093/biomet/75.2.383 JSTOR:2336190
Each method has its own advantages and disadvantages.
| #Rust | Rust |
use std::iter;
#[rustfmt::skip]
const PVALUES:[f64;50] = [
4.533_744e-01, 7.296_024e-01, 9.936_026e-02, 9.079_658e-02, 1.801_962e-01,
8.752_257e-01, 2.922_222e-01, 9.115_421e-01, 4.355_806e-01, 5.324_867e-01,
4.926_798e-01, 5.802_978e-01, 3.485_442e-01, 7.883_130e-01, 2.729_308e-01,
8.502_518e-01, 4.268_138e-01, 6.442_008e-01, 3.030_266e-01, 5.001_555e-02,
3.194_810e-01, 7.892_933e-01, 9.991_834e-01, 1.745_691e-01, 9.037_516e-01,
1.198_578e-01, 3.966_083e-01, 1.403_837e-02, 7.328_671e-01, 6.793_476e-02,
4.040_730e-03, 3.033_349e-04, 1.125_147e-02, 2.375_072e-02, 5.818_542e-04,
3.075_482e-04, 8.251_272e-03, 1.356_534e-03, 1.360_696e-02, 3.764_588e-04,
1.801_145e-05, 2.504_456e-07, 3.310_253e-02, 9.427_839e-03, 8.791_153e-04,
2.177_831e-04, 9.693_054e-04, 6.610_250e-05, 2.900_813e-02, 5.735_490e-03
];
#[derive(Debug)]
enum CorrectionType {
BenjaminiHochberg,
BenjaminiYekutieli,
Bonferroni,
Hochberg,
Holm,
Hommel,
Sidak,
}
enum SortDirection {
Increasing,
Decreasing,
}
/// orders **input** vector by value and multiplies with **multiplier** vector
/// Finally returns the multiplied values in the original order of **input**
fn ordered_multiply(input: &[f64], multiplier: &[f64], direction: &SortDirection) -> Vec<f64> {
let order_by_value = match direction {
SortDirection::Increasing => {
|a: &(f64, usize), b: &(f64, usize)| b.0.partial_cmp(&a.0).unwrap()
}
SortDirection::Decreasing => {
|a: &(f64, usize), b: &(f64, usize)| a.0.partial_cmp(&b.0).unwrap()
}
};
let cmp_minmax = match direction {
SortDirection::Increasing => |a: f64, b: f64| a.gt(&b),
SortDirection::Decreasing => |a: f64, b: f64| a.lt(&b),
};
// add original order index
let mut input_indexed = input
.iter()
.enumerate()
.map(|(idx, &p_value)| (p_value, idx))
.collect::<Vec<_>>();
// order by value desc/asc
input_indexed.sort_unstable_by(order_by_value);
// do the multiplication in place, clamp it at 1.0,
// keep the original index in place
for i in 0..input_indexed.len() {
input_indexed[i] = (
f64::min(1.0, input_indexed[i].0 * multiplier[i]),
input_indexed[i].1,
);
}
// make vector strictly monotonous increasing/decreasing in place
for i in 1..input_indexed.len() {
if cmp_minmax(input_indexed[i].0, input_indexed[i - 1].0) {
input_indexed[i] = (input_indexed[i - 1].0, input_indexed[i].1);
}
}
// re-sort back to original order
input_indexed.sort_unstable_by(|a: &(f64, usize), b: &(f64, usize)| a.1.cmp(&b.1));
// remove ordering index
let (resorted, _): (Vec<_>, Vec<_>) = input_indexed.iter().cloned().unzip();
resorted
}
#[allow(clippy::cast_precision_loss)]
fn hommel(input: &[f64]) -> Vec<f64> {
// using algorith described:
// http://stat.wharton.upenn.edu/~steele/Courses/956/ResourceDetails/MultipleComparision/Writght92.pdf
// add original order index
let mut input_indexed = input
.iter()
.enumerate()
.map(|(idx, &p_value)| (p_value, idx))
.collect::<Vec<_>>();
// order by value asc
input_indexed
.sort_unstable_by(|a: &(f64, usize), b: &(f64, usize)| a.0.partial_cmp(&b.0).unwrap());
let (p_values, order): (Vec<_>, Vec<_>) = input_indexed.iter().cloned().unzip();
let n = input.len();
// initial minimal n*p/i values
// get the smalles of these values
let min_result = (0..n)
.map(|i| ((p_values[i] * n as f64) / (i + 1) as f64))
.fold(1. / 0. /* -inf */, f64::min);
// // initialize result vector with minimal values
let mut result = iter::repeat(min_result).take(n).collect::<Vec<_>>();
for m in (2..n).rev() {
let cmin: f64;
let m_as_float = m as f64;
let mut a = p_values.clone();
// println!("\nn: {}", m);
{
// split p-values into two group
let (_, second) = p_values.split_at(n - m + 1);
// calculate minumum of m*p/i for this second group
cmin = second
.iter()
.zip(2..=m)
.map(|(p, i)| (m_as_float * p) / i as f64)
.fold(1. / 0. /* inf */, f64::min);
}
// replace p values if p<cmin in the second group
((n - m + 1)..n).for_each(|i| a[i] = a[i].max(cmin));
// replace p values if min(cmin, m*p) > p
(0..=(n - m)).for_each(|i| a[i] = a[i].max(f64::min(cmin, m_as_float * p_values[i])));
// store in the result vector if any adjusted p is higher than the current one
(0..n).for_each(|i| result[i] = result[i].max(a[i]));
}
// re-sort into the original order
let mut result = result
.into_iter()
.zip(order.into_iter())
.map(|(p, idx)| (p, idx))
.collect::<Vec<_>>();
result.sort_unstable_by(|a: &(f64, usize), b: &(f64, usize)| a.1.cmp(&b.1));
let (result, _): (Vec<_>, Vec<_>) = result.iter().cloned().unzip();
result
}
#[allow(clippy::cast_precision_loss)]
fn p_value_correction(p_values: &[f64], ctype: &CorrectionType) -> Vec<f64> {
let p_vec = p_values.to_vec();
if p_values.is_empty() {
return p_vec;
}
let fsize = p_values.len() as f64;
match ctype {
CorrectionType::BenjaminiHochberg => {
let multiplier = (0..p_values.len())
.map(|index| fsize / (fsize - index as f64))
.collect::<Vec<_>>();
ordered_multiply(&p_vec, &multiplier, &SortDirection::Increasing)
}
CorrectionType::BenjaminiYekutieli => {
let q: f64 = (1..=p_values.len()).map(|index| 1. / index as f64).sum();
let multiplier = (0..p_values.len())
.map(|index| q * fsize / (fsize - index as f64))
.collect::<Vec<_>>();
ordered_multiply(&p_vec, &multiplier, &SortDirection::Increasing)
}
CorrectionType::Bonferroni => p_vec
.iter()
.map(|p| f64::min(p * fsize, 1.0))
.collect::<Vec<_>>(),
CorrectionType::Hochberg => {
let multiplier = (0..p_values.len())
.map(|index| 1. + index as f64)
.collect::<Vec<_>>();
ordered_multiply(&p_vec, &multiplier, &SortDirection::Increasing)
}
CorrectionType::Holm => {
let multiplier = (0..p_values.len())
.map(|index| fsize - index as f64)
.collect::<Vec<_>>();
ordered_multiply(&p_vec, &multiplier, &SortDirection::Decreasing)
}
CorrectionType::Sidak => p_vec
.iter()
.map(|x| 1. - (1. - x).powf(fsize))
.collect::<Vec<_>>(),
CorrectionType::Hommel => hommel(&p_vec),
}
}
// prints array into a nice table, max 5 floats/row
fn array_to_string(a: &[f64]) -> String {
a.chunks(5)
.enumerate()
.map(|(index, e)| {
format!(
"[{:>2}]: {}",
index * 5,
e.iter()
.map(|x| format!("{:>1.10}", x))
.collect::<Vec<_>>()
.join(", ")
)
})
.collect::<Vec<_>>()
.join("\n")
}
fn main() {
let ctypes = [
CorrectionType::BenjaminiHochberg,
CorrectionType::BenjaminiYekutieli,
CorrectionType::Bonferroni,
CorrectionType::Hochberg,
CorrectionType::Holm,
CorrectionType::Sidak,
CorrectionType::Hommel,
];
for ctype in &ctypes {
println!("\n{:?}:", ctype);
println!("{}", array_to_string(&p_value_correction(&PVALUES, ctype)));
}
}
|
http://rosettacode.org/wiki/Order_disjoint_list_items | Order disjoint list items |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Given M as a list of items and another list N of items chosen from M, create M' as a list with the first occurrences of items from N sorted to be in one of the set of indices of their original occurrence in M but in the order given by their order in N.
That is, items in N are taken from M without replacement, then the corresponding positions in M' are filled by successive items from N.
For example
if M is 'the cat sat on the mat'
And N is 'mat cat'
Then the result M' is 'the mat sat on the cat'.
The words not in N are left in their original positions.
If there are duplications then only the first instances in M up to as many as are mentioned in N are potentially re-ordered.
For example
M = 'A B C A B C A B C'
N = 'C A C A'
Is ordered as:
M' = 'C B A C B A A B C'
Show the output, here, for at least the following inputs:
Data M: 'the cat sat on the mat' Order N: 'mat cat'
Data M: 'the cat sat on the mat' Order N: 'cat mat'
Data M: 'A B C A B C A B C' Order N: 'C A C A'
Data M: 'A B C A B D A B E' Order N: 'E A D A'
Data M: 'A B' Order N: 'B'
Data M: 'A B' Order N: 'B A'
Data M: 'A B B A' Order N: 'B A'
Cf
Sort disjoint sublist
| #M2000_Interpreter | M2000 Interpreter |
Function Checkit$ {
Document Ret$
Flush
Data "the cat sat on the mat", "mat cat"
Data "the cat sat on the mat","cat mat"'
Data "A B C A B C A B C", "C A C A"
Data "A B C A B D A B E", "E A D A"
Data "A B", "B"
Data "A B", "B A"
Data "A B B A","B A"
Dim A$()
while not empty
read m$, n$
A$()=piece$(m$, " ")
Let w=piece$(n$, " ")
Let z=A$()
x=each(w)
while x
y=z#pos(array$(x))
if y>-1 then a$(y)=""
end while
p=0
x=each(w)
while x
while a$(p)<>"" : p++: end while
a$(p)=array$(x)
end while
ret$=m$+" | "+n$+" -> "+z#str$()+{
}
end while
=ret$
}
Report Checkit$()
Clipboard Checkit$()
|
http://rosettacode.org/wiki/Order_disjoint_list_items | Order disjoint list items |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Given M as a list of items and another list N of items chosen from M, create M' as a list with the first occurrences of items from N sorted to be in one of the set of indices of their original occurrence in M but in the order given by their order in N.
That is, items in N are taken from M without replacement, then the corresponding positions in M' are filled by successive items from N.
For example
if M is 'the cat sat on the mat'
And N is 'mat cat'
Then the result M' is 'the mat sat on the cat'.
The words not in N are left in their original positions.
If there are duplications then only the first instances in M up to as many as are mentioned in N are potentially re-ordered.
For example
M = 'A B C A B C A B C'
N = 'C A C A'
Is ordered as:
M' = 'C B A C B A A B C'
Show the output, here, for at least the following inputs:
Data M: 'the cat sat on the mat' Order N: 'mat cat'
Data M: 'the cat sat on the mat' Order N: 'cat mat'
Data M: 'A B C A B C A B C' Order N: 'C A C A'
Data M: 'A B C A B D A B E' Order N: 'E A D A'
Data M: 'A B' Order N: 'B'
Data M: 'A B' Order N: 'B A'
Data M: 'A B B A' Order N: 'B A'
Cf
Sort disjoint sublist
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | order[m_, n_] :=
ReplacePart[m,
MapThread[
Rule, {Position[m, Alternatives @@ n][[;; Length[n]]], n}]];
Print[StringRiffle[
order[{"the", "cat", "sat", "on", "the", "mat"}, {"mat",
"cat"}]]];
Print[StringRiffle[
order[{"the", "cat", "sat", "on", "the", "mat"}, {"cat",
"mat"}]]];
Print[StringRiffle[
order[{"A", "B", "C", "A", "B", "C", "A", "B", "C"}, {"C", "A",
"C", "A"}]]];
Print[StringRiffle[
order[{"A", "B", "C", "A", "B", "D", "A", "B", "E"}, {"E", "A",
"D", "A"}]]];
Print[StringRiffle[order[{"A", "B"}, {"B"}]]];
Print[StringRiffle[order[{"A", "B"}, {"B", "A"}]]];
Print[StringRiffle[order[{"A", "B", "B", "A"}, {"B", "A"}]]]; |
http://rosettacode.org/wiki/Optional_parameters | Optional parameters | Task
Define a function/method/subroutine which sorts a sequence ("table") of sequences ("rows") of strings ("cells"), by one of the strings. Besides the input to be sorted, it shall have the following optional parameters:
ordering
A function specifying the ordering of strings; lexicographic by default.
column
An integer specifying which string of each row to compare; the first by default.
reverse
Reverses the ordering.
This task should be considered to include both positional and named optional parameters, as well as overloading on argument count as in Java or selector name as in Smalltalk, or, in the extreme, using different function names. Provide these variations of sorting in whatever way is most natural to your language. If the language supports both methods naturally, you are encouraged to describe both.
Do not implement a sorting algorithm; this task is about the interface. If you can't use a built-in sort routine, just omit the implementation (with a comment).
See also:
Named Arguments
| #Go | Go | type cell string
type spec struct {
less func(cell, cell) bool
column int
reverse bool
}
func newSpec() (s spec) {
// initialize any defaults
return
}
// sort with all defaults
t.sort(newSpec())
// reverse sort
s := newSpec
s.reverse = true
t.sort(s) |
http://rosettacode.org/wiki/Optional_parameters | Optional parameters | Task
Define a function/method/subroutine which sorts a sequence ("table") of sequences ("rows") of strings ("cells"), by one of the strings. Besides the input to be sorted, it shall have the following optional parameters:
ordering
A function specifying the ordering of strings; lexicographic by default.
column
An integer specifying which string of each row to compare; the first by default.
reverse
Reverses the ordering.
This task should be considered to include both positional and named optional parameters, as well as overloading on argument count as in Java or selector name as in Smalltalk, or, in the extreme, using different function names. Provide these variations of sorting in whatever way is most natural to your language. If the language supports both methods naturally, you are encouraged to describe both.
Do not implement a sorting algorithm; this task is about the interface. If you can't use a built-in sort routine, just omit the implementation (with a comment).
See also:
Named Arguments
| #Groovy | Groovy | def orderedSort(Collection table, column = 0, reverse = false, ordering = {x, y -> x <=> y } as Comparator) {
table.sort(false) { x, y -> (reverse ? -1 : 1) * ordering.compare(x[column], y[column])}
} |
http://rosettacode.org/wiki/Order_two_numerical_lists | Order two numerical lists | sorting
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Write a function that orders two lists or arrays filled with numbers.
The function should accept two lists as arguments and return true if the first list should be ordered before the second, and false otherwise.
The order is determined by lexicographic order: Comparing the first element of each list.
If the first elements are equal, then the second elements should be compared, and so on, until one of the list has no more elements.
If the first list runs out of elements the result is true.
If the second list or both run out of elements the result is false.
Note: further clarification of lexicographical ordering is expounded on the talk page here and here.
| #Delphi | Delphi |
program Order_two_numerical_lists;
{$APPTYPE CONSOLE}
uses
System.SysUtils,
System.Generics.Defaults;
type
TArray = record
class function LessOrEqual<T>(first, second: TArray<T>): Boolean; static;
end;
class function TArray.LessOrEqual<T>(first, second: TArray<T>): Boolean;
begin
if Length(first) = 0 then
exit(true);
if Length(second) = 0 then
exit(false);
var comp := TComparer<T>.Default.Compare(first[0], second[0]);
if comp = 0 then
exit(LessOrEqual(copy(first, 1, length(first)), copy(second, 1, length(second))));
Result := comp < 0;
end;
begin
writeln(TArray.LessOrEqual<Integer>([1, 2, 3], [2, 3, 4]));
writeln(TArray.LessOrEqual<Integer>([2, 3, 4], [1, 2, 3]));
writeln(TArray.LessOrEqual<Integer>([1, 2], [1, 2, 3]));
writeln(TArray.LessOrEqual<Integer>([1, 2, 3], [1, 2]));
writeln(TArray.LessOrEqual<Char>(['a', 'c', 'b'], ['a', 'b', 'b']));
writeln(TArray.LessOrEqual<string>(['this', 'is', 'a', 'test'], ['this', 'is',
'not', 'a', 'test']));
readln;
end. |
http://rosettacode.org/wiki/Pascal%27s_triangle | Pascal's triangle | Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere.
Its first few rows look like this:
1
1 1
1 2 1
1 3 3 1
where each element of each row is either 1 or the sum of the two elements right above it.
For example, the next row of the triangle would be:
1 (since the first element of each row doesn't have two elements above it)
4 (1 + 3)
6 (3 + 3)
4 (3 + 1)
1 (since the last element of each row doesn't have two elements above it)
So the triangle now looks like this:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
Each row n (starting with row 0 at the top) shows the coefficients of the binomial expansion of (x + y)n.
Task
Write a function that prints out the first n rows of the triangle (with f(1) yielding the row consisting of only the element 1).
This can be done either by summing elements from the previous rows or using a binary coefficient or combination function.
Behavior for n ≤ 0 does not need to be uniform, but should be noted.
See also
Evaluate binomial coefficients
| #VBScript | VBScript | Pascal_Triangle(WScript.Arguments(0))
Function Pascal_Triangle(n)
Dim values(100)
values(1) = 1
WScript.StdOut.Write values(1)
WScript.StdOut.WriteLine
For row = 2 To n
For i = row To 1 Step -1
values(i) = values(i) + values(i-1)
WScript.StdOut.Write values(i) & " "
Next
WScript.StdOut.WriteLine
Next
End Function |
http://rosettacode.org/wiki/Operator_precedence | Operator precedence |
This page uses content from Wikipedia. The original article was at Operators in C and C++. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Provide a list of precedence and associativity of all the operators and constructs that the language utilizes in descending order of precedence such that an operator which is listed on some row will be evaluated prior to any operator that is listed on a row further below it.
Operators that are in the same cell (there may be several rows of operators listed in a cell) are evaluated with the same level of precedence, in the given direction.
State whether arguments are passed by value or by reference.
| #Oforth | Oforth | q)3*2+1
9
q)(3*2)+1 / Brackets give the usual order of precedence
7
q)x:5
q)(x+5; x:20; x-5)
25 20 0 |
http://rosettacode.org/wiki/Operator_precedence | Operator precedence |
This page uses content from Wikipedia. The original article was at Operators in C and C++. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Provide a list of precedence and associativity of all the operators and constructs that the language utilizes in descending order of precedence such that an operator which is listed on some row will be evaluated prior to any operator that is listed on a row further below it.
Operators that are in the same cell (there may be several rows of operators listed in a cell) are evaluated with the same level of precedence, in the given direction.
State whether arguments are passed by value or by reference.
| #PARI.2FGP | PARI/GP | q)3*2+1
9
q)(3*2)+1 / Brackets give the usual order of precedence
7
q)x:5
q)(x+5; x:20; x-5)
25 20 0 |
http://rosettacode.org/wiki/Ordered_words | Ordered words | An ordered word is a word in which the letters appear in alphabetic order.
Examples include abbey and dirt.
Task[edit]
Find and display all the ordered words in the dictionary unixdict.txt that have the longest word length.
(Examples that access the dictionary file locally assume that you have downloaded this file yourself.)
The display needs to be shown on this page.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Fantom | Fantom |
class Main
{
public static Bool ordered (Str word)
{
word.chars.all |Int c, Int i -> Bool|
{
(i == (word.size-1) || c <= word.chars[i+1])
}
}
public static Void main ()
{
Str[] words := [,]
File(`unixdict.txt`).eachLine |Str word|
{
if (ordered(word))
{
if (words.isEmpty || words.first.size < word.size)
{ // reset the list
words = [word]
}
else if (words.size >= 1 && words.first.size == word.size)
{ // add word to existing ones
words.add (word)
}
}
}
echo (words.join (" "))
}
}
|
http://rosettacode.org/wiki/Ordered_words | Ordered words | An ordered word is a word in which the letters appear in alphabetic order.
Examples include abbey and dirt.
Task[edit]
Find and display all the ordered words in the dictionary unixdict.txt that have the longest word length.
(Examples that access the dictionary file locally assume that you have downloaded this file yourself.)
The display needs to be shown on this page.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #FBSL | FBSL | #APPTYPE CONSOLE
FUNCTION RESTfulGET(url)
DIM %HTTP = CREATEOBJECT("WinHttp.WinHttpRequest.5.1")
CALLMETHOD(HTTP, ".open %s, %s, %d", "GET", url, FALSE)
CALLMETHOD(HTTP, ".send")
RETURN GETVALUE("%s", HTTP, ".ResponseText")
END FUNCTION
DIM $TEXT = RESTfulGET("http://www.puzzlers.org/pub/wordlists/unixdict.txt")
DIM dict[] = Split(TEXT, CHR(10))
DIM max AS INTEGER = UBOUND(dict)
DIM theword AS STRING
DIM words[]
FOR DIM i = 0 TO max
theWord = dict[i]
IF isOrdered(theWord) THEN
words[LEN(theWord)] = words[LEN(theWord)] & " " & theWord
END IF
NEXT
PRINT words[UBOUND(words)]
PAUSE
FUNCTION isOrdered(s)
FOR DIM i = 1 TO LEN(s) - 1
IF s{i} > s{i + 1} THEN
RETURN FALSE
END IF
NEXT
RETURN TRUE
END FUNCTION
|
http://rosettacode.org/wiki/Palindrome_detection | Palindrome detection | A palindrome is a phrase which reads the same backward and forward.
Task[edit]
Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes)
is a palindrome.
For extra credit:
Support Unicode characters.
Write a second function (possibly as a wrapper to the first) which detects inexact palindromes, i.e. phrases that are palindromes if white-space and punctuation is ignored and case-insensitive comparison is used.
Hints
It might be useful for this task to know how to reverse a string.
This task's entries might also form the subjects of the task Test a function.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Ol | Ol |
; simple case - only lowercase letters
(define (palindrome? str)
(let ((l (string->runes str)))
(equal? l (reverse l))))
(print (palindrome? "ingirumimusnocteetconsumimurigni"))
; ==> #true
(print (palindrome? "thisisnotapalindrome"))
; ==> #false
; complex case - with ignoring letter case and punctuation
(define (alpha? x)
(<= #\a x #\z))
(define (lowercase x)
(if (<= #\A x #\Z)
(- x (- #\A #\a))
x))
(define (palindrome? str)
(let ((l (filter alpha? (map lowercase (string->runes str)))))
(equal? l (reverse l))))
(print (palindrome? "A man, a plan, a cat, a ham, a yak, a yam, a hat, a canal-Panama!"))
; ==> #true
(print (palindrome? "This is not a palindrome"))
; ==> #false
|
http://rosettacode.org/wiki/One-time_pad | One-time pad | Implement a One-time pad, for encrypting and decrypting messages.
To keep it simple, we will be using letters only.
Sub-Tasks
Generate the data for a One-time pad (user needs to specify a filename and length)
The important part is to get "true random" numbers, e.g. from /dev/random
encryption / decryption ( basically the same operation, much like Rot-13 )
For this step, much of Vigenère cipher could be reused,
with the key to be read from the file containing the One-time pad.
optional: management of One-time pads: list, mark as used, delete, etc.
Somehow, the users needs to keep track which pad to use for which partner.
To support the management of pad-files:
Such files have a file-extension ".1tp"
Lines starting with "#" may contain arbitary meta-data (i.e. comments)
Lines starting with "-" count as "used"
Whitespace within the otp-data is ignored
For example, here is the data from Wikipedia:
# Example data - Wikipedia - 2014-11-13
-ZDXWWW EJKAWO FECIFE WSNZIP PXPKIY URMZHI JZTLBC YLGDYJ
-HTSVTV RRYYEG EXNCGA GGQVRF FHZCIB EWLGGR BZXQDQ DGGIAK
YHJYEQ TDLCQT HZBSIZ IRZDYS RBYJFZ AIRCWI UCVXTW YKPQMK
CKHVEX VXYVCS WOGAAZ OUVVON GCNEVR LMBLYB SBDCDC PCGVJX
QXAUIP PXZQIJ JIUWYH COVWMJ UZOJHL DWHPER UBSRUJ HGAAPR
CRWVHI FRNTQW AJVWRT ACAKRD OZKIIB VIQGBK IJCWHF GTTSSE
EXFIPJ KICASQ IOUQTP ZSGXGH YTYCTI BAZSTN JKMFXI RERYWE
See also
one time pad encryption in Python
snapfractalpop - One-Time-Pad Command-Line-Utility (C).
Crypt-OTP-2.00 on CPAN (Perl)
| #Raku | Raku | sub MAIN {
put "Generate data for one time pad encryption.\n" ~
"File will have .1tp extension.";
my $fn;
loop {
$fn = prompt 'Filename for one time pad data: ';
if $fn !~~ /'.1tp' $/ { $fn ~= '.1tp' }
if $fn.IO.e {
my $ow = prompt "$fn aready exists, over-write? y/[n] ";
last if $ow ~~ m:i/'y'/;
redo;
}
last;
}
put 'Each line will contain 48 characters of encyption data.';
my $lines = prompt 'How many lines of data to generate? [1000] ';
$lines ||= 1000;
generate($fn, $lines);
say "One-time-pad data saved to: ", $fn.IO.absolute;
sub generate ( $fn, $lines) {
use Crypt::Random;
$fn.IO.spurt: "# one-time-pad encryption data\n" ~
((sprintf(" %s %s %s %s %s %s %s %s\n",
((('A'..'Z')[crypt_random_uniform(26)] xx 6).join) xx 8))
xx $lines).join;
}
} |
http://rosettacode.org/wiki/One-dimensional_cellular_automata | One-dimensional cellular automata | Assume an array of cells with an initial distribution of live and dead cells,
and imaginary cells off the end of the array having fixed values.
Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the current generation.
If, in the following table, a live cell is represented by 1 and a dead cell by 0 then to generate the value of the cell at a particular index in the array of cellular values you use the following table:
000 -> 0 #
001 -> 0 #
010 -> 0 # Dies without enough neighbours
011 -> 1 # Needs one neighbour to survive
100 -> 0 #
101 -> 1 # Two neighbours giving birth
110 -> 1 # Needs one neighbour to survive
111 -> 0 # Starved to death.
| #8th | 8th |
\ one-dimensional automaton
\ direct map of input state to output state:
{
" " : 32,
" #" : 32,
" # " : 32,
" ##" : 35,
"# " : 32,
"# #" : 35,
"## " : 35,
"###" : 32,
} var, lifemap
: transition \ s ix (r:s') -- (r:s')
>r dup r@ n:1- 3 s:slice
lifemap @ swap caseof
r> swap r@ -rot s:! >r ;
\ run over 'state' and generate new state
: gen \ s -- s'
clone >r
dup s:len 2 n:-
' transition 1 rot loop
drop r> ;
: life \ s -- s'
dup . cr gen ;
" ### ## # # # # # " ' life 10 times
bye
|
http://rosettacode.org/wiki/Object_serialization | Object serialization | Create a set of data types based upon inheritance. Each data type or class should have a print command that displays the contents of an instance of that class to standard output. Create instances of each class in your inheritance hierarchy and display them to standard output. Write each of the objects to a file named objects.dat in binary form using serialization or marshalling. Read the file objects.dat and print the contents of each serialized object.
| #Ada | Ada | with Ada.Calendar; use Ada.Calendar;
package Messages is
type Message is tagged record
Timestamp : Time;
end record;
procedure Print(Item : Message);
procedure Display(Item : Message'Class);
type Sensor_Message is new Message with record
Sensor_Id : Integer;
Reading : Float;
end record;
procedure Print(Item : Sensor_Message);
type Control_Message is new Message with record
Actuator_Id : Integer;
Command : Float;
end record;
procedure Print(Item : Control_Message);
end Messages; |
http://rosettacode.org/wiki/Old_lady_swallowed_a_fly | Old lady swallowed a fly | Task
Present a program which emits the lyrics to the song I Knew an Old Lady Who Swallowed a Fly, taking advantage of the repetitive structure of the song's lyrics.
This song has multiple versions with slightly different lyrics, so all these programs might not emit identical output.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #8080_Assembly | 8080 Assembly | org 100h
mvi c,-1 ; C = verse counter
verse: inr c
lxi d,lady ; There was an old lady who swallowed a ...
call prstr
mov e,c ; <animal>
call pbeast
lxi d,comma
call prstr
mov e,c ; verse
call pverse
mov a,c ; is this the first verse?
ana a
jz verse ; then we're not swallowing animals yet
cpi 7 ; otherwise, is the lady dead yet?
rz ; if so, stop.
mov b,c ; otherwise, start swallowing
swallo: lxi d,swlw1 ; She swallowed the
call prstr
mov e,b ; <current animal>
call pbeast
lxi d,swlw2 ; to catch the
call prstr
dcr b
push psw ; store state (is B zero now)
mov e,b ; <previous animal>
call pbeast
lxi d,comma
call prstr
mov a,b
cpi 2
mov e,b ; print associated verse if < 2
cc pverse
pop psw ; was B zero?
jnz swallo ; if not, swallow more
jmp verse ; if so, next verse
prstr: push b ; print string in DE
mvi c,9
call 5
pop b
ret
pverse: lxi h,verses
jmp pstrn
pbeast: lxi h,beasts
;;; Print the E'th string from the list at HL
pstrn: push b ; keep counters in B and C
mvi a,'$' ; end-of-string marker
inr e
pscan: cmp m ; keep going until we find one
inx h
jnz pscan
dcr e ; is this the one we wanted?
jnz pscan ; if not, keep going
xchg ; otherwise, put in DE
mvi c,9 ; print string using CP/M
call 5
pop b ; restore counters
ret
lady: db 'There was an old lady who swallowed a '
beasts: db '$fly$spider$bird$cat$dog$goat$cow$horse'
verses: db '$I don',39,'t know why she swallowed that fly -'
db ' Perhaps she',39,'ll die.',13,10,13,10
db '$That wiggled and jiggled and tickled inside her!',13,10
db '$How absurd to swallow a bird',13,10
db '$Imagine that! She swallowed a cat!',13,10
db '$What a hog to swallow a dog',13,10
db '$She just opened her throat and swallowed that goat',13,10
db '$I don',39,'t know how she swallowed that cow',13,10
db '$She',39,'s dead, of course.',13,10,'$'
swlw1: db 'She swallowed the $'
swlw2: db ' to catch the $'
comma: db ',',13,10,'$' |
http://rosettacode.org/wiki/Old_lady_swallowed_a_fly | Old lady swallowed a fly | Task
Present a program which emits the lyrics to the song I Knew an Old Lady Who Swallowed a Fly, taking advantage of the repetitive structure of the song's lyrics.
This song has multiple versions with slightly different lyrics, so all these programs might not emit identical output.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #8086_Assembly | 8086 Assembly | cpu 8086
org 100h
section .text
mov bl,-1 ; BL = verse counter
verse: inc bl
mov dx,lady ; There was an old lady who swallowed
call prstr
mov dl,bl ; <animal>
call pbeast
mov dx,comma
call prstr
mov dl,bl ; verse
call pverse
test bl,bl ; is this the first verse?
jz verse ; then we're not swallowing anything yet
cmp bl,7 ; otherwise, is the lady dead yet?
je stop ; if so, stop.
mov bh,bl ; otherwise, start swallowing
swallo: mov dx,swlw1 ; She swallowed the
call prstr
mov dl,bh ; <current animal>
call pbeast
mov dx,swlw2 ; to catch the
call prstr
dec bh ; <previous animal>
mov dl,bh
call pbeast
mov dx,comma
call prstr
cmp bh,2 ; print associated verse if BH<2
jae .next
mov dl,bh
call pverse
.next: test bh,bh ; is BH zero yet?
jnz swallo ; if not, swallow next animal
jmp verse ; otherwise, print next verse
pverse: mov di,verses ; Print verse DL
jmp pstrn
pbeast: mov di,beasts ; Print animal DL
;;; Print DL'th string from [DI]
pstrn: inc dl
mov al,'$' ; end-of-string marker
.scan: mov cx,-1
repne scasb
dec dl
jnz .scan
mov dx,di
prstr: mov ah,9 ; MS-DOS syscall to print a string
int 21h
stop: ret
section .data
lady: db 'There was an old lady who swallowed a '
beasts: db '$fly$spider$bird$cat$dog$goat$cow$horse'
verses: db '$I don',39,'t know why she swallowed that fly -'
db ' Perhaps she',39,'ll die.',13,10,13,10
db '$That wiggled and jiggled and tickled inside her!',13,10
db '$How absurd to swallow a bird',13,10
db '$Imagine that! She swallowed a cat!',13,10
db '$What a hog to swallow a dog',13,10
db '$She just opened her throat and swallowed that goat',13,10
db '$I don',39,'t know how she swallowed that cow',13,10
db '$She',39,'s dead, of course.',13,10,'$'
swlw1: db 'She swallowed the $'
swlw2: db ' to catch the $'
comma: db ',',13,10,'$' |
http://rosettacode.org/wiki/Numerical_and_alphabetical_suffixes | Numerical and alphabetical suffixes | This task is about expressing numbers with an attached (abutted) suffix multiplier(s), the suffix(es) could be:
an alphabetic (named) multiplier which could be abbreviated
metric multiplier(s) which can be specified multiple times
"binary" multiplier(s) which can be specified multiple times
explanation marks (!) which indicate a factorial or multifactorial
The (decimal) numbers can be expressed generally as:
{±} {digits} {.} {digits}
────── or ──────
{±} {digits} {.} {digits} {E or e} {±} {digits}
where:
numbers won't have embedded blanks (contrary to the expaciated examples above where whitespace was used for readability)
this task will only be dealing with decimal numbers, both in the mantissa and exponent
± indicates an optional plus or minus sign (+ or -)
digits are the decimal digits (0 ──► 9)
the digits can have comma(s) interjected to separate the periods (thousands) such as: 12,467,000
. is the decimal point, sometimes also called a dot
e or E denotes the use of decimal exponentiation (a number multiplied by raising ten to some power)
This isn't a pure or perfect definition of the way we express decimal numbers, but it should convey the intent for this task.
The use of the word periods (thousands) is not meant to confuse, that word (as used above) is what the comma separates;
the groups of decimal digits are called periods, and in almost all cases, are groups of three decimal digits.
If an e or E is specified, there must be a legal number expressed before it, and there must be a legal (exponent) expressed after it.
Also, there must be some digits expressed in all cases, not just a sign and/or decimal point.
Superfluous signs, decimal points, exponent numbers, and zeros need not be preserved.
I.E.:
+7 007 7.00 7E-0 7E000 70e-1 could all be expressed as 7
All numbers to be "expanded" can be assumed to be valid and there won't be a requirement to verify their validity.
Abbreviated alphabetic suffixes to be supported (where the capital letters signify the minimum abbreation that can be used)
PAIRs multiply the number by 2 (as in pairs of shoes or pants)
SCOres multiply the number by 20 (as 3score would be 60)
DOZens multiply the number by 12
GRoss multiply the number by 144 (twelve dozen)
GREATGRoss multiply the number by 1,728 (a dozen gross)
GOOGOLs multiply the number by 10^100 (ten raised to the 100&sup>th</sup> power)
Note that the plurals are supported, even though they're usually used when expressing exact numbers (She has 2 dozen eggs, and dozens of quavas)
Metric suffixes to be supported (whether or not they're officially sanctioned)
K multiply the number by 10^3 kilo (1,000)
M multiply the number by 10^6 mega (1,000,000)
G multiply the number by 10^9 giga (1,000,000,000)
T multiply the number by 10^12 tera (1,000,000,000,000)
P multiply the number by 10^15 peta (1,000,000,000,000,000)
E multiply the number by 10^18 exa (1,000,000,000,000,000,000)
Z multiply the number by 10^21 zetta (1,000,000,000,000,000,000,000)
Y multiply the number by 10^24 yotta (1,000,000,000,000,000,000,000,000)
X multiply the number by 10^27 xenta (1,000,000,000,000,000,000,000,000,000)
W multiply the number by 10^30 wekta (1,000,000,000,000,000,000,000,000,000,000)
V multiply the number by 10^33 vendeka (1,000,000,000,000,000,000,000,000,000,000,000)
U multiply the number by 10^36 udekta (1,000,000,000,000,000,000,000,000,000,000,000,000)
Binary suffixes to be supported (whether or not they're officially sanctioned)
Ki multiply the number by 2^10 kibi (1,024)
Mi multiply the number by 2^20 mebi (1,048,576)
Gi multiply the number by 2^30 gibi (1,073,741,824)
Ti multiply the number by 2^40 tebi (1,099,571,627,776)
Pi multiply the number by 2^50 pebi (1,125,899,906,884,629)
Ei multiply the number by 2^60 exbi (1,152,921,504,606,846,976)
Zi multiply the number by 2^70 zeb1 (1,180,591,620,717,411,303,424)
Yi multiply the number by 2^80 yobi (1,208,925,819,614,629,174,706,176)
Xi multiply the number by 2^90 xebi (1,237,940,039,285,380,274,899,124,224)
Wi multiply the number by 2^100 webi (1,267,650,600,228,229,401,496,703,205,376)
Vi multiply the number by 2^110 vebi (1,298,074,214,633,706,907,132,624,082,305,024)
Ui multiply the number by 2^120 uebi (1,329,227,995,784,915,872,903,807,060,280,344,576)
All of the metric and binary suffixes can be expressed in lowercase, uppercase, or mixed case.
All of the metric and binary suffixes can be stacked (expressed multiple times), and also be intermixed:
I.E.: 123k 123K 123GKi 12.3GiGG 12.3e-7T .78E100e
Factorial suffixes to be supported
! compute the (regular) factorial product: 5! is 5 × 4 × 3 × 2 × 1 = 120
!! compute the double factorial product: 8! is 8 × 6 × 4 × 2 = 384
!!! compute the triple factorial product: 8! is 8 × 5 × 2 = 80
!!!! compute the quadruple factorial product: 8! is 8 × 4 = 32
!!!!! compute the quintuple factorial product: 8! is 8 × 3 = 24
··· the number of factorial symbols that can be specified is to be unlimited (as per what can be entered/typed) ···
Factorial suffixes aren't, of course, the usual type of multipliers, but are used here in a similar vein.
Multifactorials aren't to be confused with super─factorials where (4!)! would be (24)!.
Task
Using the test cases (below), show the "expanded" numbers here, on this page.
For each list, show the input on one line, and also show the output on one line.
When showing the input line, keep the spaces (whitespace) and case (capitalizations) as is.
For each result (list) displayed on one line, separate each number with two blanks.
Add commas to the output numbers were appropriate.
Test cases
2greatGRo 24Gros 288Doz 1,728pairs 172.8SCOre
1,567 +1.567k 0.1567e-2m
25.123kK 25.123m 2.5123e-00002G
25.123kiKI 25.123Mi 2.5123e-00002Gi +.25123E-7Ei
-.25123e-34Vikki 2e-77gooGols
9! 9!! 9!!! 9!!!! 9!!!!! 9!!!!!! 9!!!!!!! 9!!!!!!!! 9!!!!!!!!!
where the last number for the factorials has nine factorial symbols (!) after the 9
Related tasks
Multifactorial (which has a clearer and more succinct definition of multifactorials.)
Factorial
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Go | Go | package main
import (
"fmt"
"math"
"math/big"
"strconv"
"strings"
)
type minmult struct {
min int
mult float64
}
var abbrevs = map[string]minmult{
"PAIRs": {4, 2}, "SCOres": {3, 20}, "DOZens": {3, 12},
"GRoss": {2, 144}, "GREATGRoss": {7, 1728}, "GOOGOLs": {6, 1e100},
}
var metric = map[string]float64{
"K": 1e3, "M": 1e6, "G": 1e9, "T": 1e12, "P": 1e15, "E": 1e18,
"Z": 1e21, "Y": 1e24, "X": 1e27, "W": 1e30, "V": 1e33, "U": 1e36,
}
var binary = map[string]float64{
"Ki": b(10), "Mi": b(20), "Gi": b(30), "Ti": b(40), "Pi": b(50), "Ei": b(60),
"Zi": b(70), "Yi": b(80), "Xi": b(90), "Wi": b(100), "Vi": b(110), "Ui": b(120),
}
func b(e float64) float64 {
return math.Pow(2, e)
}
func googol() *big.Float {
g1 := new(big.Float).SetPrec(500)
g1.SetInt64(10000000000)
g := new(big.Float)
g.Set(g1)
for i := 2; i <= 10; i++ {
g.Mul(g, g1)
}
return g
}
func fact(num string, d int) int {
prod := 1
n, _ := strconv.Atoi(num)
for i := n; i > 0; i -= d {
prod *= i
}
return prod
}
func parse(number string) *big.Float {
bf := new(big.Float).SetPrec(500)
t1 := new(big.Float).SetPrec(500)
t2 := new(big.Float).SetPrec(500)
// find index of last digit
var i int
for i = len(number) - 1; i >= 0; i-- {
if '0' <= number[i] && number[i] <= '9' {
break
}
}
num := number[:i+1]
num = strings.Replace(num, ",", "", -1) // get rid of any commas
suf := strings.ToUpper(number[i+1:])
if suf == "" {
bf.SetString(num)
return bf
}
if suf[0] == '!' {
prod := fact(num, len(suf))
bf.SetInt64(int64(prod))
return bf
}
for k, v := range abbrevs {
kk := strings.ToUpper(k)
if strings.HasPrefix(kk, suf) && len(suf) >= v.min {
t1.SetString(num)
if k != "GOOGOLs" {
t2.SetFloat64(v.mult)
} else {
t2 = googol() // for greater accuracy
}
bf.Mul(t1, t2)
return bf
}
}
bf.SetString(num)
for k, v := range metric {
for j := 0; j < len(suf); j++ {
if k == suf[j:j+1] {
if j < len(suf)-1 && suf[j+1] == 'I' {
t1.SetFloat64(binary[k+"i"])
bf.Mul(bf, t1)
j++
} else {
t1.SetFloat64(v)
bf.Mul(bf, t1)
}
}
}
}
return bf
}
func commatize(s string) string {
if len(s) == 0 {
return ""
}
neg := s[0] == '-'
if neg {
s = s[1:]
}
frac := ""
if ix := strings.Index(s, "."); ix >= 0 {
frac = s[ix:]
s = s[:ix]
}
le := len(s)
for i := le - 3; i >= 1; i -= 3 {
s = s[0:i] + "," + s[i:]
}
if !neg {
return s + frac
}
return "-" + s + frac
}
func process(numbers []string) {
fmt.Print("numbers = ")
for _, number := range numbers {
fmt.Printf("%s ", number)
}
fmt.Print("\nresults = ")
for _, number := range numbers {
res := parse(number)
t := res.Text('g', 50)
fmt.Printf("%s ", commatize(t))
}
fmt.Println("\n")
}
func main() {
numbers := []string{"2greatGRo", "24Gros", "288Doz", "1,728pairs", "172.8SCOre"}
process(numbers)
numbers = []string{"1,567", "+1.567k", "0.1567e-2m"}
process(numbers)
numbers = []string{"25.123kK", "25.123m", "2.5123e-00002G"}
process(numbers)
numbers = []string{"25.123kiKI", "25.123Mi", "2.5123e-00002Gi", "+.25123E-7Ei"}
process(numbers)
numbers = []string{"-.25123e-34Vikki", "2e-77gooGols"}
process(numbers)
numbers = []string{"9!", "9!!", "9!!!", "9!!!!", "9!!!!!", "9!!!!!!",
"9!!!!!!!", "9!!!!!!!!", "9!!!!!!!!!"}
process(numbers)
} |
http://rosettacode.org/wiki/Old_Russian_measure_of_length | Old Russian measure of length | Task
Write a program to perform a conversion of the old Russian measures of length to the metric system (and vice versa).
It is an example of a linear transformation of several variables.
The program should accept a single value in a selected unit of measurement, and convert and return it to the other units:
vershoks, arshins, sazhens, versts, meters, centimeters and kilometers.
Also see
Old Russian measure of length
| #D | D | import std.stdio, std.string, std.algorithm, std.conv;
void main(in string[] args) {
auto factor = ["arshin": 0.7112,
"centimeter": 0.01,
"diuym": 0.0254,
"fut": 0.3048,
"kilometer": 1_000.0,
"liniya": 0.00254,
"meter": 1.0,
"milia": 7_467.6,
"piad": 0.1778,
"sazhen": 2.1336,
"tochka": 0.000254,
"vershok": 0.04445,
"versta": 1_066.8];
if (args.length != 3 || !isNumeric(args[1]) || args[2] !in factor)
return writeln("Please provide args Value and Unit.");
immutable magnitude = args[1].to!double;
immutable meters = magnitude * factor[args[2]];
writefln("%s %s to:\n", args[1], args[2]);
foreach (immutable key; factor.keys.schwartzSort!(k => factor[k]))
writefln("%10s: %s", key, meters / factor[key]);
} |
http://rosettacode.org/wiki/OpenGL | OpenGL |
Task
Display a smooth shaded triangle with OpenGL.
Triangle created using C example compiled with GCC 4.1.2 and freeglut3.
| #Euphoria | Euphoria |
include get.e
include dll.e
include machine.e
include msgbox.e
include constants.ew
include GLfunc.ew
include GLconst.ew
without warning
atom hRC, hDC, hWnd, hInstance, ClassName
sequence keys keys = repeat(0,256) -- array to hold key presses
integer active, fullscreen, retval
active = TRUE
fullscreen = TRUE
hRC = NULL
hDC = NULL
hWnd = NULL
hInstance = NULL
atom rtri, rquad
rtri = 0.0
rquad = 0.0
integer dmScreenSettings, WindowRect
procedure ReSizeGLScene(integer width, integer height)
if height = 0 then
height = 1
end if
c_proc(glViewport,{0,0,width,height})
c_proc(glMatrixMode,{GL_PROJECTION})
c_proc(glLoadIdentity,{})
c_proc(gluPerspective,{45.0,width/height,0.1,100.0})
c_proc(glMatrixMode,{GL_MODELVIEW})
c_proc(glLoadIdentity,{})
end procedure
procedure InitGL()
c_proc(glShadeModel,{GL_SMOOTH})
c_proc(glClearColor,{0.0,0.0,0.0,0.0})
c_proc(glClearDepth,{1.0})
c_proc(glEnable,{GL_DEPTH_TEST})
c_proc(glDepthFunc,{GL_LEQUAL})
c_proc(glHint,{GL_PERSPECTIVE_CORRECTION_HINT,GL_NICEST})
end procedure
function DrawGLScene()
c_proc(glClear, {or_bits(GL_COLOR_BUFFER_BIT,GL_DEPTH_BUFFER_BIT)})
c_proc(glLoadIdentity, {})
c_proc(glTranslatef, {-1.5,0.0,-6.0})
c_proc(glRotatef, {rtri,0.0,1.0,0.0})
c_proc(glBegin, {GL_TRIANGLES})
c_proc(glColor3f, {1.0,0.0,0.0})
c_proc(glVertex3f, {0.0,1.0,0.0})
c_proc(glColor3f, {0.0,1.0,0.0})
c_proc(glVertex3f, {-1.0,-1.0,0.0})
c_proc(glColor3f, {0.0,0.0,1.0})
c_proc(glVertex3f, {1.0,-1.0,0.0})
c_proc(glEnd, {})
c_proc(glLoadIdentity, {})
c_proc(glTranslatef, {1.5,0.0,-6.0})
c_proc(glRotatef, {rquad,1.0,0.0,0.0})
c_proc(glColor3f, {0.5,0.5,1.0})
c_proc(glBegin, {GL_QUADS})
c_proc(glVertex3f, {1.0,1.0,0.0})
c_proc(glVertex3f, {-1.0,1.0,0.0})
c_proc(glVertex3f, {-1.0,-1.0,0.0})
c_proc(glVertex3f, {1.0,-1.0,0.0})
c_proc(glEnd, {})
rtri += 0.2
rquad -= 0.15
return TRUE
end function
procedure KillGLWindow()
if fullscreen then
if c_func(ChangeDisplaySettingsA,{NULL,0}) then end if
if c_func(ShowCursor,{TRUE}) then end if
end if
if hRC then
if c_func(wglMakeCurrent,{NULL,NULL}) then end if
if c_func(wglDeleteContext,{hRC}) then end if
hRC = NULL
end if
if hRC and not c_func(ReleaseDC,{hWnd,hDC}) then
hDC = NULL
end if
if hWnd and not c_func(DestroyWindow,{hWnd}) then
hWnd = NULL
end if
if dmScreenSettings then
free(dmScreenSettings)
end if
free(WindowRect)
end procedure
function WndProc(atom hWnd, integer uMsg, atom wParam, atom lParam)
if uMsg = WM_ACTIVATE then
if not floor(wParam/#10000) then
active = TRUE
else
active = FALSE
end if
elsif uMsg = WM_SYSCOMMAND then
if wParam = SC_SCREENSAVE then end if
if wParam = SC_MONITORPOWER then end if
elsif uMsg = WM_CLOSE then
c_proc(PostQuitMessage,{0})
elsif uMsg = WM_KEYDOWN then
keys[wParam] = TRUE
elsif uMsg = WM_KEYUP then
keys[wParam] = FALSE
elsif uMsg = WM_SIZE then
ReSizeGLScene(and_bits(lParam,#FFFF),floor(lParam/#10000))
end if
return c_func(DefWindowProcA,{hWnd, uMsg, wParam, lParam})
end function
integer wc wc = allocate(40)
function ClassRegistration()
integer WndProcAddress, id
id = routine_id("WndProc")
if id = -1 then
puts(1, "routine_id failed!\n")
abort(1)
end if
WndProcAddress = call_back(id)
hInstance = c_func(GetModuleHandleA,{NULL})
ClassName = allocate_string("OpenGL")
poke4(wc,or_all({CS_HREDRAW, CS_VREDRAW, CS_OWNDC}))
poke4(wc+4,WndProcAddress)
poke4(wc+8,0)
poke4(wc+12,0)
poke4(wc+16,hInstance)
poke4(wc+20,c_func(LoadIconA,{NULL,IDI_WINLOGO}))
poke4(wc+24,c_func(LoadCursorA,{NULL, IDC_ARROW}))
poke4(wc+28,NULL)
poke4(wc+32,NULL)
poke4(wc+36,ClassName)
if not c_func(RegisterClassA,{wc}) then
retval = message_box("Failed to register class","Error", or_bits(MB_OK,MB_ICONINFORMATION))
return FALSE
else
return TRUE
end if
end function
integer regd regd = FALSE
procedure CreateGLWindow(atom title, integer width, integer height, integer bits, integer fullscreenflag)
atom PixelFormat, pfd, dwExStyle, dwStyle
sequence s
if regd = FALSE then
if ClassRegistration() then
regd = TRUE
end if
end if
fullscreen = fullscreenflag
if fullscreen then
dmScreenSettings = allocate(156)
mem_set(dmScreenSettings,0,156)
s = int_to_bytes(156)
poke(dmScreenSettings + 36,{s[1],s[2]})
poke4(dmScreenSettings + 40,or_all({DM_BITSPERPEL,DM_PELSWIDTH,DM_PELSHEIGHT}))
poke4(dmScreenSettings + 104, bits)
poke4(dmScreenSettings + 108, width)
poke4(dmScreenSettings + 112, height)
if c_func(ChangeDisplaySettingsA,{dmScreenSettings,CDS_FULLSCREEN}) != DISP_CHANGE_SUCCESSFUL then
if message_box("The requested fullscreen mode is not supported by\nyour video card. " &
"Use windowed mode instead?","Error", or_bits(MB_YESNO,MB_ICONEXCLAMATION)) = IDYES then
else
retval = message_box("Program will now close","Error",or_bits(MB_OK,MB_ICONSTOP))
end if
end if
else
dmScreenSettings = NULL
end if
if fullscreen then
dwExStyle = WS_EX_APPWINDOW
dwStyle = WS_POPUP
if c_func(ShowCursor,{FALSE}) then end if
else
dwExStyle = or_bits(WS_EX_APPWINDOW,WS_EX_WINDOWEDGE)
dwStyle = WS_OVERLAPPEDWINDOW
end if
WindowRect = allocate(16)
poke4(WindowRect,0)
poke4(WindowRect + 4,width)
poke4(WindowRect + 8, 0)
poke4(WindowRect + 12, height)
if c_func(AdjustWindowRectEx,{WindowRect, dwStyle, FALSE, dwExStyle}) then end if
hWnd = c_func(CreateWindowExA,{dwExStyle, --extended window style
ClassName, --class
title, --window caption
or_all({WS_CLIPSIBLINGS,WS_CLIPCHILDREN,dwStyle}), --window style
0,
0,
peek4u(WindowRect + 4) - peek4u(WindowRect),
peek4u(WindowRect + 12) - peek4u(WindowRect + 8),
NULL,
NULL,
hInstance,
NULL})
if hWnd = NULL then
KillGLWindow()
retval = message_box("Window creation error","Error",or_bits(MB_OK,MB_ICONEXCLAMATION))
end if
pfd = allocate(40) --PIXELFORMATDESCRIPTOR
mem_set(pfd,0,40)
poke(pfd, 40) --size of pfd structure
poke(pfd + 2, 1) --version
poke4(pfd + 4, or_all({PFD_DRAW_TO_WINDOW,PFD_SUPPORT_OPENGL,PFD_DOUBLEBUFFER})) --properties flags
poke(pfd + 8, PFD_TYPE_RGBA) --request an rgba format
poke(pfd + 9, 24) --select color depth
poke(pfd + 23, 24) --32bit Z-buffer
hDC = c_func(GetDC,{hWnd}) --create GL device context to match window device context
if not hDC then
KillGLWindow()
retval = message_box("Can't create a GL device context","Error",or_bits(MB_OK,MB_ICONEXCLAMATION))
end if
PixelFormat = c_func(ChoosePixelFormat,{hDC,pfd}) --find a pixel format matching PIXELFORMATDESCRIPTOR
if not PixelFormat then
KillGLWindow()
retval = message_box("Can't find a suitable pixel format","Error",or_bits(MB_OK,MB_ICONEXCLAMATION))
end if
if not (c_func(SetPixelFormat,{hDC,PixelFormat,pfd})) then --set the pixel format
KillGLWindow()
retval = message_box("Can't set the pixel format","Error",or_bits(MB_OK,MB_ICONEXCLAMATION))
end if
if not c_func(DescribePixelFormat, {hDC,PixelFormat,40,pfd}) then
retval = message_box("Can't describe the pixel format","Error",or_bits(MB_OK,MB_ICONEXCLAMATION))
end if
hRC = c_func(wglCreateContext,{hDC}) --create GL rendering context
if not hRC then
KillGLWindow()
retval = message_box("Can't create a GL rendering context","Error",or_bits(MB_OK,MB_ICONEXCLAMATION))
end if
if not (c_func(wglMakeCurrent,{hDC,hRC})) then --make the GL rendering context active
KillGLWindow()
retval = message_box("Can't activate the GL rendering context","Error",or_bits(MB_OK,MB_ICONEXCLAMATION))
end if
retval = c_func(ShowWindow,{hWnd,SW_SHOW}) --show the window
retval = c_func(SetForegroundWindow,{hWnd}) --set it to always be in foreground
retval = c_func(SetFocus,{hWnd}) --give it focus
ReSizeGLScene(width, height) --draw the GL scene to match the window size
InitGL() --initialize OpenGL
end procedure
integer MSG MSG = allocate(28)
integer title title = allocate_string("OpenGL")
procedure WinMain()
integer done, msg_message
done = FALSE
if message_box("Would you like to run in fullscreen mode?","Start Fullscreen?",or_bits(MB_YESNO,MB_ICONQUESTION)) = IDNO then
fullscreen = FALSE
else
fullscreen = TRUE
end if
CreateGLWindow(title,640,480,24,fullscreen)
while not done do
if c_func(PeekMessageA,{MSG,NULL,0,0,PM_REMOVE}) then
msg_message = peek4u(MSG+4)
if msg_message = WM_QUIT then
done = TRUE
else
retval = c_func(TranslateMessage,{MSG})
retval = c_func(DispatchMessageA,{MSG})
end if
else
if ((active and not DrawGLScene()) or keys[VK_ESCAPE]) then
done = TRUE
else
retval = c_func(SwapBuffers,{hDC})
if keys[VK_F1] then
keys[VK_F1] = FALSE
KillGLWindow()
if fullscreen = 0 then
fullscreen = 1
else
fullscreen = 0
end if
CreateGLWindow(title,640,480,24,fullscreen)
end if
end if
end if
end while
KillGLWindow()
end procedure
WinMain()
|
http://rosettacode.org/wiki/One_of_n_lines_in_a_file | One of n lines in a file | A method of choosing a line randomly from a file:
Without reading the file more than once
When substantial parts of the file cannot be held in memory
Without knowing how many lines are in the file
Is to:
keep the first line of the file as a possible choice, then
Read the second line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/2.
Read the third line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/3.
...
Read the Nth line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/N
Return the computed possible choice when no further lines exist in the file.
Task
Create a function/method/routine called one_of_n that given n, the number of actual lines in a file, follows the algorithm above to return an integer - the line number of the line chosen from the file.
The number returned can vary, randomly, in each run.
Use one_of_n in a simulation to find what woud be the chosen line of a 10 line file simulated 1,000,000 times.
Print and show how many times each of the 10 lines is chosen as a rough measure of how well the algorithm works.
Note: You may choose a smaller number of repetitions if necessary, but mention this up-front.
Note: This is a specific version of a Reservoir Sampling algorithm: https://en.wikipedia.org/wiki/Reservoir_sampling
| #C.23 | C# |
class Program
{
private static Random rnd = new Random();
public static int one_of_n(int n)
{
int currentChoice = 1;
for (int i = 2; i <= n; i++)
{
double outerLimit = 1D / (double)i;
if (rnd.NextDouble() < outerLimit)
currentChoice = i;
}
return currentChoice;
}
static void Main(string[] args)
{
Dictionary<int, int> results = new Dictionary<int, int>();
for (int i = 1; i < 11; i++)
results.Add(i, 0);
for (int i = 0; i < 1000000; i++)
{
int result = one_of_n(10);
results[result] = results[result] + 1;
}
for (int i = 1; i < 11; i++)
Console.WriteLine("{0}\t{1}", i, results[i]);
Console.ReadLine();
}
}
|
http://rosettacode.org/wiki/P-value_correction | P-value correction | Given a list of p-values, adjust the p-values for multiple comparisons. This is done in order to control the false positive, or Type 1 error rate.
This is also known as the "false discovery rate" (FDR). After adjustment, the p-values will be higher but still inside [0,1].
The adjusted p-values are sometimes called "q-values".
Task
Given one list of p-values, return the p-values correcting for multiple comparisons
p = {4.533744e-01, 7.296024e-01, 9.936026e-02, 9.079658e-02, 1.801962e-01,
8.752257e-01, 2.922222e-01, 9.115421e-01, 4.355806e-01, 5.324867e-01,
4.926798e-01, 5.802978e-01, 3.485442e-01, 7.883130e-01, 2.729308e-01,
8.502518e-01, 4.268138e-01, 6.442008e-01, 3.030266e-01, 5.001555e-02,
3.194810e-01, 7.892933e-01, 9.991834e-01, 1.745691e-01, 9.037516e-01,
1.198578e-01, 3.966083e-01, 1.403837e-02, 7.328671e-01, 6.793476e-02,
4.040730e-03, 3.033349e-04, 1.125147e-02, 2.375072e-02, 5.818542e-04,
3.075482e-04, 8.251272e-03, 1.356534e-03, 1.360696e-02, 3.764588e-04,
1.801145e-05, 2.504456e-07, 3.310253e-02, 9.427839e-03, 8.791153e-04,
2.177831e-04, 9.693054e-04, 6.610250e-05, 2.900813e-02, 5.735490e-03}
There are several methods to do this, see:
Yoav Benjamini, Yosef Hochberg "Controlling the False Discovery Rate: A Practical and Powerful Approach to Multiple Testing", Journal of the Royal Statistical Society. Series B, Vol. 57, No. 1 (1995), pp. 289-300, JSTOR:2346101
Yoav Benjamini, Daniel Yekutieli, "The control of the false discovery rate in multiple testing under dependency", Ann. Statist., Vol. 29, No. 4 (2001), pp. 1165-1188, DOI:10.1214/aos/1013699998 JSTOR:2674075
Sture Holm, "A Simple Sequentially Rejective Multiple Test Procedure", Scandinavian Journal of Statistics, Vol. 6, No. 2 (1979), pp. 65-70, JSTOR:4615733
Yosef Hochberg, "A sharper Bonferroni procedure for multiple tests of significance", Biometrika, Vol. 75, No. 4 (1988), pp 800–802, DOI:10.1093/biomet/75.4.800 JSTOR:2336325
Gerhard Hommel, "A stagewise rejective multiple test procedure based on a modified Bonferroni test", Biometrika, Vol. 75, No. 2 (1988), pp 383–386, DOI:10.1093/biomet/75.2.383 JSTOR:2336190
Each method has its own advantages and disadvantages.
| #SAS | SAS | data pvalues;
input raw_p @@;
cards;
4.533744e-01 7.296024e-01 9.936026e-02 9.079658e-02 1.801962e-01
8.752257e-01 2.922222e-01 9.115421e-01 4.355806e-01 5.324867e-01
4.926798e-01 5.802978e-01 3.485442e-01 7.883130e-01 2.729308e-01
8.502518e-01 4.268138e-01 6.442008e-01 3.030266e-01 5.001555e-02
3.194810e-01 7.892933e-01 9.991834e-01 1.745691e-01 9.037516e-01
1.198578e-01 3.966083e-01 1.403837e-02 7.328671e-01 6.793476e-02
4.040730e-03 3.033349e-04 1.125147e-02 2.375072e-02 5.818542e-04
3.075482e-04 8.251272e-03 1.356534e-03 1.360696e-02 3.764588e-04
1.801145e-05 2.504456e-07 3.310253e-02 9.427839e-03 8.791153e-04
2.177831e-04 9.693054e-04 6.610250e-05 2.900813e-02 5.735490e-03
;
run;
proc multtest pdata=pvalues bon sid hom hoc holm;
run; |
http://rosettacode.org/wiki/Order_disjoint_list_items | Order disjoint list items |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Given M as a list of items and another list N of items chosen from M, create M' as a list with the first occurrences of items from N sorted to be in one of the set of indices of their original occurrence in M but in the order given by their order in N.
That is, items in N are taken from M without replacement, then the corresponding positions in M' are filled by successive items from N.
For example
if M is 'the cat sat on the mat'
And N is 'mat cat'
Then the result M' is 'the mat sat on the cat'.
The words not in N are left in their original positions.
If there are duplications then only the first instances in M up to as many as are mentioned in N are potentially re-ordered.
For example
M = 'A B C A B C A B C'
N = 'C A C A'
Is ordered as:
M' = 'C B A C B A A B C'
Show the output, here, for at least the following inputs:
Data M: 'the cat sat on the mat' Order N: 'mat cat'
Data M: 'the cat sat on the mat' Order N: 'cat mat'
Data M: 'A B C A B C A B C' Order N: 'C A C A'
Data M: 'A B C A B D A B E' Order N: 'E A D A'
Data M: 'A B' Order N: 'B'
Data M: 'A B' Order N: 'B A'
Data M: 'A B B A' Order N: 'B A'
Cf
Sort disjoint sublist
| #Nim | Nim | import algorithm, strutils
proc orderDisjoint(m, n: string): string =
# Build the list of items.
var m = m.splitWhitespace()
let n = n.splitWhitespace()
# Find the indexes of items to replace.
var indexes: seq[int]
for item in n:
let idx = m.find(item)
if idx >= 0:
indexes.add idx
m[idx] = "" # Set to empty string for next searches.
indexes.sort()
# Do the replacements.
for i, idx in indexes:
m[idx] = n[i]
result = m.join(" ")
when isMainModule:
template process(a, b: string) =
echo a, " | ", b, " → ", orderDisjoint(a, b)
process("the cat sat on the mat", "mat cat")
process("the cat sat on the mat", "cat mat")
process("A B C A B C A B C", "C A C A")
process("A B C A B D A B E", "E A D A")
process("A B", "B")
process("A B", "B A")
process("A B B A", "B A") |
http://rosettacode.org/wiki/Order_disjoint_list_items | Order disjoint list items |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Given M as a list of items and another list N of items chosen from M, create M' as a list with the first occurrences of items from N sorted to be in one of the set of indices of their original occurrence in M but in the order given by their order in N.
That is, items in N are taken from M without replacement, then the corresponding positions in M' are filled by successive items from N.
For example
if M is 'the cat sat on the mat'
And N is 'mat cat'
Then the result M' is 'the mat sat on the cat'.
The words not in N are left in their original positions.
If there are duplications then only the first instances in M up to as many as are mentioned in N are potentially re-ordered.
For example
M = 'A B C A B C A B C'
N = 'C A C A'
Is ordered as:
M' = 'C B A C B A A B C'
Show the output, here, for at least the following inputs:
Data M: 'the cat sat on the mat' Order N: 'mat cat'
Data M: 'the cat sat on the mat' Order N: 'cat mat'
Data M: 'A B C A B C A B C' Order N: 'C A C A'
Data M: 'A B C A B D A B E' Order N: 'E A D A'
Data M: 'A B' Order N: 'B'
Data M: 'A B' Order N: 'B A'
Data M: 'A B B A' Order N: 'B A'
Cf
Sort disjoint sublist
| #Perl | Perl | sub dsort {
my ($m, $n) = @_;
my %h;
$h{$_}++ for @$n;
map $h{$_}-- > 0 ? shift @$n : $_, @$m;
}
for (split "\n", <<"IN")
the cat sat on the mat | mat cat
the cat sat on the mat | cat mat
A B C A B C A B C | C A C A
A B C A B D A B E | E A D A
A B | B
A B | B A
A B B A | B A
IN
{
my ($a, $b) = map([split], split '\|');
print "@$a | @$b -> @{[dsort($a, $b)]}\n";
} |
http://rosettacode.org/wiki/Optional_parameters | Optional parameters | Task
Define a function/method/subroutine which sorts a sequence ("table") of sequences ("rows") of strings ("cells"), by one of the strings. Besides the input to be sorted, it shall have the following optional parameters:
ordering
A function specifying the ordering of strings; lexicographic by default.
column
An integer specifying which string of each row to compare; the first by default.
reverse
Reverses the ordering.
This task should be considered to include both positional and named optional parameters, as well as overloading on argument count as in Java or selector name as in Smalltalk, or, in the extreme, using different function names. Provide these variations of sorting in whatever way is most natural to your language. If the language supports both methods naturally, you are encouraged to describe both.
Do not implement a sorting algorithm; this task is about the interface. If you can't use a built-in sort routine, just omit the implementation (with a comment).
See also:
Named Arguments
| #Haskell | Haskell |
{-# LANGUAGE RecordWildCards #-}
data SorterArgs = SorterArgs { cmp :: String, col :: Int, rev :: Bool } deriving Show
defSortArgs = SorterArgs "lex" 0 False
sorter :: SorterArgs -> [[String]] -> [[String]]
sorter (SorterArgs{..}) = case cmp of
_ -> undefined
main = do
sorter defSortArgs{cmp = "foo", col=1, rev=True} [[]]
sorter defSortArgs{cmp = "foo"} [[]]
sorter defSortArgs [[]]
return ()
|
http://rosettacode.org/wiki/Order_two_numerical_lists | Order two numerical lists | sorting
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Write a function that orders two lists or arrays filled with numbers.
The function should accept two lists as arguments and return true if the first list should be ordered before the second, and false otherwise.
The order is determined by lexicographic order: Comparing the first element of each list.
If the first elements are equal, then the second elements should be compared, and so on, until one of the list has no more elements.
If the first list runs out of elements the result is true.
If the second list or both run out of elements the result is false.
Note: further clarification of lexicographical ordering is expounded on the talk page here and here.
| #Ela | Ela | [] <. _ = true
_ <. [] = false
(x::xs) <. (y::ys) | x == y = xs <. ys
| else = x < y
[1,2,1,3,2] <. [1,2,0,4,4,0,0,0] |
http://rosettacode.org/wiki/Order_two_numerical_lists | Order two numerical lists | sorting
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Write a function that orders two lists or arrays filled with numbers.
The function should accept two lists as arguments and return true if the first list should be ordered before the second, and false otherwise.
The order is determined by lexicographic order: Comparing the first element of each list.
If the first elements are equal, then the second elements should be compared, and so on, until one of the list has no more elements.
If the first list runs out of elements the result is true.
If the second list or both run out of elements the result is false.
Note: further clarification of lexicographical ordering is expounded on the talk page here and here.
| #Elixir | Elixir | iex(1)> [1,2,3] < [1,2,3,4]
true
iex(2)> [1,2,3] < [1,2,4]
true |
http://rosettacode.org/wiki/Pascal%27s_triangle | Pascal's triangle | Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere.
Its first few rows look like this:
1
1 1
1 2 1
1 3 3 1
where each element of each row is either 1 or the sum of the two elements right above it.
For example, the next row of the triangle would be:
1 (since the first element of each row doesn't have two elements above it)
4 (1 + 3)
6 (3 + 3)
4 (3 + 1)
1 (since the last element of each row doesn't have two elements above it)
So the triangle now looks like this:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
Each row n (starting with row 0 at the top) shows the coefficients of the binomial expansion of (x + y)n.
Task
Write a function that prints out the first n rows of the triangle (with f(1) yielding the row consisting of only the element 1).
This can be done either by summing elements from the previous rows or using a binary coefficient or combination function.
Behavior for n ≤ 0 does not need to be uniform, but should be noted.
See also
Evaluate binomial coefficients
| #Vedit_macro_language | Vedit macro language | #100 = Get_Num("Number of rows: ", STATLINE)
#0=0; #1=1
Ins_Char(' ', COUNT, #100*3-2) Num_Ins(1)
for (#99 = 2; #99 <= #100; #99++) {
Ins_Char(' ', COUNT, (#100-#99)*3)
#@99 = 0
for (#98 = #99; #98 > 0; #98--) {
#97 = #98-1
#@98 += #@97
Num_Ins(#@98, COUNT, 6)
}
Ins_Newline
} |
http://rosettacode.org/wiki/Operator_precedence | Operator precedence |
This page uses content from Wikipedia. The original article was at Operators in C and C++. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Provide a list of precedence and associativity of all the operators and constructs that the language utilizes in descending order of precedence such that an operator which is listed on some row will be evaluated prior to any operator that is listed on a row further below it.
Operators that are in the same cell (there may be several rows of operators listed in a cell) are evaluated with the same level of precedence, in the given direction.
State whether arguments are passed by value or by reference.
| #Pascal | Pascal | q)3*2+1
9
q)(3*2)+1 / Brackets give the usual order of precedence
7
q)x:5
q)(x+5; x:20; x-5)
25 20 0 |
http://rosettacode.org/wiki/Operator_precedence | Operator precedence |
This page uses content from Wikipedia. The original article was at Operators in C and C++. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Provide a list of precedence and associativity of all the operators and constructs that the language utilizes in descending order of precedence such that an operator which is listed on some row will be evaluated prior to any operator that is listed on a row further below it.
Operators that are in the same cell (there may be several rows of operators listed in a cell) are evaluated with the same level of precedence, in the given direction.
State whether arguments are passed by value or by reference.
| #Perl | Perl | q)3*2+1
9
q)(3*2)+1 / Brackets give the usual order of precedence
7
q)x:5
q)(x+5; x:20; x-5)
25 20 0 |
http://rosettacode.org/wiki/Operator_precedence | Operator precedence |
This page uses content from Wikipedia. The original article was at Operators in C and C++. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Provide a list of precedence and associativity of all the operators and constructs that the language utilizes in descending order of precedence such that an operator which is listed on some row will be evaluated prior to any operator that is listed on a row further below it.
Operators that are in the same cell (there may be several rows of operators listed in a cell) are evaluated with the same level of precedence, in the given direction.
State whether arguments are passed by value or by reference.
| #Phix | Phix | q)3*2+1
9
q)(3*2)+1 / Brackets give the usual order of precedence
7
q)x:5
q)(x+5; x:20; x-5)
25 20 0 |
http://rosettacode.org/wiki/Ordered_words | Ordered words | An ordered word is a word in which the letters appear in alphabetic order.
Examples include abbey and dirt.
Task[edit]
Find and display all the ordered words in the dictionary unixdict.txt that have the longest word length.
(Examples that access the dictionary file locally assume that you have downloaded this file yourself.)
The display needs to be shown on this page.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Forth | Forth |
include lib/stmstack.4th \ include string stack library
: check-word ( a n -- a n f)
2dup bl >r \ start off with a space
begin
dup \ when not end of word
while
over c@ r@ >= \ check character
while
r> drop over c@ >r chop \ chop character off
repeat r> drop nip 0= \ cleanup and set flag
;
: open-file ( -- h)
1 dup argn = abort" Usage: ordered infile"
args input open error? abort" Cannot open file"
dup use \ return and use the handle
;
: read-file ( --)
0 >r \ begin with zero length
begin
refill \ EOF detected?
while
0 parse dup r@ >= \ equal or longer string length?
if \ check the word and adjust length
check-word if r> drop dup >r >s else 2drop then
else \ if it checks out, put on the stack
2drop \ otherwise drop the word
then
repeat r> drop \ clean it up
;
: read-back ( --)
s> dup >r type cr \ longest string is on top of stack
begin s> dup r@ >= while type cr repeat
2drop r> drop \ keep printing until shorter word
; \ has been found
: ordered ( --)
open-file s.clear read-file read-back close
; \ open file, clear the stack, read file
\ read it back and close the file
ordered |
http://rosettacode.org/wiki/Palindrome_detection | Palindrome detection | A palindrome is a phrase which reads the same backward and forward.
Task[edit]
Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes)
is a palindrome.
For extra credit:
Support Unicode characters.
Write a second function (possibly as a wrapper to the first) which detects inexact palindromes, i.e. phrases that are palindromes if white-space and punctuation is ignored and case-insensitive comparison is used.
Hints
It might be useful for this task to know how to reverse a string.
This task's entries might also form the subjects of the task Test a function.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Oz | Oz | fun {IsPalindrome S}
{Reverse S} == S
end |
http://rosettacode.org/wiki/One-time_pad | One-time pad | Implement a One-time pad, for encrypting and decrypting messages.
To keep it simple, we will be using letters only.
Sub-Tasks
Generate the data for a One-time pad (user needs to specify a filename and length)
The important part is to get "true random" numbers, e.g. from /dev/random
encryption / decryption ( basically the same operation, much like Rot-13 )
For this step, much of Vigenère cipher could be reused,
with the key to be read from the file containing the One-time pad.
optional: management of One-time pads: list, mark as used, delete, etc.
Somehow, the users needs to keep track which pad to use for which partner.
To support the management of pad-files:
Such files have a file-extension ".1tp"
Lines starting with "#" may contain arbitary meta-data (i.e. comments)
Lines starting with "-" count as "used"
Whitespace within the otp-data is ignored
For example, here is the data from Wikipedia:
# Example data - Wikipedia - 2014-11-13
-ZDXWWW EJKAWO FECIFE WSNZIP PXPKIY URMZHI JZTLBC YLGDYJ
-HTSVTV RRYYEG EXNCGA GGQVRF FHZCIB EWLGGR BZXQDQ DGGIAK
YHJYEQ TDLCQT HZBSIZ IRZDYS RBYJFZ AIRCWI UCVXTW YKPQMK
CKHVEX VXYVCS WOGAAZ OUVVON GCNEVR LMBLYB SBDCDC PCGVJX
QXAUIP PXZQIJ JIUWYH COVWMJ UZOJHL DWHPER UBSRUJ HGAAPR
CRWVHI FRNTQW AJVWRT ACAKRD OZKIIB VIQGBK IJCWHF GTTSSE
EXFIPJ KICASQ IOUQTP ZSGXGH YTYCTI BAZSTN JKMFXI RERYWE
See also
one time pad encryption in Python
snapfractalpop - One-Time-Pad Command-Line-Utility (C).
Crypt-OTP-2.00 on CPAN (Perl)
| #Tcl | Tcl | puts "# True random chars for one-time pad"
proc randInt { min max } {
set randDev [open /dev/urandom rb]
set random [read $randDev 8]
binary scan $random H16 random
set random [expr {([scan $random %x] % (($max-$min) + 1) + $min)}]
close $randDev
return $random
}
proc randStr { sLen grp alfa } {
set aLen [string length $alfa]; incr aLen -1
set rs ""
for {set i 0} {$i < $sLen} {incr i} {
if { [expr {$i % $grp} ] == 0} { append rs " " }
set r [randInt 0 $aLen]
set char [string index $alfa $r]
append rs $char
##puts "$i: $r $char"
}
return $rs
}
set alfa "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
set len 48
set lines 4
set fn "test.1tp"
# Write file:
set fh [open $fn w]
puts $fh "# OTP"
for {set ln 0} {$ln < $lines} {incr ln} {
set line [randStr $len 6 $alfa]
##puts "$ln :$line."
puts $fh $line
}
close $fh
# Read file:
puts "# File $fn:"
set fh [open $fn]
puts [read $fh [file size $fn]]
close $fh
puts "# Done." |
http://rosettacode.org/wiki/Odd_word_problem | Odd word problem | Task
Write a program that solves the odd word problem with the restrictions given below.
Description
You are promised an input stream consisting of English letters and punctuations.
It is guaranteed that:
the words (sequence of consecutive letters) are delimited by one and only one punctuation,
the stream will begin with a word,
the words will be at least one letter long, and
a full stop (a period, [.]) appears after, and only after, the last word.
Example
A stream with six words:
what,is,the;meaning,of:life.
The task is to reverse the letters in every other word while leaving punctuations intact, producing:
what,si,the;gninaem,of:efil.
while observing the following restrictions:
Only I/O allowed is reading or writing one character at a time, which means: no reading in a string, no peeking ahead, no pushing characters back into the stream, and no storing characters in a global variable for later use;
You are not to explicitly save characters in a collection data structure, such as arrays, strings, hash tables, etc, for later reversal;
You are allowed to use recursions, closures, continuations, threads, co-routines, etc., even if their use implies the storage of multiple characters.
Test cases
Work on both the "life" example given above, and also the text:
we,are;not,in,kansas;any,more.
| #Ada | Ada | with Ada.Text_IO;
procedure Odd_Word_Problem is
use Ada.Text_IO; -- Get, Put, and Look_Ahead
function Current return Character is
-- reads the current input character, without consuming it
End_Of_Line: Boolean;
C: Character;
begin
Look_Ahead(C, End_Of_Line);
if End_Of_Line then
raise Constraint_Error with "end of line before the terminating '.'";
end if;
return C;
end Current;
procedure Skip is
-- consumes the current input character
C: Character;
begin
Get(C);
end Skip;
function Is_Alpha(Ch: Character) return Boolean is
begin
return (Ch in 'a' .. 'z') or (Ch in 'A' .. 'Z');
end Is_Alpha;
procedure Odd_Word(C: Character) is
begin
if Is_Alpha(C) then
Skip;
Odd_Word(Current);
Put(C);
end if;
end Odd_Word;
begin -- Odd_Word_Problem
Put(Current);
while Is_Alpha(Current) loop -- read an even word
Skip;
Put(Current);
end loop;
if Current /= '.' then -- read an odd word
Skip;
Odd_Word(Current);
Put(Current);
if Current /= '.' then -- read the remaining words
Skip;
Odd_Word_Problem;
end if;
end if;
end Odd_Word_Problem; |
http://rosettacode.org/wiki/One-dimensional_cellular_automata | One-dimensional cellular automata | Assume an array of cells with an initial distribution of live and dead cells,
and imaginary cells off the end of the array having fixed values.
Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the current generation.
If, in the following table, a live cell is represented by 1 and a dead cell by 0 then to generate the value of the cell at a particular index in the array of cellular values you use the following table:
000 -> 0 #
001 -> 0 #
010 -> 0 # Dies without enough neighbours
011 -> 1 # Needs one neighbour to survive
100 -> 0 #
101 -> 1 # Two neighbours giving birth
110 -> 1 # Needs one neighbour to survive
111 -> 0 # Starved to death.
| #ACL2 | ACL2 | (defun rc-step-r (cells)
(if (endp (rest cells))
nil
(cons (if (second cells)
(xor (first cells) (third cells))
(and (first cells) (third cells)))
(rc-step-r (rest cells)))))
(defun rc-step (cells)
(cons (and (first cells) (second cells))
(rc-step-r cells)))
(defun rc-steps-r (cells n prev)
(declare (xargs :measure (nfix n)))
(if (or (zp n) (equal cells prev))
nil
(let ((new (rc-step cells)))
(cons new (rc-steps-r new (1- n) cells)))))
(defun rc-steps (cells n)
(cons cells (rc-steps-r cells n nil)))
(defun pretty-row (row)
(if (endp row)
(cw "~%")
(prog2$ (cw (if (first row) "#" "-"))
(pretty-row (rest row)))))
(defun pretty-output (out)
(if (endp out)
nil
(prog2$ (pretty-row (first out))
(pretty-output (rest out))))) |
http://rosettacode.org/wiki/Object_serialization | Object serialization | Create a set of data types based upon inheritance. Each data type or class should have a print command that displays the contents of an instance of that class to standard output. Create instances of each class in your inheritance hierarchy and display them to standard output. Write each of the objects to a file named objects.dat in binary form using serialization or marshalling. Read the file objects.dat and print the contents of each serialized object.
| #ALGOL_68 | ALGOL 68 | MODE ENTITY = STRUCT([6]CHAR name, INT creation);
FORMAT entity repr = $"Name: "g", Created:"g$;
MODE PERSON = STRUCT(ENTITY entity, STRING email);
FORMAT person repr = $f(entity repr)", Email: "g$;
PERSON instance1 := PERSON(ENTITY("Cletus", 20080808), "test+1@localhost.localdomain");
print((name OF entity OF instance1, new line));
ENTITY instance2 := ENTITY("Entity",20111111);
print((name OF instance2, new line));
FILE target;
INT errno := open(target, "rows.dat", stand back channel); # open file #
# Serialise #
put(target,(instance1, new line, instance2, new line));
printf(($"Serialised..."l$));
close(target); # flush file stream #
errno := open(target, "rows.dat", stand back channel); # load again #
# Unserialise #
PERSON i1;
ENTITY i2;
get(target,(i1, new line, i2, new line));
printf(($"Unserialised..."l$));
printf((person repr, i1, $l$));
printf((entity repr, i2, $l$)) |
http://rosettacode.org/wiki/Old_lady_swallowed_a_fly | Old lady swallowed a fly | Task
Present a program which emits the lyrics to the song I Knew an Old Lady Who Swallowed a Fly, taking advantage of the repetitive structure of the song's lyrics.
This song has multiple versions with slightly different lyrics, so all these programs might not emit identical output.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Ada | Ada | with Ada.Text_IO, Ada.Containers.Indefinite_Doubly_Linked_Lists; use Ada.Text_IO;
procedure Swallow_Fly is
package Strings is new Ada.Containers.Indefinite_Doubly_Linked_Lists(String);
Lines, Animals: Strings.List;
procedure Swallow(Animal: String;
Second_Line: String;
Permanent_Second_Line: Boolean := True) is
procedure Print(C: Strings.Cursor) is
begin
Put_Line(Strings.Element(C));
end Print;
begin
Put_Line("There was an old lady who swallowed a " & Animal & ",");
Put_Line(Second_Line);
if not Animals.Is_Empty then
Lines.Prepend("She swallowed the " & Animal & " to catch the " &
Animals.Last_Element & ",");
end if;
Lines.Iterate(Print'Access);
New_Line;
if Permanent_Second_Line then
Lines.Prepend(Second_Line);
end if;
Animals.Append(Animal); -- you need "to catch the " most recent animal
end Swallow;
procedure Swallow_TSA(Animal: String; Part_Of_Line_2: String) is
begin
Swallow(Animal, Part_Of_Line_2 &", to swallow a " & Animal & ";", False);
end Swallow_TSA;
procedure Swallow_SSA(Animal: String; Part_Of_Line_2: String) is
begin
Swallow(Animal, Part_Of_Line_2 &" she swallowed a " & Animal & ";", False);
end Swallow_SSA;
begin
Lines.Append("Perhaps she'll die!");
Swallow("fly", "But I don't know why she swallowed the fly,");
Swallow("spider", "That wriggled and jiggled and tickled inside her;");
Swallow_TSA("bird", "Quite absurd");
Swallow_TSA("cat", "Fancy that");
Swallow_TSA("dog", "What a hog");
Swallow_TSA("pig", "Her mouth was so big");
Swallow_TSA("goat","She just opened her throat");
Swallow_SSA("cow", "I don't know how");
Swallow_TSA("donkey", "It was rather wonky");
Put_Line("There was an old lady who swallowed a horse ...");
Put_Line("She's dead, of course!");
end Swallow_Fly; |
http://rosettacode.org/wiki/Numerical_and_alphabetical_suffixes | Numerical and alphabetical suffixes | This task is about expressing numbers with an attached (abutted) suffix multiplier(s), the suffix(es) could be:
an alphabetic (named) multiplier which could be abbreviated
metric multiplier(s) which can be specified multiple times
"binary" multiplier(s) which can be specified multiple times
explanation marks (!) which indicate a factorial or multifactorial
The (decimal) numbers can be expressed generally as:
{±} {digits} {.} {digits}
────── or ──────
{±} {digits} {.} {digits} {E or e} {±} {digits}
where:
numbers won't have embedded blanks (contrary to the expaciated examples above where whitespace was used for readability)
this task will only be dealing with decimal numbers, both in the mantissa and exponent
± indicates an optional plus or minus sign (+ or -)
digits are the decimal digits (0 ──► 9)
the digits can have comma(s) interjected to separate the periods (thousands) such as: 12,467,000
. is the decimal point, sometimes also called a dot
e or E denotes the use of decimal exponentiation (a number multiplied by raising ten to some power)
This isn't a pure or perfect definition of the way we express decimal numbers, but it should convey the intent for this task.
The use of the word periods (thousands) is not meant to confuse, that word (as used above) is what the comma separates;
the groups of decimal digits are called periods, and in almost all cases, are groups of three decimal digits.
If an e or E is specified, there must be a legal number expressed before it, and there must be a legal (exponent) expressed after it.
Also, there must be some digits expressed in all cases, not just a sign and/or decimal point.
Superfluous signs, decimal points, exponent numbers, and zeros need not be preserved.
I.E.:
+7 007 7.00 7E-0 7E000 70e-1 could all be expressed as 7
All numbers to be "expanded" can be assumed to be valid and there won't be a requirement to verify their validity.
Abbreviated alphabetic suffixes to be supported (where the capital letters signify the minimum abbreation that can be used)
PAIRs multiply the number by 2 (as in pairs of shoes or pants)
SCOres multiply the number by 20 (as 3score would be 60)
DOZens multiply the number by 12
GRoss multiply the number by 144 (twelve dozen)
GREATGRoss multiply the number by 1,728 (a dozen gross)
GOOGOLs multiply the number by 10^100 (ten raised to the 100&sup>th</sup> power)
Note that the plurals are supported, even though they're usually used when expressing exact numbers (She has 2 dozen eggs, and dozens of quavas)
Metric suffixes to be supported (whether or not they're officially sanctioned)
K multiply the number by 10^3 kilo (1,000)
M multiply the number by 10^6 mega (1,000,000)
G multiply the number by 10^9 giga (1,000,000,000)
T multiply the number by 10^12 tera (1,000,000,000,000)
P multiply the number by 10^15 peta (1,000,000,000,000,000)
E multiply the number by 10^18 exa (1,000,000,000,000,000,000)
Z multiply the number by 10^21 zetta (1,000,000,000,000,000,000,000)
Y multiply the number by 10^24 yotta (1,000,000,000,000,000,000,000,000)
X multiply the number by 10^27 xenta (1,000,000,000,000,000,000,000,000,000)
W multiply the number by 10^30 wekta (1,000,000,000,000,000,000,000,000,000,000)
V multiply the number by 10^33 vendeka (1,000,000,000,000,000,000,000,000,000,000,000)
U multiply the number by 10^36 udekta (1,000,000,000,000,000,000,000,000,000,000,000,000)
Binary suffixes to be supported (whether or not they're officially sanctioned)
Ki multiply the number by 2^10 kibi (1,024)
Mi multiply the number by 2^20 mebi (1,048,576)
Gi multiply the number by 2^30 gibi (1,073,741,824)
Ti multiply the number by 2^40 tebi (1,099,571,627,776)
Pi multiply the number by 2^50 pebi (1,125,899,906,884,629)
Ei multiply the number by 2^60 exbi (1,152,921,504,606,846,976)
Zi multiply the number by 2^70 zeb1 (1,180,591,620,717,411,303,424)
Yi multiply the number by 2^80 yobi (1,208,925,819,614,629,174,706,176)
Xi multiply the number by 2^90 xebi (1,237,940,039,285,380,274,899,124,224)
Wi multiply the number by 2^100 webi (1,267,650,600,228,229,401,496,703,205,376)
Vi multiply the number by 2^110 vebi (1,298,074,214,633,706,907,132,624,082,305,024)
Ui multiply the number by 2^120 uebi (1,329,227,995,784,915,872,903,807,060,280,344,576)
All of the metric and binary suffixes can be expressed in lowercase, uppercase, or mixed case.
All of the metric and binary suffixes can be stacked (expressed multiple times), and also be intermixed:
I.E.: 123k 123K 123GKi 12.3GiGG 12.3e-7T .78E100e
Factorial suffixes to be supported
! compute the (regular) factorial product: 5! is 5 × 4 × 3 × 2 × 1 = 120
!! compute the double factorial product: 8! is 8 × 6 × 4 × 2 = 384
!!! compute the triple factorial product: 8! is 8 × 5 × 2 = 80
!!!! compute the quadruple factorial product: 8! is 8 × 4 = 32
!!!!! compute the quintuple factorial product: 8! is 8 × 3 = 24
··· the number of factorial symbols that can be specified is to be unlimited (as per what can be entered/typed) ···
Factorial suffixes aren't, of course, the usual type of multipliers, but are used here in a similar vein.
Multifactorials aren't to be confused with super─factorials where (4!)! would be (24)!.
Task
Using the test cases (below), show the "expanded" numbers here, on this page.
For each list, show the input on one line, and also show the output on one line.
When showing the input line, keep the spaces (whitespace) and case (capitalizations) as is.
For each result (list) displayed on one line, separate each number with two blanks.
Add commas to the output numbers were appropriate.
Test cases
2greatGRo 24Gros 288Doz 1,728pairs 172.8SCOre
1,567 +1.567k 0.1567e-2m
25.123kK 25.123m 2.5123e-00002G
25.123kiKI 25.123Mi 2.5123e-00002Gi +.25123E-7Ei
-.25123e-34Vikki 2e-77gooGols
9! 9!! 9!!! 9!!!! 9!!!!! 9!!!!!! 9!!!!!!! 9!!!!!!!! 9!!!!!!!!!
where the last number for the factorials has nine factorial symbols (!) after the 9
Related tasks
Multifactorial (which has a clearer and more succinct definition of multifactorials.)
Factorial
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Julia | Julia | using Formatting
partialsuffixes = Dict("PAIR" => "PAIRS", "SCO" => "SCORES", "DOZ" => "DOZENS",
"GR" => "GROSS", "GREATGR" => "GREATGROSS", "GOOGOL" => "GOOGOLS")
partials = sort(collect(keys(partialsuffixes)), lt=(a,b)->length(a)<length(b), rev=true)
multicharsuffixes = Dict("PAIRS" => 2, "SCORES" => 20, "DOZENS" => 12, "GROSS" => 144,
"GREATGROSS" => 1728, "GOOGOLS" => BigInt(10)^100)
twocharsuffixes = Dict(
"KI" => BigInt(2)^10, "MI" => BigInt(2)^20, "GI" => BigInt(2)^30, "TI" => BigInt(2)^40,
"PI" => BigInt(2)^50, "EI" => BigInt(2)^60, "ZI" => BigInt(2)^70, "YI" => BigInt(2)^80,
"XI" => BigInt(2)^90, "WI" => BigInt(2)^100, "VI" => BigInt(2)^110, "UI" => BigInt(2)^120)
twosuff = collect(keys(twocharsuffixes))
onecharsuffixes = Dict("K" => 10^3, "M" => 10^6, "G" => 10^9, "T" => 10^12, "P" => 10^15,
"E" => 10^18, "Z" => 10^21, "Y" => BigInt(10)^24,
"X" => BigInt(10)^27, "W" => BigInt(10)^30,
"V" => BigInt(10)^33, "U" => BigInt(10)^36)
onesuff = collect(keys(onecharsuffixes))
function firstsuffix(s, x)
str = uppercase(s)
if str[1] == '!'
lastbang = something(findfirst(x -> x != '!', str), length(str))
return prod(x:-lastbang:1) / x, lastbang
end
for pstr in partials
if match(Regex("^" * pstr), str) != nothing
fullsuffix = partialsuffixes[pstr]
n = length(pstr)
while n < length(fullsuffix) && n < length(str) && fullsuffix[n+1] == str[n+1]
n += 1
end
return BigInt(multicharsuffixes[fullsuffix]), n
end
end
for pstr in twosuff
if match(Regex("^" * pstr), str) != nothing
return BigInt(twocharsuffixes[pstr]), 2
end
end
for pstr in onesuff
if match(Regex("^" * pstr), str) != nothing
return BigInt(onecharsuffixes[pstr]), 1
end
end
return 1, length(s)
end
function parsesuffix(s, x)
str = s
mult = BigInt(1)
n = 1
while n <= length(str)
multiplier, n = firstsuffix(str, x)
mult *= multiplier
str = str[n+1:end]
end
mult
end
function suffixednumber(s)
if (endnum = findlast(isdigit, s)) == nothing
return NaN
end
x = BigFloat(replace(s[1:endnum], "," => ""))
return x * (endnum < length(s) ? parsesuffix(s[endnum + 1:end], x) : 1)
end
const testcases =
["2greatGRo 24Gros 288Doz 1,728pairs 172.8SCOre",
"1,567 +1.567k 0.1567e-2m",
"25.123kK 25.123m 2.5123e-00002G",
"25.123kiKI 25.123Mi 2.5123e-00002Gi +.25123E-7Ei",
"-.25123e-34Vikki 2e-77gooGols",
"9! 9!! 9!!! 9!!!! 9!!!!! 9!!!!!! 9!!!!!!! 9!!!!!!!! 9!!!!!!!!!"]
function testsuffixes()
for line in testcases
cases = split(line)
println("Testing: ", string.(cases))
println("Results: ", join(map(x -> format(suffixednumber(x), commas=true), cases), " "), "\n")
end
end
testsuffixes()
|
http://rosettacode.org/wiki/Numerical_and_alphabetical_suffixes | Numerical and alphabetical suffixes | This task is about expressing numbers with an attached (abutted) suffix multiplier(s), the suffix(es) could be:
an alphabetic (named) multiplier which could be abbreviated
metric multiplier(s) which can be specified multiple times
"binary" multiplier(s) which can be specified multiple times
explanation marks (!) which indicate a factorial or multifactorial
The (decimal) numbers can be expressed generally as:
{±} {digits} {.} {digits}
────── or ──────
{±} {digits} {.} {digits} {E or e} {±} {digits}
where:
numbers won't have embedded blanks (contrary to the expaciated examples above where whitespace was used for readability)
this task will only be dealing with decimal numbers, both in the mantissa and exponent
± indicates an optional plus or minus sign (+ or -)
digits are the decimal digits (0 ──► 9)
the digits can have comma(s) interjected to separate the periods (thousands) such as: 12,467,000
. is the decimal point, sometimes also called a dot
e or E denotes the use of decimal exponentiation (a number multiplied by raising ten to some power)
This isn't a pure or perfect definition of the way we express decimal numbers, but it should convey the intent for this task.
The use of the word periods (thousands) is not meant to confuse, that word (as used above) is what the comma separates;
the groups of decimal digits are called periods, and in almost all cases, are groups of three decimal digits.
If an e or E is specified, there must be a legal number expressed before it, and there must be a legal (exponent) expressed after it.
Also, there must be some digits expressed in all cases, not just a sign and/or decimal point.
Superfluous signs, decimal points, exponent numbers, and zeros need not be preserved.
I.E.:
+7 007 7.00 7E-0 7E000 70e-1 could all be expressed as 7
All numbers to be "expanded" can be assumed to be valid and there won't be a requirement to verify their validity.
Abbreviated alphabetic suffixes to be supported (where the capital letters signify the minimum abbreation that can be used)
PAIRs multiply the number by 2 (as in pairs of shoes or pants)
SCOres multiply the number by 20 (as 3score would be 60)
DOZens multiply the number by 12
GRoss multiply the number by 144 (twelve dozen)
GREATGRoss multiply the number by 1,728 (a dozen gross)
GOOGOLs multiply the number by 10^100 (ten raised to the 100&sup>th</sup> power)
Note that the plurals are supported, even though they're usually used when expressing exact numbers (She has 2 dozen eggs, and dozens of quavas)
Metric suffixes to be supported (whether or not they're officially sanctioned)
K multiply the number by 10^3 kilo (1,000)
M multiply the number by 10^6 mega (1,000,000)
G multiply the number by 10^9 giga (1,000,000,000)
T multiply the number by 10^12 tera (1,000,000,000,000)
P multiply the number by 10^15 peta (1,000,000,000,000,000)
E multiply the number by 10^18 exa (1,000,000,000,000,000,000)
Z multiply the number by 10^21 zetta (1,000,000,000,000,000,000,000)
Y multiply the number by 10^24 yotta (1,000,000,000,000,000,000,000,000)
X multiply the number by 10^27 xenta (1,000,000,000,000,000,000,000,000,000)
W multiply the number by 10^30 wekta (1,000,000,000,000,000,000,000,000,000,000)
V multiply the number by 10^33 vendeka (1,000,000,000,000,000,000,000,000,000,000,000)
U multiply the number by 10^36 udekta (1,000,000,000,000,000,000,000,000,000,000,000,000)
Binary suffixes to be supported (whether or not they're officially sanctioned)
Ki multiply the number by 2^10 kibi (1,024)
Mi multiply the number by 2^20 mebi (1,048,576)
Gi multiply the number by 2^30 gibi (1,073,741,824)
Ti multiply the number by 2^40 tebi (1,099,571,627,776)
Pi multiply the number by 2^50 pebi (1,125,899,906,884,629)
Ei multiply the number by 2^60 exbi (1,152,921,504,606,846,976)
Zi multiply the number by 2^70 zeb1 (1,180,591,620,717,411,303,424)
Yi multiply the number by 2^80 yobi (1,208,925,819,614,629,174,706,176)
Xi multiply the number by 2^90 xebi (1,237,940,039,285,380,274,899,124,224)
Wi multiply the number by 2^100 webi (1,267,650,600,228,229,401,496,703,205,376)
Vi multiply the number by 2^110 vebi (1,298,074,214,633,706,907,132,624,082,305,024)
Ui multiply the number by 2^120 uebi (1,329,227,995,784,915,872,903,807,060,280,344,576)
All of the metric and binary suffixes can be expressed in lowercase, uppercase, or mixed case.
All of the metric and binary suffixes can be stacked (expressed multiple times), and also be intermixed:
I.E.: 123k 123K 123GKi 12.3GiGG 12.3e-7T .78E100e
Factorial suffixes to be supported
! compute the (regular) factorial product: 5! is 5 × 4 × 3 × 2 × 1 = 120
!! compute the double factorial product: 8! is 8 × 6 × 4 × 2 = 384
!!! compute the triple factorial product: 8! is 8 × 5 × 2 = 80
!!!! compute the quadruple factorial product: 8! is 8 × 4 = 32
!!!!! compute the quintuple factorial product: 8! is 8 × 3 = 24
··· the number of factorial symbols that can be specified is to be unlimited (as per what can be entered/typed) ···
Factorial suffixes aren't, of course, the usual type of multipliers, but are used here in a similar vein.
Multifactorials aren't to be confused with super─factorials where (4!)! would be (24)!.
Task
Using the test cases (below), show the "expanded" numbers here, on this page.
For each list, show the input on one line, and also show the output on one line.
When showing the input line, keep the spaces (whitespace) and case (capitalizations) as is.
For each result (list) displayed on one line, separate each number with two blanks.
Add commas to the output numbers were appropriate.
Test cases
2greatGRo 24Gros 288Doz 1,728pairs 172.8SCOre
1,567 +1.567k 0.1567e-2m
25.123kK 25.123m 2.5123e-00002G
25.123kiKI 25.123Mi 2.5123e-00002Gi +.25123E-7Ei
-.25123e-34Vikki 2e-77gooGols
9! 9!! 9!!! 9!!!! 9!!!!! 9!!!!!! 9!!!!!!! 9!!!!!!!! 9!!!!!!!!!
where the last number for the factorials has nine factorial symbols (!) after the 9
Related tasks
Multifactorial (which has a clearer and more succinct definition of multifactorials.)
Factorial
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Nim | Nim | import re, strutils, parseutils, tables, math
const input = """
2greatGRo 24Gros 288Doz 1,728pairs 172.8SCOre
1,567 +1.567k 0.1567e-2m
25.123kK 25.123m 2.5123e-00002G
25.123kiKI 25.123Mi 2.5123e-00002Gi +.25123E-7Ei
-.25123e-34Vikki 2e-77gooGols
9! 9!! 9!!! 9!!!! 9!!!!! 9!!!!!! 9!!!!!!! 9!!!!!!!! 9!!!!!!!!!
"""
let
abbrAlpha = re(r"(PAIR)(s)?$|(SCO)(r|re|res)?$|(DOZ)(e|en|ens)?$|(GR)(o|os|oss)?$|(GREATGR)(o|os|oss)?$|(GOOGOL)(s)?$",
flags = {reIgnoreCase})
metricBinary = re(r"[KMGTPEZYXWVU]i?", flags = {reIgnoreCase})
factorial = re"!+$"
const
alphaValues = [2e0, 20e0, 12e0, 144e0, 1728e0, 1e100]
metricBinaryValueTab = {"K": 10.0^3, "KI": 2.0^10, "M": 10.0^6, "MI": 2.0^20,
"G": 10.0^9, "GI": 2.0^30, "T": 10.0^12, "TI": 2.0^40, "P": 10.0^15,
"PI": 2.0^50, "E": 10.0^18, "EI": 2.0^60, "Z": 10.0^21, "ZI": 2.0^70,
"Y": 10.0^24, "YI": 2.0^80, "X": 10.0^27, "XI": 2.0^90, "W": 10.0^30,
"WI": 2.0^100, "V": 10.0^33, "VI": 2.0^110, "U": 10.0^36,
"UI": 2.0^120}.toTable
var
matches: array[12, string]
res, fac: float
suffix: string
proc sepFloat(f: float): string =
var
s = $f
i, num: int
num = parseInt(s, i)
if num == 0:
return s
else:
return insertSep($i, ',', 3)&s[num..^1]
for line in input.splitLines():
if not isEmptyOrWhiteSpace(line):
echo("Input:\n", line, "\nOutput:")
var output = " "
for raw_number in line.replace(",", "").splitWhiteSpace():
suffix = raw_number[parseutils.parseFloat(raw_number, res)..^1].toUpper()
if suffix.match(abbrAlpha, matches):
for i, v in matches.mpairs():
if i mod 2 == 0 and not v.isEmptyOrWhiteSpace():
res*=alphaValues[i div 2]
v = ""
break
elif suffix.match(factorial):
fac = abs(res)-toFloat(len(suffix))
while fac > 0:
res*=fac
fac-=toFloat(len(suffix))
elif suffix.match(metricBinary):
for m in suffix.findAll(metricBinary):
res*=metricBinaryValueTab[m]
output &= sepFloat(res)&" "
echo(output)
|
http://rosettacode.org/wiki/Numerical_and_alphabetical_suffixes | Numerical and alphabetical suffixes | This task is about expressing numbers with an attached (abutted) suffix multiplier(s), the suffix(es) could be:
an alphabetic (named) multiplier which could be abbreviated
metric multiplier(s) which can be specified multiple times
"binary" multiplier(s) which can be specified multiple times
explanation marks (!) which indicate a factorial or multifactorial
The (decimal) numbers can be expressed generally as:
{±} {digits} {.} {digits}
────── or ──────
{±} {digits} {.} {digits} {E or e} {±} {digits}
where:
numbers won't have embedded blanks (contrary to the expaciated examples above where whitespace was used for readability)
this task will only be dealing with decimal numbers, both in the mantissa and exponent
± indicates an optional plus or minus sign (+ or -)
digits are the decimal digits (0 ──► 9)
the digits can have comma(s) interjected to separate the periods (thousands) such as: 12,467,000
. is the decimal point, sometimes also called a dot
e or E denotes the use of decimal exponentiation (a number multiplied by raising ten to some power)
This isn't a pure or perfect definition of the way we express decimal numbers, but it should convey the intent for this task.
The use of the word periods (thousands) is not meant to confuse, that word (as used above) is what the comma separates;
the groups of decimal digits are called periods, and in almost all cases, are groups of three decimal digits.
If an e or E is specified, there must be a legal number expressed before it, and there must be a legal (exponent) expressed after it.
Also, there must be some digits expressed in all cases, not just a sign and/or decimal point.
Superfluous signs, decimal points, exponent numbers, and zeros need not be preserved.
I.E.:
+7 007 7.00 7E-0 7E000 70e-1 could all be expressed as 7
All numbers to be "expanded" can be assumed to be valid and there won't be a requirement to verify their validity.
Abbreviated alphabetic suffixes to be supported (where the capital letters signify the minimum abbreation that can be used)
PAIRs multiply the number by 2 (as in pairs of shoes or pants)
SCOres multiply the number by 20 (as 3score would be 60)
DOZens multiply the number by 12
GRoss multiply the number by 144 (twelve dozen)
GREATGRoss multiply the number by 1,728 (a dozen gross)
GOOGOLs multiply the number by 10^100 (ten raised to the 100&sup>th</sup> power)
Note that the plurals are supported, even though they're usually used when expressing exact numbers (She has 2 dozen eggs, and dozens of quavas)
Metric suffixes to be supported (whether or not they're officially sanctioned)
K multiply the number by 10^3 kilo (1,000)
M multiply the number by 10^6 mega (1,000,000)
G multiply the number by 10^9 giga (1,000,000,000)
T multiply the number by 10^12 tera (1,000,000,000,000)
P multiply the number by 10^15 peta (1,000,000,000,000,000)
E multiply the number by 10^18 exa (1,000,000,000,000,000,000)
Z multiply the number by 10^21 zetta (1,000,000,000,000,000,000,000)
Y multiply the number by 10^24 yotta (1,000,000,000,000,000,000,000,000)
X multiply the number by 10^27 xenta (1,000,000,000,000,000,000,000,000,000)
W multiply the number by 10^30 wekta (1,000,000,000,000,000,000,000,000,000,000)
V multiply the number by 10^33 vendeka (1,000,000,000,000,000,000,000,000,000,000,000)
U multiply the number by 10^36 udekta (1,000,000,000,000,000,000,000,000,000,000,000,000)
Binary suffixes to be supported (whether or not they're officially sanctioned)
Ki multiply the number by 2^10 kibi (1,024)
Mi multiply the number by 2^20 mebi (1,048,576)
Gi multiply the number by 2^30 gibi (1,073,741,824)
Ti multiply the number by 2^40 tebi (1,099,571,627,776)
Pi multiply the number by 2^50 pebi (1,125,899,906,884,629)
Ei multiply the number by 2^60 exbi (1,152,921,504,606,846,976)
Zi multiply the number by 2^70 zeb1 (1,180,591,620,717,411,303,424)
Yi multiply the number by 2^80 yobi (1,208,925,819,614,629,174,706,176)
Xi multiply the number by 2^90 xebi (1,237,940,039,285,380,274,899,124,224)
Wi multiply the number by 2^100 webi (1,267,650,600,228,229,401,496,703,205,376)
Vi multiply the number by 2^110 vebi (1,298,074,214,633,706,907,132,624,082,305,024)
Ui multiply the number by 2^120 uebi (1,329,227,995,784,915,872,903,807,060,280,344,576)
All of the metric and binary suffixes can be expressed in lowercase, uppercase, or mixed case.
All of the metric and binary suffixes can be stacked (expressed multiple times), and also be intermixed:
I.E.: 123k 123K 123GKi 12.3GiGG 12.3e-7T .78E100e
Factorial suffixes to be supported
! compute the (regular) factorial product: 5! is 5 × 4 × 3 × 2 × 1 = 120
!! compute the double factorial product: 8! is 8 × 6 × 4 × 2 = 384
!!! compute the triple factorial product: 8! is 8 × 5 × 2 = 80
!!!! compute the quadruple factorial product: 8! is 8 × 4 = 32
!!!!! compute the quintuple factorial product: 8! is 8 × 3 = 24
··· the number of factorial symbols that can be specified is to be unlimited (as per what can be entered/typed) ···
Factorial suffixes aren't, of course, the usual type of multipliers, but are used here in a similar vein.
Multifactorials aren't to be confused with super─factorials where (4!)! would be (24)!.
Task
Using the test cases (below), show the "expanded" numbers here, on this page.
For each list, show the input on one line, and also show the output on one line.
When showing the input line, keep the spaces (whitespace) and case (capitalizations) as is.
For each result (list) displayed on one line, separate each number with two blanks.
Add commas to the output numbers were appropriate.
Test cases
2greatGRo 24Gros 288Doz 1,728pairs 172.8SCOre
1,567 +1.567k 0.1567e-2m
25.123kK 25.123m 2.5123e-00002G
25.123kiKI 25.123Mi 2.5123e-00002Gi +.25123E-7Ei
-.25123e-34Vikki 2e-77gooGols
9! 9!! 9!!! 9!!!! 9!!!!! 9!!!!!! 9!!!!!!! 9!!!!!!!! 9!!!!!!!!!
where the last number for the factorials has nine factorial symbols (!) after the 9
Related tasks
Multifactorial (which has a clearer and more succinct definition of multifactorials.)
Factorial
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Perl | Perl | #!/usr/bin/perl
use strict; # https://rosettacode.org/wiki/Numerical_and_alphabetical_suffixes
use warnings;
my %suffix = qw( k 1e3 m 1e6 g 1e9 t 1e12 p 1e15 e 1e18 z 1e21 y 1e24 x 1e27
w 1e30 v 1e33 u 1e36 ki 2**10 mi 2**20 gi 2**30 ti 2**40 pi 2**50 ei 2**60
zi 2**70 yi 2**80 xi 2**90 wi 2**100 vi 2**110 ui 2**120 );
local $" = ' '; # strange rule...
print "numbers = ${_}results = @{[ map suffix($_), split ]}\n\n" while <DATA>;
sub suffix
{
my ($value, $mods) = shift =~ tr/,//dr =~ /([+-]?[\d.]+(?:e[+-]\d+)?)(.*)/i;
$value *= $^R while $mods =~ /
PAIRs? (?{ 2 })
| SCO(re?)? (?{ 20 })
| DOZ(e(ns?)?)? (?{ 12 })
| GREATGR(o(ss?)?)? (?{ 1728 }) # must be before GRoss
| GR(o(ss?)?)? (?{ 144 })
| GOOGOLs? (?{ 10**100 })
| [kmgtpezyxwvu]i? (?{ eval $suffix{ lc $& } })
| !+ (?{ my $factor = $value;
$value *= $factor while ($factor -= length $&) > 1;
1 })
/gix;
return $value =~ s/(\..*)|\B(?=(\d\d\d)+(?!\d))/$1 || ','/ger;
}
__DATA__
2greatGRo 24Gros 288Doz 1,728pairs 172.8SCOre
1,567 +1.567k 0.1567e-2m
25.123kK 25.123m 2.5123e-00002G
25.123kiKI 25.123Mi 2.5123e-00002Gi +.25123E-7Ei
-.25123e-34Vikki 2e-77gooGols
9! 9!! 9!!! 9!!!! 9!!!!! 9!!!!!! 9!!!!!!! 9!!!!!!!! 9!!!!!!!!! |
http://rosettacode.org/wiki/Old_Russian_measure_of_length | Old Russian measure of length | Task
Write a program to perform a conversion of the old Russian measures of length to the metric system (and vice versa).
It is an example of a linear transformation of several variables.
The program should accept a single value in a selected unit of measurement, and convert and return it to the other units:
vershoks, arshins, sazhens, versts, meters, centimeters and kilometers.
Also see
Old Russian measure of length
| #Delphi | Delphi |
program Old_Russian_measure_of_length;
{$APPTYPE CONSOLE}
uses
System.SysUtils;
const
units: array[0..12] of string = ('tochka', 'liniya', 'dyuim', 'vershok',
'piad', 'fut', 'arshin', 'sazhen', 'versta', 'milia', 'centimeter', 'meter',
'kilometer');
convs: array[0..12] of double = (0.0254, 0.254, 2.54, 4.445, 17.78, 30.48,
71.12, 213.36, 10668, 74676, 1, 100, 10000);
function ReadInt(): integer;
var
data: string;
begin
Readln(data);
Result := StrToIntDef(data, -1);
end;
function ReadFloat(): Double;
var
data: string;
begin
Readln(data);
Result := StrToFloatDef(data, -1);
end;
var
yn, u: string;
i, unt: integer;
value: Double;
begin
repeat
for i := 0 to High(units) do
begin
u := units[i];
Writeln(format('%2d %s', [i + 1, u]));
end;
Writeln;
unt := 0;
repeat
Writeln('Please choose a unit 1 to 13 : ');
unt := ReadInt();
until (unt >= 1) and (unt <= 13);
dec(unt);
repeat
Writeln('Now enter a value in that unit : ');
value := ReadFloat();
until value >= 0;
Writeln(#10'The equivalent in the remaining units is:'#10);
for i := 0 to High(units) do
begin
u := units[i];
if i = unt then
Continue;
Writeln(format(' %10s : %g', [u, value * convs[unt] / convs[i]]));
end;
Writeln;
yn := '';
Writeln('Do another one y/n : ');
readln(yn);
until yn.toLower = 'n';
end. |
http://rosettacode.org/wiki/OpenGL | OpenGL |
Task
Display a smooth shaded triangle with OpenGL.
Triangle created using C example compiled with GCC 4.1.2 and freeglut3.
| #Factor | Factor | USING: kernel math math.rectangles opengl.gl sequences ui
ui.gadgets ui.render ;
IN: rosettacode.opengl
TUPLE: triangle-gadget < gadget ;
: reshape ( width height -- )
[ 0 0 ] 2dip glViewport
GL_PROJECTION glMatrixMode
glLoadIdentity
-30.0 30.0 -30.0 30.0 -30.0 30.0 glOrtho
GL_MODELVIEW glMatrixMode ;
: paint ( -- )
0.3 0.3 0.3 0.0 glClearColor
GL_COLOR_BUFFER_BIT GL_DEPTH_BUFFER_BIT bitor glClear
GL_SMOOTH glShadeModel
glLoadIdentity
-15.0 -15.0 0.0 glTranslatef
GL_TRIANGLES glBegin
1.0 0.0 0.0 glColor3f 0.0 0.0 glVertex2f
0.0 1.0 0.0 glColor3f 30.0 0.0 glVertex2f
0.0 0.0 1.0 glColor3f 0.0 30.0 glVertex2f
glEnd
glFlush ;
M: triangle-gadget pref-dim* drop { 640 480 } ;
M: triangle-gadget draw-gadget*
rect-bounds nip first2 reshape paint ;
: triangle-window ( -- )
[ triangle-gadget new "Triangle" open-window ] with-ui ;
MAIN: triangle-window
|
http://rosettacode.org/wiki/OpenGL | OpenGL |
Task
Display a smooth shaded triangle with OpenGL.
Triangle created using C example compiled with GCC 4.1.2 and freeglut3.
| #Forth | Forth | import glconst import float
glconst also float also opengl also |
http://rosettacode.org/wiki/One_of_n_lines_in_a_file | One of n lines in a file | A method of choosing a line randomly from a file:
Without reading the file more than once
When substantial parts of the file cannot be held in memory
Without knowing how many lines are in the file
Is to:
keep the first line of the file as a possible choice, then
Read the second line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/2.
Read the third line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/3.
...
Read the Nth line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/N
Return the computed possible choice when no further lines exist in the file.
Task
Create a function/method/routine called one_of_n that given n, the number of actual lines in a file, follows the algorithm above to return an integer - the line number of the line chosen from the file.
The number returned can vary, randomly, in each run.
Use one_of_n in a simulation to find what woud be the chosen line of a 10 line file simulated 1,000,000 times.
Print and show how many times each of the 10 lines is chosen as a rough measure of how well the algorithm works.
Note: You may choose a smaller number of repetitions if necessary, but mention this up-front.
Note: This is a specific version of a Reservoir Sampling algorithm: https://en.wikipedia.org/wiki/Reservoir_sampling
| #C.2B.2B | C++ | #include <random>
#include <iostream>
#include <iterator>
#include <algorithm>
using namespace std;
mt19937 engine; //mersenne twister
unsigned int one_of_n(unsigned int n) {
unsigned int choice;
for(unsigned int i = 0; i < n; ++i) {
uniform_int_distribution<unsigned int> distribution(0, i);
if(!distribution(engine))
choice = i;
}
return choice;
}
int main() {
engine = mt19937(random_device()()); //seed random generator from system
unsigned int results[10] = {0};
for(unsigned int i = 0; i < 1000000; ++i)
results[one_of_n(10)]++;
ostream_iterator<unsigned int> out_it(cout, " ");
copy(results, results+10, out_it);
cout << '\n';
}
|
http://rosettacode.org/wiki/P-value_correction | P-value correction | Given a list of p-values, adjust the p-values for multiple comparisons. This is done in order to control the false positive, or Type 1 error rate.
This is also known as the "false discovery rate" (FDR). After adjustment, the p-values will be higher but still inside [0,1].
The adjusted p-values are sometimes called "q-values".
Task
Given one list of p-values, return the p-values correcting for multiple comparisons
p = {4.533744e-01, 7.296024e-01, 9.936026e-02, 9.079658e-02, 1.801962e-01,
8.752257e-01, 2.922222e-01, 9.115421e-01, 4.355806e-01, 5.324867e-01,
4.926798e-01, 5.802978e-01, 3.485442e-01, 7.883130e-01, 2.729308e-01,
8.502518e-01, 4.268138e-01, 6.442008e-01, 3.030266e-01, 5.001555e-02,
3.194810e-01, 7.892933e-01, 9.991834e-01, 1.745691e-01, 9.037516e-01,
1.198578e-01, 3.966083e-01, 1.403837e-02, 7.328671e-01, 6.793476e-02,
4.040730e-03, 3.033349e-04, 1.125147e-02, 2.375072e-02, 5.818542e-04,
3.075482e-04, 8.251272e-03, 1.356534e-03, 1.360696e-02, 3.764588e-04,
1.801145e-05, 2.504456e-07, 3.310253e-02, 9.427839e-03, 8.791153e-04,
2.177831e-04, 9.693054e-04, 6.610250e-05, 2.900813e-02, 5.735490e-03}
There are several methods to do this, see:
Yoav Benjamini, Yosef Hochberg "Controlling the False Discovery Rate: A Practical and Powerful Approach to Multiple Testing", Journal of the Royal Statistical Society. Series B, Vol. 57, No. 1 (1995), pp. 289-300, JSTOR:2346101
Yoav Benjamini, Daniel Yekutieli, "The control of the false discovery rate in multiple testing under dependency", Ann. Statist., Vol. 29, No. 4 (2001), pp. 1165-1188, DOI:10.1214/aos/1013699998 JSTOR:2674075
Sture Holm, "A Simple Sequentially Rejective Multiple Test Procedure", Scandinavian Journal of Statistics, Vol. 6, No. 2 (1979), pp. 65-70, JSTOR:4615733
Yosef Hochberg, "A sharper Bonferroni procedure for multiple tests of significance", Biometrika, Vol. 75, No. 4 (1988), pp 800–802, DOI:10.1093/biomet/75.4.800 JSTOR:2336325
Gerhard Hommel, "A stagewise rejective multiple test procedure based on a modified Bonferroni test", Biometrika, Vol. 75, No. 2 (1988), pp 383–386, DOI:10.1093/biomet/75.2.383 JSTOR:2336190
Each method has its own advantages and disadvantages.
| #Stata | Stata | ssc install qqvalue |
http://rosettacode.org/wiki/Order_disjoint_list_items | Order disjoint list items |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Given M as a list of items and another list N of items chosen from M, create M' as a list with the first occurrences of items from N sorted to be in one of the set of indices of their original occurrence in M but in the order given by their order in N.
That is, items in N are taken from M without replacement, then the corresponding positions in M' are filled by successive items from N.
For example
if M is 'the cat sat on the mat'
And N is 'mat cat'
Then the result M' is 'the mat sat on the cat'.
The words not in N are left in their original positions.
If there are duplications then only the first instances in M up to as many as are mentioned in N are potentially re-ordered.
For example
M = 'A B C A B C A B C'
N = 'C A C A'
Is ordered as:
M' = 'C B A C B A A B C'
Show the output, here, for at least the following inputs:
Data M: 'the cat sat on the mat' Order N: 'mat cat'
Data M: 'the cat sat on the mat' Order N: 'cat mat'
Data M: 'A B C A B C A B C' Order N: 'C A C A'
Data M: 'A B C A B D A B E' Order N: 'E A D A'
Data M: 'A B' Order N: 'B'
Data M: 'A B' Order N: 'B A'
Data M: 'A B B A' Order N: 'B A'
Cf
Sort disjoint sublist
| #Phix | Phix | with javascript_semantics
function order_disjoint(sequence m, sequence n)
integer rlen = length(n)
sequence rdis = repeat(0,rlen)
for i=1 to rlen do
object e = n[i]
integer j = find(e,m)
while j!=0 and find(j,rdis) do
j = find(e,m,j+1)
end while
rdis[i] = j
end for
rdis = sort(rdis)
while rlen and rdis[1]=0 do
rdis = rdis[2..$]
rlen -= 1
end while
for i=1 to rlen do
m[rdis[i]]=n[i]
end for
return join(m)
end function
sequence tests = {{"the cat sat on the mat","mat cat"},
{"the cat sat on the mat","cat mat"},
{"A B C A B C A B C","C A C A"},
{"A B C A B D A B E","E A D A"},
{"A B","B"},
{"A B","B A"},
{"A B B A","B A"},
{"",""},
{"A","A"},
{"A B",""},
{"A B B A","A B"},
{"A B A B","A B"},
{"A B A B","B A B A"},
{"A B C C B A","A C A C"},
{"A B C C B A","C A C A"},
{"A X","Y A"},
{"A X","Y A X"},
{"A X","Y X A"}}
for i=1 to length(tests) do
string {m,n} = tests[i]
printf(1,"\"%s\",\"%s\" => \"%s\"\n",{m,n,order_disjoint(split(m),split(n))})
end for
|
http://rosettacode.org/wiki/Optional_parameters | Optional parameters | Task
Define a function/method/subroutine which sorts a sequence ("table") of sequences ("rows") of strings ("cells"), by one of the strings. Besides the input to be sorted, it shall have the following optional parameters:
ordering
A function specifying the ordering of strings; lexicographic by default.
column
An integer specifying which string of each row to compare; the first by default.
reverse
Reverses the ordering.
This task should be considered to include both positional and named optional parameters, as well as overloading on argument count as in Java or selector name as in Smalltalk, or, in the extreme, using different function names. Provide these variations of sorting in whatever way is most natural to your language. If the language supports both methods naturally, you are encouraged to describe both.
Do not implement a sorting algorithm; this task is about the interface. If you can't use a built-in sort routine, just omit the implementation (with a comment).
See also:
Named Arguments
| #Icon_and_Unicon | Icon and Unicon |
procedure main()
X := [ [1,2,3], [2,3,1], [3,1,2]) # A list of lists
Sort(X) # vanilla sort
Sort(X,"ordering","numeric","column",2,"reverse") # using optional parameters
end
procedure Sort(X,A[]) # A[] provides for a variable number of arguments
while a := get(A) do {
case a of {
"ordering" : op := case get(A) | runerr(205,a) of {
"lexicographic"|"string": "<<"
"numeric": "<"
default: runerr(205,op)
}
"column" : col := 0 < integer(col := get(A)) | runerr(205,col)
"reverse" : reverseorder := reverse
default: runerr(205,a)
}
return (\reverseorder|1)(bubblesortf(X,\c|1,\op|"<<")) # reverse or return the sorted list
end |
http://rosettacode.org/wiki/Order_two_numerical_lists | Order two numerical lists | sorting
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Write a function that orders two lists or arrays filled with numbers.
The function should accept two lists as arguments and return true if the first list should be ordered before the second, and false otherwise.
The order is determined by lexicographic order: Comparing the first element of each list.
If the first elements are equal, then the second elements should be compared, and so on, until one of the list has no more elements.
If the first list runs out of elements the result is true.
If the second list or both run out of elements the result is false.
Note: further clarification of lexicographical ordering is expounded on the talk page here and here.
| #Erlang | Erlang |
5> [1,2,3] < [1,2,3,4].
true
6> [1,2,3] < [1,2,4].
true
|
http://rosettacode.org/wiki/Pascal%27s_triangle | Pascal's triangle | Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere.
Its first few rows look like this:
1
1 1
1 2 1
1 3 3 1
where each element of each row is either 1 or the sum of the two elements right above it.
For example, the next row of the triangle would be:
1 (since the first element of each row doesn't have two elements above it)
4 (1 + 3)
6 (3 + 3)
4 (3 + 1)
1 (since the last element of each row doesn't have two elements above it)
So the triangle now looks like this:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
Each row n (starting with row 0 at the top) shows the coefficients of the binomial expansion of (x + y)n.
Task
Write a function that prints out the first n rows of the triangle (with f(1) yielding the row consisting of only the element 1).
This can be done either by summing elements from the previous rows or using a binary coefficient or combination function.
Behavior for n ≤ 0 does not need to be uniform, but should be noted.
See also
Evaluate binomial coefficients
| #Visual_Basic | Visual Basic | Sub pascaltriangle()
'Pascal's triangle
Const m = 11
Dim t(40) As Integer, u(40) As Integer
Dim i As Integer, n As Integer, s As String, ss As String
ss = ""
For n = 1 To m
u(1) = 1
s = ""
For i = 1 To n
u(i + 1) = t(i) + t(i + 1)
s = s & u(i) & " "
t(i) = u(i)
Next i
ss = ss & s & vbCrLf
Next n
MsgBox ss, , "Pascal's triangle"
End Sub 'pascaltriangle |
http://rosettacode.org/wiki/Operator_precedence | Operator precedence |
This page uses content from Wikipedia. The original article was at Operators in C and C++. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Provide a list of precedence and associativity of all the operators and constructs that the language utilizes in descending order of precedence such that an operator which is listed on some row will be evaluated prior to any operator that is listed on a row further below it.
Operators that are in the same cell (there may be several rows of operators listed in a cell) are evaluated with the same level of precedence, in the given direction.
State whether arguments are passed by value or by reference.
| #PHP | PHP | q)3*2+1
9
q)(3*2)+1 / Brackets give the usual order of precedence
7
q)x:5
q)(x+5; x:20; x-5)
25 20 0 |
http://rosettacode.org/wiki/Operator_precedence | Operator precedence |
This page uses content from Wikipedia. The original article was at Operators in C and C++. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Provide a list of precedence and associativity of all the operators and constructs that the language utilizes in descending order of precedence such that an operator which is listed on some row will be evaluated prior to any operator that is listed on a row further below it.
Operators that are in the same cell (there may be several rows of operators listed in a cell) are evaluated with the same level of precedence, in the given direction.
State whether arguments are passed by value or by reference.
| #PicoLisp | PicoLisp | q)3*2+1
9
q)(3*2)+1 / Brackets give the usual order of precedence
7
q)x:5
q)(x+5; x:20; x-5)
25 20 0 |
http://rosettacode.org/wiki/Ordered_words | Ordered words | An ordered word is a word in which the letters appear in alphabetic order.
Examples include abbey and dirt.
Task[edit]
Find and display all the ordered words in the dictionary unixdict.txt that have the longest word length.
(Examples that access the dictionary file locally assume that you have downloaded this file yourself.)
The display needs to be shown on this page.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Fortran | Fortran |
!***************************************************************************************
module ordered_module
!***************************************************************************************
implicit none
!the dictionary file:
integer,parameter :: file_unit = 1000
character(len=*),parameter :: filename = 'unixdict.txt'
!maximum number of characters in a word:
integer,parameter :: max_chars = 50
type word
character(len=max_chars) :: str !the word from the dictionary
integer :: n = 0 !length of this word
logical :: ordered = .false. !if it is an ordered word
end type word
!the dictionary structure:
type(word),dimension(:),allocatable :: dict
contains
!***************************************************************************************
!******************************************************************************
function count_lines_in_file(fid) result(n_lines)
!******************************************************************************
implicit none
integer :: n_lines
integer,intent(in) :: fid
character(len=1) :: tmp
integer :: i
integer :: ios
!the file is assumed to be open already.
rewind(fid) !rewind to beginning of the file
n_lines = 0
do !read each line until the end of the file.
read(fid,'(A1)',iostat=ios) tmp
if (ios < 0) exit !End of file
n_lines = n_lines + 1 !row counter
end do
rewind(fid) !rewind to beginning of the file
!******************************************************************************
end function count_lines_in_file
!******************************************************************************
!******************************************************************************
pure elemental function ordered_word(word) result(yn)
!******************************************************************************
! turns true if word is an ordered word, false if it is not.
!******************************************************************************
implicit none
character(len=*),intent(in) :: word
logical :: yn
integer :: i
yn = .true.
do i=1,len_trim(word)-1
if (ichar(word(i+1:i+1))<ichar(word(i:i))) then
yn = .false.
exit
end if
end do
!******************************************************************************
end function ordered_word
!******************************************************************************
!***************************************************************************************
end module ordered_module
!***************************************************************************************
!****************************************************
program main
!****************************************************
use ordered_module
implicit none
integer :: i,n,n_max
!open the dictionary and read in all the words:
open(unit=file_unit,file=filename) !open the file
n = count_lines_in_file(file_unit) !count lines in the file
allocate(dict(n)) !allocate dictionary structure
do i=1,n !
read(file_unit,'(A)') dict(i)%str !each line is a word in the dictionary
dict(i)%n = len_trim(dict(i)%str) !save word length
end do
close(file_unit) !close the file
!use elemental procedure to get ordered words:
dict%ordered = ordered_word(dict%str)
!max length of an ordered word:
n_max = maxval(dict%n, mask=dict%ordered)
!write the output:
do i=1,n
if (dict(i)%ordered .and. dict(i)%n==n_max) write(*,'(A,A)',advance='NO') trim(dict(i)%str),' '
end do
write(*,*) ''
!****************************************************
end program main
!****************************************************
|
http://rosettacode.org/wiki/Palindrome_detection | Palindrome detection | A palindrome is a phrase which reads the same backward and forward.
Task[edit]
Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes)
is a palindrome.
For extra credit:
Support Unicode characters.
Write a second function (possibly as a wrapper to the first) which detects inexact palindromes, i.e. phrases that are palindromes if white-space and punctuation is ignored and case-insensitive comparison is used.
Hints
It might be useful for this task to know how to reverse a string.
This task's entries might also form the subjects of the task Test a function.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #PARI.2FGP | PARI/GP | ispal(s)={
s=Vec(s);
for(i=1,#v\2,
if(v[i]!=v[#v-i+1],return(0))
);
1
}; |
http://rosettacode.org/wiki/One-time_pad | One-time pad | Implement a One-time pad, for encrypting and decrypting messages.
To keep it simple, we will be using letters only.
Sub-Tasks
Generate the data for a One-time pad (user needs to specify a filename and length)
The important part is to get "true random" numbers, e.g. from /dev/random
encryption / decryption ( basically the same operation, much like Rot-13 )
For this step, much of Vigenère cipher could be reused,
with the key to be read from the file containing the One-time pad.
optional: management of One-time pads: list, mark as used, delete, etc.
Somehow, the users needs to keep track which pad to use for which partner.
To support the management of pad-files:
Such files have a file-extension ".1tp"
Lines starting with "#" may contain arbitary meta-data (i.e. comments)
Lines starting with "-" count as "used"
Whitespace within the otp-data is ignored
For example, here is the data from Wikipedia:
# Example data - Wikipedia - 2014-11-13
-ZDXWWW EJKAWO FECIFE WSNZIP PXPKIY URMZHI JZTLBC YLGDYJ
-HTSVTV RRYYEG EXNCGA GGQVRF FHZCIB EWLGGR BZXQDQ DGGIAK
YHJYEQ TDLCQT HZBSIZ IRZDYS RBYJFZ AIRCWI UCVXTW YKPQMK
CKHVEX VXYVCS WOGAAZ OUVVON GCNEVR LMBLYB SBDCDC PCGVJX
QXAUIP PXZQIJ JIUWYH COVWMJ UZOJHL DWHPER UBSRUJ HGAAPR
CRWVHI FRNTQW AJVWRT ACAKRD OZKIIB VIQGBK IJCWHF GTTSSE
EXFIPJ KICASQ IOUQTP ZSGXGH YTYCTI BAZSTN JKMFXI RERYWE
See also
one time pad encryption in Python
snapfractalpop - One-Time-Pad Command-Line-Utility (C).
Crypt-OTP-2.00 on CPAN (Perl)
| #Wren | Wren | import "io" for File, Directory
import "/srandom" for SRandom
import "/ioutil" for FileUtil, Input
import "/dynamic" for Enum
import "/str" for Char, Str
var CHARS_PER_LINE = 48
var CHUNK_SIZE = 6
var COLS = 8
var DEMO = true // would normally be set to false
var FileType = Enum.create("FileType", ["OTP", "ENC", "DEC"])
var toAlpha = Fn.new { |s| s.where { |c| Char.isAsciiUpper(c) }.join() }
var isOtpRelated = Fn.new { |s|
return s.endsWith(".1tp") || s.endsWith(".1tp_cpy") ||
s.endsWith(".1tp_enc") || s.endsWith(".1tp_dec")
}
var inChunks = Fn.new { |s, nLines, ft|
var chunks = Str.chunks(s, CHUNK_SIZE)
var sb = ""
for (i in 0...nLines) {
var j = i * COLS
var ch = chunks[j...j+COLS].join(" ")
sb = sb + " " + ch + "\n"
}
sb = " file\n" + sb
return (ft == FileType.OTP) ? "# OTP" + sb :
(ft == FileType.ENC) ? "# Encrypted" + sb :
(ft == FileType.DEC) ? "# Decrypted" + sb : ""
}
var makePad = Fn.new { |nLines|
var nChars = nLines * CHARS_PER_LINE
var sb = ""
/* generate random upper case letters */
for (i in 0...nChars) sb = sb + String.fromByte(SRandom.int(65, 91))
return inChunks.call(sb, nLines, FileType.OTP)
}
var vigenere = Fn.new { |text, key, encrypt|
var sb = ""
var i = 0
for (c in text) {
var ci = encrypt ? (c.bytes[0] + key[i].bytes[0] - 130) % 26 :
(c.bytes[0] - key[i].bytes[0] + 26) % 26
sb = sb + String.fromByte(ci + 65)
i = i + 1
}
var temp = sb.count % CHARS_PER_LINE
if (temp > 0) { // pad with random characters so each line is a full one
for (i in temp...CHARS_PER_LINE) sb = sb + String.fromByte(SRandom.int(65, 91))
}
var ft = encrypt ? FileType.ENC : FileType.DEC
return inChunks.call(sb, (sb.count / CHARS_PER_LINE).floor, ft)
}
var menu = Fn.new {
System.print("""
1. Create one time pad file.
2. Delete one time pad file.
3. List one time pad files.
4. Encrypt plain text.
5. Decrypt cipher text.
6. Quit program.
""")
return Input.integer("Your choice (1 to 6) : ", 1, 6)
}
while (true) {
var choice = menu.call()
System.print()
if (choice == 1) { // Create OTP
System.print("Note that encrypted lines always contain 48 characters.\n")
var fileName = Input.text("OTP file name to create (without extension) : ", 1) + ".1tp"
var nLines = Input.integer("Number of lines in OTP (max 1000) : ", 1, 1000)
var key = makePad.call(nLines)
File.create(fileName) { |f| f.writeBytes(key) }
System.print("\n'%(fileName)' has been created in the current directory.")
if (DEMO) {
// a copy of the OTP file would normally be on a different machine
var fileName2 = fileName + "_cpy" // copy for decryption
File.create(fileName2) { |f| f.writeBytes(key) }
System.print("'%(fileName2)' has been created in the current directory.")
System.print("\nThe contents of these files are :\n")
System.print(key)
}
} else if (choice == 2) { // Delete OTP
System.print("Note that this will also delete ALL associated files.\n")
var toDelete1 = Input.text("OTP file name to delete (without extension) : ", 1) + ".1tp"
var toDelete2 = toDelete1 + "_cpy"
var toDelete3 = toDelete1 + "_enc"
var toDelete4 = toDelete1 + "_dec"
var allToDelete = [toDelete1, toDelete2, toDelete3, toDelete4]
var deleted = 0
System.print()
for (name in allToDelete) {
if (File.exists(name)) {
File.delete(name)
deleted = deleted + 1
System.print("'%(name)' has been deleted from the current directory.")
}
}
if (deleted == 0) System.print("There are no files to delete.")
} else if (choice == 3) { // List OTPs
System.print("The OTP (and related) files in the current directory are:\n")
var otpFiles = Directory.list("./").where { |f| File.exists(f) && isOtpRelated.call(f) }.toList
System.print(otpFiles.join("\n")) // already sorted
} else if (choice == 4) { // Encrypt
var keyFile = Input.text("OTP file name to use (without extension) : ", 1) + ".1tp"
if (File.exists(keyFile)) {
var lines = FileUtil.readLines(keyFile)
var first = lines.count
for (i in 0...lines.count) {
if (lines[i].startsWith(" ")) {
first = i
break
}
}
if (first == lines.count) {
System.print("\nThat file has no unused lines.")
continue
}
var lines2 = lines.skip(first).toList // get rid of comments and used lines
var text = toAlpha.call(Str.upper(Input.text("Text to encrypt :-\n\n", 1)))
var len = text.count
var nLines = (len / CHARS_PER_LINE).floor
if (len % CHARS_PER_LINE > 0) nLines = nLines + 1
if (lines2.count >= nLines) {
var key = toAlpha.call(lines2.take(nLines).join(""))
var encrypted = vigenere.call(text, key, true)
var encFile = keyFile + "_enc"
File.create(encFile) { |f| f.writeBytes(encrypted) }
System.print("\n'%(encFile)' has been created in the current directory.")
for (i in first...first + nLines) {
lines[i] = "-" + lines[i][1..-1]
}
File.create(keyFile) { |f| f.writeBytes(lines.join("\n")) }
if (DEMO) {
System.print("\nThe contents of the encrypted file are :\n")
System.print(encrypted)
}
} else System.print("Not enough lines left in that file to do encryption")
} else System.print("\nhat file does not exist.")
} else if (choice == 5) { // Decrypt
var keyFile = Input.text("OTP file name to use (without extension) : ", 1) + ".1tp_cpy"
if (File.exists(keyFile)) {
var keyLines = FileUtil.readLines(keyFile)
var first = keyLines.count
for (i in 0...keyLines.count) {
if (keyLines[i].startsWith(" ")) {
first = i
break
}
}
if (first == keyLines.count) {
System.print("\nThat file has no unused lines.")
continue
}
var keyLines2 = keyLines[first..-1] // get rid of comments and used lines
var encFile = keyFile[0..-4] + "enc"
if (File.exists(encFile)) {
var encLines = FileUtil.readLines(encFile)[1..-1] // exclude comment line
var nLines = encLines.count
if (keyLines2.count >= nLines) {
var encrypted = toAlpha.call(encLines.join(""))
var key = toAlpha.call(keyLines2.take(nLines).join(""))
var decrypted = vigenere.call(encrypted, key, false)
var decFile = keyFile[0..-4] + "dec"
File.create(decFile) { |f| f.writeBytes(decrypted) }
System.print("\n'%(decFile)' has been created in the current directory.")
for (i in first...first + nLines) {
keyLines[i] = "-" + keyLines[i][1..-1]
}
File.create(keyFile) { |f| f.writeBytes(keyLines.join("\n")) }
if (DEMO) {
System.print("\nThe contents of the decrypted file are :\n")
System.print(decrypted)
}
} else System.print("Not enough lines left in that file to do decryption")
} else System.print("\n'%(encFile)' is missing.")
} else System.print("\nThat file does not exist.")
} else {
return // Quit
}
} |
http://rosettacode.org/wiki/Odd_word_problem | Odd word problem | Task
Write a program that solves the odd word problem with the restrictions given below.
Description
You are promised an input stream consisting of English letters and punctuations.
It is guaranteed that:
the words (sequence of consecutive letters) are delimited by one and only one punctuation,
the stream will begin with a word,
the words will be at least one letter long, and
a full stop (a period, [.]) appears after, and only after, the last word.
Example
A stream with six words:
what,is,the;meaning,of:life.
The task is to reverse the letters in every other word while leaving punctuations intact, producing:
what,si,the;gninaem,of:efil.
while observing the following restrictions:
Only I/O allowed is reading or writing one character at a time, which means: no reading in a string, no peeking ahead, no pushing characters back into the stream, and no storing characters in a global variable for later use;
You are not to explicitly save characters in a collection data structure, such as arrays, strings, hash tables, etc, for later reversal;
You are allowed to use recursions, closures, continuations, threads, co-routines, etc., even if their use implies the storage of multiple characters.
Test cases
Work on both the "life" example given above, and also the text:
we,are;not,in,kansas;any,more.
| #ALGOL_68 | ALGOL 68 | # recursively reverses the current word in the input and returns the #
# the character that followed it #
# "ch" should contain the first letter of the word on entry and will be #
# updated to the punctuation following the word on exit #
PROC reverse word = ( REF CHAR ch )VOID:
BEGIN
CHAR next ch;
read( ( next ch ) );
IF ( next ch <= "Z" AND next ch >= "A" )
OR ( next ch <= "z" AND next ch >= "a" )
THEN
reverse word( next ch )
FI;
print( ( ch ) );
ch := next ch
END; # reverse word #
# recursively prints the current word in the input and returns the #
# character that followed it #
# "ch" should contain the first letter of the word on entry and will be #
# updated to the punctuation following the word on exit #
PROC normal word = ( REF CHAR ch )VOID:
BEGIN
print( ( ch ) );
read ( ( ch ) );
IF ( ch <= "Z" AND ch >= "A" )
OR ( ch <= "z" AND ch >= "a" )
THEN
normal word( ch )
FI
END; # normal word #
# read and print words and punctuation from the input stream, reversing #
# every second word #
PROC reverse every other word = VOID:
BEGIN
CHAR ch;
read( ( ch ) );
WHILE
ch /= "."
DO
normal word( ch );
IF ch /= "."
THEN
print( ( ch ) );
read ( ( ch ) );
reverse word( ch )
FI
OD;
print( ( ch ) )
END; # reverse every other word #
main: (
reverse every other word
) |
http://rosettacode.org/wiki/One-dimensional_cellular_automata | One-dimensional cellular automata | Assume an array of cells with an initial distribution of live and dead cells,
and imaginary cells off the end of the array having fixed values.
Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the current generation.
If, in the following table, a live cell is represented by 1 and a dead cell by 0 then to generate the value of the cell at a particular index in the array of cellular values you use the following table:
000 -> 0 #
001 -> 0 #
010 -> 0 # Dies without enough neighbours
011 -> 1 # Needs one neighbour to survive
100 -> 0 #
101 -> 1 # Two neighbours giving birth
110 -> 1 # Needs one neighbour to survive
111 -> 0 # Starved to death.
| #Action.21 | Action! | CHAR FUNC CalcCell(CHAR prev,curr,next)
IF prev='. AND curr='# AND next='# THEN
RETURN ('#)
ELSEIF prev='# AND curr='. AND next='# THEN
RETURN ('#)
ELSEIF prev='# AND curr='# AND next='. THEN
RETURN ('#)
FI
RETURN ('.)
PROC NextGeneration(CHAR ARRAY s)
BYTE i
CHAR prev,curr,next
IF s(0)<4 THEN RETURN FI
prev=s(1) curr=s(2) next=s(3)
i=2
DO
s(i)=CalcCell(prev,curr,next)
i==+1
IF i=s(0) THEN EXIT FI
prev=curr curr=next next=s(i+1)
OD
RETURN
PROC Main()
DEFINE MAXGEN="9"
CHAR ARRAY s=".###.##.#.#.#.#..#.."
BYTE i
FOR i=0 TO MAXGEN
DO
PrintF("Generation %I: %S%E",i,s)
IF i<MAXGEN THEN
NextGeneration(s)
FI
OD
RETURN |
http://rosettacode.org/wiki/Numerical_integration/Gauss-Legendre_Quadrature | Numerical integration/Gauss-Legendre Quadrature |
In a general Gaussian quadrature rule, an definite integral of
f
(
x
)
{\displaystyle f(x)}
is first approximated over the interval
[
−
1
,
1
]
{\displaystyle [-1,1]}
by a polynomial approximable function
g
(
x
)
{\displaystyle g(x)}
and a known weighting function
W
(
x
)
{\displaystyle W(x)}
.
∫
−
1
1
f
(
x
)
d
x
=
∫
−
1
1
W
(
x
)
g
(
x
)
d
x
{\displaystyle \int _{-1}^{1}f(x)\,dx=\int _{-1}^{1}W(x)g(x)\,dx}
Those are then approximated by a sum of function values at specified points
x
i
{\displaystyle x_{i}}
multiplied by some weights
w
i
{\displaystyle w_{i}}
:
∫
−
1
1
W
(
x
)
g
(
x
)
d
x
≈
∑
i
=
1
n
w
i
g
(
x
i
)
{\displaystyle \int _{-1}^{1}W(x)g(x)\,dx\approx \sum _{i=1}^{n}w_{i}g(x_{i})}
In the case of Gauss-Legendre quadrature, the weighting function
W
(
x
)
=
1
{\displaystyle W(x)=1}
, so we can approximate an integral of
f
(
x
)
{\displaystyle f(x)}
with:
∫
−
1
1
f
(
x
)
d
x
≈
∑
i
=
1
n
w
i
f
(
x
i
)
{\displaystyle \int _{-1}^{1}f(x)\,dx\approx \sum _{i=1}^{n}w_{i}f(x_{i})}
For this, we first need to calculate the nodes and the weights, but after we have them, we can reuse them for numerious integral evaluations, which greatly speeds up the calculation compared to more simple numerical integration methods.
The
n
{\displaystyle n}
evaluation points
x
i
{\displaystyle x_{i}}
for a n-point rule, also called "nodes", are roots of n-th order Legendre Polynomials
P
n
(
x
)
{\displaystyle P_{n}(x)}
. Legendre polynomials are defined by the following recursive rule:
P
0
(
x
)
=
1
{\displaystyle P_{0}(x)=1}
P
1
(
x
)
=
x
{\displaystyle P_{1}(x)=x}
n
P
n
(
x
)
=
(
2
n
−
1
)
x
P
n
−
1
(
x
)
−
(
n
−
1
)
P
n
−
2
(
x
)
{\displaystyle nP_{n}(x)=(2n-1)xP_{n-1}(x)-(n-1)P_{n-2}(x)}
There is also a recursive equation for their derivative:
P
n
′
(
x
)
=
n
x
2
−
1
(
x
P
n
(
x
)
−
P
n
−
1
(
x
)
)
{\displaystyle P_{n}'(x)={\frac {n}{x^{2}-1}}\left(xP_{n}(x)-P_{n-1}(x)\right)}
The roots of those polynomials are in general not analytically solvable, so they have to be approximated numerically, for example by Newton-Raphson iteration:
x
n
+
1
=
x
n
−
f
(
x
n
)
f
′
(
x
n
)
{\displaystyle x_{n+1}=x_{n}-{\frac {f(x_{n})}{f'(x_{n})}}}
The first guess
x
0
{\displaystyle x_{0}}
for the
i
{\displaystyle i}
-th root of a
n
{\displaystyle n}
-order polynomial
P
n
{\displaystyle P_{n}}
can be given by
x
0
=
cos
(
π
i
−
1
4
n
+
1
2
)
{\displaystyle x_{0}=\cos \left(\pi \,{\frac {i-{\frac {1}{4}}}{n+{\frac {1}{2}}}}\right)}
After we get the nodes
x
i
{\displaystyle x_{i}}
, we compute the appropriate weights by:
w
i
=
2
(
1
−
x
i
2
)
[
P
n
′
(
x
i
)
]
2
{\displaystyle w_{i}={\frac {2}{\left(1-x_{i}^{2}\right)[P'_{n}(x_{i})]^{2}}}}
After we have the nodes and the weights for a n-point quadrature rule, we can approximate an integral over any interval
[
a
,
b
]
{\displaystyle [a,b]}
by
∫
a
b
f
(
x
)
d
x
≈
b
−
a
2
∑
i
=
1
n
w
i
f
(
b
−
a
2
x
i
+
a
+
b
2
)
{\displaystyle \int _{a}^{b}f(x)\,dx\approx {\frac {b-a}{2}}\sum _{i=1}^{n}w_{i}f\left({\frac {b-a}{2}}x_{i}+{\frac {a+b}{2}}\right)}
Task description
Similar to the task Numerical Integration, the task here is to calculate the definite integral of a function
f
(
x
)
{\displaystyle f(x)}
, but by applying an n-point Gauss-Legendre quadrature rule, as described here, for example. The input values should be an function f to integrate, the bounds of the integration interval a and b, and the number of gaussian evaluation points n. An reference implementation in Common Lisp is provided for comparison.
To demonstrate the calculation, compute the weights and nodes for an 5-point quadrature rule and then use them to compute:
∫
−
3
3
exp
(
x
)
d
x
≈
∑
i
=
1
5
w
i
exp
(
x
i
)
≈
20.036
{\displaystyle \int _{-3}^{3}\exp(x)\,dx\approx \sum _{i=1}^{5}w_{i}\;\exp(x_{i})\approx 20.036}
| #11l | 11l | F legendreIn(x, n)
F prev1(idx, pn1)
R (2 * idx - 1) * @x * pn1
F prev2(idx, pn2)
R (idx - 1) * pn2
I n == 0
R 1.0
E I n == 1
R x
E
V result = 0.0
V p1 = x
V p2 = 1.0
L(i) 2 .. n
result = (prev1(i, p1) - prev2(i, p2)) / i
p2 = p1
p1 = result
R result
F deriveLegendreIn(x, n)
F calcresult(curr, prev)
R Float(@n) / (@x ^ 2 - 1) * (@x * curr - prev)
R calcresult(legendreIn(x, n), legendreIn(x, n - 1))
F guess(n, i)
R cos(math:pi * (i - 0.25) / (n + 0.5))
F nodes(n)
V result = [(0.0, 0.0)] * n
F calc(x)
R legendreIn(x, @n) / deriveLegendreIn(x, @n)
L(i) 0 .< n
V x = guess(n, i + 1)
V x0 = x
x -= calc(x)
L abs(x - x0) > 1e-12
x0 = x
x -= calc(x)
result[i] = (x, 2 / ((1.0 - x ^ 2) * (deriveLegendreIn(x, n)) ^ 2))
R result
F integ(f, ns, p1, p2)
F dist()
R (@p2 - @p1) / 2
F avg()
R (@p1 + @p2) / 2
V result = dist()
V sum = 0.0
V thenodes = [0.0] * ns
V weights = [0.0] * ns
L(nw) nodes(ns)
sum += nw[1] * f(dist() * nw[0] + avg())
thenodes[L.index] = nw[0]
weights[L.index] = nw[1]
print(‘ nodes:’, end' ‘’)
L(n) thenodes
print(‘ #.5’.format(n), end' ‘’)
print()
print(‘ weights:’, end' ‘’)
L(w) weights
print(‘ #.5’.format(w), end' ‘’)
print()
R result * sum
print(‘integral: ’integ(x -> exp(x), 5, -3, 3)) |
http://rosettacode.org/wiki/Object_serialization | Object serialization | Create a set of data types based upon inheritance. Each data type or class should have a print command that displays the contents of an instance of that class to standard output. Create instances of each class in your inheritance hierarchy and display them to standard output. Write each of the objects to a file named objects.dat in binary form using serialization or marshalling. Read the file objects.dat and print the contents of each serialized object.
| #C.23 | C# | using System;
using System.IO;
using System.Collections.Generic;
using System.Runtime.Serialization.Formatters.Binary;
namespace Object_serialization
{
[Serializable] public class Being
{
public bool Alive { get; set; }
}
[Serializable] public class Animal: Being
{
public Animal() { }
public Animal(long id, string name, bool alive = true)
{
Id = id;
Name = name;
Alive = alive;
}
public long Id { get; set; }
public string Name { get; set; }
public void Print() { Console.WriteLine("{0}, id={1} is {2}",
Name, Id, Alive ? "alive" : "dead"); }
}
internal class Program
{
private static void Main()
{
string path =
Environment.GetFolderPath(Environment.SpecialFolder.Desktop)+"\\objects.dat";
var n = new List<Animal>
{
new Animal(1, "Fido"),
new Animal(2, "Lupo"),
new Animal(7, "Wanda"),
new Animal(3, "Kiki", alive: false)
};
foreach(Animal animal in n)
animal.Print();
using(var stream = new FileStream(path, FileMode.Create, FileAccess.Write))
new BinaryFormatter().Serialize(stream, n);
n.Clear();
Console.WriteLine("---------------");
List<Animal> m;
using(var stream = new FileStream(path, FileMode.Open, FileAccess.Read))
m = (List<Animal>) new BinaryFormatter().Deserialize(stream);
foreach(Animal animal in m)
animal.Print();
}
}
} |
http://rosettacode.org/wiki/Old_lady_swallowed_a_fly | Old lady swallowed a fly | Task
Present a program which emits the lyrics to the song I Knew an Old Lady Who Swallowed a Fly, taking advantage of the repetitive structure of the song's lyrics.
This song has multiple versions with slightly different lyrics, so all these programs might not emit identical output.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #ALGOL_68 | ALGOL 68 | #!/usr/local/bin/a68g --script #
STRING sw=" swallow ",swd=sw[:UPB sw-1]+"ed ", tsa=". To"+sw+"a";
INT count prev := 0; [9]STRING prev;
PROC vs = (STRING in wot,[]STRING co)VOID: (
STRING wot = " "+in wot;
printf(($g$,"I know an old lady who",swd,"a",wot,".",$l$));
IF UPB co = 1 THEN
printf(($gl$,co))
ELIF UPB co > 1 THEN
printf(($g$,co,wot+".",$l$))
FI;
IF count prev NE UPB prev THEN
prev[count prev+:=1]:=wot;
FOR i FROM count prev BY -1 TO 2 DO
printf(($gl$,"She"+swd+"the"+prev[i]+" to catch the"+prev[i-1]+"."))
OD;
printf(($gl$,"I don't know why she"+swd+"the fly.",
"Perhaps she'll die.", $l$))
FI
);
vs("fly",());
vs("spider","That wriggled and jiggled and tickled inside her.");
vs("Bird",("Quite absurd",tsa));
vs("Cat",("Fancy that",tsa));
vs("Dog",("What a hog",tsa));
vs("Pig",("Her mouth was so big",tsa));
vs("Goat",("She just opened her throat",tsa));
vs("Cow",("I don't know how",tsa));
vs("Donkey",("It was rather wonky",tsa));
vs("Horse","She's dead, of course!") |
http://rosettacode.org/wiki/Numerical_and_alphabetical_suffixes | Numerical and alphabetical suffixes | This task is about expressing numbers with an attached (abutted) suffix multiplier(s), the suffix(es) could be:
an alphabetic (named) multiplier which could be abbreviated
metric multiplier(s) which can be specified multiple times
"binary" multiplier(s) which can be specified multiple times
explanation marks (!) which indicate a factorial or multifactorial
The (decimal) numbers can be expressed generally as:
{±} {digits} {.} {digits}
────── or ──────
{±} {digits} {.} {digits} {E or e} {±} {digits}
where:
numbers won't have embedded blanks (contrary to the expaciated examples above where whitespace was used for readability)
this task will only be dealing with decimal numbers, both in the mantissa and exponent
± indicates an optional plus or minus sign (+ or -)
digits are the decimal digits (0 ──► 9)
the digits can have comma(s) interjected to separate the periods (thousands) such as: 12,467,000
. is the decimal point, sometimes also called a dot
e or E denotes the use of decimal exponentiation (a number multiplied by raising ten to some power)
This isn't a pure or perfect definition of the way we express decimal numbers, but it should convey the intent for this task.
The use of the word periods (thousands) is not meant to confuse, that word (as used above) is what the comma separates;
the groups of decimal digits are called periods, and in almost all cases, are groups of three decimal digits.
If an e or E is specified, there must be a legal number expressed before it, and there must be a legal (exponent) expressed after it.
Also, there must be some digits expressed in all cases, not just a sign and/or decimal point.
Superfluous signs, decimal points, exponent numbers, and zeros need not be preserved.
I.E.:
+7 007 7.00 7E-0 7E000 70e-1 could all be expressed as 7
All numbers to be "expanded" can be assumed to be valid and there won't be a requirement to verify their validity.
Abbreviated alphabetic suffixes to be supported (where the capital letters signify the minimum abbreation that can be used)
PAIRs multiply the number by 2 (as in pairs of shoes or pants)
SCOres multiply the number by 20 (as 3score would be 60)
DOZens multiply the number by 12
GRoss multiply the number by 144 (twelve dozen)
GREATGRoss multiply the number by 1,728 (a dozen gross)
GOOGOLs multiply the number by 10^100 (ten raised to the 100&sup>th</sup> power)
Note that the plurals are supported, even though they're usually used when expressing exact numbers (She has 2 dozen eggs, and dozens of quavas)
Metric suffixes to be supported (whether or not they're officially sanctioned)
K multiply the number by 10^3 kilo (1,000)
M multiply the number by 10^6 mega (1,000,000)
G multiply the number by 10^9 giga (1,000,000,000)
T multiply the number by 10^12 tera (1,000,000,000,000)
P multiply the number by 10^15 peta (1,000,000,000,000,000)
E multiply the number by 10^18 exa (1,000,000,000,000,000,000)
Z multiply the number by 10^21 zetta (1,000,000,000,000,000,000,000)
Y multiply the number by 10^24 yotta (1,000,000,000,000,000,000,000,000)
X multiply the number by 10^27 xenta (1,000,000,000,000,000,000,000,000,000)
W multiply the number by 10^30 wekta (1,000,000,000,000,000,000,000,000,000,000)
V multiply the number by 10^33 vendeka (1,000,000,000,000,000,000,000,000,000,000,000)
U multiply the number by 10^36 udekta (1,000,000,000,000,000,000,000,000,000,000,000,000)
Binary suffixes to be supported (whether or not they're officially sanctioned)
Ki multiply the number by 2^10 kibi (1,024)
Mi multiply the number by 2^20 mebi (1,048,576)
Gi multiply the number by 2^30 gibi (1,073,741,824)
Ti multiply the number by 2^40 tebi (1,099,571,627,776)
Pi multiply the number by 2^50 pebi (1,125,899,906,884,629)
Ei multiply the number by 2^60 exbi (1,152,921,504,606,846,976)
Zi multiply the number by 2^70 zeb1 (1,180,591,620,717,411,303,424)
Yi multiply the number by 2^80 yobi (1,208,925,819,614,629,174,706,176)
Xi multiply the number by 2^90 xebi (1,237,940,039,285,380,274,899,124,224)
Wi multiply the number by 2^100 webi (1,267,650,600,228,229,401,496,703,205,376)
Vi multiply the number by 2^110 vebi (1,298,074,214,633,706,907,132,624,082,305,024)
Ui multiply the number by 2^120 uebi (1,329,227,995,784,915,872,903,807,060,280,344,576)
All of the metric and binary suffixes can be expressed in lowercase, uppercase, or mixed case.
All of the metric and binary suffixes can be stacked (expressed multiple times), and also be intermixed:
I.E.: 123k 123K 123GKi 12.3GiGG 12.3e-7T .78E100e
Factorial suffixes to be supported
! compute the (regular) factorial product: 5! is 5 × 4 × 3 × 2 × 1 = 120
!! compute the double factorial product: 8! is 8 × 6 × 4 × 2 = 384
!!! compute the triple factorial product: 8! is 8 × 5 × 2 = 80
!!!! compute the quadruple factorial product: 8! is 8 × 4 = 32
!!!!! compute the quintuple factorial product: 8! is 8 × 3 = 24
··· the number of factorial symbols that can be specified is to be unlimited (as per what can be entered/typed) ···
Factorial suffixes aren't, of course, the usual type of multipliers, but are used here in a similar vein.
Multifactorials aren't to be confused with super─factorials where (4!)! would be (24)!.
Task
Using the test cases (below), show the "expanded" numbers here, on this page.
For each list, show the input on one line, and also show the output on one line.
When showing the input line, keep the spaces (whitespace) and case (capitalizations) as is.
For each result (list) displayed on one line, separate each number with two blanks.
Add commas to the output numbers were appropriate.
Test cases
2greatGRo 24Gros 288Doz 1,728pairs 172.8SCOre
1,567 +1.567k 0.1567e-2m
25.123kK 25.123m 2.5123e-00002G
25.123kiKI 25.123Mi 2.5123e-00002Gi +.25123E-7Ei
-.25123e-34Vikki 2e-77gooGols
9! 9!! 9!!! 9!!!! 9!!!!! 9!!!!!! 9!!!!!!! 9!!!!!!!! 9!!!!!!!!!
where the last number for the factorials has nine factorial symbols (!) after the 9
Related tasks
Multifactorial (which has a clearer and more succinct definition of multifactorials.)
Factorial
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Phix | Phix | with javascript_semantics
include builtins/bigatom.e
{} = ba_scale(34) -- (min rqd for accuracy on the "Vikki" test)
-- (the default is 25, not quite enough here)
constant suffixes = {{"GREATGRoss",7,1728},
{"GOOGOLs",6,ba_new("1e100")},
{"SCOres",3,20},
{"DOZens",3,12},
{"GRoss",2,144},
{"PAIRs",4,2},
"KMGTPEZYXWVU"}
function decode(string suffix)
bigatom res = BA_ONE
suffix = upper(suffix)
while length(suffix)>0 do
bool found = false
for i=length(suffix) to 2 by -1 do
for s=1 to length(suffixes)-1 do
if i<=length(suffixes[s][1])
and i>=suffixes[s][2]
and suffix[1..i]=upper(suffixes[s][1][1..i]) then
res = ba_mul(res,suffixes[s][3])
suffix = suffix[i+1..$]
found = true
exit
end if
end for
if found then exit end if
end for
if not found then
integer k = find(suffix[1],suffixes[$])
if k=0 then ?9/0 end if
if length(suffix)>=2 and suffix[2]='I' then
res = ba_mul(res,ba_power(1024,k))
suffix = suffix[3..$]
else
res = ba_mul(res,ba_power(1000,k))
suffix = suffix[2..$]
end if
end if
end while
return res
end function
function facto(bigatom n, integer f)
if f!=0 then
bigatom nf = ba_sub(n,f)
while ba_compare(nf,2)>=0 do
n = ba_mul(n,nf)
nf = ba_sub(nf,f)
end while
end if
return n
end function
constant test_cases = """
2greatGRo 24Gros 288Doz 1,728pairs 172.8SCOre
1,567 +1.567k 0.1567e-2m
25.123kK 25.123m 2.5123e-00002G
25.123kiKI 25.123Mi 2.5123e-00002Gi +.25123E-7Ei
-.25123e-34Vikki 2e-77gooGols
9! 9!! 9!!! 9!!!! 9!!!!! 9!!!!!! 9!!!!!!! 9!!!!!!!! 9!!!!!!!!!
0.017k!!
"""
constant tests = split(substitute(test_cases,"\n"," "),no_empty:=true)
for i=1 to length(tests) do
string test = tests[i], suffix = "", facts = ""
for f=length(test) to 1 by -1 do
if test[f]!='!' then
{test,facts} = {test[1..f],test[f+1..$]}
exit
end if
end for
for d=length(test) to 1 by -1 do
integer digit = test[d]
if digit>='0' and digit<='9' then
{test,suffix} = {test[1..d],test[d+1..$]}
exit
end if
end for
bigatom n = ba_new(substitute(test,",",""))
n = ba_mul(n,decode(suffix))
n = facto(n,length(facts))
string ns = ba_sprintf("%,B",n)
printf(1,"%30s : %s\n",{tests[i],ns})
end for
|
http://rosettacode.org/wiki/Old_Russian_measure_of_length | Old Russian measure of length | Task
Write a program to perform a conversion of the old Russian measures of length to the metric system (and vice versa).
It is an example of a linear transformation of several variables.
The program should accept a single value in a selected unit of measurement, and convert and return it to the other units:
vershoks, arshins, sazhens, versts, meters, centimeters and kilometers.
Also see
Old Russian measure of length
| #Elena | Elena | import system'collections;
import system'routines;
import extensions;
unit2mult = new Map<string, real>()
.setAt("arshin", 0.7112r)
.setAt("centimeter", 0.01r)
.setAt("diuym", 0.0254r)
.setAt("fut", 0.3048r)
.setAt("kilometer", 1000.0r)
.setAt("liniya", 0.00254r)
.setAt("meter", 1.0r)
.setAt("milia", 7467.6r)
.setAt("piad", 0.1778r)
.setAt("sazhen", 2.1336r)
.setAt("tochka", 0.000254r)
.setAt("vershok", 0.04445r)
.setAt("versta", 1066.8r);
public program()
{
if (program_arguments.Length != 3)
{ console.writeLine:"need two arguments - number then units"; AbortException.raise() };
real value := program_arguments[1].toReal();
string unit := program_arguments[2];
ifnot (unit2mult.containsKey(unit))
{
console.printLine("only following units are supported:",
unit2mult.selectBy:(x=>x.Item1).asEnumerable());
AbortException.raise()
};
console.printLine(value," ",unit," to:");
unit2mult.forEach:(u,mlt)
{
console.printPaddingLeft(30, u, ":").printLine(value * unit2mult[unit] / mlt)
}
} |
http://rosettacode.org/wiki/Old_Russian_measure_of_length | Old Russian measure of length | Task
Write a program to perform a conversion of the old Russian measures of length to the metric system (and vice versa).
It is an example of a linear transformation of several variables.
The program should accept a single value in a selected unit of measurement, and convert and return it to the other units:
vershoks, arshins, sazhens, versts, meters, centimeters and kilometers.
Also see
Old Russian measure of length
| #Factor | Factor | USING: formatting inverse io kernel math prettyprint quotations
sequences units.imperial units.si vocabs ;
IN: rosetta-code.units.russian
: arshin ( n -- d ) 2+1/3 * feet ;
: tochka ( n -- d ) 1/2800 * arshin ;
: liniya ( n -- d ) 1/280 * arshin ;
: dyuim ( n -- d ) 1/28 * arshin ;
: vershok ( n -- d ) 1/16 * arshin ;
: ladon ( n -- d ) 7+1/2 * cm ;
: piad ( n -- d ) 1/4 * arshin ;
: fut ( n -- d ) 3/7 * arshin ;
: lokot ( n -- d ) 45 * cm ;
: shag ( n -- d ) 71 * cm ;
: sazhen ( n -- d ) 3 * arshin ;
: versta ( n -- d ) 1,500 * arshin ;
: milya ( n -- d ) 10,500 * arshin ;
<PRIVATE
: convert ( quot -- )
[ unparse rest rest but-last write "to:" print ] [ call ] bi
"rosetta-code.units.russian" vocab-words { cm m km } append
[ dup "%8u : " printf 1quotation [undo] call( x -- x ) . ]
with each nl ; inline
: main ( -- )
[ 6 m ] [ 1+7/8 milya ] [ 2 furlongs ] [ convert ] tri@ ;
PRIVATE>
MAIN: main |
http://rosettacode.org/wiki/OpenGL | OpenGL |
Task
Display a smooth shaded triangle with OpenGL.
Triangle created using C example compiled with GCC 4.1.2 and freeglut3.
| #FreeBASIC | FreeBASIC | #include "fbgfx.bi"
#include once "GL/gl.bi"
#include once "GL/glu.bi"
screen 18, 16, , 2
glViewport 0, 0, 640, 480 'Set the viewport
glMatrixMode GL_PROJECTION ' Select projection
glLoadIdentity ' Set this to default
gluPerspective 45.0, 640./480., 0.1, 100.0 ' Set perspective view options
glMatrixMode GL_MODELVIEW ' Set to modelview mode
glLoadIdentity ' ...and set it to default
glClearColor 0.5, 0.5, 0.5, 0.0 ' Set clearscreen color to middle grey
glShadeModel GL_SMOOTH ' set to smooth shading
glClearDepth 1.0 ' Allow the deletion of the depth buffer
glEnable GL_DEPTH_TEST ' turn on depth testing
glDepthFunc GL_LEQUAL ' The Type Of Depth Test To Do
glHint GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ' niceness tweaks
do
glClear GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT ' clear screen and depth
glLoadIdentity
glTranslatef 0.0f, 0.0f, -6.0f ' move camera back so we can see the triangle
glBegin GL_TRIANGLES ' Drawing Using Triangles
glColor3f 1.0f, 0.0f, 0.0f ' red
glVertex3f 0.0f, 1.0f, 0.0f ' Top
glColor3f 0.0f, 1.0f, 0.0f ' green
glVertex3f -1.0f,-1.0f, 0.0f ' Bottom Left
glColor3f 0.0f, 0.0f, 1.0f ' blue
glVertex3f 1.0f,-1.0f, 0.0f ' Bottom Right
glEnd ' Finished Drawing The Triangle
flip
loop while inkey = "" |
http://rosettacode.org/wiki/One_of_n_lines_in_a_file | One of n lines in a file | A method of choosing a line randomly from a file:
Without reading the file more than once
When substantial parts of the file cannot be held in memory
Without knowing how many lines are in the file
Is to:
keep the first line of the file as a possible choice, then
Read the second line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/2.
Read the third line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/3.
...
Read the Nth line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/N
Return the computed possible choice when no further lines exist in the file.
Task
Create a function/method/routine called one_of_n that given n, the number of actual lines in a file, follows the algorithm above to return an integer - the line number of the line chosen from the file.
The number returned can vary, randomly, in each run.
Use one_of_n in a simulation to find what woud be the chosen line of a 10 line file simulated 1,000,000 times.
Print and show how many times each of the 10 lines is chosen as a rough measure of how well the algorithm works.
Note: You may choose a smaller number of repetitions if necessary, but mention this up-front.
Note: This is a specific version of a Reservoir Sampling algorithm: https://en.wikipedia.org/wiki/Reservoir_sampling
| #Chapel | Chapel | use Random;
proc one_of_n(n) {
var rand = new RandomStream();
var keep = 1;
for i in 2..n do
if rand.getNext() < 1.0 / i then
keep = i;
delete rand;
return keep;
} |
http://rosettacode.org/wiki/One_of_n_lines_in_a_file | One of n lines in a file | A method of choosing a line randomly from a file:
Without reading the file more than once
When substantial parts of the file cannot be held in memory
Without knowing how many lines are in the file
Is to:
keep the first line of the file as a possible choice, then
Read the second line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/2.
Read the third line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/3.
...
Read the Nth line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/N
Return the computed possible choice when no further lines exist in the file.
Task
Create a function/method/routine called one_of_n that given n, the number of actual lines in a file, follows the algorithm above to return an integer - the line number of the line chosen from the file.
The number returned can vary, randomly, in each run.
Use one_of_n in a simulation to find what woud be the chosen line of a 10 line file simulated 1,000,000 times.
Print and show how many times each of the 10 lines is chosen as a rough measure of how well the algorithm works.
Note: You may choose a smaller number of repetitions if necessary, but mention this up-front.
Note: This is a specific version of a Reservoir Sampling algorithm: https://en.wikipedia.org/wiki/Reservoir_sampling
| #Clojure | Clojure | (defn rand-seq-elem [sequence]
(let [f (fn [[k old] new]
[(inc k) (if (zero? (rand-int k)) new old)])]
(->> sequence (reduce f [1 nil]) second)))
(defn one-of-n [n]
(rand-seq-elem (range 1 (inc n))))
(let [countmap (frequencies (repeatedly 1000000 #(one-of-n 10)))]
(doseq [[n cnt] (sort countmap)]
(println n cnt))) |
http://rosettacode.org/wiki/P-value_correction | P-value correction | Given a list of p-values, adjust the p-values for multiple comparisons. This is done in order to control the false positive, or Type 1 error rate.
This is also known as the "false discovery rate" (FDR). After adjustment, the p-values will be higher but still inside [0,1].
The adjusted p-values are sometimes called "q-values".
Task
Given one list of p-values, return the p-values correcting for multiple comparisons
p = {4.533744e-01, 7.296024e-01, 9.936026e-02, 9.079658e-02, 1.801962e-01,
8.752257e-01, 2.922222e-01, 9.115421e-01, 4.355806e-01, 5.324867e-01,
4.926798e-01, 5.802978e-01, 3.485442e-01, 7.883130e-01, 2.729308e-01,
8.502518e-01, 4.268138e-01, 6.442008e-01, 3.030266e-01, 5.001555e-02,
3.194810e-01, 7.892933e-01, 9.991834e-01, 1.745691e-01, 9.037516e-01,
1.198578e-01, 3.966083e-01, 1.403837e-02, 7.328671e-01, 6.793476e-02,
4.040730e-03, 3.033349e-04, 1.125147e-02, 2.375072e-02, 5.818542e-04,
3.075482e-04, 8.251272e-03, 1.356534e-03, 1.360696e-02, 3.764588e-04,
1.801145e-05, 2.504456e-07, 3.310253e-02, 9.427839e-03, 8.791153e-04,
2.177831e-04, 9.693054e-04, 6.610250e-05, 2.900813e-02, 5.735490e-03}
There are several methods to do this, see:
Yoav Benjamini, Yosef Hochberg "Controlling the False Discovery Rate: A Practical and Powerful Approach to Multiple Testing", Journal of the Royal Statistical Society. Series B, Vol. 57, No. 1 (1995), pp. 289-300, JSTOR:2346101
Yoav Benjamini, Daniel Yekutieli, "The control of the false discovery rate in multiple testing under dependency", Ann. Statist., Vol. 29, No. 4 (2001), pp. 1165-1188, DOI:10.1214/aos/1013699998 JSTOR:2674075
Sture Holm, "A Simple Sequentially Rejective Multiple Test Procedure", Scandinavian Journal of Statistics, Vol. 6, No. 2 (1979), pp. 65-70, JSTOR:4615733
Yosef Hochberg, "A sharper Bonferroni procedure for multiple tests of significance", Biometrika, Vol. 75, No. 4 (1988), pp 800–802, DOI:10.1093/biomet/75.4.800 JSTOR:2336325
Gerhard Hommel, "A stagewise rejective multiple test procedure based on a modified Bonferroni test", Biometrika, Vol. 75, No. 2 (1988), pp 383–386, DOI:10.1093/biomet/75.2.383 JSTOR:2336190
Each method has its own advantages and disadvantages.
| #Wren | Wren | import "/dynamic" for Enum
import "/fmt" for Fmt
import "/seq" for Lst
import "/math" for Nums
import "/sort" for Sort
var Direction = Enum.create("Direction", ["UP", "DOWN"])
// test also for 'Unknown' correction type
var types = [
"Benjamini-Hochberg", "Benjamini-Yekutieli", "Bonferroni", "Hochberg",
"Holm", "Hommel", "Šidák", "Unknown"
]
var pFormat = Fn.new { |p, cols|
var i = -cols
var fmt = "$1.10f"
return Lst.chunks(p, cols).map { |chunk|
i = i + cols
return Fmt.swrite("[$2d $s", i, chunk.map { |v| Fmt.swrite(fmt, v) }.join(" "))
}.join("\n")
}
var check = Fn.new { |p|
if (p.count == 0 || Nums.min(p) < 0 || Nums.max(p) > 1) {
Fiber.abort("p-values must be in range 0 to 1")
}
return p
}
var ratchet = Fn.new { |p, dir|
var pp = p.toList
var m = pp[0]
if (dir == Direction.UP) {
for (i in 1...pp.count) {
if (pp[i] > m) pp[i] = m
m = pp[i]
}
} else {
for (i in 1...pp.count) {
if (pp[i] < m) pp[i] = m
m = pp[i]
}
}
return pp.map { |v| (v < 1) ? v : 1 }.toList
}
var schwartzian = Fn.new { |p, mult, dir|
var size = p.count
var pwi = List.filled(size, null)
for (i in 0...size) pwi[i] = [i, p[i]]
var cmp = (dir == Direction.UP) ? Fn.new { |a, b| (b[1] - a[1]).sign } :
Fn.new { |a, b| (a[1] - b[1]).sign }
var order = Sort.merge(pwi, cmp).map { |e| e[0] }.toList
var pa = List.filled(size, 0)
for (i in 0...size) pa[i] = mult[i] * p[order[i]]
pa = ratchet.call(pa, dir)
var owi = List.filled(order.count, null)
for (i in 0...order.count) owi[i] = [i, order[i]]
cmp = Fn.new { |a, b| (a[1] - b[1]).sign }
var order2 = Sort.merge(owi, cmp).map { |e| e[0] }.toList
var res = List.filled(size, 0)
for (i in 0...size) res[i] = pa[order2[i]]
return res
}
var adjust = Fn.new { |p, type|
var size = p.count
if (size == 0) Fiber.abort("List cannot be empty.")
if (type == "Benjamini-Hochberg") {
var mult = List.filled(size, 0)
for (i in 0...size) mult[i] = size / (size - i)
return schwartzian.call(p, mult, Direction.UP)
} else if (type == "Benjamini-Yekutieli") {
var q = (1..size).reduce { |acc, i| acc + 1/i }
var mult = List.filled(size, 0)
for (i in 0...size) mult[i] = q * size / (size - i)
return schwartzian.call(p, mult, Direction.UP)
} else if (type == "Bonferroni") {
return p.map { |v| (v * size).min(1) }.toList
} else if (type == "Hochberg") {
var mult = List.filled(size, 0)
for (i in 0...size) mult[i] = i + 1
return schwartzian.call(p, mult, Direction.UP)
} else if (type == "Holm") {
var mult = List.filled(size, 0)
for (i in 0...size) mult[i] = size - i
return schwartzian.call(p, mult, Direction.DOWN)
} else if (type == "Hommel") {
var pwi = List.filled(size, null)
for (i in 0...size) pwi[i] = [i, p[i]]
var cmp = Fn.new { |a, b| (a[1] - b[1]).sign }
var order = Sort.merge(pwi, cmp).map { |e| e[0] }.toList
var s = List.filled(size, 0)
for (i in 0...size) s[i] = p[order[i]]
var m = List.filled(size, 0)
for (i in 0...size) m[i] = s[i] * size / (i + 1)
var min = Nums.min(m)
var q = List.filled(size, min)
var pa = List.filled(size, min)
for (j in size-1..2) {
var lower = List.filled(size - j + 1, 0) // lower indices
for (i in 0...lower.count) lower[i] = i
var upper = List.filled(j - 1, 0) // upper indices
for (i in 0...upper.count) upper[i] = size - j + 1 + i
var qmin = j * s[upper[0]] / 2
for (i in 1...upper.count) {
var temp = s[upper[i]] * j / (2 + i)
if (temp < qmin) qmin = temp
}
for (i in 0...lower.count) {
q[lower[i]] = qmin.min(s[lower[i]] * j)
}
for (i in 0...upper.count) q[upper[i]] = q[size - j]
for (i in 0...size) if (pa[i] < q[i]) pa[i] = q[i]
}
var owi = List.filled(order.count, null)
for (i in 0...order.count) owi[i] = [i, order[i]]
var order2 = Sort.merge(owi, cmp).map { |e| e[0] }.toList
var res = List.filled(size, 0)
for (i in 0...size) res[i] = pa[order2[i]]
return res
} else if (type == "Šidák") {
return p.map { |v| 1 - (1 - v).pow(size) }.toList
} else {
System.print("\nSorry, do not know how to do '%(type)' correction.\n" +
"Perhaps you want one of these?:\n" +
types[0...-1].map { |t| " %(t)" }.join("\n")
)
Fiber.suspend()
}
}
var adjusted = Fn.new { |p, type| "\n%(type)\n%(pFormat.call(adjust.call(check.call(p), type), 5))" }
var pValues = [
4.533744e-01, 7.296024e-01, 9.936026e-02, 9.079658e-02, 1.801962e-01,
8.752257e-01, 2.922222e-01, 9.115421e-01, 4.355806e-01, 5.324867e-01,
4.926798e-01, 5.802978e-01, 3.485442e-01, 7.883130e-01, 2.729308e-01,
8.502518e-01, 4.268138e-01, 6.442008e-01, 3.030266e-01, 5.001555e-02,
3.194810e-01, 7.892933e-01, 9.991834e-01, 1.745691e-01, 9.037516e-01,
1.198578e-01, 3.966083e-01, 1.403837e-02, 7.328671e-01, 6.793476e-02,
4.040730e-03, 3.033349e-04, 1.125147e-02, 2.375072e-02, 5.818542e-04,
3.075482e-04, 8.251272e-03, 1.356534e-03, 1.360696e-02, 3.764588e-04,
1.801145e-05, 2.504456e-07, 3.310253e-02, 9.427839e-03, 8.791153e-04,
2.177831e-04, 9.693054e-04, 6.610250e-05, 2.900813e-02, 5.735490e-03
]
types.each { |type| System.print(adjusted.call(pValues, type)) } |
http://rosettacode.org/wiki/Order_disjoint_list_items | Order disjoint list items |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Given M as a list of items and another list N of items chosen from M, create M' as a list with the first occurrences of items from N sorted to be in one of the set of indices of their original occurrence in M but in the order given by their order in N.
That is, items in N are taken from M without replacement, then the corresponding positions in M' are filled by successive items from N.
For example
if M is 'the cat sat on the mat'
And N is 'mat cat'
Then the result M' is 'the mat sat on the cat'.
The words not in N are left in their original positions.
If there are duplications then only the first instances in M up to as many as are mentioned in N are potentially re-ordered.
For example
M = 'A B C A B C A B C'
N = 'C A C A'
Is ordered as:
M' = 'C B A C B A A B C'
Show the output, here, for at least the following inputs:
Data M: 'the cat sat on the mat' Order N: 'mat cat'
Data M: 'the cat sat on the mat' Order N: 'cat mat'
Data M: 'A B C A B C A B C' Order N: 'C A C A'
Data M: 'A B C A B D A B E' Order N: 'E A D A'
Data M: 'A B' Order N: 'B'
Data M: 'A B' Order N: 'B A'
Data M: 'A B B A' Order N: 'B A'
Cf
Sort disjoint sublist
| #PicoLisp | PicoLisp | (de orderDisjoint (M N)
(for S N
(and (memq S M) (set @ NIL)) )
(mapcar
'((S) (or S (pop 'N)))
M ) ) |
http://rosettacode.org/wiki/Order_disjoint_list_items | Order disjoint list items |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Given M as a list of items and another list N of items chosen from M, create M' as a list with the first occurrences of items from N sorted to be in one of the set of indices of their original occurrence in M but in the order given by their order in N.
That is, items in N are taken from M without replacement, then the corresponding positions in M' are filled by successive items from N.
For example
if M is 'the cat sat on the mat'
And N is 'mat cat'
Then the result M' is 'the mat sat on the cat'.
The words not in N are left in their original positions.
If there are duplications then only the first instances in M up to as many as are mentioned in N are potentially re-ordered.
For example
M = 'A B C A B C A B C'
N = 'C A C A'
Is ordered as:
M' = 'C B A C B A A B C'
Show the output, here, for at least the following inputs:
Data M: 'the cat sat on the mat' Order N: 'mat cat'
Data M: 'the cat sat on the mat' Order N: 'cat mat'
Data M: 'A B C A B C A B C' Order N: 'C A C A'
Data M: 'A B C A B D A B E' Order N: 'E A D A'
Data M: 'A B' Order N: 'B'
Data M: 'A B' Order N: 'B A'
Data M: 'A B B A' Order N: 'B A'
Cf
Sort disjoint sublist
| #PowerShell | PowerShell |
function sublistsort($M, $N) {
$arr = $M.Split(' ')
$array = $N.Split(' ') | group
$Count = @($array |foreach {$_.Count})
$ip, $i = @(), 0
$arr | foreach{
$name = "$_"
$j = $array.Name.IndexOf($name)
if($j -gt -1){
$k = $Count[$j] - 1
if($k -ge 0) {
$ip += @($i)
$Count[$j] = $k
}
}
$i++
}
$i = 0
$N.Split(' ') | foreach{ $arr[$ip[$i++]] = "$_"}
[pscustomobject]@{
"M" = "$M "
"N" = "$N "
"M'" = "$($arr)"
}
}
$M1 = 'the cat sat on the mat'
$N1 = 'mat cat'
$M2 = 'the cat sat on the mat'
$N2 = 'cat mat'
$M3 = 'A B C A B C A B C'
$N3 = 'C A C A'
$M4 = 'A B C A B D A B E'
$N4 = 'E A D A'
$M5 = 'A B'
$N5 = 'B'
$M6 = 'A B'
$N6 = 'B A'
$M7 = 'A B B A'
$N7 = 'B A'
sublistsort $M1 $N1
sublistsort $M2 $N2
sublistsort $M3 $N3
sublistsort $M4 $N4
sublistsort $M5 $N5
sublistsort $M6 $N6
sublistsort $M7 $N7
|
http://rosettacode.org/wiki/Optional_parameters | Optional parameters | Task
Define a function/method/subroutine which sorts a sequence ("table") of sequences ("rows") of strings ("cells"), by one of the strings. Besides the input to be sorted, it shall have the following optional parameters:
ordering
A function specifying the ordering of strings; lexicographic by default.
column
An integer specifying which string of each row to compare; the first by default.
reverse
Reverses the ordering.
This task should be considered to include both positional and named optional parameters, as well as overloading on argument count as in Java or selector name as in Smalltalk, or, in the extreme, using different function names. Provide these variations of sorting in whatever way is most natural to your language. If the language supports both methods naturally, you are encouraged to describe both.
Do not implement a sorting algorithm; this task is about the interface. If you can't use a built-in sort routine, just omit the implementation (with a comment).
See also:
Named Arguments
| #J | J | srtbl=: verb define
'' srtbl y
:
'`ordering column reverse'=. x , (#x)}. ]`0:`0:
|.^:reverse y /: ordering (column {"1 ])y
) |
http://rosettacode.org/wiki/Optional_parameters | Optional parameters | Task
Define a function/method/subroutine which sorts a sequence ("table") of sequences ("rows") of strings ("cells"), by one of the strings. Besides the input to be sorted, it shall have the following optional parameters:
ordering
A function specifying the ordering of strings; lexicographic by default.
column
An integer specifying which string of each row to compare; the first by default.
reverse
Reverses the ordering.
This task should be considered to include both positional and named optional parameters, as well as overloading on argument count as in Java or selector name as in Smalltalk, or, in the extreme, using different function names. Provide these variations of sorting in whatever way is most natural to your language. If the language supports both methods naturally, you are encouraged to describe both.
Do not implement a sorting algorithm; this task is about the interface. If you can't use a built-in sort routine, just omit the implementation (with a comment).
See also:
Named Arguments
| #Java | Java | import java.util.*;
public class OptionalParams {
// "natural ordering" comparator
static <T extends Comparable<? super T>> Comparator<T> naturalOrdering() {
return Collections.reverseOrder(Collections.<T>reverseOrder());
}
public static <T extends Comparable<? super T>> void
sortTable(T[][] table) {
sortTable(table, 0);
}
public static <T extends Comparable<? super T>> void
sortTable(T[][] table,
int column) {
sortTable(table, column, false);
}
public static <T extends Comparable<? super T>> void
sortTable(T[][] table,
int column, boolean reverse) {
sortTable(table, column, reverse, OptionalParams.<T>naturalOrdering());
}
public static <T> void sortTable(T[][] table,
final int column,
final boolean reverse,
final Comparator<T> ordering) {
Comparator<T[]> myCmp = new Comparator<T[]>() {
public int compare(T[] x, T[] y) {
return (reverse ? -1 : 1) *
ordering.compare(x[column], y[column]);
}
};
Arrays.sort(table, myCmp);
}
public static void main(String[] args) {
String[][] data0 = {{"a", "b", "c"},
{"", "q", "z"},
{"zap", "zip", "Zot"}};
System.out.println(Arrays.deepToString(data0));
// prints: [[a, b, c], [, q, z], [zap, zip, Zot]]
// we copy it so that we don't change the original copy
String[][] data = data0.clone();
sortTable(data);
System.out.println(Arrays.deepToString(data));
// prints: [[, q, z], [a, b, c], [zap, zip, Zot]]
data = data0.clone();
sortTable(data, 2);
System.out.println(Arrays.deepToString(data));
// prints: [[zap, zip, Zot], [a, b, c], [, q, z]]
data = data0.clone();
sortTable(data, 1);
System.out.println(Arrays.deepToString(data));
// prints: [[a, b, c], [, q, z], [zap, zip, Zot]]
data = data0.clone();
sortTable(data, 1, true);
System.out.println(Arrays.deepToString(data));
// prints: [[zap, zip, Zot], [, q, z], [a, b, c]]
data = data0.clone();
sortTable(data, 0, false, new Comparator<String>() {
public int compare(String a, String b) {
return b.length() - a.length();
}
});
System.out.println(Arrays.deepToString(data));
// prints: [[zap, zip, Zot], [a, b, c], [, q, z]]
}
} |
http://rosettacode.org/wiki/Order_two_numerical_lists | Order two numerical lists | sorting
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Write a function that orders two lists or arrays filled with numbers.
The function should accept two lists as arguments and return true if the first list should be ordered before the second, and false otherwise.
The order is determined by lexicographic order: Comparing the first element of each list.
If the first elements are equal, then the second elements should be compared, and so on, until one of the list has no more elements.
If the first list runs out of elements the result is true.
If the second list or both run out of elements the result is false.
Note: further clarification of lexicographical ordering is expounded on the talk page here and here.
| #F.23 | F# | let inline cmp x y = if x < y then -1 else if x = y then 0 else 1
let before (s1 : seq<'a>) (s2 : seq<'a>) = (Seq.compareWith cmp s1 s2) < 0
[
([0], []);
([], []);
([], [0]);
([-1], [0]);
([0], [0]);
([0], [-1]);
([0], [0; -1]);
([0], [0; 0]);
([0], [0; 1]);
([0; -1], [0]);
([0; 0], [0]);
([0; 0], [1]);
]
|> List.iter (fun (x, y) -> printf "%A %s %A\n" x (if before x y then "< " else ">=") y) |
http://rosettacode.org/wiki/Pascal%27s_triangle | Pascal's triangle | Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere.
Its first few rows look like this:
1
1 1
1 2 1
1 3 3 1
where each element of each row is either 1 or the sum of the two elements right above it.
For example, the next row of the triangle would be:
1 (since the first element of each row doesn't have two elements above it)
4 (1 + 3)
6 (3 + 3)
4 (3 + 1)
1 (since the last element of each row doesn't have two elements above it)
So the triangle now looks like this:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
Each row n (starting with row 0 at the top) shows the coefficients of the binomial expansion of (x + y)n.
Task
Write a function that prints out the first n rows of the triangle (with f(1) yielding the row consisting of only the element 1).
This can be done either by summing elements from the previous rows or using a binary coefficient or combination function.
Behavior for n ≤ 0 does not need to be uniform, but should be noted.
See also
Evaluate binomial coefficients
| #Visual_Basic_.NET | Visual Basic .NET | Imports System.Numerics
Module Module1
Iterator Function GetRow(rowNumber As BigInteger) As IEnumerable(Of BigInteger)
Dim denominator As BigInteger = 1
Dim numerator = rowNumber
Dim currentValue As BigInteger = 1
For counter = 0 To rowNumber
Yield currentValue
currentValue = currentValue * numerator
numerator = numerator - 1
currentValue = currentValue / denominator
denominator = denominator + 1
Next
End Function
Function GetTriangle(quantityOfRows As Integer) As IEnumerable(Of BigInteger())
Dim range = Enumerable.Range(0, quantityOfRows).Select(Function(num) New BigInteger(num))
Return range.Select(Function(num) GetRow(num).ToArray())
End Function
Function CenterString(text As String, width As Integer)
Dim spaces = width - text.Length
Dim padLeft = (spaces / 2) + text.Length
Return text.PadLeft(padLeft).PadRight(width)
End Function
Function FormatTriangleString(triangle As IEnumerable(Of BigInteger())) As String
Dim maxDigitWidth = triangle.Last().Max().ToString().Length
Dim rows = triangle.Select(Function(arr) String.Join(" ", arr.Select(Function(array) CenterString(array.ToString(), maxDigitWidth))))
Dim maxRowWidth = rows.Last().Length
Return String.Join(Environment.NewLine, rows.Select(Function(row) CenterString(row, maxRowWidth)))
End Function
Sub Main()
Dim triangle = GetTriangle(20)
Dim output = FormatTriangleString(triangle)
Console.WriteLine(output)
End Sub
End Module |
http://rosettacode.org/wiki/Operator_precedence | Operator precedence |
This page uses content from Wikipedia. The original article was at Operators in C and C++. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Provide a list of precedence and associativity of all the operators and constructs that the language utilizes in descending order of precedence such that an operator which is listed on some row will be evaluated prior to any operator that is listed on a row further below it.
Operators that are in the same cell (there may be several rows of operators listed in a cell) are evaluated with the same level of precedence, in the given direction.
State whether arguments are passed by value or by reference.
| #PL.2FI | PL/I | q)3*2+1
9
q)(3*2)+1 / Brackets give the usual order of precedence
7
q)x:5
q)(x+5; x:20; x-5)
25 20 0 |
http://rosettacode.org/wiki/Operator_precedence | Operator precedence |
This page uses content from Wikipedia. The original article was at Operators in C and C++. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Provide a list of precedence and associativity of all the operators and constructs that the language utilizes in descending order of precedence such that an operator which is listed on some row will be evaluated prior to any operator that is listed on a row further below it.
Operators that are in the same cell (there may be several rows of operators listed in a cell) are evaluated with the same level of precedence, in the given direction.
State whether arguments are passed by value or by reference.
| #PureBasic | PureBasic | q)3*2+1
9
q)(3*2)+1 / Brackets give the usual order of precedence
7
q)x:5
q)(x+5; x:20; x-5)
25 20 0 |
http://rosettacode.org/wiki/Ordered_words | Ordered words | An ordered word is a word in which the letters appear in alphabetic order.
Examples include abbey and dirt.
Task[edit]
Find and display all the ordered words in the dictionary unixdict.txt that have the longest word length.
(Examples that access the dictionary file locally assume that you have downloaded this file yourself.)
The display needs to be shown on this page.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
Function isOrdered(s As Const String) As Boolean
If Len(s) <= 1 Then Return True
For i As Integer = 1 To Len(s) - 1
If s[i] < s[i - 1] Then Return False
Next
Return True
End Function
Dim words() As String
Dim word As String
Dim maxLength As Integer = 0
Dim count As Integer = 0
Open "undict.txt" For Input As #1
While Not Eof(1)
Line Input #1, word
If isOrdered(word) Then
If Len(word) = maxLength Then
Redim Preserve words(0 To count)
words(count) = word
count += 1
ElseIf Len(word) > maxLength Then
Erase words
maxLength = Len(word)
Redim words(0 To 0)
words(0) = word
count = 1
End If
End If
Wend
Close #1
Print "The ordered words with the longest length ("; Str(maxLength); ") in undict.txt are :"
Print
For i As Integer = 0 To UBound(words)
Print words(i)
Next
Print
Print "Press any key to quit"
Sleep |
http://rosettacode.org/wiki/Palindrome_detection | Palindrome detection | A palindrome is a phrase which reads the same backward and forward.
Task[edit]
Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes)
is a palindrome.
For extra credit:
Support Unicode characters.
Write a second function (possibly as a wrapper to the first) which detects inexact palindromes, i.e. phrases that are palindromes if white-space and punctuation is ignored and case-insensitive comparison is used.
Hints
It might be useful for this task to know how to reverse a string.
This task's entries might also form the subjects of the task Test a function.
Related tasks
Word plays
Ordered words
Palindrome detection
Semordnilap
Anagrams
Anagrams/Deranged anagrams
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Pascal | Pascal | program Palindro;
{ RECURSIVE }
function is_palindro_r(s : String) : Boolean;
begin
if length(s) <= 1 then
is_palindro_r := true
else begin
if s[1] = s[length(s)] then
is_palindro_r := is_palindro_r(copy(s, 2, length(s)-2))
else
is_palindro_r := false
end
end; { is_palindro_r }
{ NON RECURSIVE; see [[Reversing a string]] for "reverse" }
function is_palindro(s : String) : Boolean;
begin
if s = reverse(s) then
is_palindro := true
else
is_palindro := false
end; |
http://rosettacode.org/wiki/One-time_pad | One-time pad | Implement a One-time pad, for encrypting and decrypting messages.
To keep it simple, we will be using letters only.
Sub-Tasks
Generate the data for a One-time pad (user needs to specify a filename and length)
The important part is to get "true random" numbers, e.g. from /dev/random
encryption / decryption ( basically the same operation, much like Rot-13 )
For this step, much of Vigenère cipher could be reused,
with the key to be read from the file containing the One-time pad.
optional: management of One-time pads: list, mark as used, delete, etc.
Somehow, the users needs to keep track which pad to use for which partner.
To support the management of pad-files:
Such files have a file-extension ".1tp"
Lines starting with "#" may contain arbitary meta-data (i.e. comments)
Lines starting with "-" count as "used"
Whitespace within the otp-data is ignored
For example, here is the data from Wikipedia:
# Example data - Wikipedia - 2014-11-13
-ZDXWWW EJKAWO FECIFE WSNZIP PXPKIY URMZHI JZTLBC YLGDYJ
-HTSVTV RRYYEG EXNCGA GGQVRF FHZCIB EWLGGR BZXQDQ DGGIAK
YHJYEQ TDLCQT HZBSIZ IRZDYS RBYJFZ AIRCWI UCVXTW YKPQMK
CKHVEX VXYVCS WOGAAZ OUVVON GCNEVR LMBLYB SBDCDC PCGVJX
QXAUIP PXZQIJ JIUWYH COVWMJ UZOJHL DWHPER UBSRUJ HGAAPR
CRWVHI FRNTQW AJVWRT ACAKRD OZKIIB VIQGBK IJCWHF GTTSSE
EXFIPJ KICASQ IOUQTP ZSGXGH YTYCTI BAZSTN JKMFXI RERYWE
See also
one time pad encryption in Python
snapfractalpop - One-Time-Pad Command-Line-Utility (C).
Crypt-OTP-2.00 on CPAN (Perl)
| #TypeScript | TypeScript |
#!/usr/bin/env node
import { writeFileSync, existsSync, readFileSync, unlinkSync } from 'node:fs';
//https://www.elitizon.com/2021/01-09-how-to-create-a-cli-command-with-typescript/#:~:text=%20Boost%20your%20productivity%20by%20creating%20your%20own,information.%20Required%3A%20string.%20%20...%20%20More%20
const a:string[] = process.argv;
const argv:string[] = a.splice(2)
/**
* Extension of the pad files
*/
const padExtension:string = ".1tp";
/**
* Extension of the key generated
*/
const keyExtension:string = ".key";
/**
* Array of commands usable
*/
const commands:string[] = ["--generate", "--encrypt","--decrypt"];
/**
* The alphabet
*/
const stringLetter = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
/**
* Main function
*/
const main = ():void => {
// if no args have been give display help
if(argv.length == 0){
help();
return;
}
// Check if there is a command in the file
if(commands.includes(argv[0])){
let choise = argv[0].trim().toLowerCase();
if(choise === "--generate"){
console.log("Generating action chosen");
// Check if the arguments have been given to generate a new key
if(!argv[1]){
("Pad name not specified")
help();
return;
}
// Check if the length of the filename is at least 4 characters
if(argv[1].length <= 3){
console.log("The name of the pad should be at least 4 letters long");
help();
return;
}
// Check if the filesize is a number(should be the second argv)
let fileSize = +argv[2];
if(isNaN(fileSize)){
console.log("File size should be a number");
help();
return
}
createFile(argv[1], fileSize)
}
// If the selected action is to encrypt
if( choise === "--encrypt"){
console.log("Encrypting action chosen");
let padDataName = argv[2] ? `${argv[2].trim()}${padExtension}` : `${argv[1].trim()}${padExtension}`
// Check if the files exist
if(!argv[1] && !argv[2]){
console.log("Parameters not given");
help();
return;
}
// Check if the text file exists and the pad file
if(!existsSync(`${argv[1].trim().toLowerCase()}.txt`)){
console.log("Text file doesn't exit");
help();
return;
}
console.log("Reading file")
// Get the data from the file as well as the data from the padfile
let fileDataEnc = readFileSync(`${argv[1].trim().toLowerCase()}.txt`, 'utf-8');
if(!existsSync(`${argv[2]}${padExtension}`)){
console.log("1tp file doesn't exist, generating new 1pt file");
createFile(argv[1], fileDataEnc.length);
}
console.log("Reading 1pt file");
// Get the pad data
let padDataEnc = RetrievePadData(padDataName);
// if the file 1pt file has been specified but it's not big enough
if(fileDataEnc.length > padDataEnc.length){
console.log("The file is bigger than the 1tp file. Generating a new padfile");
createFile(argv[1], fileDataEnc.length);
padDataEnc = RetrievePadData(`${argv[1]}${padExtension}`)
}
console.log("Converting the file");
let keyEnc = padFunction(fileDataEnc,padDataEnc);
createFile(`${argv[1]}.key`, keyEnc.length, false, keyEnc);
}
if(choise === "--decrypt"){
console.log("Decrypting action chosen");
// Check if the necessary args were given
if(!argv[1]){
console.log("No file specified For decryption specified")
return;
}
if(!argv[2]){
console.log("No 1pt file was given, Please specify the file to use");
return;
}
if(!argv[3] || argv[3].trim() != '-o') {
console.log("No file for output specified");
}
let fileNameDec = `${argv[1].trim()}${keyExtension}`;
let padNameDec = `${argv[2].trim()}${padExtension}`;
// Check if the files exists or not
if(!existsSync(fileNameDec)){
console.log("File specified does not exist");
return;
}
if(!existsSync(padNameDec)){
console.log("1pt file specified doesn't exist");
return;
}
console.log("Read the encrypted file");
let fileDataDec = readFileSync(fileNameDec, 'utf-8');
console.log("Reading the 1pt file");
let padDataDec = RetrievePadData(padNameDec);
// decrypt the file
console.log("Generating the file");
let keyDec = padFunction(fileDataDec, padDataDec)
if(argv[3] && argv[3].trim()==='-o'){
let textFileDec = `${argv[1].trim()}.txt`;
if(!argv[4]){
console.log("No output file specified, creating a new file")
}
if(argv[4] && argv[4].trim().length < 3){
console.log("The name of the output file should be greater than 4 characters");
console.log(`Creating new file`)
}else {
argv[4] ? textFileDec = `${argv[4].trim()}.txt` : textFileDec = `${argv[1].trim()}.txt`
}
console.log("Generating text file");
createFile(textFileDec, 0, false, keyDec );
// https://sebhastian.com/javascript-delete-file/
console.log("Deleting encrypted file");
unlinkSync(fileNameDec);
console.log("Deleting 1pt file");
unlinkSync(padNameDec);
}else {
console.log("The decrypted file is: \n\n")
console.log(keyDec);
}
}
}else {
console.log("Invalid action");
help();
return;
}
}
/**
* Display help messages
*/
const help = ():void => {
console.log("\n\n\n1tp is a tool used to encrypt and decrypt text files");
console.log("Look at the commands below to learn the use of it");
console.log("The input file for encryption should be a txt file");
console.log("The output will be a .kye file and a .1pt file");
console.log("\n\n**Note: Don't add file extensios while running the command**");
console.log("**Note: if during creation, the application encouters a file already existing, it will overwrite the file**");
console.log("Options: ");
console.log("\t -h | --help \t\t\t\t\t\t\t View help");
console.log("\t --generate <pad name> <size of file> \t\t\t\t Create a pad file given a size");
console.log("\t --encrypt <txt file> <pad name> \t\t\t\t Encrypt a file give a pad file");
console.log("\t\t\t\t All parameters for encryption are required");
console.log("\t --decrypt <key file> <pad name> -o <txt file> \t Decrypt a file give a key and 1tp files");
console.log("\t\t\t\t If output file is not specified it will display the text inside the console");
console.log("\t\t\t\t If only the `-o` option is defined without a txt file, it will create a new file");
console.log("\n** Note: Decrypting a file will delete the key and the 1pt files**");
}
/**
* Create a file with a random key
* @param file Name of the file being created
* @param fileSize Size of the file being created
*/
const createFile = (file:string, fileSize:number = 1024, key:boolean = true, data:string = ""):void => {
let fileName:string;
if(key){
fileName = `${file.trim().toLowerCase()}${padExtension}`;
// https://flaviocopes.com/how-to-check-if-file-exists-node/#:~:text=The%20way%20to%20check%20if%20a%20file%20exists,the%20existence%20of%20a%20file%20without%20opening%20it%3A
console.log("Generating the One time pad");
const pad = generateOneTimePad(fileSize);
//https://code-boxx.com/create-save-files-javascript/#:~:text=%20The%20possible%20ways%20to%20create%20and%20save,the%20server.%0Avar%20data%20%3D%20new%20FormData...%20More%20
console.log("Writing to file");
writeFileSync(fileName, pad);
return;
}
console.log("Writing to file");
writeFileSync(file, data);
};
/**
* Generate a pad
* @param fileSize Size of the new pad being created
* @returns the new pad
*/
const generateOneTimePad = (fileSize:number):string => {
/**
* String in which we will put the one time pad
*/
let otp:string = "";
/**
* used to organize the key
*/
let splitCounter = 0;
let columnCounter = 0;
for (let i = 0; i <= fileSize;) {
if(splitCounter < 6){
// Generate a random letter from the alphabet given
otp += (stringLetter.charAt(Math.random()*1000%stringLetter.length))
splitCounter++;
i++;
continue;
}
// Used to organize the key so it looks estetic
if(columnCounter < 7){
splitCounter = 0;
columnCounter++;
otp += ("\t");
continue;
}else{
splitCounter = 0;
columnCounter = 0;
otp += ("\n");
continue;
}
}
return otp
}
/**
* Get the pad data from the file
* @returns Text pad data
*/
const RetrievePadData = (padFile:string):string => {
// Retrieve the pad data
let padData = ""
// read the file
const data = readFileSync(`${padFile}`, 'utf-8')
// Take out all the tabs and new lines we added while generating the key
const stringArray = data.toString().split("\n");
for (let index = 0; index < stringArray.length; index++) {
const element = stringArray[index].split("\t");
for (let i = 0; i < element.length; i++) {
padData += element[i];
}
}
return padData;
}
/**
* One time pad function
* @param fileData Data of the file to encrypt or decrypt
* @param padData Data of the pad file
* @returns The generated encryption or decryption
*/
const padFunction = (fileData:string, padData:string ):string => {
let key = "";
for (let i = 0; i < fileData.length; i++) {
key += String.fromCharCode(-fileData[i].charCodeAt(0)+padData[i].toLowerCase().charCodeAt(0)+97);
// console.log(`File char: ${fileData[i]} ${fileData[i].charCodeAt(0)} Pad Data: ${padData[i]} ${padData[i].toLocaleLowerCase().charCodeAt(0)} Key: ${key[i]} ${key[i].charCodeAt(0)}`)
}
return key;
}
main();
|
Subsets and Splits
Select Specific Languages Codes
Retrieves specific programming language names and codes from training data, providing basic filtering but limited analytical value beyond identifying these particular languages.