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/URL_decoding
URL decoding
This task   (the reverse of   URL encoding   and distinct from   URL parser)   is to provide a function or mechanism to convert an URL-encoded string into its original unencoded form. Test cases   The encoded string   "http%3A%2F%2Ffoo%20bar%2F"   should be reverted to the unencoded form   "http://foo bar/".   The encoded string   "google.com/search?q=%60Abdu%27l-Bah%C3%A1"   should revert to the unencoded form   "google.com/search?q=`Abdu'l-Bahá".
#BaCon
BaCon
FUNCTION Url_Decode$(url$)   LOCAL result$   SPLIT url$ BY "%" TO item$ SIZE total FOR x = 1 TO total-1 result$ = result$ & CHR$(DEC(LEFT$(item$[x], 2))) & MID$(item$[x], 3) NEXT RETURN item$[0] & result$   END FUNCTION   PRINT Url_Decode$("http%3A%2F%2Ffoo%20bar%2F") PRINT Url_Decode$("google.com/search?q=%60Abdu%27l-Bah%C3%A1")
http://rosettacode.org/wiki/URL_decoding
URL decoding
This task   (the reverse of   URL encoding   and distinct from   URL parser)   is to provide a function or mechanism to convert an URL-encoded string into its original unencoded form. Test cases   The encoded string   "http%3A%2F%2Ffoo%20bar%2F"   should be reverted to the unencoded form   "http://foo bar/".   The encoded string   "google.com/search?q=%60Abdu%27l-Bah%C3%A1"   should revert to the unencoded form   "google.com/search?q=`Abdu'l-Bahá".
#BBC_BASIC
BBC BASIC
PRINT FNurldecode("http%3A%2F%2Ffoo%20bar%2F") END   DEF FNurldecode(url$) LOCAL i% REPEAT i% = INSTR(url$, "%", i%+1) IF i% THEN url$ = LEFT$(url$,i%-1) + \ \ CHR$EVAL("&"+FNupper(MID$(url$,i%+1,2))) + \ \ MID$(url$,i%+3) ENDIF UNTIL i% = 0 = url$   DEF FNupper(A$) LOCAL A%,C% FOR A% = 1 TO LEN(A$) C% = ASCMID$(A$,A%) IF C% >= 97 IF C% <= 122 MID$(A$,A%,1) = CHR$(C%-32) NEXT = A$
http://rosettacode.org/wiki/Update_a_configuration_file
Update a configuration file
We have a configuration file as follows: # This is a configuration file in standard configuration file format # # Lines begininning with a hash or a semicolon are ignored by the application # program. Blank lines are also ignored by the application program. # The first word on each non comment line is the configuration option. # Remaining words or numbers on the line are configuration parameter # data fields. # Note that configuration option names are not case sensitive. However, # configuration parameter data is case sensitive and the lettercase must # be preserved. # This is a favourite fruit FAVOURITEFRUIT banana # This is a boolean that should be set NEEDSPEELING # This boolean is commented out ; SEEDSREMOVED # How many bananas we have NUMBEROFBANANAS 48 The task is to manipulate the configuration file as follows: Disable the needspeeling option (using a semicolon prefix) Enable the seedsremoved option by removing the semicolon and any leading whitespace Change the numberofbananas parameter to 1024 Enable (or create if it does not exist in the file) a parameter for numberofstrawberries with a value of 62000 Note that configuration option names are not case sensitive. This means that changes should be effected, regardless of the case. Options should always be disabled by prefixing them with a semicolon. Lines beginning with hash symbols should not be manipulated and left unchanged in the revised file. If a configuration option does not exist within the file (in either enabled or disabled form), it should be added during this update. Duplicate configuration option names in the file should be removed, leaving just the first entry. For the purpose of this task, the revised file should contain appropriate entries, whether enabled or not for needspeeling,seedsremoved,numberofbananas and numberofstrawberries.) The update should rewrite configuration option names in capital letters. However lines beginning with hashes and any parameter data must not be altered (eg the banana for favourite fruit must not become capitalized). The update process should also replace double semicolon prefixes with just a single semicolon (unless it is uncommenting the option, in which case it should remove all leading semicolons). Any lines beginning with a semicolon or groups of semicolons, but no following option should be removed, as should any leading or trailing whitespace on the lines. Whitespace between the option and parameters should consist only of a single space, and any non-ASCII extended characters, tabs characters, or control codes (other than end of line markers), should also be removed. Related tasks Read a configuration file
#BASIC
BASIC
  ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' Read a Configuration File V1.0 ' ' ' ' Developed by A. David Garza Marín in VB-DOS for ' ' RosettaCode. December 2, 2016. ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' '   ' OPTION EXPLICIT ' For VB-DOS, PDS 7.1 ' OPTION _EXPLICIT ' For QB64   ' SUBs and FUNCTIONs DECLARE SUB AppendCommentToConfFile (WhichFile AS STRING, WhichComment AS STRING, LeaveALine AS INTEGER) DECLARE SUB setNValToVarArr (WhichVariable AS STRING, WhichIndex AS INTEGER, WhatValue AS DOUBLE) DECLARE SUB setSValToVar (WhichVariable AS STRING, WhatValue AS STRING) DECLARE SUB setSValToVarArr (WhichVariable AS STRING, WhichIndex AS INTEGER, WhatValue AS STRING) DECLARE SUB doModifyArrValueFromConfFile (WhichFile AS STRING, WhichVariable AS STRING, WhichIndex AS INTEGER, WhatValue AS STRING, Separator AS STRING, ToComment AS INTEGER) DECLARE SUB doModifyValueFromConfFile (WhichFile AS STRING, WhichVariable AS STRING, WhatValue AS STRING, Separator AS STRING, ToComment AS INTEGER) DECLARE FUNCTION CreateConfFile% (WhichFile AS STRING) DECLARE FUNCTION ErrorMessage$ (WhichError AS INTEGER) DECLARE FUNCTION FileExists% (WhichFile AS STRING) DECLARE FUNCTION FindVarPos% (WhichVariable AS STRING) DECLARE FUNCTION FindVarPosArr% (WhichVariable AS STRING, WhichIndex AS INTEGER) DECLARE FUNCTION getArrayVariable$ (WhichVariable AS STRING, WhichIndex AS INTEGER) DECLARE FUNCTION getVariable$ (WhichVariable AS STRING) DECLARE FUNCTION getVarType% (WhatValue AS STRING) DECLARE FUNCTION GetDummyFile$ (WhichFile AS STRING) DECLARE FUNCTION HowManyElementsInTheArray% (WhichVariable AS STRING) DECLARE FUNCTION IsItAnArray% (WhichVariable AS STRING) DECLARE FUNCTION IsItTheVariableImLookingFor% (TextToAnalyze AS STRING, WhichVariable AS STRING) DECLARE FUNCTION NewValueForTheVariable$ (WhichVariable AS STRING, WhichIndex AS INTEGER, WhatValue AS STRING, Separator AS STRING) DECLARE FUNCTION ReadConfFile% (NameOfConfFile AS STRING) DECLARE FUNCTION YorN$ ()   ' Register for values located TYPE regVarValue VarName AS STRING * 20 VarType AS INTEGER ' 1=String, 2=Integer, 3=Real, 4=Comment VarValue AS STRING * 30 END TYPE   ' Var DIM rVarValue() AS regVarValue, iErr AS INTEGER, i AS INTEGER, iHMV AS INTEGER DIM iArrayElements AS INTEGER, iWhichElement AS INTEGER, iCommentStat AS INTEGER DIM iAnArray AS INTEGER, iSave AS INTEGER DIM otherfamily(1 TO 2) AS STRING DIM sVar AS STRING, sVal AS STRING, sComment AS STRING CONST ConfFileName = "config2.fil" CONST False = 0, True = NOT False   ' ------------------- Main Program ------------------------ DO CLS ERASE rVarValue PRINT "This program reads a configuration file and shows the result." PRINT PRINT "Default file name: "; ConfFileName PRINT iErr = ReadConfFile(ConfFileName) IF iErr = 0 THEN iHMV = UBOUND(rVarValue) PRINT "Variables found in file:" FOR i = 1 TO iHMV PRINT RTRIM$(rVarValue(i).VarName); " = "; RTRIM$(rVarValue(i).VarValue); " ("; SELECT CASE rVarValue(i).VarType CASE 0: PRINT "Undefined"; CASE 1: PRINT "String"; CASE 2: PRINT "Integer"; CASE 3: PRINT "Real"; CASE 4: PRINT "Is a commented variable"; END SELECT PRINT ")" NEXT i PRINT   INPUT "Type the variable name to modify (Blank=End)"; sVar sVar = RTRIM$(LTRIM$(sVar)) IF LEN(sVar) > 0 THEN i = FindVarPos%(sVar) IF i > 0 THEN ' Variable found iAnArray = IsItAnArray%(sVar) IF iAnArray THEN iArrayElements = HowManyElementsInTheArray%(sVar) PRINT "This is an array of"; iArrayElements; " elements." INPUT "Which one do you want to modify (Default=1)"; iWhichElement IF iWhichElement = 0 THEN iWhichElement = 1 ELSE iArrayElements = 1 iWhichElement = 1 END IF PRINT "The current value of the variable is: " IF iAnArray THEN PRINT sVar; "("; iWhichElement; ") = "; RTRIM$(rVarValue(i + (iWhichElement - 1)).VarValue) ELSE PRINT sVar; " = "; RTRIM$(rVarValue(i + (iWhichElement - 1)).VarValue) END IF ELSE PRINT "The variable was not found. It will be added." END IF PRINT INPUT "Please, set the new value for the variable (Blank=Unmodified)"; sVal sVal = RTRIM$(LTRIM$(sVal)) IF i > 0 THEN IF rVarValue(i + (iWhichElement - 1)).VarType = 4 THEN PRINT "Do you want to remove the comment status to the variable? (Y/N)" iCommentStat = NOT (YorN = "Y") iCommentStat = ABS(iCommentStat) ' Gets 0 (Toggle) or 1 (Leave unmodified) iSave = (iCommentStat = 0) ELSE PRINT "Do you want to toggle the variable as a comment? (Y/N)" iCommentStat = (YorN = "Y") ' Gets 0 (Uncommented) or -1 (Toggle as a Comment) iSave = iCommentStat END IF END IF   ' Now, update or add the variable to the conf file IF i > 0 THEN IF sVal = "" THEN sVal = RTRIM$(rVarValue(i).VarValue) END IF ELSE PRINT "The variable will be added to the configuration file." PRINT "Do you want to add a remark for it? (Y/N)" IF YorN$ = "Y" THEN LINE INPUT "Please, write your remark: ", sComment sComment = LTRIM$(RTRIM$(sComment)) IF sComment <> "" THEN AppendCommentToConfFile ConfFileName, sComment, True END IF END IF END IF   ' Verifies if the variable will be modified, and applies the modification IF sVal <> "" OR iSave THEN IF iWhichElement > 1 THEN setSValToVarArr sVar, iWhichElement, sVal doModifyArrValueFromConfFile ConfFileName, sVar, iWhichElement, sVal, " ", iCommentStat ELSE setSValToVar sVar, sVal doModifyValueFromConfFile ConfFileName, sVar, sVal, " ", iCommentStat END IF END IF   END IF ELSE PRINT ErrorMessage$(iErr) END IF PRINT PRINT "Do you want to add or modify another variable? (Y/N)" LOOP UNTIL YorN$ = "N" ' --------- End of Main Program ----------------------- PRINT PRINT "End of program." END   FileError: iErr = ERR RESUME NEXT   SUB AppendCommentToConfFile (WhichFile AS STRING, WhichComment AS STRING, LeaveALine AS INTEGER) ' Parameters: ' WhichFile: Name of the file where a comment will be appended. ' WhichComment: A comment. It is suggested to add a comment no larger than 75 characters. ' This procedure adds a # at the beginning of the string if there is no # ' sign on it in order to ensure it will be added as a comment.   ' Var DIM iFil AS INTEGER   iFil = FileExists%(WhichFile) IF NOT iFil THEN iFil = CreateConfFile%(WhichFile) ' Here, iFil is used as dummy to save memory END IF   IF iFil THEN ' Everything is Ok iFil = FREEFILE ' Now, iFil is used to be the ID of the file WhichComment = LTRIM$(RTRIM$(WhichComment))   IF LEFT$(WhichComment, 1) <> "#" THEN ' Is it in comment format? WhichComment = "# " + WhichComment END IF   ' Append the comment to the file OPEN WhichFile FOR APPEND AS #iFil IF LeaveALine THEN PRINT #iFil, "" END IF PRINT #iFil, WhichComment CLOSE #iFil END IF   END SUB   FUNCTION CreateConfFile% (WhichFile AS STRING) ' Var DIM iFile AS INTEGER   ON ERROR GOTO FileError   iFile = FREEFILE OPEN WhichFile FOR OUTPUT AS #iFile CLOSE iFile   ON ERROR GOTO 0   CreateConfFile = FileExists%(WhichFile) END FUNCTION   SUB doModifyArrValueFromConfFile (WhichFile AS STRING, WhichVariable AS STRING, WhichIndex AS INTEGER, WhatValue AS STRING, Separator AS STRING, ToComment AS INTEGER) ' Parameters: ' WhichFile: The name of the Configuration File. It can include the full path. ' WhichVariable: The name of the variable to be modified or added to the conf file. ' WhichIndex: The index number of the element to be modified in a matrix (Default=1) ' WhatValue: The new value to set in the variable specified in WhichVariable. ' Separator: The separator between the variable name and its value in the conf file. Defaults to a space " ". ' ToComment: A value to set or remove the comment mode of a variable: -1=Toggle to Comment, 0=Toggle to not comment, 1=Leave as it is.   ' Var DIM iFile AS INTEGER, iFile2 AS INTEGER, iError AS INTEGER DIM iMod AS INTEGER, iIsComment AS INTEGER DIM sLine AS STRING, sDummyFile AS STRING, sChar AS STRING   ' If conf file doesn't exists, create one. iError = 0 iMod = 0 IF NOT FileExists%(WhichFile) THEN iError = CreateConfFile%(WhichFile) END IF   IF NOT iError THEN ' File exists or it was created Separator = RTRIM$(LTRIM$(Separator)) IF Separator = "" THEN Separator = " " ' Defaults to Space END IF sDummyFile = GetDummyFile$(WhichFile)   ' It is assumed a text file iFile = FREEFILE OPEN WhichFile FOR INPUT AS #iFile   iFile2 = FREEFILE OPEN sDummyFile FOR OUTPUT AS #iFile2   ' Goes through the file to find the variable DO WHILE NOT EOF(iFile) LINE INPUT #iFile, sLine sLine = RTRIM$(LTRIM$(sLine)) sChar = LEFT$(sLine, 1) iIsComment = (sChar = ";") IF iIsComment THEN ' Variable is commented sLine = LTRIM$(MID$(sLine, 2)) END IF   IF sChar <> "#" AND LEN(sLine) > 0 THEN ' Is not a comment? IF IsItTheVariableImLookingFor%(sLine, WhichVariable) THEN sLine = NewValueForTheVariable$(WhichVariable, WhichIndex, WhatValue, Separator) iMod = True IF ToComment = True THEN sLine = "; " + sLine END IF ELSEIF iIsComment THEN sLine = "; " + sLine END IF   END IF   PRINT #iFile2, sLine LOOP   ' Reviews if a modification was done, if not, then it will ' add the variable to the file. IF NOT iMod THEN sLine = NewValueForTheVariable$(WhichVariable, 1, WhatValue, Separator) PRINT #iFile2, sLine END IF CLOSE iFile2, iFile   ' Removes the conf file and sets the dummy file as the conf file KILL WhichFile NAME sDummyFile AS WhichFile END IF   END SUB   SUB doModifyValueFromConfFile (WhichFile AS STRING, WhichVariable AS STRING, WhatValue AS STRING, Separator AS STRING, ToComment AS INTEGER) ' To see details of parameters, please see doModifyArrValueFromConfFile doModifyArrValueFromConfFile WhichFile, WhichVariable, 1, WhatValue, Separator, ToComment END SUB   FUNCTION ErrorMessage$ (WhichError AS INTEGER) ' Var DIM sError AS STRING   SELECT CASE WhichError CASE 0: sError = "Everything went ok." CASE 1: sError = "Configuration file doesn't exist." CASE 2: sError = "There are no variables in the given file." END SELECT   ErrorMessage$ = sError END FUNCTION   FUNCTION FileExists% (WhichFile AS STRING) ' Var DIM iFile AS INTEGER DIM iItExists AS INTEGER SHARED iErr AS INTEGER   ON ERROR GOTO FileError iFile = FREEFILE iErr = 0 OPEN WhichFile FOR BINARY AS #iFile IF iErr = 0 THEN iItExists = LOF(iFile) > 0 CLOSE #iFile   IF NOT iItExists THEN KILL WhichFile END IF END IF ON ERROR GOTO 0 FileExists% = iItExists   END FUNCTION   FUNCTION FindVarPos% (WhichVariable AS STRING) ' Will find the position of the variable FindVarPos% = FindVarPosArr%(WhichVariable, 1) END FUNCTION   FUNCTION FindVarPosArr% (WhichVariable AS STRING, WhichIndex AS INTEGER) ' Var DIM i AS INTEGER, iHMV AS INTEGER, iCount AS INTEGER, iPos AS INTEGER DIM sVar AS STRING, sVal AS STRING, sWV AS STRING SHARED rVarValue() AS regVarValue   ' Looks for a variable name and returns its position iHMV = UBOUND(rVarValue) sWV = UCASE$(LTRIM$(RTRIM$(WhichVariable))) sVal = "" iCount = 0 DO i = i + 1 sVar = UCASE$(RTRIM$(rVarValue(i).VarName)) IF sVar = sWV THEN iCount = iCount + 1 IF iCount = WhichIndex THEN iPos = i END IF END IF LOOP UNTIL i >= iHMV OR iPos > 0   FindVarPosArr% = iPos END FUNCTION   FUNCTION getArrayVariable$ (WhichVariable AS STRING, WhichIndex AS INTEGER) ' Var DIM i AS INTEGER DIM sVal AS STRING SHARED rVarValue() AS regVarValue   i = FindVarPosArr%(WhichVariable, WhichIndex) sVal = "" IF i > 0 THEN sVal = RTRIM$(rVarValue(i).VarValue) END IF   ' Found it or not, it will return the result. ' If the result is "" then it didn't found the requested variable. getArrayVariable$ = sVal   END FUNCTION   FUNCTION GetDummyFile$ (WhichFile AS STRING) ' Var DIM i AS INTEGER, j AS INTEGER   ' Gets the path specified in WhichFile i = 1 DO j = INSTR(i, WhichFile, "\") IF j > 0 THEN i = j + 1 LOOP UNTIL j = 0   GetDummyFile$ = LEFT$(WhichFile, i - 1) + "$dummyf$.tmp" END FUNCTION   FUNCTION getVariable$ (WhichVariable AS STRING) ' Var DIM i AS INTEGER, iHMV AS INTEGER DIM sVal AS STRING   ' For a single variable, looks in the first (and only) ' element of the array that contains the name requested. sVal = getArrayVariable$(WhichVariable, 1)   getVariable$ = sVal END FUNCTION   FUNCTION getVarType% (WhatValue AS STRING) ' Var DIM sValue AS STRING, dValue AS DOUBLE, iType AS INTEGER   sValue = RTRIM$(WhatValue) iType = 0 IF LEN(sValue) > 0 THEN IF ASC(LEFT$(sValue, 1)) < 48 OR ASC(LEFT$(sValue, 1)) > 57 THEN iType = 1 ' String ELSE dValue = VAL(sValue) IF CLNG(dValue) = dValue THEN iType = 2 ' Integer ELSE iType = 3 ' Real END IF END IF END IF   getVarType% = iType END FUNCTION   FUNCTION HowManyElementsInTheArray% (WhichVariable AS STRING) ' Var DIM i AS INTEGER, iHMV AS INTEGER, iCount AS INTEGER, iPos AS INTEGER, iQuit AS INTEGER DIM sVar AS STRING, sVal AS STRING, sWV AS STRING SHARED rVarValue() AS regVarValue   ' Looks for a variable name and returns its value iHMV = UBOUND(rVarValue) sWV = UCASE$(LTRIM$(RTRIM$(WhichVariable))) sVal = ""   ' Look for all instances of WhichVariable in the ' list. This is because elements of an array will not alwasy ' be one after another, but alternate. FOR i = 1 TO iHMV sVar = UCASE$(RTRIM$(rVarValue(i).VarName)) IF sVar = sWV THEN iCount = iCount + 1 END IF NEXT i   HowManyElementsInTheArray = iCount END FUNCTION   FUNCTION IsItAnArray% (WhichVariable AS STRING) ' Returns if a Variable is an Array IsItAnArray% = (HowManyElementsInTheArray%(WhichVariable) > 1)   END FUNCTION   FUNCTION IsItTheVariableImLookingFor% (TextToAnalyze AS STRING, WhichVariable AS STRING) ' Var DIM sVar AS STRING, sDT AS STRING, sDV AS STRING DIM iSep AS INTEGER   sDT = UCASE$(RTRIM$(LTRIM$(TextToAnalyze))) sDV = UCASE$(RTRIM$(LTRIM$(WhichVariable))) iSep = INSTR(sDT, "=") IF iSep = 0 THEN iSep = INSTR(sDT, " ") IF iSep > 0 THEN sVar = RTRIM$(LEFT$(sDT, iSep - 1)) ELSE sVar = sDT END IF   ' It will return True or False IsItTheVariableImLookingFor% = (sVar = sDV) END FUNCTION   FUNCTION NewValueForTheVariable$ (WhichVariable AS STRING, WhichIndex AS INTEGER, WhatValue AS STRING, Separator AS STRING) ' Var DIM iItem AS INTEGER, iItems AS INTEGER, iFirstItem AS INTEGER DIM i AS INTEGER, iCount AS INTEGER, iHMV AS INTEGER DIM sLine AS STRING, sVar AS STRING, sVar2 AS STRING SHARED rVarValue() AS regVarValue   IF IsItAnArray%(WhichVariable) THEN iItems = HowManyElementsInTheArray(WhichVariable) iFirstItem = FindVarPosArr%(WhichVariable, 1) ELSE iItems = 1 iFirstItem = FindVarPos%(WhichVariable) END IF iItem = FindVarPosArr%(WhichVariable, WhichIndex) sLine = "" sVar = UCASE$(WhichVariable) iHMV = UBOUND(rVarValue)   IF iItem > 0 THEN i = iFirstItem DO sVar2 = UCASE$(RTRIM$(rVarValue(i).VarName))   IF sVar = sVar2 THEN ' Does it found an element of the array? iCount = iCount + 1 IF LEN(sLine) > 0 THEN ' Add a comma sLine = sLine + ", " END IF IF i = iItem THEN sLine = sLine + WhatValue ELSE sLine = sLine + RTRIM$(rVarValue(i).VarValue) END IF END IF i = i + 1 LOOP UNTIL i > iHMV OR iCount = iItems   sLine = WhichVariable + Separator + sLine ELSE sLine = WhichVariable + Separator + WhatValue END IF   NewValueForTheVariable$ = sLine END FUNCTION   FUNCTION ReadConfFile% (NameOfConfFile AS STRING) ' Var DIM iFile AS INTEGER, iType AS INTEGER, iVar AS INTEGER, iHMV AS INTEGER DIM iVal AS INTEGER, iCurVar AS INTEGER, i AS INTEGER, iErr AS INTEGER DIM dValue AS DOUBLE, iIsComment AS INTEGER DIM sLine AS STRING, sVar AS STRING, sValue AS STRING SHARED rVarValue() AS regVarValue   ' This procedure reads a configuration file with variables ' and values separated by the equal sign (=) or a space. ' It needs the FileExists% function. ' Lines begining with # or blank will be ignored. IF FileExists%(NameOfConfFile) THEN iFile = FREEFILE REDIM rVarValue(1 TO 10) AS regVarValue OPEN NameOfConfFile FOR INPUT AS #iFile WHILE NOT EOF(iFile) LINE INPUT #iFile, sLine sLine = RTRIM$(LTRIM$(sLine)) IF LEN(sLine) > 0 THEN ' Does it have any content? IF LEFT$(sLine, 1) <> "#" THEN ' Is not a comment? iIsComment = (LEFT$(sLine, 1) = ";") IF iIsComment THEN ' It is a commented variable sLine = LTRIM$(MID$(sLine, 2)) END IF iVar = INSTR(sLine, "=") ' Is there an equal sign? IF iVar = 0 THEN iVar = INSTR(sLine, " ") ' if not then is there a space?   GOSUB AddASpaceForAVariable iCurVar = iHMV IF iVar > 0 THEN ' Is a variable and a value rVarValue(iHMV).VarName = LEFT$(sLine, iVar - 1) ELSE ' Is just a variable name rVarValue(iHMV).VarName = sLine rVarValue(iHMV).VarValue = "" END IF   IF iVar > 0 THEN ' Get the value(s) sLine = LTRIM$(MID$(sLine, iVar + 1)) DO ' Look for commas iVal = INSTR(sLine, ",") IF iVal > 0 THEN ' There is a comma rVarValue(iHMV).VarValue = RTRIM$(LEFT$(sLine, iVal - 1)) GOSUB AddASpaceForAVariable rVarValue(iHMV).VarName = rVarValue(iHMV - 1).VarName ' Repeats the variable name sLine = LTRIM$(MID$(sLine, iVal + 1)) END IF LOOP UNTIL iVal = 0 rVarValue(iHMV).VarValue = sLine   END IF   ' Determine the variable type of each variable found in this step FOR i = iCurVar TO iHMV IF iIsComment THEN rVarValue(i).VarType = 4 ' Is a comment ELSE GOSUB DetermineVariableType END IF NEXT i   END IF END IF WEND CLOSE iFile IF iHMV > 0 THEN REDIM PRESERVE rVarValue(1 TO iHMV) AS regVarValue iErr = 0 ' Everything ran ok. ELSE REDIM rVarValue(1 TO 1) AS regVarValue iErr = 2 ' No variables found in configuration file END IF ELSE iErr = 1 ' File doesn't exist END IF   ReadConfFile = iErr   EXIT FUNCTION   AddASpaceForAVariable: iHMV = iHMV + 1   IF UBOUND(rVarValue) < iHMV THEN ' Are there space for a new one? REDIM PRESERVE rVarValue(1 TO iHMV + 9) AS regVarValue END IF RETURN   DetermineVariableType: sValue = RTRIM$(rVarValue(i).VarValue) IF LEN(sValue) > 0 THEN IF ASC(LEFT$(sValue, 1)) < 48 OR ASC(LEFT$(sValue, 1)) > 57 THEN rVarValue(i).VarType = 1 ' String ELSE dValue = VAL(sValue) IF CLNG(dValue) = dValue THEN rVarValue(i).VarType = 2 ' Integer ELSE rVarValue(i).VarType = 3 ' Real END IF END IF END IF RETURN   END FUNCTION   SUB setNValToVar (WhichVariable AS STRING, WhatValue AS DOUBLE) ' Sets a numeric value to a variable setNValToVarArr WhichVariable, 1, WhatValue END SUB   SUB setNValToVarArr (WhichVariable AS STRING, WhichIndex AS INTEGER, WhatValue AS DOUBLE) ' Sets a numeric value to a variable array ' Var DIM sVal AS STRING sVal = FORMAT$(WhatValue) setSValToVarArr WhichVariable, WhichIndex, sVal END SUB   SUB setSValToVar (WhichVariable AS STRING, WhatValue AS STRING) ' Sets a string value to a variable setSValToVarArr WhichVariable, 1, WhatValue END SUB   SUB setSValToVarArr (WhichVariable AS STRING, WhichIndex AS INTEGER, WhatValue AS STRING) ' Sets a string value to a variable array ' Var DIM i AS INTEGER DIM sVar AS STRING SHARED rVarValue() AS regVarValue   i = FindVarPosArr%(WhichVariable, WhichIndex) IF i = 0 THEN ' Should add the variable IF UBOUND(rVarValue) > 0 THEN sVar = RTRIM$(rVarValue(1).VarName) IF sVar <> "" THEN i = UBOUND(rVarValue) + 1 REDIM PRESERVE rVarValue(1 TO i) AS regVarValue ELSE i = 1 END IF ELSE REDIM rVarValue(1 TO i) AS regVarValue END IF rVarValue(i).VarName = WhichVariable END IF   ' Sets the new value to the variable rVarValue(i).VarValue = WhatValue rVarValue(i).VarType = getVarType%(WhatValue) END SUB   FUNCTION YorN$ () ' Var DIM sYorN AS STRING   DO sYorN = UCASE$(INPUT$(1)) IF INSTR("YN", sYorN) = 0 THEN BEEP END IF LOOP UNTIL sYorN = "Y" OR sYorN = "N"   YorN$ = sYorN END FUNCTION  
http://rosettacode.org/wiki/User_input/Text
User input/Text
User input/Text is part of Short Circuit's Console Program Basics selection. Task Input a string and the integer   75000   from the text console. See also: User input/Graphical
#AWK
AWK
~/src/opt/run $ awk 'BEGIN{printf "enter a string: "}{s=$0;i=$0+0;print "ok,"s"/"i}' enter a string: hello world ok,hello world/0 75000 ok,75000/75000
http://rosettacode.org/wiki/User_input/Text
User input/Text
User input/Text is part of Short Circuit's Console Program Basics selection. Task Input a string and the integer   75000   from the text console. See also: User input/Graphical
#Axe
Axe
Disp "String:" input→A length(A)→L   .Copy the string to a safe location Copy(A,L₁,L)   .Display the string Disp "You entered:",i For(I,0,L-1) Disp {L₁+I}►Char End Disp i   Disp "Integer:",i input→B length(B)→L   .Parse the string and convert to an integer 0→C For(I,0,L-1) {B+I}-'0'→N If N>10 .Error checking Disp "Not a number",i Return End C*10+N→C End   .Display and check the integer Disp "You entered:",i,C►Dec,i If C≠7500 Disp "That isn't 7500" End
http://rosettacode.org/wiki/User_input/Graphical
User input/Graphical
In this task, the goal is to input a string and the integer 75000, from graphical user interface. See also: User input/Text
#BaCon
BaCon
OPTION GUI TRUE PRAGMA GUI gtk3   DECLARE text TYPE STRING DECLARE data TYPE FLOATING   gui = GUIDEFINE(" \ { type=WINDOW name=window callback=delete-event title=\"Rosetta Code\" width-request=300 } \ { type=BOX name=box parent=window orientation=GTK_ORIENTATION_VERTICAL } \ { type=ENTRY name=entry parent=box margin=4 callback=activate } \ { type=SPIN_BUTTON name=spin parent=box margin=4 numeric=TRUE } \ { type=BUTTON_BOX name=bbox parent=box } \ { type=BUTTON name=button parent=bbox margin=4 callback=clicked label=\"Exit\" }")   CALL GUISET(gui, "spin", "adjustment", gtk_adjustment_new(75000, 0, 100000, 1, 1, 0))   REPEAT event$ = GUIEVENT$(gui) UNTIL event$ = "button" OR event$ = "window"   CALL GUIGET(gui, "entry", "text", &text) PRINT text FORMAT "Entered: %s\n"   CALL GUIGET(gui, "spin", "value", &data) PRINT data FORMAT "Entered: %g\n"
http://rosettacode.org/wiki/User_input/Graphical
User input/Graphical
In this task, the goal is to input a string and the integer 75000, from graphical user interface. See also: User input/Text
#BBC_BASIC
BBC BASIC
INSTALL @lib$+"WINLIB2" INSTALL @lib$+"WINLIB5" ES_NUMBER = 8192   form% = FN_newdialog("Rosetta Code", 100, 100, 100, 64, 8, 1000) PROC_static(form%, "String:", 100, 8, 8, 30, 14, 0) PROC_editbox(form%, "Example", 101, 40, 6, 52, 14, 0) PROC_static(form%, "Number:", 102, 8, 26, 30, 14, 0) PROC_editbox(form%, "75000", 103, 40, 24, 52, 14, ES_NUMBER) PROC_pushbutton(form%, "Read", FN_setproc(PROCread), 30, 43, 40, 16, 0) PROC_showdialog(form%)   REPEAT WAIT 1 UNTIL !form% = 0 QUIT   DEF PROCread LOCAL buffer%, number% DIM buffer% LOCAL 255 SYS "GetDlgItemText", !form%, 101, buffer%, 255 SYS "GetDlgItemInt", !form%, 103, 0, 1 TO number% PRINT "String = """ $$buffer% """" PRINT "Number = " ; number% ENDPROC
http://rosettacode.org/wiki/UTF-8_encode_and_decode
UTF-8 encode and decode
As described in UTF-8 and in Wikipedia, UTF-8 is a popular encoding of (multi-byte) Unicode code-points into eight-bit octets. The goal of this task is to write a encoder that takes a unicode code-point (an integer representing a unicode character) and returns a sequence of 1-4 bytes representing that character in the UTF-8 encoding. Then you have to write the corresponding decoder that takes a sequence of 1-4 UTF-8 encoded bytes and return the corresponding unicode character. Demonstrate the functionality of your encoder and decoder on the following five characters: Character Name Unicode UTF-8 encoding (hex) --------------------------------------------------------------------------------- A LATIN CAPITAL LETTER A U+0041 41 ö LATIN SMALL LETTER O WITH DIAERESIS U+00F6 C3 B6 Ж CYRILLIC CAPITAL LETTER ZHE U+0416 D0 96 € EURO SIGN U+20AC E2 82 AC 𝄞 MUSICAL SYMBOL G CLEF U+1D11E F0 9D 84 9E Provided below is a reference implementation in Common Lisp.
#BaCon
BaCon
DECLARE x TYPE STRING   CONST letter$ = "A ö Ж € 𝄞"   PRINT "Char", TAB$(1), "Unicode", TAB$(2), "UTF-8 (hex)" PRINT "-----------------------------------"   FOR x IN letter$ PRINT x, TAB$(1), "U+", HEX$(UCS(x)), TAB$(2), COIL$(LEN(x), HEX$(x[_-1] & 255)) NEXT
http://rosettacode.org/wiki/UTF-8_encode_and_decode
UTF-8 encode and decode
As described in UTF-8 and in Wikipedia, UTF-8 is a popular encoding of (multi-byte) Unicode code-points into eight-bit octets. The goal of this task is to write a encoder that takes a unicode code-point (an integer representing a unicode character) and returns a sequence of 1-4 bytes representing that character in the UTF-8 encoding. Then you have to write the corresponding decoder that takes a sequence of 1-4 UTF-8 encoded bytes and return the corresponding unicode character. Demonstrate the functionality of your encoder and decoder on the following five characters: Character Name Unicode UTF-8 encoding (hex) --------------------------------------------------------------------------------- A LATIN CAPITAL LETTER A U+0041 41 ö LATIN SMALL LETTER O WITH DIAERESIS U+00F6 C3 B6 Ж CYRILLIC CAPITAL LETTER ZHE U+0416 D0 96 € EURO SIGN U+20AC E2 82 AC 𝄞 MUSICAL SYMBOL G CLEF U+1D11E F0 9D 84 9E Provided below is a reference implementation in Common Lisp.
#C
C
  #include <stdio.h> #include <stdlib.h> #include <inttypes.h>   typedef struct { char mask; /* char data will be bitwise AND with this */ char lead; /* start bytes of current char in utf-8 encoded character */ uint32_t beg; /* beginning of codepoint range */ uint32_t end; /* end of codepoint range */ int bits_stored; /* the number of bits from the codepoint that fits in char */ }utf_t;   utf_t * utf[] = { /* mask lead beg end bits */ [0] = &(utf_t){0b00111111, 0b10000000, 0, 0, 6 }, [1] = &(utf_t){0b01111111, 0b00000000, 0000, 0177, 7 }, [2] = &(utf_t){0b00011111, 0b11000000, 0200, 03777, 5 }, [3] = &(utf_t){0b00001111, 0b11100000, 04000, 0177777, 4 }, [4] = &(utf_t){0b00000111, 0b11110000, 0200000, 04177777, 3 }, &(utf_t){0}, };   /* All lengths are in bytes */ int codepoint_len(const uint32_t cp); /* len of associated utf-8 char */ int utf8_len(const char ch); /* len of utf-8 encoded char */   char *to_utf8(const uint32_t cp); uint32_t to_cp(const char chr[4]);   int codepoint_len(const uint32_t cp) { int len = 0; for(utf_t **u = utf; *u; ++u) { if((cp >= (*u)->beg) && (cp <= (*u)->end)) { break; } ++len; } if(len > 4) /* Out of bounds */ exit(1);   return len; }   int utf8_len(const char ch) { int len = 0; for(utf_t **u = utf; *u; ++u) { if((ch & ~(*u)->mask) == (*u)->lead) { break; } ++len; } if(len > 4) { /* Malformed leading byte */ exit(1); } return len; }   char *to_utf8(const uint32_t cp) { static char ret[5]; const int bytes = codepoint_len(cp);   int shift = utf[0]->bits_stored * (bytes - 1); ret[0] = (cp >> shift & utf[bytes]->mask) | utf[bytes]->lead; shift -= utf[0]->bits_stored; for(int i = 1; i < bytes; ++i) { ret[i] = (cp >> shift & utf[0]->mask) | utf[0]->lead; shift -= utf[0]->bits_stored; } ret[bytes] = '\0'; return ret; }   uint32_t to_cp(const char chr[4]) { int bytes = utf8_len(*chr); int shift = utf[0]->bits_stored * (bytes - 1); uint32_t codep = (*chr++ & utf[bytes]->mask) << shift;   for(int i = 1; i < bytes; ++i, ++chr) { shift -= utf[0]->bits_stored; codep |= ((char)*chr & utf[0]->mask) << shift; }   return codep; }   int main(void) { const uint32_t *in, input[] = {0x0041, 0x00f6, 0x0416, 0x20ac, 0x1d11e, 0x0};   printf("Character Unicode UTF-8 encoding (hex)\n"); printf("----------------------------------------\n");   char *utf8; uint32_t codepoint; for(in = input; *in; ++in) { utf8 = to_utf8(*in); codepoint = to_cp(utf8); printf("%s U+%-7.4x", utf8, codepoint);   for(int i = 0; utf8[i] && i < 4; ++i) { printf("%hhx ", utf8[i]); } printf("\n"); } return 0; }  
http://rosettacode.org/wiki/Use_another_language_to_call_a_function
Use another language to call a function
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. This task is inverse to the task Call foreign language function. Consider the following C program: #include <stdio.h>   extern int Query (char * Data, size_t * Length);   int main (int argc, char * argv []) { char Buffer [1024]; size_t Size = sizeof (Buffer);   if (0 == Query (Buffer, &Size)) { printf ("failed to call Query\n"); } else { char * Ptr = Buffer; while (Size-- > 0) putchar (*Ptr++); putchar ('\n'); } } Implement the missing Query function in your language, and let this C program call it. The function should place the string Here am I into the buffer which is passed to it as the parameter Data. The buffer size in bytes is passed as the parameter Length. When there is no room in the buffer, Query shall return 0. Otherwise it overwrites the beginning of Buffer, sets the number of overwritten bytes into Length and returns 1.
#Haskell
Haskell
#ifdef __GLASGOW_HASKELL__ #include "Called_stub.h" extern void __stginit_Called(void); #endif #include <stdio.h> #include <HsFFI.h>   int main (int argc, char * argv []) { char Buffer [1024]; size_t Size = sizeof (Buffer);   hs_init(&argc, &argv); #ifdef __GLASGOW_HASKELL__ hs_add_root(__stginit_Called); #endif   if (0 == query_hs (Buffer, &Size)) { printf ("failed to call Query\n"); } else { char * Ptr = Buffer; while (Size-- > 0) putchar (*Ptr++); putchar ('\n'); }   hs_exit(); return 0; }
http://rosettacode.org/wiki/Use_another_language_to_call_a_function
Use another language to call a function
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. This task is inverse to the task Call foreign language function. Consider the following C program: #include <stdio.h>   extern int Query (char * Data, size_t * Length);   int main (int argc, char * argv []) { char Buffer [1024]; size_t Size = sizeof (Buffer);   if (0 == Query (Buffer, &Size)) { printf ("failed to call Query\n"); } else { char * Ptr = Buffer; while (Size-- > 0) putchar (*Ptr++); putchar ('\n'); } } Implement the missing Query function in your language, and let this C program call it. The function should place the string Here am I into the buffer which is passed to it as the parameter Data. The buffer size in bytes is passed as the parameter Length. When there is no room in the buffer, Query shall return 0. Otherwise it overwrites the beginning of Buffer, sets the number of overwritten bytes into Length and returns 1.
#Haxe
Haxe
untyped __call__("functionName", args);
http://rosettacode.org/wiki/URL_parser
URL parser
URLs are strings with a simple syntax: scheme://[username:password@]domain[:port]/path?query_string#fragment_id Task Parse a well-formed URL to retrieve the relevant information:   scheme, domain, path, ... Note:   this task has nothing to do with URL encoding or URL decoding. According to the standards, the characters:    ! * ' ( ) ; : @ & = + $ , / ? % # [ ] only need to be percent-encoded   (%)   in case of possible confusion. Also note that the path, query and fragment are case sensitive, even if the scheme and domain are not. The way the returned information is provided (set of variables, array, structured, record, object,...) is language-dependent and left to the programmer, but the code should be clear enough to reuse. Extra credit is given for clear error diagnostics.   Here is the official standard:     https://tools.ietf.org/html/rfc3986,   and here is a simpler   BNF:     http://www.w3.org/Addressing/URL/5_URI_BNF.html. Test cases According to T. Berners-Lee foo://example.com:8042/over/there?name=ferret#nose     should parse into:   scheme = foo   domain = example.com   port = :8042   path = over/there   query = name=ferret   fragment = nose urn:example:animal:ferret:nose     should parse into:   scheme = urn   path = example:animal:ferret:nose other URLs that must be parsed include:   jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true   ftp://ftp.is.co.za/rfc/rfc1808.txt   http://www.ietf.org/rfc/rfc2396.txt#header1   ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two   mailto:[email protected]   news:comp.infosystems.www.servers.unix   tel:+1-816-555-1212   telnet://192.0.2.16:80/   urn:oasis:names:specification:docbook:dtd:xml:4.1.2
#J
J
split=:1 :0 ({. ; ] }.~ 1+[)~ i.&m )   uriparts=:3 :0 'server fragment'=. '#' split y 'sa query'=. '?' split server 'scheme authpath'=. ':' split sa scheme;authpath;query;fragment )   queryparts=:3 :0 (0<#y)#<;._1 '?',y )   authpathparts=:3 :0 if. '//' -: 2{.y do. split=. <;.1 y (}.1{::split);;2}.split else. '';y end. )   authparts=:3 :0 if. '@' e. y do. 'userinfo hostport'=. '@' split y else. hostport=. y [ userinfo=.'' end. if. '[' = {.hostport do. 'host_t port_t'=. ']' split hostport assert. (0=#port_t)+.':'={.port_t (':' split userinfo),(host_t,']');}.port_t else. (':' split userinfo),':' split hostport end. )   taskparts=:3 :0 'scheme authpath querystring fragment'=. uriparts y 'auth path'=. authpathparts authpath 'user creds host port'=. authparts auth query=. queryparts querystring export=. ;:'scheme user creds host port path query fragment' (#~ 0<#@>@{:"1) (,. do each) export )
http://rosettacode.org/wiki/URL_encoding
URL encoding
Task Provide a function or mechanism to convert a provided string into URL encoding representation. In URL encoding, special characters, control characters and extended characters are converted into a percent symbol followed by a two digit hexadecimal code, So a space character encodes into %20 within the string. For the purposes of this task, every character except 0-9, A-Z and a-z requires conversion, so the following characters all require conversion by default: ASCII control codes (Character ranges 00-1F hex (0-31 decimal) and 7F (127 decimal). ASCII symbols (Character ranges 32-47 decimal (20-2F hex)) ASCII symbols (Character ranges 58-64 decimal (3A-40 hex)) ASCII symbols (Character ranges 91-96 decimal (5B-60 hex)) ASCII symbols (Character ranges 123-126 decimal (7B-7E hex)) Extended characters with character codes of 128 decimal (80 hex) and above. Example The string "http://foo bar/" would be encoded as "http%3A%2F%2Ffoo%20bar%2F". Variations Lowercase escapes are legal, as in "http%3a%2f%2ffoo%20bar%2f". Some standards give different rules: RFC 3986, Uniform Resource Identifier (URI): Generic Syntax, section 2.3, says that "-._~" should not be encoded. HTML 5, section 4.10.22.5 URL-encoded form data, says to preserve "-._*", and to encode space " " to "+". The options below provide for utilization of an exception string, enabling preservation (non encoding) of particular characters to meet specific standards. Options It is permissible to use an exception string (containing a set of symbols that do not need to be converted). However, this is an optional feature and is not a requirement of this task. Related tasks   URL decoding   URL parser
#Clojure
Clojure
(import 'java.net.URLEncoder) (URLEncoder/encode "http://foo bar/" "UTF-8")
http://rosettacode.org/wiki/Variables
Variables
Task Demonstrate a language's methods of:   variable declaration   initialization   assignment   datatypes   scope   referencing,     and   other variable related facilities
#COBOL
COBOL
MOVE 5 TO x MOVE FUNCTION SOME-FUNC(x) TO y MOVE "foo" TO z MOVE "values 1234" TO group-item SET some-index TO 5
http://rosettacode.org/wiki/Van_Eck_sequence
Van Eck sequence
The sequence is generated by following this pseudo-code: A: The first term is zero. Repeatedly apply: If the last term is *new* to the sequence so far then: B: The next term is zero. Otherwise: C: The next term is how far back this last term occured previously. Example Using A: 0 Using B: 0 0 Using C: 0 0 1 Using B: 0 0 1 0 Using C: (zero last occurred two steps back - before the one) 0 0 1 0 2 Using B: 0 0 1 0 2 0 Using C: (two last occurred two steps back - before the zero) 0 0 1 0 2 0 2 2 Using C: (two last occurred one step back) 0 0 1 0 2 0 2 2 1 Using C: (one last appeared six steps back) 0 0 1 0 2 0 2 2 1 6 ... Task Create a function/procedure/method/subroutine/... to generate the Van Eck sequence of numbers. Use it to display here, on this page: The first ten terms of the sequence. Terms 991 - to - 1000 of the sequence. References Don't Know (the Van Eck Sequence) - Numberphile video. Wikipedia Article: Van Eck's Sequence. OEIS sequence: A181391.
#Dyalect
Dyalect
let max = 1000 var a = Array.Empty(max, 0) for n in 0..(max-2) { var m = n - 1 while m >= 0 { if a[m] == a[n] { a[n+1] = n - m break } m -= 1 } } print("The first ten terms of the Van Eck sequence are: \(a[0..10].ToArray())") print("Terms 991 to 1000 of the sequence are: \(a[991..999].ToArray())")
http://rosettacode.org/wiki/Van_Eck_sequence
Van Eck sequence
The sequence is generated by following this pseudo-code: A: The first term is zero. Repeatedly apply: If the last term is *new* to the sequence so far then: B: The next term is zero. Otherwise: C: The next term is how far back this last term occured previously. Example Using A: 0 Using B: 0 0 Using C: 0 0 1 Using B: 0 0 1 0 Using C: (zero last occurred two steps back - before the one) 0 0 1 0 2 Using B: 0 0 1 0 2 0 Using C: (two last occurred two steps back - before the zero) 0 0 1 0 2 0 2 2 Using C: (two last occurred one step back) 0 0 1 0 2 0 2 2 1 Using C: (one last appeared six steps back) 0 0 1 0 2 0 2 2 1 6 ... Task Create a function/procedure/method/subroutine/... to generate the Van Eck sequence of numbers. Use it to display here, on this page: The first ten terms of the sequence. Terms 991 - to - 1000 of the sequence. References Don't Know (the Van Eck Sequence) - Numberphile video. Wikipedia Article: Van Eck's Sequence. OEIS sequence: A181391.
#F.23
F#
  // Generate Van Eck's Sequence. Nigel Galloway: June 19th., 2019 let ecK()=let n=System.Collections.Generic.Dictionary<int,int>() Seq.unfold(fun (g,e)->Some(g,((if n.ContainsKey g then let i=n.[g] in n.[g]<-e;e-i else n.[g]<-e;0),e+1)))(0,0)  
http://rosettacode.org/wiki/Vampire_number
Vampire number
A vampire number is a natural decimal number with an even number of digits,   that can be factored into two integers. These two factors are called the   fangs,   and must have the following properties:   they each contain half the number of the decimal digits of the original number   together they consist of exactly the same decimal digits as the original number   at most one of them has a trailing zero An example of a vampire number and its fangs:   1260 : (21, 60) Task Print the first   25   vampire numbers and their fangs. Check if the following numbers are vampire numbers and,   if so,   print them and their fangs: 16758243290880, 24959017348650, 14593825548650 Note that a vampire number can have more than one pair of fangs. See also numberphile.com. vampire search algorithm vampire numbers on OEIS
#Kotlin
Kotlin
// version 1.1   data class Fangs(val fang1: Long = 0L, val fang2: Long = 0L)   fun pow10(n: Int): Long = when { n < 0 -> throw IllegalArgumentException("Can't be negative") else -> { var pow = 1L for (i in 1..n) pow *= 10L pow } }   fun countDigits(n: Long): Int = when { n < 0L -> throw IllegalArgumentException("Can't be negative") n == 0L -> 1 else -> { var count = 0 var nn = n while (nn > 0L) { count++ nn /= 10L } count } }   fun hasTrailingZero(n: Long): Boolean = when { n < 0L -> throw IllegalArgumentException("Can't be negative") else -> n % 10L == 0L }   fun sortedString(s: String): String { val ca = s.toCharArray() ca.sort() return String(ca) }   fun isVampiric(n: Long, fl: MutableList<Fangs>): Boolean { if (n < 0L) return false val len = countDigits(n) if (len % 2L == 1L) return false val hlen = len / 2 val first = pow10(hlen - 1) val last = 10L * first var j: Long var cd: Int val ss = sortedString(n.toString()) for (i in first until last) { if (n % i != 0L) continue j = n / i if (j < i) return fl.size > 0 cd = countDigits(j) if (cd > hlen) continue if (cd < hlen) return fl.size > 0 if (ss != sortedString(i.toString() + j.toString())) continue if (!(hasTrailingZero(i) && hasTrailingZero(j))) { fl.add(Fangs(i, j)) } } return fl.size > 0 }   fun showFangs(fangsList: MutableList<Fangs>): String { var s = "" for ((fang1, fang2) in fangsList) { s += " = $fang1 x $fang2" } return s }   fun main(args: Array<String>) { println("The first 25 vampire numbers and their fangs are:") var count = 0 var n: Long = 0 val fl = mutableListOf<Fangs>() while (true) { if (isVampiric(n, fl)) { count++ println("${"%2d".format(count)} : $n\t${showFangs(fl)}") fl.clear() if (count == 25) break } n++ } println() val va = longArrayOf(16758243290880L, 24959017348650L, 14593825548650L) for (v in va) { if (isVampiric(v, fl)) { println("$v\t${showFangs(fl)}") fl.clear() } else { println("$v\t = not vampiric") } } }
http://rosettacode.org/wiki/Variadic_function
Variadic function
Task Create a function which takes in a variable number of arguments and prints each one on its own line. Also show, if possible in your language, how to call the function on a list of arguments constructed at runtime. Functions of this type are also known as Variadic Functions. Related task   Call a function
#Klingphix
Klingphix
:varfunc 1 tolist flatten len [ get print nl ] for drop ;   "Enter any number of words separated by space: " input nl stklen [split varfunc nl] if   nl "End " input
http://rosettacode.org/wiki/Variadic_function
Variadic function
Task Create a function which takes in a variable number of arguments and prints each one on its own line. Also show, if possible in your language, how to call the function on a list of arguments constructed at runtime. Functions of this type are also known as Variadic Functions. Related task   Call a function
#Kotlin
Kotlin
// version 1.1   fun variadic(vararg va: String) { for (v in va) println(v) }   fun main(args: Array<String>) { variadic("First", "Second", "Third") println("\nEnter four strings for the function to print:") val va = Array(4) { "" } for (i in 1..4) { print("String $i = ") va[i - 1] = readLine()!! } println() variadic(*va) }
http://rosettacode.org/wiki/Variable_size/Get
Variable size/Get
Demonstrate how to get the size of a variable. See also: Host introspection
#zkl
zkl
(123).len() //-->1 (byte) (0).MAX.len() //-->8 (bytes), ie the max number of bytes in an int (1.0).MAX.len() //-->8 (bytes), ie the max number of bytes in an float "this is a test".len() //-->14 L(1,2,3,4).len() //-->4 Dictionary("1",1, "2",2).len() //-->2 (keys) Data(0,Int,1,2,3,4).len() //-->4 (bytes) Data(0,String,"1","2","3","4").len() //-->8 bytes (ASCIIZ)
http://rosettacode.org/wiki/Vector
Vector
Task Implement a Vector class (or a set of functions) that models a Physical Vector. The four basic operations and a pretty print function should be implemented. The Vector may be initialized in any reasonable way. Start and end points, and direction Angular coefficient and value (length) The four operations to be implemented are: Vector + Vector addition Vector - Vector subtraction Vector * scalar multiplication Vector / scalar division
#Racket
Racket
#lang racket   (require racket/flonum)   (define (rad->deg x) (fl* 180. (fl/ (exact->inexact x) pi)))   ;Custom printer ;no shared internal structures (define (vec-print v port mode) (write-string "Vec:\n" port) (write-string (format " -Slope: ~a\n" (vec-slope v)) port) (write-string (format " -Angle(deg): ~a\n" (rad->deg (vec-angle v))) port) (write-string (format " -Norm: ~a\n" (vec-norm v)) port) (write-string (format " -X: ~a\n" (vec-x v)) port) (write-string (format " -Y: ~a\n" (vec-y v)) port))   (struct vec (x y) #:methods gen:custom-write [(define write-proc vec-print)])   ;Alternative constructor (define (vec/slope-norm s n) (vec (* n (/ 1 (sqrt (+ 1 (sqr s))))) (* n (/ s (sqrt (+ 1 (sqr s)))))))   ;Properties (define (vec-norm v) (sqrt (+ (sqr (vec-x v)) (sqr (vec-y v)))))   (define (vec-slope v) (fl/ (exact->inexact (vec-y v)) (exact->inexact (vec-x v))))   (define (vec-angle v) (atan (vec-y v) (vec-x v)))   ;Operations (define (vec+ v w) (vec (+ (vec-x v) (vec-x w)) (+ (vec-y v) (vec-y w))))   (define (vec- v w) (vec (- (vec-x v) (vec-x w)) (- (vec-y v) (vec-y w))))   (define (vec*e v l) (vec (* (vec-x v) l) (* (vec-y v) l)))   (define (vec/e v l) (vec (/ (vec-x v) l) (/ (vec-y v) l)))
http://rosettacode.org/wiki/Vector
Vector
Task Implement a Vector class (or a set of functions) that models a Physical Vector. The four basic operations and a pretty print function should be implemented. The Vector may be initialized in any reasonable way. Start and end points, and direction Angular coefficient and value (length) The four operations to be implemented are: Vector + Vector addition Vector - Vector subtraction Vector * scalar multiplication Vector / scalar division
#Raku
Raku
class Vector { has Real $.x; has Real $.y;   multi submethod BUILD (:$!x!, :$!y!) { * } multi submethod BUILD (:$length!, :$angle!) { $!x = $length * cos $angle; $!y = $length * sin $angle; } multi submethod BUILD (:from([$x1, $y1])!, :to([$x2, $y2])!) { $!x = $x2 - $x1; $!y = $y2 - $y1; }   method length { sqrt $.x ** 2 + $.y ** 2 } method angle { atan2 $.y, $.x }   method add ($v) { Vector.new(x => $.x + $v.x, y => $.y + $v.y) } method subtract ($v) { Vector.new(x => $.x - $v.x, y => $.y - $v.y) } method multiply ($n) { Vector.new(x => $.x * $n, y => $.y * $n ) } method divide ($n) { Vector.new(x => $.x / $n, y => $.y / $n ) }   method gist { "vec[$.x, $.y]" } }   multi infix:<+> (Vector $v, Vector $w) is export { $v.add: $w } multi infix:<-> (Vector $v, Vector $w) is export { $v.subtract: $w } multi prefix:<-> (Vector $v) is export { $v.multiply: -1 } multi infix:<*> (Vector $v, $n) is export { $v.multiply: $n } multi infix:</> (Vector $v, $n) is export { $v.divide: $n }     #####[ Usage example: ]#####   say my $u = Vector.new(x => 3, y => 4); #: vec[3, 4] say my $v = Vector.new(from => [1, 0], to => [2, 3]); #: vec[1, 3] say my $w = Vector.new(length => 1, angle => pi/4); #: vec[0.707106781186548, 0.707106781186547]   say $u.length; #: 5 say $u.angle * 180/pi; #: 53.130102354156   say $u + $v; #: vec[4, 7] say $u - $v; #: vec[2, 1] say -$u; #: vec[-3, -4] say $u * 10; #: vec[30, 40] say $u / 2; #: vec[1.5, 2]
http://rosettacode.org/wiki/Vigen%C3%A8re_cipher
Vigenère cipher
Task Implement a   Vigenère cypher,   both encryption and decryption. The program should handle keys and text of unequal length, and should capitalize everything and discard non-alphabetic characters. (If your program handles non-alphabetic characters in another way, make a note of it.) Related tasks   Caesar cipher   Rot-13   Substitution Cipher
#Racket
Racket
  #lang racket (define chr integer->char) (define ord char->integer)   (define (encrypt msg key) (define cleaned (list->string (for/list ([c (string-upcase msg)] #:when (char-alphabetic? c)) c))) (list->string (for/list ([c cleaned] [k (in-cycle key)]) (chr (+ (modulo (+ (ord c) (ord k)) 26) (ord #\A))))))   (define (decrypt msg key) (list->string (for/list ([c msg] [k (in-cycle key)]) (chr (+ (modulo (- (ord c) (ord k)) 26) (ord #\A))))))   (decrypt (encrypt "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!" "VIGENERECIPHER") "VIGENERECIPHER")  
http://rosettacode.org/wiki/Vigen%C3%A8re_cipher
Vigenère cipher
Task Implement a   Vigenère cypher,   both encryption and decryption. The program should handle keys and text of unequal length, and should capitalize everything and discard non-alphabetic characters. (If your program handles non-alphabetic characters in another way, make a note of it.) Related tasks   Caesar cipher   Rot-13   Substitution Cipher
#Raku
Raku
sub s2v ($s) { $s.uc.comb(/ <[ A..Z ]> /)».ord »-» 65 } sub v2s (@v) { (@v »%» 26 »+» 65)».chr.join }   sub blacken ($red, $key) { v2s(s2v($red) »+» s2v($key)) } sub redden ($blk, $key) { v2s(s2v($blk) »-» s2v($key)) }   my $red = "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!"; my $key = "Vigenere Cipher!!!";   say $red; say my $black = blacken($red, $key); say redden($black, $key);
http://rosettacode.org/wiki/Vector_products
Vector products
A vector is defined as having three dimensions as being represented by an ordered collection of three numbers:   (X, Y, Z). If you imagine a graph with the   x   and   y   axis being at right angles to each other and having a third,   z   axis coming out of the page, then a triplet of numbers,   (X, Y, Z)   would represent a point in the region,   and a vector from the origin to the point. Given the vectors: A = (a1, a2, a3) B = (b1, b2, b3) C = (c1, c2, c3) then the following common vector products are defined: The dot product       (a scalar quantity) A • B = a1b1   +   a2b2   +   a3b3 The cross product       (a vector quantity) A x B = (a2b3  -   a3b2,     a3b1   -   a1b3,     a1b2   -   a2b1) The scalar triple product       (a scalar quantity) A • (B x C) The vector triple product       (a vector quantity) A x (B x C) Task Given the three vectors: a = ( 3, 4, 5) b = ( 4, 3, 5) c = (-5, -12, -13) Create a named function/subroutine/method to compute the dot product of two vectors. Create a function to compute the cross product of two vectors. Optionally create a function to compute the scalar triple product of three vectors. Optionally create a function to compute the vector triple product of three vectors. Compute and display: a • b Compute and display: a x b Compute and display: a • (b x c), the scalar triple product. Compute and display: a x (b x c), the vector triple product. References   A starting page on Wolfram MathWorld is   Vector Multiplication .   Wikipedia   dot product.   Wikipedia   cross product.   Wikipedia   triple product. Related tasks   Dot product   Quaternion type
#EchoLisp
EchoLisp
  (lib 'math)   (define (scalar-triple-product a b c) (dot-product a (cross-product b c)))   (define (vector-triple-product a b c) (cross-product a (cross-product b c)))   (define a #(3 4 5)) (define b #(4 3 5)) (define c #(-5 -12 -13))   (cross-product a b) → #( 5 5 -7) (dot-product a b) → 49 (scalar-triple-product a b c) → 6 (vector-triple-product a b c) → #( -267 204 -3)  
http://rosettacode.org/wiki/Validate_International_Securities_Identification_Number
Validate International Securities Identification Number
An International Securities Identification Number (ISIN) is a unique international identifier for a financial security such as a stock or bond. Task Write a function or program that takes a string as input, and checks whether it is a valid ISIN. It is only valid if it has the correct format,   and   the embedded checksum is correct. Demonstrate that your code passes the test-cases listed below. Details The format of an ISIN is as follows: ┌───────────── a 2-character ISO country code (A-Z) │ ┌─────────── a 9-character security code (A-Z, 0-9) │ │        ┌── a checksum digit (0-9) AU0000XVGZA3 For this task, you may assume that any 2-character alphabetic sequence is a valid country code. The checksum can be validated as follows: Replace letters with digits, by converting each character from base 36 to base 10, e.g. AU0000XVGZA3 →1030000033311635103. Perform the Luhn test on this base-10 number. There is a separate task for this test: Luhn test of credit card numbers. You don't have to replicate the implementation of this test here   ───   you can just call the existing function from that task.   (Add a comment stating if you did this.) Test cases ISIN Validity Comment US0378331005 valid US0373831005 not valid The transposition typo is caught by the checksum constraint. U50378331005 not valid The substitution typo is caught by the format constraint. US03378331005 not valid The duplication typo is caught by the format constraint. AU0000XVGZA3 valid AU0000VXGZA3 valid Unfortunately, not all transposition typos are caught by the checksum constraint. FR0000988040 valid (The comments are just informational.   Your function should simply return a Boolean result.   See #Raku for a reference solution.) Related task: Luhn test of credit card numbers Also see Interactive online ISIN validator Wikipedia article: International Securities Identification Number
#Haskell
Haskell
module ISINVerification2 where   import Data.Char (isUpper, isDigit, digitToInt)   verifyISIN :: String -> Bool verifyISIN isin = correctFormat isin && mod (oddsum + multiplied_even_sum) 10 == 0 where reverted = reverse $ convertToNumber isin theOdds = fst $ collectOddandEven reverted theEvens = snd $ collectOddandEven reverted oddsum = sum $ map digitToInt theOdds multiplied_even_sum = addUpDigits $ map ((* 2) . digitToInt) theEvens   capitalLetters :: String capitalLetters = ['A','B' .. 'Z']   numbers :: String numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']   correctFormat :: String -> Bool correctFormat isin = (length isin == 12) && all (`elem` capitalLetters) (take 2 isin) && all (\c -> elem c capitalLetters || elem c numbers) (drop 2 $ take 11 isin) && elem (last isin) numbers   convertToNumber :: String -> String convertToNumber = concatMap convert where convert :: Char -> String convert c = if isDigit c then show $ digitToInt c else show (fromEnum c - 55)   collectOddandEven :: String -> (String, String) collectOddandEven term | odd $ length term = ( concat [ take 1 $ drop n term | n <- [0,2 .. length term - 1] ] , concat [ take 1 $ drop d term | d <- [1,3 .. length term - 2] ]) | otherwise = ( concat [ take 1 $ drop n term | n <- [0,2 .. length term - 2] ] , concat [ take 1 $ drop d term | d <- [1,3 .. length term - 1] ])   addUpDigits :: [Int] -> Int addUpDigits list = sum $ map (\d -> if d > 9 then sum $ map digitToInt $ show d else d) list   printSolution :: String -> IO () printSolution str = do putStr $ str ++ " is" if verifyISIN str then putStrLn " valid" else putStrLn " not valid"   main :: IO () main = do let isinnumbers = [ "US0378331005" , "US0373831005" , "U50378331005" , "US03378331005" , "AU0000XVGZA3" , "AU0000VXGZA3" , "FR0000988040" ] mapM_ printSolution isinnumbers
http://rosettacode.org/wiki/Van_der_Corput_sequence
Van der Corput sequence
When counting integers in binary, if you put a (binary) point to the righEasyLangt of the count then the column immediately to the left denotes a digit with a multiplier of 2 0 {\displaystyle 2^{0}} ; the digit in the next column to the left has a multiplier of 2 1 {\displaystyle 2^{1}} ; and so on. So in the following table: 0. 1. 10. 11. ... the binary number "10" is 1 × 2 1 + 0 × 2 0 {\displaystyle 1\times 2^{1}+0\times 2^{0}} . You can also have binary digits to the right of the “point”, just as in the decimal number system. In that case, the digit in the place immediately to the right of the point has a weight of 2 − 1 {\displaystyle 2^{-1}} , or 1 / 2 {\displaystyle 1/2} . The weight for the second column to the right of the point is 2 − 2 {\displaystyle 2^{-2}} or 1 / 4 {\displaystyle 1/4} . And so on. If you take the integer binary count of the first table, and reflect the digits about the binary point, you end up with the van der Corput sequence of numbers in base 2. .0 .1 .01 .11 ... The third member of the sequence, binary 0.01, is therefore 0 × 2 − 1 + 1 × 2 − 2 {\displaystyle 0\times 2^{-1}+1\times 2^{-2}} or 1 / 4 {\displaystyle 1/4} . Distribution of 2500 points each: Van der Corput (top) vs pseudorandom 0 ≤ x < 1 {\displaystyle 0\leq x<1} Monte Carlo simulations This sequence is also a superset of the numbers representable by the "fraction" field of an old IEEE floating point standard. In that standard, the "fraction" field represented the fractional part of a binary number beginning with "1." e.g. 1.101001101. Hint A hint at a way to generate members of the sequence is to modify a routine used to change the base of an integer: >>> def base10change(n, base): digits = [] while n: n,remainder = divmod(n, base) digits.insert(0, remainder) return digits   >>> base10change(11, 2) [1, 0, 1, 1] the above showing that 11 in decimal is 1 × 2 3 + 0 × 2 2 + 1 × 2 1 + 1 × 2 0 {\displaystyle 1\times 2^{3}+0\times 2^{2}+1\times 2^{1}+1\times 2^{0}} . Reflected this would become .1101 or 1 × 2 − 1 + 1 × 2 − 2 + 0 × 2 − 3 + 1 × 2 − 4 {\displaystyle 1\times 2^{-1}+1\times 2^{-2}+0\times 2^{-3}+1\times 2^{-4}} Task description Create a function/method/routine that given n, generates the n'th term of the van der Corput sequence in base 2. Use the function to compute and display the first ten members of the sequence. (The first member of the sequence is for n=0). As a stretch goal/extra credit, compute and show members of the sequence for bases other than 2. See also The Basic Low Discrepancy Sequences Non-decimal radices/Convert Van der Corput sequence
#Forth
Forth
: fvdc ( base n -- f ) 0e 1e ( F: vdc denominator ) begin dup while over s>d d>f f* over /mod ( base rem n ) swap s>d d>f fover f/ frot f+ fswap repeat 2drop fdrop ;   : test 10 0 do 2 i fvdc cr f. loop ;
http://rosettacode.org/wiki/Van_der_Corput_sequence
Van der Corput sequence
When counting integers in binary, if you put a (binary) point to the righEasyLangt of the count then the column immediately to the left denotes a digit with a multiplier of 2 0 {\displaystyle 2^{0}} ; the digit in the next column to the left has a multiplier of 2 1 {\displaystyle 2^{1}} ; and so on. So in the following table: 0. 1. 10. 11. ... the binary number "10" is 1 × 2 1 + 0 × 2 0 {\displaystyle 1\times 2^{1}+0\times 2^{0}} . You can also have binary digits to the right of the “point”, just as in the decimal number system. In that case, the digit in the place immediately to the right of the point has a weight of 2 − 1 {\displaystyle 2^{-1}} , or 1 / 2 {\displaystyle 1/2} . The weight for the second column to the right of the point is 2 − 2 {\displaystyle 2^{-2}} or 1 / 4 {\displaystyle 1/4} . And so on. If you take the integer binary count of the first table, and reflect the digits about the binary point, you end up with the van der Corput sequence of numbers in base 2. .0 .1 .01 .11 ... The third member of the sequence, binary 0.01, is therefore 0 × 2 − 1 + 1 × 2 − 2 {\displaystyle 0\times 2^{-1}+1\times 2^{-2}} or 1 / 4 {\displaystyle 1/4} . Distribution of 2500 points each: Van der Corput (top) vs pseudorandom 0 ≤ x < 1 {\displaystyle 0\leq x<1} Monte Carlo simulations This sequence is also a superset of the numbers representable by the "fraction" field of an old IEEE floating point standard. In that standard, the "fraction" field represented the fractional part of a binary number beginning with "1." e.g. 1.101001101. Hint A hint at a way to generate members of the sequence is to modify a routine used to change the base of an integer: >>> def base10change(n, base): digits = [] while n: n,remainder = divmod(n, base) digits.insert(0, remainder) return digits   >>> base10change(11, 2) [1, 0, 1, 1] the above showing that 11 in decimal is 1 × 2 3 + 0 × 2 2 + 1 × 2 1 + 1 × 2 0 {\displaystyle 1\times 2^{3}+0\times 2^{2}+1\times 2^{1}+1\times 2^{0}} . Reflected this would become .1101 or 1 × 2 − 1 + 1 × 2 − 2 + 0 × 2 − 3 + 1 × 2 − 4 {\displaystyle 1\times 2^{-1}+1\times 2^{-2}+0\times 2^{-3}+1\times 2^{-4}} Task description Create a function/method/routine that given n, generates the n'th term of the van der Corput sequence in base 2. Use the function to compute and display the first ten members of the sequence. (The first member of the sequence is for n=0). As a stretch goal/extra credit, compute and show members of the sequence for bases other than 2. See also The Basic Low Discrepancy Sequences Non-decimal radices/Convert Van der Corput sequence
#Fortran
Fortran
FUNCTION VDC(N,BASE) !Calculates a Van der Corput number... Converts 1234 in decimal to 4321 in V, and P = 10000. INTEGER N !For this integer, INTEGER BASE !In this base. INTEGER I !A copy of N that can be damaged. INTEGER P !Successive powers of BASE. INTEGER V !Accumulates digits. P = 1 ! = BASE**0 V = 0 !Start with no digits, as if N = 0. I = N !Here we go. DO WHILE (I .NE. 0) !While something remains, V = V*BASE + MOD(I,BASE) !Extract its low-order digit. I = I/BASE !Reduce it by a power. P = P*BASE !And track the power. END DO !Thus extract the digits in reverse order: right-to-left. VDC = V/FLOAT(P) !The power is one above the highest digit. END FUNCTION VDC !Numerology is weird.   PROGRAM POKE INTEGER FIRST,LAST !Might as well document some constants. PARAMETER (FIRST = 0,LAST = 9) !Thus, the first ten values. INTEGER I,BASE !Steppers. REAL VDC !Stop the compiler moaning about undeclared items.   WRITE (6,1) FIRST,LAST,(I, I = FIRST,LAST) !Announce. 1 FORMAT ("Calculates values ",I0," to ",I0," of the ", 1 "Van der Corput sequence, in various bases."/ 2 "Base",666I9)   DO BASE = 2,13 !A selection of bases. WRITE (6,2) BASE,(VDC(I,BASE), I = FIRST,LAST) !Show the specified span. 2 FORMAT (I4,666F9.6) !Aligns with FORMAT 1. END DO !On to the next base.   END
http://rosettacode.org/wiki/URL_decoding
URL decoding
This task   (the reverse of   URL encoding   and distinct from   URL parser)   is to provide a function or mechanism to convert an URL-encoded string into its original unencoded form. Test cases   The encoded string   "http%3A%2F%2Ffoo%20bar%2F"   should be reverted to the unencoded form   "http://foo bar/".   The encoded string   "google.com/search?q=%60Abdu%27l-Bah%C3%A1"   should revert to the unencoded form   "google.com/search?q=`Abdu'l-Bahá".
#Bracmat
Bracmat
( ( decode = decoded hexcode notencoded .  :?decoded & whl ' ( @(!arg:?notencoded "%" (% %:?hexcode) ?arg) & !decoded !notencoded chr$(x2d$!hexcode):?decoded ) & str$(!decoded !arg) ) & out$(decode$http%3A%2F%2Ffoo%20bar%2F) );
http://rosettacode.org/wiki/URL_decoding
URL decoding
This task   (the reverse of   URL encoding   and distinct from   URL parser)   is to provide a function or mechanism to convert an URL-encoded string into its original unencoded form. Test cases   The encoded string   "http%3A%2F%2Ffoo%20bar%2F"   should be reverted to the unencoded form   "http://foo bar/".   The encoded string   "google.com/search?q=%60Abdu%27l-Bah%C3%A1"   should revert to the unencoded form   "google.com/search?q=`Abdu'l-Bahá".
#C
C
#include <stdio.h> #include <string.h>   inline int ishex(int x) { return (x >= '0' && x <= '9') || (x >= 'a' && x <= 'f') || (x >= 'A' && x <= 'F'); }   int decode(const char *s, char *dec) { char *o; const char *end = s + strlen(s); int c;   for (o = dec; s <= end; o++) { c = *s++; if (c == '+') c = ' '; else if (c == '%' && ( !ishex(*s++) || !ishex(*s++) || !sscanf(s - 2, "%2x", &c))) return -1;   if (dec) *o = c; }   return o - dec; }   int main() { const char *url = "http%3A%2F%2ffoo+bar%2fabcd"; char out[strlen(url) + 1];   printf("length: %d\n", decode(url, 0)); puts(decode(url, out) < 0 ? "bad string" : out);   return 0; }
http://rosettacode.org/wiki/Update_a_configuration_file
Update a configuration file
We have a configuration file as follows: # This is a configuration file in standard configuration file format # # Lines begininning with a hash or a semicolon are ignored by the application # program. Blank lines are also ignored by the application program. # The first word on each non comment line is the configuration option. # Remaining words or numbers on the line are configuration parameter # data fields. # Note that configuration option names are not case sensitive. However, # configuration parameter data is case sensitive and the lettercase must # be preserved. # This is a favourite fruit FAVOURITEFRUIT banana # This is a boolean that should be set NEEDSPEELING # This boolean is commented out ; SEEDSREMOVED # How many bananas we have NUMBEROFBANANAS 48 The task is to manipulate the configuration file as follows: Disable the needspeeling option (using a semicolon prefix) Enable the seedsremoved option by removing the semicolon and any leading whitespace Change the numberofbananas parameter to 1024 Enable (or create if it does not exist in the file) a parameter for numberofstrawberries with a value of 62000 Note that configuration option names are not case sensitive. This means that changes should be effected, regardless of the case. Options should always be disabled by prefixing them with a semicolon. Lines beginning with hash symbols should not be manipulated and left unchanged in the revised file. If a configuration option does not exist within the file (in either enabled or disabled form), it should be added during this update. Duplicate configuration option names in the file should be removed, leaving just the first entry. For the purpose of this task, the revised file should contain appropriate entries, whether enabled or not for needspeeling,seedsremoved,numberofbananas and numberofstrawberries.) The update should rewrite configuration option names in capital letters. However lines beginning with hashes and any parameter data must not be altered (eg the banana for favourite fruit must not become capitalized). The update process should also replace double semicolon prefixes with just a single semicolon (unless it is uncommenting the option, in which case it should remove all leading semicolons). Any lines beginning with a semicolon or groups of semicolons, but no following option should be removed, as should any leading or trailing whitespace on the lines. Whitespace between the option and parameters should consist only of a single space, and any non-ASCII extended characters, tabs characters, or control codes (other than end of line markers), should also be removed. Related tasks Read a configuration file
#C
C
#include <stdio.h> #include <stdlib.h> #include <string.h>   #define strcomp(X, Y) strcasecmp(X, Y)   struct option { const char *name, *value; int flag; };   /* TODO: dynamically obtain these */ struct option updlist[] = { { "NEEDSPEELING", NULL }, { "SEEDSREMOVED", "" }, { "NUMBEROFBANANAS", "1024" }, { "NUMBEROFSTRAWBERRIES", "62000" }, { NULL, NULL } };   int output_opt(FILE *to, struct option *opt) { if (opt->value == NULL) return fprintf(to, "; %s\n", opt->name); else if (opt->value[0] == 0) return fprintf(to, "%s\n", opt->name); else return fprintf(to, "%s %s\n", opt->name, opt->value); }   int update(FILE *from, FILE *to, struct option *updlist) { char line_buf[256], opt_name[128]; int i; for (;;) { size_t len, space_span, span_to_hash; if (fgets(line_buf, sizeof line_buf, from) == NULL) break; len = strlen(line_buf); space_span = strspn(line_buf, "\t "); span_to_hash = strcspn(line_buf, "#"); if (space_span == span_to_hash) goto line_out; if (space_span == len) goto line_out; if ((sscanf(line_buf, "; %127s", opt_name) == 1) || (sscanf(line_buf, "%127s", opt_name) == 1)) { int flag = 0; for (i = 0; updlist[i].name; i++) { if (strcomp(updlist[i].name, opt_name) == 0) { if (output_opt(to, &updlist[i]) < 0) return -1; updlist[i].flag = 1; flag = 1; } } if (flag == 0) goto line_out; } else line_out: if (fprintf(to, "%s", line_buf) < 0) return -1; continue; } { for (i = 0; updlist[i].name; i++) { if (!updlist[i].flag) if (output_opt(to, &updlist[i]) < 0) return -1; } } return feof(from) ? 0 : -1; }   int main(void) { if (update(stdin, stdout, updlist) < 0) { fprintf(stderr, "failed\n"); return (EXIT_FAILURE); } return 0; }
http://rosettacode.org/wiki/User_input/Text
User input/Text
User input/Text is part of Short Circuit's Console Program Basics selection. Task Input a string and the integer   75000   from the text console. See also: User input/Graphical
#BASIC
BASIC
INPUT "Enter a string"; s$ INPUT "Enter a number: ", i%
http://rosettacode.org/wiki/User_input/Text
User input/Text
User input/Text is part of Short Circuit's Console Program Basics selection. Task Input a string and the integer   75000   from the text console. See also: User input/Graphical
#Batch_File
Batch File
@echo off set /p var= echo %var% 75000
http://rosettacode.org/wiki/User_input/Graphical
User input/Graphical
In this task, the goal is to input a string and the integer 75000, from graphical user interface. See also: User input/Text
#C
C
#include <gtk/gtk.h>   void ok_hit(GtkButton *o, GtkWidget **w) { GtkMessageDialog *msg;   gdouble v = gtk_spin_button_get_value((GtkSpinButton *)w[1]); const gchar *c = gtk_entry_get_text((GtkEntry *)w[0]);   msg = (GtkMessageDialog *) gtk_message_dialog_new(NULL, GTK_DIALOG_MODAL, (v==75000) ? GTK_MESSAGE_INFO : GTK_MESSAGE_ERROR, GTK_BUTTONS_OK, "You wrote '%s' and selected the number %d%s", c, (gint)v, (v==75000) ? "" : " which is wrong (75000 expected)!"); gtk_widget_show_all(GTK_WIDGET(msg)); (void)gtk_dialog_run(GTK_DIALOG(msg)); gtk_widget_destroy(GTK_WIDGET(msg)); if ( v==75000 ) gtk_main_quit(); }   int main(int argc, char **argv) { GtkWindow *win; GtkEntry *entry; GtkSpinButton *spin; GtkButton *okbutton; GtkLabel *entry_l, *spin_l; GtkHBox *hbox[2]; GtkVBox *vbox; GtkWidget *widgs[2];   gtk_init(&argc, &argv);   win = (GtkWindow *)gtk_window_new(GTK_WINDOW_TOPLEVEL); gtk_window_set_title(win, "Insert values");   entry_l = (GtkLabel *)gtk_label_new("Insert a string"); spin_l = (GtkLabel *)gtk_label_new("Insert 75000");   entry = (GtkEntry *)gtk_entry_new(); spin = (GtkSpinButton *)gtk_spin_button_new_with_range(0, 80000, 1);   widgs[0] = GTK_WIDGET(entry); widgs[1] = GTK_WIDGET(spin);   okbutton = (GtkButton *)gtk_button_new_with_label("Ok");   hbox[0] = (GtkHBox *)gtk_hbox_new(FALSE, 1); hbox[1] = (GtkHBox *)gtk_hbox_new(FALSE, 1);   vbox = (GtkVBox *)gtk_vbox_new(TRUE, 1);   gtk_container_add(GTK_CONTAINER(hbox[0]), GTK_WIDGET(entry_l)); gtk_container_add(GTK_CONTAINER(hbox[0]), GTK_WIDGET(entry)); gtk_container_add(GTK_CONTAINER(hbox[1]), GTK_WIDGET(spin_l)); gtk_container_add(GTK_CONTAINER(hbox[1]), GTK_WIDGET(spin));   gtk_container_add(GTK_CONTAINER(vbox), GTK_WIDGET(hbox[0])); gtk_container_add(GTK_CONTAINER(vbox), GTK_WIDGET(hbox[1])); gtk_container_add(GTK_CONTAINER(vbox), GTK_WIDGET(okbutton));   gtk_container_add(GTK_CONTAINER(win), GTK_WIDGET(vbox));   g_signal_connect(G_OBJECT(win), "delete-event", (GCallback)gtk_main_quit, NULL); g_signal_connect(G_OBJECT(okbutton), "clicked", (GCallback)ok_hit, widgs);   gtk_widget_show_all(GTK_WIDGET(win)); gtk_main();   return 0; }
http://rosettacode.org/wiki/UTF-8_encode_and_decode
UTF-8 encode and decode
As described in UTF-8 and in Wikipedia, UTF-8 is a popular encoding of (multi-byte) Unicode code-points into eight-bit octets. The goal of this task is to write a encoder that takes a unicode code-point (an integer representing a unicode character) and returns a sequence of 1-4 bytes representing that character in the UTF-8 encoding. Then you have to write the corresponding decoder that takes a sequence of 1-4 UTF-8 encoded bytes and return the corresponding unicode character. Demonstrate the functionality of your encoder and decoder on the following five characters: Character Name Unicode UTF-8 encoding (hex) --------------------------------------------------------------------------------- A LATIN CAPITAL LETTER A U+0041 41 ö LATIN SMALL LETTER O WITH DIAERESIS U+00F6 C3 B6 Ж CYRILLIC CAPITAL LETTER ZHE U+0416 D0 96 € EURO SIGN U+20AC E2 82 AC 𝄞 MUSICAL SYMBOL G CLEF U+1D11E F0 9D 84 9E Provided below is a reference implementation in Common Lisp.
#C.23
C#
using System; using System.Text;   namespace Rosetta { class Program { static byte[] MyEncoder(int codepoint) => Encoding.UTF8.GetBytes(char.ConvertFromUtf32(codepoint)); static string MyDecoder(byte[] utf8bytes) => Encoding.UTF8.GetString(utf8bytes); static void Main(string[] args) { Console.OutputEncoding = Encoding.UTF8; // makes sure it doesn't print rectangles... foreach (int unicodePoint in new int[] { 0x0041, 0x00F6, 0x0416, 0x20AC, 0x1D11E}) { byte[] asUtf8bytes = MyEncoder(unicodePoint); string theCharacter = MyDecoder(asUtf8bytes); Console.WriteLine("{0,8} {1,5} {2,-15}", unicodePoint.ToString("X4"), theCharacter, BitConverter.ToString(asUtf8bytes)); } } } } /* Output: * 0041 A 41 00F6 ö C3-B6 0416 Ж D0-96 20AC € E2-82-AC 1D11E 𝄞 F0-9D-84-9E */  
http://rosettacode.org/wiki/Use_another_language_to_call_a_function
Use another language to call a function
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. This task is inverse to the task Call foreign language function. Consider the following C program: #include <stdio.h>   extern int Query (char * Data, size_t * Length);   int main (int argc, char * argv []) { char Buffer [1024]; size_t Size = sizeof (Buffer);   if (0 == Query (Buffer, &Size)) { printf ("failed to call Query\n"); } else { char * Ptr = Buffer; while (Size-- > 0) putchar (*Ptr++); putchar ('\n'); } } Implement the missing Query function in your language, and let this C program call it. The function should place the string Here am I into the buffer which is passed to it as the parameter Data. The buffer size in bytes is passed as the parameter Length. When there is no room in the buffer, Query shall return 0. Otherwise it overwrites the beginning of Buffer, sets the number of overwritten bytes into Length and returns 1.
#J
J
  query=:3 :'0&#^:(y < #)''Here am I'''  
http://rosettacode.org/wiki/Use_another_language_to_call_a_function
Use another language to call a function
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. This task is inverse to the task Call foreign language function. Consider the following C program: #include <stdio.h>   extern int Query (char * Data, size_t * Length);   int main (int argc, char * argv []) { char Buffer [1024]; size_t Size = sizeof (Buffer);   if (0 == Query (Buffer, &Size)) { printf ("failed to call Query\n"); } else { char * Ptr = Buffer; while (Size-- > 0) putchar (*Ptr++); putchar ('\n'); } } Implement the missing Query function in your language, and let this C program call it. The function should place the string Here am I into the buffer which is passed to it as the parameter Data. The buffer size in bytes is passed as the parameter Length. When there is no room in the buffer, Query shall return 0. Otherwise it overwrites the beginning of Buffer, sets the number of overwritten bytes into Length and returns 1.
#Java
Java
/* Query.java */ public class Query { public static boolean call(byte[] data, int[] length) throws java.io.UnsupportedEncodingException { String message = "Here am I"; byte[] mb = message.getBytes("utf-8"); if (length[0] < mb.length) return false; length[0] = mb.length; System.arraycopy(mb, 0, data, 0, mb.length); return true; } }
http://rosettacode.org/wiki/URL_parser
URL parser
URLs are strings with a simple syntax: scheme://[username:password@]domain[:port]/path?query_string#fragment_id Task Parse a well-formed URL to retrieve the relevant information:   scheme, domain, path, ... Note:   this task has nothing to do with URL encoding or URL decoding. According to the standards, the characters:    ! * ' ( ) ; : @ & = + $ , / ? % # [ ] only need to be percent-encoded   (%)   in case of possible confusion. Also note that the path, query and fragment are case sensitive, even if the scheme and domain are not. The way the returned information is provided (set of variables, array, structured, record, object,...) is language-dependent and left to the programmer, but the code should be clear enough to reuse. Extra credit is given for clear error diagnostics.   Here is the official standard:     https://tools.ietf.org/html/rfc3986,   and here is a simpler   BNF:     http://www.w3.org/Addressing/URL/5_URI_BNF.html. Test cases According to T. Berners-Lee foo://example.com:8042/over/there?name=ferret#nose     should parse into:   scheme = foo   domain = example.com   port = :8042   path = over/there   query = name=ferret   fragment = nose urn:example:animal:ferret:nose     should parse into:   scheme = urn   path = example:animal:ferret:nose other URLs that must be parsed include:   jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true   ftp://ftp.is.co.za/rfc/rfc1808.txt   http://www.ietf.org/rfc/rfc2396.txt#header1   ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two   mailto:[email protected]   news:comp.infosystems.www.servers.unix   tel:+1-816-555-1212   telnet://192.0.2.16:80/   urn:oasis:names:specification:docbook:dtd:xml:4.1.2
#Java
Java
import java.net.URI; import java.net.URISyntaxException; public class WebAddressParser{ public static void main(String[] args){ parseAddress("foo://example.com:8042/over/there?name=ferret#nose"); parseAddress("urn:example:animal:ferret:nose"); }   static void parseAddress(String a){ System.out.println("Parsing " + a); try{   // this line does the work URI u = new URI(a);   System.out.println("\tscheme = " + u.getScheme()); System.out.println("\tdomain = " + u.getHost()); System.out.println("\tport = " + (-1==u.getPort()?"default":u.getPort())); System.out.println("\tpath = " + (null==u.getPath()?u.getSchemeSpecificPart():u.getPath())); System.out.println("\tquery = " + u.getQuery()); System.out.println("\tfragment = " + u.getFragment()); } catch (URISyntaxException x){ System.err.println("Oops: " + x); } } }  
http://rosettacode.org/wiki/URL_encoding
URL encoding
Task Provide a function or mechanism to convert a provided string into URL encoding representation. In URL encoding, special characters, control characters and extended characters are converted into a percent symbol followed by a two digit hexadecimal code, So a space character encodes into %20 within the string. For the purposes of this task, every character except 0-9, A-Z and a-z requires conversion, so the following characters all require conversion by default: ASCII control codes (Character ranges 00-1F hex (0-31 decimal) and 7F (127 decimal). ASCII symbols (Character ranges 32-47 decimal (20-2F hex)) ASCII symbols (Character ranges 58-64 decimal (3A-40 hex)) ASCII symbols (Character ranges 91-96 decimal (5B-60 hex)) ASCII symbols (Character ranges 123-126 decimal (7B-7E hex)) Extended characters with character codes of 128 decimal (80 hex) and above. Example The string "http://foo bar/" would be encoded as "http%3A%2F%2Ffoo%20bar%2F". Variations Lowercase escapes are legal, as in "http%3a%2f%2ffoo%20bar%2f". Some standards give different rules: RFC 3986, Uniform Resource Identifier (URI): Generic Syntax, section 2.3, says that "-._~" should not be encoded. HTML 5, section 4.10.22.5 URL-encoded form data, says to preserve "-._*", and to encode space " " to "+". The options below provide for utilization of an exception string, enabling preservation (non encoding) of particular characters to meet specific standards. Options It is permissible to use an exception string (containing a set of symbols that do not need to be converted). However, this is an optional feature and is not a requirement of this task. Related tasks   URL decoding   URL parser
#ColdFusion
ColdFusion
(defun needs-encoding-p (char) (not (digit-char-p char 36)))   (defun encode-char (char) (format nil "%~2,'0X" (char-code char)))   (defun url-encode (url) (apply #'concatenate 'string (map 'list (lambda (char) (if (needs-encoding-p char) (encode-char char) (string char))) url)))   (url-encode "http://foo bar/")
http://rosettacode.org/wiki/URL_encoding
URL encoding
Task Provide a function or mechanism to convert a provided string into URL encoding representation. In URL encoding, special characters, control characters and extended characters are converted into a percent symbol followed by a two digit hexadecimal code, So a space character encodes into %20 within the string. For the purposes of this task, every character except 0-9, A-Z and a-z requires conversion, so the following characters all require conversion by default: ASCII control codes (Character ranges 00-1F hex (0-31 decimal) and 7F (127 decimal). ASCII symbols (Character ranges 32-47 decimal (20-2F hex)) ASCII symbols (Character ranges 58-64 decimal (3A-40 hex)) ASCII symbols (Character ranges 91-96 decimal (5B-60 hex)) ASCII symbols (Character ranges 123-126 decimal (7B-7E hex)) Extended characters with character codes of 128 decimal (80 hex) and above. Example The string "http://foo bar/" would be encoded as "http%3A%2F%2Ffoo%20bar%2F". Variations Lowercase escapes are legal, as in "http%3a%2f%2ffoo%20bar%2f". Some standards give different rules: RFC 3986, Uniform Resource Identifier (URI): Generic Syntax, section 2.3, says that "-._~" should not be encoded. HTML 5, section 4.10.22.5 URL-encoded form data, says to preserve "-._*", and to encode space " " to "+". The options below provide for utilization of an exception string, enabling preservation (non encoding) of particular characters to meet specific standards. Options It is permissible to use an exception string (containing a set of symbols that do not need to be converted). However, this is an optional feature and is not a requirement of this task. Related tasks   URL decoding   URL parser
#Common_Lisp
Common Lisp
(defun needs-encoding-p (char) (not (digit-char-p char 36)))   (defun encode-char (char) (format nil "%~2,'0X" (char-code char)))   (defun url-encode (url) (apply #'concatenate 'string (map 'list (lambda (char) (if (needs-encoding-p char) (encode-char char) (string char))) url)))   (url-encode "http://foo bar/")
http://rosettacode.org/wiki/Variables
Variables
Task Demonstrate a language's methods of:   variable declaration   initialization   assignment   datatypes   scope   referencing,     and   other variable related facilities
#Common_Lisp
Common Lisp
(defparameter *x* nil "nothing")
http://rosettacode.org/wiki/Variables
Variables
Task Demonstrate a language's methods of:   variable declaration   initialization   assignment   datatypes   scope   referencing,     and   other variable related facilities
#D
D
  float bite = 36.321; ///_Defines a floating-point number (float), "bite", with a value of 36.321 float[3] bites; ///_Defines a static array of 3 floats float[] more_bites; ///_Defines a dynamic array of floats  
http://rosettacode.org/wiki/Van_Eck_sequence
Van Eck sequence
The sequence is generated by following this pseudo-code: A: The first term is zero. Repeatedly apply: If the last term is *new* to the sequence so far then: B: The next term is zero. Otherwise: C: The next term is how far back this last term occured previously. Example Using A: 0 Using B: 0 0 Using C: 0 0 1 Using B: 0 0 1 0 Using C: (zero last occurred two steps back - before the one) 0 0 1 0 2 Using B: 0 0 1 0 2 0 Using C: (two last occurred two steps back - before the zero) 0 0 1 0 2 0 2 2 Using C: (two last occurred one step back) 0 0 1 0 2 0 2 2 1 Using C: (one last appeared six steps back) 0 0 1 0 2 0 2 2 1 6 ... Task Create a function/procedure/method/subroutine/... to generate the Van Eck sequence of numbers. Use it to display here, on this page: The first ten terms of the sequence. Terms 991 - to - 1000 of the sequence. References Don't Know (the Van Eck Sequence) - Numberphile video. Wikipedia Article: Van Eck's Sequence. OEIS sequence: A181391.
#Factor
Factor
USING: assocs fry kernel make math namespaces prettyprint sequences ;   : van-eck ( n -- seq ) [ 0 , 1 - H{ } clone '[ building get [ length 1 - ] [ last ] bi _ 3dup 2dup key? [ at - ] [ 3drop 0 ] if , set-at ] times ] { } make ;   1000 van-eck 10 [ head ] [ tail* ] 2bi [ . ] bi@
http://rosettacode.org/wiki/Van_Eck_sequence
Van Eck sequence
The sequence is generated by following this pseudo-code: A: The first term is zero. Repeatedly apply: If the last term is *new* to the sequence so far then: B: The next term is zero. Otherwise: C: The next term is how far back this last term occured previously. Example Using A: 0 Using B: 0 0 Using C: 0 0 1 Using B: 0 0 1 0 Using C: (zero last occurred two steps back - before the one) 0 0 1 0 2 Using B: 0 0 1 0 2 0 Using C: (two last occurred two steps back - before the zero) 0 0 1 0 2 0 2 2 Using C: (two last occurred one step back) 0 0 1 0 2 0 2 2 1 Using C: (one last appeared six steps back) 0 0 1 0 2 0 2 2 1 6 ... Task Create a function/procedure/method/subroutine/... to generate the Van Eck sequence of numbers. Use it to display here, on this page: The first ten terms of the sequence. Terms 991 - to - 1000 of the sequence. References Don't Know (the Van Eck Sequence) - Numberphile video. Wikipedia Article: Van Eck's Sequence. OEIS sequence: A181391.
#Fortran
Fortran
program VanEck implicit none integer eck(1000), i, j   eck(1) = 0 do 20 i=1, 999 do 10 j=i-1, 1, -1 if (eck(i) .eq. eck(j)) then eck(i+1) = i-j go to 20 end if 10 continue eck(i+1) = 0 20 continue   do 30 i=1, 10 30 write (*,'(I4)',advance='no') eck(i) write (*,*)   do 40 i=991, 1000 40 write (*,'(I4)',advance='no') eck(i) write (*,*)   end program
http://rosettacode.org/wiki/Vampire_number
Vampire number
A vampire number is a natural decimal number with an even number of digits,   that can be factored into two integers. These two factors are called the   fangs,   and must have the following properties:   they each contain half the number of the decimal digits of the original number   together they consist of exactly the same decimal digits as the original number   at most one of them has a trailing zero An example of a vampire number and its fangs:   1260 : (21, 60) Task Print the first   25   vampire numbers and their fangs. Check if the following numbers are vampire numbers and,   if so,   print them and their fangs: 16758243290880, 24959017348650, 14593825548650 Note that a vampire number can have more than one pair of fangs. See also numberphile.com. vampire search algorithm vampire numbers on OEIS
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
ClearAll[VampireQ] VampireQ[num_Integer] := Module[{poss, divs}, divs = Select[Divisors[num], # <= Sqrt[num] &]; poss = {#, num/#} & /@ divs; If[Length[poss] > 0, poss = Select[poss, Mod[#, 10] =!= {0, 0} &]; If[Length[poss] > 0, poss = Select[poss, Length[IntegerDigits[First[#]]] == Length[IntegerDigits[Last[#]]] &]; If[Length[poss] > 0, poss = Select[poss, Sort[IntegerDigits[num]] == Sort[Join @@ (IntegerDigits /@ #)] &]; If[Length[poss] > 0 , Sow[{num, poss}]; True , False ] , False ] , False ] , False ] ]
http://rosettacode.org/wiki/Vampire_number
Vampire number
A vampire number is a natural decimal number with an even number of digits,   that can be factored into two integers. These two factors are called the   fangs,   and must have the following properties:   they each contain half the number of the decimal digits of the original number   together they consist of exactly the same decimal digits as the original number   at most one of them has a trailing zero An example of a vampire number and its fangs:   1260 : (21, 60) Task Print the first   25   vampire numbers and their fangs. Check if the following numbers are vampire numbers and,   if so,   print them and their fangs: 16758243290880, 24959017348650, 14593825548650 Note that a vampire number can have more than one pair of fangs. See also numberphile.com. vampire search algorithm vampire numbers on OEIS
#Nim
Nim
import algorithm, math, sequtils, strformat, strutils, sugar   const Pow10 = collect(newSeq, for n in 0..18: 10 ^ n)   template isOdd(n: int): bool = (n and 1) != 0   proc fangs(n: Positive): seq[(int, int)] = ## Return the list fo fangs of "n" (empty if "n" is not vampiric). let nDigits = sorted($n) if nDigits.len.isOdd: return @[] let fangLen = nDigits.len div 2 let inf = Pow10[fangLen - 1] let sup = inf * 10 - 1 for d in inf..sup: if n mod d != 0: continue let q = n div d if q < d: return let dDigits = $d let qDigits = $q if qDigits.len > fangLen: continue if qDigits.len < fangLen: return if nDigits != sorted(dDigits & qDigits): continue if dDigits[^1] != '0' or qDigits[^1] != '0': # Finally, "n" is vampiric. Add the fangs to the result. result.add (d, q)     echo "First 25 vampire numbers with their fangs:" var count = 0 var n = 10 var limit = 100 while count != 25: let fangList = n.fangs if fangList.len != 0: inc count echo &"{count:2}: {n:>6} = ", fangList.mapIt(&"{it[0]:3} × {it[1]:3}").join(" = ") inc n if n == limit: n *= 10 limit *= 10   echo() for n in [16_758_243_290_880, 24_959_017_348_650, 14_593_825_548_650]: let fangList = n.fangs if fangList.len == 0: echo &"{n} is not vampiric." else: echo &"{n} = ", fangList.mapIt(&"{it[0]} × {it[1]}").join(" = ")
http://rosettacode.org/wiki/Variadic_function
Variadic function
Task Create a function which takes in a variable number of arguments and prints each one on its own line. Also show, if possible in your language, how to call the function on a list of arguments constructed at runtime. Functions of this type are also known as Variadic Functions. Related task   Call a function
#Ksh
Ksh
  #!/bin/ksh   # Variadic function   # # Variables: # typeset -a arr=( 0 2 4 6 8 )   # # Functions: # function _variadic { while [[ -n $1 ]]; do print $1 shift done }   ###### # main # ######   _variadic Mary had a little lamb echo _variadic ${arr[@]}
http://rosettacode.org/wiki/Variadic_function
Variadic function
Task Create a function which takes in a variable number of arguments and prints each one on its own line. Also show, if possible in your language, how to call the function on a list of arguments constructed at runtime. Functions of this type are also known as Variadic Functions. Related task   Call a function
#Lambdatalk
Lambdatalk
  {def foo {lambda {:s} {if {S.empty? {S.rest :s}} then {br}{S.first :s} else {br}{S.first :s} {foo {S.rest :s}}}}}   {foo hello brave new world} -> hello brave new world   {foo {S.serie 1 10}} -> 1 2 3 4 5 6 7 8 9 10    
http://rosettacode.org/wiki/Vector
Vector
Task Implement a Vector class (or a set of functions) that models a Physical Vector. The four basic operations and a pretty print function should be implemented. The Vector may be initialized in any reasonable way. Start and end points, and direction Angular coefficient and value (length) The four operations to be implemented are: Vector + Vector addition Vector - Vector subtraction Vector * scalar multiplication Vector / scalar division
#Red
Red
Red [ Source: https://github.com/vazub/rosetta-red Tabs: 4 ]   comment { Vector type is one of base datatypes in Red, with all arithmetic already implemented.   Caveats to keep in mind: - Arithmetic on a single vector will modify the vector in place, so we use copy to avoid that - Division result on integer vectors will get truncated, use floats for decimal precision }   v1: make vector! [5.0 7.0] v2: make vector! [2.0 3.0]   prin pad "v1: " 10 print v1 prin pad "v2: " 10 print v2 prin pad "v1 + v2: " 10 print v1 + v2 prin pad "v1 - v2: " 10 print v1 - v2 prin pad "v1 * 11" 10 print (copy v1) * 11 prin pad "v1 / 2" 10 print (copy v1) / 2  
http://rosettacode.org/wiki/Vector
Vector
Task Implement a Vector class (or a set of functions) that models a Physical Vector. The four basic operations and a pretty print function should be implemented. The Vector may be initialized in any reasonable way. Start and end points, and direction Angular coefficient and value (length) The four operations to be implemented are: Vector + Vector addition Vector - Vector subtraction Vector * scalar multiplication Vector / scalar division
#REXX
REXX
/*REXX program shows how to support mathematical functions for vectors using functions. */ s1 = 11 /*define the s1 scalar: eleven */ s2 = 2 /*define the s2 scalar: two */ x = '(5, 7)' /*define the X vector: five and seven*/ y = '(2, 3)' /*define the Y vector: two and three*/ z = '(2, 45)' /*define vector of length 2 at 45º */ call show 'define a vector (length,ºangle):', z , Vdef(z) call show 'addition (vector+vector):', x " + " y , Vadd(x, y) call show 'subtraction (vector-vector):', x " - " y , vsub(x, y) call show 'multiplication (Vector*scalar):', x " * " s1, Vmul(x, s1) call show 'division (vector/scalar):', x " ÷ " s2, Vdiv(x, s2) exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ $fuzz: return min( arg(1), max(1, digits() - arg(2) ) ) cosD: return cos( d2r( arg(1) ) ) d2d: return arg(1) // 360 /*normalize degrees ──► a unit circle. */ d2r: return r2r( d2d(arg(1)) * pi() / 180) /*convert degrees ──► radians. */ pi: pi=3.14159265358979323846264338327950288419716939937510582; return pi r2d: return d2d( (arg(1)*180 / pi())) /*convert radians ──► degrees. */ r2r: return arg(1) // (pi() * 2) /*normalize radians ──► a unit circle. */ show: say right( arg(1), 33) right( arg(2), 20) ' ──► ' arg(3); return sinD: return sin( d2r( d2d( arg(1) ) ) ) V: return word( translate( arg(1), , '{[(JI)]}') 0, 1) /*get the number or zero*/ V$: parse arg r,c; _='['r; if c\=0 then _=_"," c; return _']' V#: a=V(a); b=V(b); c=V(c); d=V(d); ac=a*c; ad=a*d; bc=b*c; bd=b*d; s=c*c+d*d; return Vadd: procedure; arg a ',' b,c "," d; call V#; return V$(a+c, b+d) Vsub: procedure; arg a ',' b,c "," d; call V#; return V$(a-c, b-d) Vmul: procedure; arg a ',' b,c "," d; call V#; return V$(ac-bd, bc+ad) Vdiv: procedure; arg a ',' b,c "," d; call V#; return V$((ac+bd)/s, (bc-ad)/s) Vdef: procedure; arg a ',' b,c "," d; call V#; return V$(a*sinD(b), a*cosD(b)) /*──────────────────────────────────────────────────────────────────────────────────────*/ cos: procedure; parse arg x; x=r2r(x); a=abs(x); numeric fuzz $fuzz(9, 9) if a=pi then return -1; if a=pi*.5 | a=pi*2 then return 0; return .sinCos(1,-1) /*──────────────────────────────────────────────────────────────────────────────────────*/ sin: procedure; parse arg x; x=r2r(x); numeric fuzz $fuzz(5, 3) if x=pi*.5 then return 1; if x=pi*1.5 then return -1 if abs(x)=pi | x=0 then return 0; return .sinCos(x,+1) /*──────────────────────────────────────────────────────────────────────────────────────*/ .sinCos: parse arg z 1 _,i; q=x*x do k=2 by 2 until p=z; p=z; _= -_*q / (k*(k+i)); z=z+_; end; return z
http://rosettacode.org/wiki/Vigen%C3%A8re_cipher
Vigenère cipher
Task Implement a   Vigenère cypher,   both encryption and decryption. The program should handle keys and text of unequal length, and should capitalize everything and discard non-alphabetic characters. (If your program handles non-alphabetic characters in another way, make a note of it.) Related tasks   Caesar cipher   Rot-13   Substitution Cipher
#Red
Red
red.exe -c vign1.red
http://rosettacode.org/wiki/Vigen%C3%A8re_cipher
Vigenère cipher
Task Implement a   Vigenère cypher,   both encryption and decryption. The program should handle keys and text of unequal length, and should capitalize everything and discard non-alphabetic characters. (If your program handles non-alphabetic characters in another way, make a note of it.) Related tasks   Caesar cipher   Rot-13   Substitution Cipher
#REXX
REXX
/*REXX program encrypts (and displays) uppercased text using the Vigenère cypher.*/ @.1 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' L=length(@.1) do j=2 to L; jm=j-1; [email protected] @.j=substr(q, 2, L - 1)left(q, 1) end /*j*/   cypher = space('WHOOP DE DOO NO BIG DEAL HERE OR THERE', 0) oMsg = 'People solve problems by trial and error; judgement helps pick the trial.' oMsgU = oMsg; upper oMsgU cypher_= copies(cypher, length(oMsg) % length(cypher) ) say ' original text =' oMsg xMsg= Ncypher(oMsgU); say ' cyphered text =' xMsg bMsg= Dcypher(xMsg) ; say 're-cyphered text =' bMsg exit /*──────────────────────────────────────────────────────────────────────────────────────*/ Ncypher: parse arg x; nMsg=; #=1 /*unsupported char? ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓*/ do i=1 for length(x); j=pos(substr(x,i,1), @.1); if j==0 then iterate nMsg=nMsg || substr(@.j, pos( substr( cypher_, #, 1), @.1), 1); #=#+1 end /*j*/ return nMsg /*──────────────────────────────────────────────────────────────────────────────────────*/ Dcypher: parse arg x; dMsg= do i=1 for length(x); j=pos(substr(cypher_, i, 1), @.1) dMsg=dMsg || substr(@.1, pos( substr(x, i, 1), @.j), 1 ) end /*j*/ return dMsg
http://rosettacode.org/wiki/Vector_products
Vector products
A vector is defined as having three dimensions as being represented by an ordered collection of three numbers:   (X, Y, Z). If you imagine a graph with the   x   and   y   axis being at right angles to each other and having a third,   z   axis coming out of the page, then a triplet of numbers,   (X, Y, Z)   would represent a point in the region,   and a vector from the origin to the point. Given the vectors: A = (a1, a2, a3) B = (b1, b2, b3) C = (c1, c2, c3) then the following common vector products are defined: The dot product       (a scalar quantity) A • B = a1b1   +   a2b2   +   a3b3 The cross product       (a vector quantity) A x B = (a2b3  -   a3b2,     a3b1   -   a1b3,     a1b2   -   a2b1) The scalar triple product       (a scalar quantity) A • (B x C) The vector triple product       (a vector quantity) A x (B x C) Task Given the three vectors: a = ( 3, 4, 5) b = ( 4, 3, 5) c = (-5, -12, -13) Create a named function/subroutine/method to compute the dot product of two vectors. Create a function to compute the cross product of two vectors. Optionally create a function to compute the scalar triple product of three vectors. Optionally create a function to compute the vector triple product of three vectors. Compute and display: a • b Compute and display: a x b Compute and display: a • (b x c), the scalar triple product. Compute and display: a x (b x c), the vector triple product. References   A starting page on Wolfram MathWorld is   Vector Multiplication .   Wikipedia   dot product.   Wikipedia   cross product.   Wikipedia   triple product. Related tasks   Dot product   Quaternion type
#Elixir
Elixir
defmodule Vector do def dot_product({a1,a2,a3}, {b1,b2,b3}), do: a1*b1 + a2*b2 + a3*b3   def cross_product({a1,a2,a3}, {b1,b2,b3}), do: {a2*b3 - a3*b2, a3*b1 - a1*b3, a1*b2 - a2*b1}   def scalar_triple_product(a, b, c), do: dot_product(a, cross_product(b, c))   def vector_triple_product(a, b, c), do: cross_product(a, cross_product(b, c)) end   a = {3, 4, 5} b = {4, 3, 5} c = {-5, -12, -13}   IO.puts "a = #{inspect a}" IO.puts "b = #{inspect b}" IO.puts "c = #{inspect c}" IO.puts "a . b = #{inspect Vector.dot_product(a, b)}" IO.puts "a x b = #{inspect Vector.cross_product(a, b)}" IO.puts "a . (b x c) = #{inspect Vector.scalar_triple_product(a, b, c)}" IO.puts "a x (b x c) = #{inspect Vector.vector_triple_product(a, b, c)}"
http://rosettacode.org/wiki/Validate_International_Securities_Identification_Number
Validate International Securities Identification Number
An International Securities Identification Number (ISIN) is a unique international identifier for a financial security such as a stock or bond. Task Write a function or program that takes a string as input, and checks whether it is a valid ISIN. It is only valid if it has the correct format,   and   the embedded checksum is correct. Demonstrate that your code passes the test-cases listed below. Details The format of an ISIN is as follows: ┌───────────── a 2-character ISO country code (A-Z) │ ┌─────────── a 9-character security code (A-Z, 0-9) │ │        ┌── a checksum digit (0-9) AU0000XVGZA3 For this task, you may assume that any 2-character alphabetic sequence is a valid country code. The checksum can be validated as follows: Replace letters with digits, by converting each character from base 36 to base 10, e.g. AU0000XVGZA3 →1030000033311635103. Perform the Luhn test on this base-10 number. There is a separate task for this test: Luhn test of credit card numbers. You don't have to replicate the implementation of this test here   ───   you can just call the existing function from that task.   (Add a comment stating if you did this.) Test cases ISIN Validity Comment US0378331005 valid US0373831005 not valid The transposition typo is caught by the checksum constraint. U50378331005 not valid The substitution typo is caught by the format constraint. US03378331005 not valid The duplication typo is caught by the format constraint. AU0000XVGZA3 valid AU0000VXGZA3 valid Unfortunately, not all transposition typos are caught by the checksum constraint. FR0000988040 valid (The comments are just informational.   Your function should simply return a Boolean result.   See #Raku for a reference solution.) Related task: Luhn test of credit card numbers Also see Interactive online ISIN validator Wikipedia article: International Securities Identification Number
#J
J
require'regex' validFmt=: 0 -: '^[A-Z]{2}[A-Z0-9]{9}[0-9]{1}$'&rxindex   df36=: ;@([: <@":"0 '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'&i.) NB. decimal from base 36 luhn=: 0 = 10 (| +/@,) 10 #.inv 1 2 *&|: _2 "."0\ |. NB. as per task Luhn_test_of_credit_card_numbers#J   validISIN=: validFmt *. luhn@df36
http://rosettacode.org/wiki/Validate_International_Securities_Identification_Number
Validate International Securities Identification Number
An International Securities Identification Number (ISIN) is a unique international identifier for a financial security such as a stock or bond. Task Write a function or program that takes a string as input, and checks whether it is a valid ISIN. It is only valid if it has the correct format,   and   the embedded checksum is correct. Demonstrate that your code passes the test-cases listed below. Details The format of an ISIN is as follows: ┌───────────── a 2-character ISO country code (A-Z) │ ┌─────────── a 9-character security code (A-Z, 0-9) │ │        ┌── a checksum digit (0-9) AU0000XVGZA3 For this task, you may assume that any 2-character alphabetic sequence is a valid country code. The checksum can be validated as follows: Replace letters with digits, by converting each character from base 36 to base 10, e.g. AU0000XVGZA3 →1030000033311635103. Perform the Luhn test on this base-10 number. There is a separate task for this test: Luhn test of credit card numbers. You don't have to replicate the implementation of this test here   ───   you can just call the existing function from that task.   (Add a comment stating if you did this.) Test cases ISIN Validity Comment US0378331005 valid US0373831005 not valid The transposition typo is caught by the checksum constraint. U50378331005 not valid The substitution typo is caught by the format constraint. US03378331005 not valid The duplication typo is caught by the format constraint. AU0000XVGZA3 valid AU0000VXGZA3 valid Unfortunately, not all transposition typos are caught by the checksum constraint. FR0000988040 valid (The comments are just informational.   Your function should simply return a Boolean result.   See #Raku for a reference solution.) Related task: Luhn test of credit card numbers Also see Interactive online ISIN validator Wikipedia article: International Securities Identification Number
#Java
Java
public class ISIN {   public static void main(String[] args) { String[] isins = { "US0378331005", "US0373831005", "U50378331005", "US03378331005", "AU0000XVGZA3", "AU0000VXGZA3", "FR0000988040" }; for (String isin : isins) System.out.printf("%s is %s\n", isin, ISINtest(isin) ? "valid" : "not valid"); }   static boolean ISINtest(String isin) { isin = isin.trim().toUpperCase();   if (!isin.matches("^[A-Z]{2}[A-Z0-9]{9}\\d$")) return false;   StringBuilder sb = new StringBuilder(); for (char c : isin.substring(0, 12).toCharArray()) sb.append(Character.digit(c, 36));   return luhnTest(sb.toString()); }   static boolean luhnTest(String number) { int s1 = 0, s2 = 0; String reverse = new StringBuffer(number).reverse().toString(); for (int i = 0; i < reverse.length(); i++){ int digit = Character.digit(reverse.charAt(i), 10); //This is for odd digits, they are 1-indexed in the algorithm. if (i % 2 == 0){ s1 += digit; } else { // Add 2 * digit for 0-4, add 2 * digit - 9 for 5-9. s2 += 2 * digit; if(digit >= 5){ s2 -= 9; } } } return (s1 + s2) % 10 == 0; } }
http://rosettacode.org/wiki/Van_der_Corput_sequence
Van der Corput sequence
When counting integers in binary, if you put a (binary) point to the righEasyLangt of the count then the column immediately to the left denotes a digit with a multiplier of 2 0 {\displaystyle 2^{0}} ; the digit in the next column to the left has a multiplier of 2 1 {\displaystyle 2^{1}} ; and so on. So in the following table: 0. 1. 10. 11. ... the binary number "10" is 1 × 2 1 + 0 × 2 0 {\displaystyle 1\times 2^{1}+0\times 2^{0}} . You can also have binary digits to the right of the “point”, just as in the decimal number system. In that case, the digit in the place immediately to the right of the point has a weight of 2 − 1 {\displaystyle 2^{-1}} , or 1 / 2 {\displaystyle 1/2} . The weight for the second column to the right of the point is 2 − 2 {\displaystyle 2^{-2}} or 1 / 4 {\displaystyle 1/4} . And so on. If you take the integer binary count of the first table, and reflect the digits about the binary point, you end up with the van der Corput sequence of numbers in base 2. .0 .1 .01 .11 ... The third member of the sequence, binary 0.01, is therefore 0 × 2 − 1 + 1 × 2 − 2 {\displaystyle 0\times 2^{-1}+1\times 2^{-2}} or 1 / 4 {\displaystyle 1/4} . Distribution of 2500 points each: Van der Corput (top) vs pseudorandom 0 ≤ x < 1 {\displaystyle 0\leq x<1} Monte Carlo simulations This sequence is also a superset of the numbers representable by the "fraction" field of an old IEEE floating point standard. In that standard, the "fraction" field represented the fractional part of a binary number beginning with "1." e.g. 1.101001101. Hint A hint at a way to generate members of the sequence is to modify a routine used to change the base of an integer: >>> def base10change(n, base): digits = [] while n: n,remainder = divmod(n, base) digits.insert(0, remainder) return digits   >>> base10change(11, 2) [1, 0, 1, 1] the above showing that 11 in decimal is 1 × 2 3 + 0 × 2 2 + 1 × 2 1 + 1 × 2 0 {\displaystyle 1\times 2^{3}+0\times 2^{2}+1\times 2^{1}+1\times 2^{0}} . Reflected this would become .1101 or 1 × 2 − 1 + 1 × 2 − 2 + 0 × 2 − 3 + 1 × 2 − 4 {\displaystyle 1\times 2^{-1}+1\times 2^{-2}+0\times 2^{-3}+1\times 2^{-4}} Task description Create a function/method/routine that given n, generates the n'th term of the van der Corput sequence in base 2. Use the function to compute and display the first ten members of the sequence. (The first member of the sequence is for n=0). As a stretch goal/extra credit, compute and show members of the sequence for bases other than 2. See also The Basic Low Discrepancy Sequences Non-decimal radices/Convert Van der Corput sequence
#FreeBASIC
FreeBASIC
' version 03-12-2016 ' compile with: fbc -s console   Function num_base(number As ULongInt, _base_ As UInteger) As String   If _base_ > 9 Then Print "base not handled by function" Sleep 5000 Return "" End If   Dim As ULongInt n Dim As String ans   While number <> 0 n = number Mod _base_ ans = Str(n) + ans number = number \ _base_ Wend   If ans = "" Then ans = "0"   Return "." + ans   End Function   ' ------=< MAIN >=------   Dim As ULong k, l For k = 2 To 5 Print "Base = "; k For l = 0 To 12 Print left(num_base(l, k) + " ",6); Next Print : print Next   ' empty keyboard buffer While Inkey <> "" : Wend Print : Print "hit any key to end program" Sleep End
http://rosettacode.org/wiki/Van_der_Corput_sequence
Van der Corput sequence
When counting integers in binary, if you put a (binary) point to the righEasyLangt of the count then the column immediately to the left denotes a digit with a multiplier of 2 0 {\displaystyle 2^{0}} ; the digit in the next column to the left has a multiplier of 2 1 {\displaystyle 2^{1}} ; and so on. So in the following table: 0. 1. 10. 11. ... the binary number "10" is 1 × 2 1 + 0 × 2 0 {\displaystyle 1\times 2^{1}+0\times 2^{0}} . You can also have binary digits to the right of the “point”, just as in the decimal number system. In that case, the digit in the place immediately to the right of the point has a weight of 2 − 1 {\displaystyle 2^{-1}} , or 1 / 2 {\displaystyle 1/2} . The weight for the second column to the right of the point is 2 − 2 {\displaystyle 2^{-2}} or 1 / 4 {\displaystyle 1/4} . And so on. If you take the integer binary count of the first table, and reflect the digits about the binary point, you end up with the van der Corput sequence of numbers in base 2. .0 .1 .01 .11 ... The third member of the sequence, binary 0.01, is therefore 0 × 2 − 1 + 1 × 2 − 2 {\displaystyle 0\times 2^{-1}+1\times 2^{-2}} or 1 / 4 {\displaystyle 1/4} . Distribution of 2500 points each: Van der Corput (top) vs pseudorandom 0 ≤ x < 1 {\displaystyle 0\leq x<1} Monte Carlo simulations This sequence is also a superset of the numbers representable by the "fraction" field of an old IEEE floating point standard. In that standard, the "fraction" field represented the fractional part of a binary number beginning with "1." e.g. 1.101001101. Hint A hint at a way to generate members of the sequence is to modify a routine used to change the base of an integer: >>> def base10change(n, base): digits = [] while n: n,remainder = divmod(n, base) digits.insert(0, remainder) return digits   >>> base10change(11, 2) [1, 0, 1, 1] the above showing that 11 in decimal is 1 × 2 3 + 0 × 2 2 + 1 × 2 1 + 1 × 2 0 {\displaystyle 1\times 2^{3}+0\times 2^{2}+1\times 2^{1}+1\times 2^{0}} . Reflected this would become .1101 or 1 × 2 − 1 + 1 × 2 − 2 + 0 × 2 − 3 + 1 × 2 − 4 {\displaystyle 1\times 2^{-1}+1\times 2^{-2}+0\times 2^{-3}+1\times 2^{-4}} Task description Create a function/method/routine that given n, generates the n'th term of the van der Corput sequence in base 2. Use the function to compute and display the first ten members of the sequence. (The first member of the sequence is for n=0). As a stretch goal/extra credit, compute and show members of the sequence for bases other than 2. See also The Basic Low Discrepancy Sequences Non-decimal radices/Convert Van der Corput sequence
#F.C5.8Drmul.C3.A6
Fōrmulæ
package main   import "fmt"   func v2(n uint) (r float64) { p := .5 for n > 0 { if n&1 == 1 { r += p } p *= .5 n >>= 1 } return }   func newV(base uint) func(uint) float64 { invb := 1 / float64(base) return func(n uint) (r float64) { p := invb for n > 0 { r += p * float64(n%base) p *= invb n /= base } return } }   func main() { fmt.Println("Base 2:") for i := uint(0); i < 10; i++ { fmt.Println(i, v2(i)) } fmt.Println("Base 3:") v3 := newV(3) for i := uint(0); i < 10; i++ { fmt.Println(i, v3(i)) } }
http://rosettacode.org/wiki/URL_decoding
URL decoding
This task   (the reverse of   URL encoding   and distinct from   URL parser)   is to provide a function or mechanism to convert an URL-encoded string into its original unencoded form. Test cases   The encoded string   "http%3A%2F%2Ffoo%20bar%2F"   should be reverted to the unencoded form   "http://foo bar/".   The encoded string   "google.com/search?q=%60Abdu%27l-Bah%C3%A1"   should revert to the unencoded form   "google.com/search?q=`Abdu'l-Bahá".
#C.23
C#
using System;   namespace URLEncode { internal class Program { private static void Main(string[] args) { Console.WriteLine(Decode("http%3A%2F%2Ffoo%20bar%2F")); }   private static string Decode(string uri) { return Uri.UnescapeDataString(uri); } } }
http://rosettacode.org/wiki/URL_decoding
URL decoding
This task   (the reverse of   URL encoding   and distinct from   URL parser)   is to provide a function or mechanism to convert an URL-encoded string into its original unencoded form. Test cases   The encoded string   "http%3A%2F%2Ffoo%20bar%2F"   should be reverted to the unencoded form   "http://foo bar/".   The encoded string   "google.com/search?q=%60Abdu%27l-Bah%C3%A1"   should revert to the unencoded form   "google.com/search?q=`Abdu'l-Bahá".
#C.2B.2B
C++
#include <string> #include "Poco/URI.h" #include <iostream>   int main( ) { std::string encoded( "http%3A%2F%2Ffoo%20bar%2F" ) ; std::string decoded ; Poco::URI::decode ( encoded , decoded ) ; std::cout << encoded << " is decoded: " << decoded << " !" << std::endl ; return 0 ; }
http://rosettacode.org/wiki/Update_a_configuration_file
Update a configuration file
We have a configuration file as follows: # This is a configuration file in standard configuration file format # # Lines begininning with a hash or a semicolon are ignored by the application # program. Blank lines are also ignored by the application program. # The first word on each non comment line is the configuration option. # Remaining words or numbers on the line are configuration parameter # data fields. # Note that configuration option names are not case sensitive. However, # configuration parameter data is case sensitive and the lettercase must # be preserved. # This is a favourite fruit FAVOURITEFRUIT banana # This is a boolean that should be set NEEDSPEELING # This boolean is commented out ; SEEDSREMOVED # How many bananas we have NUMBEROFBANANAS 48 The task is to manipulate the configuration file as follows: Disable the needspeeling option (using a semicolon prefix) Enable the seedsremoved option by removing the semicolon and any leading whitespace Change the numberofbananas parameter to 1024 Enable (or create if it does not exist in the file) a parameter for numberofstrawberries with a value of 62000 Note that configuration option names are not case sensitive. This means that changes should be effected, regardless of the case. Options should always be disabled by prefixing them with a semicolon. Lines beginning with hash symbols should not be manipulated and left unchanged in the revised file. If a configuration option does not exist within the file (in either enabled or disabled form), it should be added during this update. Duplicate configuration option names in the file should be removed, leaving just the first entry. For the purpose of this task, the revised file should contain appropriate entries, whether enabled or not for needspeeling,seedsremoved,numberofbananas and numberofstrawberries.) The update should rewrite configuration option names in capital letters. However lines beginning with hashes and any parameter data must not be altered (eg the banana for favourite fruit must not become capitalized). The update process should also replace double semicolon prefixes with just a single semicolon (unless it is uncommenting the option, in which case it should remove all leading semicolons). Any lines beginning with a semicolon or groups of semicolons, but no following option should be removed, as should any leading or trailing whitespace on the lines. Whitespace between the option and parameters should consist only of a single space, and any non-ASCII extended characters, tabs characters, or control codes (other than end of line markers), should also be removed. Related tasks Read a configuration file
#D
D
import std.stdio, std.file, std.string, std.regex, std.path, std.typecons;   final class Config { enum EntryType { empty, enabled, disabled, comment, ignore }   static protected struct Entry { EntryType type; string name, value; } protected Entry[] entries; protected string path;   this(in string path) { if (!isValidPath(path) || (exists(path) && !isFile(path))) throw new Exception("Invalid filename");   this.path = path; if (!exists(path)) return;   auto r = regex(r"^(;*)\s*([A-Z0-9]+)\s*([A-Z0-9]*)", "i"); auto f = File(path, "r"); foreach (const buf; f.byLine()) { auto line = buf.strip().idup; if (!line.length) entries ~= Entry(EntryType.empty); else if (line[0] == '#') entries ~= Entry(EntryType.comment, line); else { line = line.removechars("^a-zA-Z0-9\x20;"); auto m = match(line, r); if (!m.empty && m.front[2].length) { EntryType t = EntryType.enabled; if (m.front[1].length) t = EntryType.disabled; addOption(m.front[2], m.front[3], t); } } } }   void enableOption(in string name) pure { immutable i = getOptionIndex(name); if (!i.isNull) entries[i].type = EntryType.enabled; }   void disableOption(in string name) pure { immutable i = getOptionIndex(name); if (!i.isNull) entries[i].type = EntryType.disabled; }   void setOption(in string name, in string value) pure { immutable i = getOptionIndex(name); if (!i.isNull) entries[i].value = value; }   void addOption(in string name, in string val, in EntryType t = EntryType.enabled) pure { entries ~= Entry(t, name.toUpper(), val); }   void removeOption(in string name) pure { immutable i = getOptionIndex(name); if (!i.isNull) entries[i].type = EntryType.ignore; }   Nullable!size_t getOptionIndex(in string name) const pure { foreach (immutable i, const ref e; entries) { if (e.type != EntryType.enabled && e.type != EntryType.disabled) continue; if (e.name == name.toUpper()) return typeof(return)(i); } return typeof(return).init; }   void store() { auto f = File(path, "w+"); foreach (immutable e; entries) { final switch (e.type) { case EntryType.empty: f.writeln(); break; case EntryType.enabled: f.writefln("%s %s", e.name, e.value); break; case EntryType.disabled: f.writefln("; %s %s", e.name, e.value); break; case EntryType.comment: f.writeln(e.name); break; case EntryType.ignore: continue; } } } }   void main() { auto cfg = new Config("config.txt"); cfg.enableOption("seedsremoved"); cfg.disableOption("needspeeling"); cfg.setOption("numberofbananas", "1024"); cfg.addOption("numberofstrawberries", "62000"); cfg.store(); }
http://rosettacode.org/wiki/User_input/Text
User input/Text
User input/Text is part of Short Circuit's Console Program Basics selection. Task Input a string and the integer   75000   from the text console. See also: User input/Graphical
#BBC_BASIC
BBC BASIC
INPUT LINE "Enter a string: " string$ INPUT "Enter a number: " number   PRINT "String = """ string$ """" PRINT "Number = " ; number
http://rosettacode.org/wiki/User_input/Text
User input/Text
User input/Text is part of Short Circuit's Console Program Basics selection. Task Input a string and the integer   75000   from the text console. See also: User input/Graphical
#Befunge
Befunge
<>:v:"Enter a string: " ^,_ >~:1+v ^ _@
http://rosettacode.org/wiki/User_input/Graphical
User input/Graphical
In this task, the goal is to input a string and the integer 75000, from graphical user interface. See also: User input/Text
#C.2B.2B
C++
task.h
http://rosettacode.org/wiki/User_input/Graphical
User input/Graphical
In this task, the goal is to input a string and the integer 75000, from graphical user interface. See also: User input/Text
#Clojure
Clojure
(import 'javax.swing.JOptionPane) (let [number (-> "Enter an Integer" JOptionPane/showInputDialog Integer/parseInt) string (JOptionPane/showInputDialog "Enter a String")] [number string])
http://rosettacode.org/wiki/UTF-8_encode_and_decode
UTF-8 encode and decode
As described in UTF-8 and in Wikipedia, UTF-8 is a popular encoding of (multi-byte) Unicode code-points into eight-bit octets. The goal of this task is to write a encoder that takes a unicode code-point (an integer representing a unicode character) and returns a sequence of 1-4 bytes representing that character in the UTF-8 encoding. Then you have to write the corresponding decoder that takes a sequence of 1-4 UTF-8 encoded bytes and return the corresponding unicode character. Demonstrate the functionality of your encoder and decoder on the following five characters: Character Name Unicode UTF-8 encoding (hex) --------------------------------------------------------------------------------- A LATIN CAPITAL LETTER A U+0041 41 ö LATIN SMALL LETTER O WITH DIAERESIS U+00F6 C3 B6 Ж CYRILLIC CAPITAL LETTER ZHE U+0416 D0 96 € EURO SIGN U+20AC E2 82 AC 𝄞 MUSICAL SYMBOL G CLEF U+1D11E F0 9D 84 9E Provided below is a reference implementation in Common Lisp.
#Common_Lisp
Common Lisp
  (defun ascii-byte-p (octet) "Return t if octet is a single-byte 7-bit ASCII char. The most significant bit is 0, so the allowed pattern is 0xxx xxxx." (assert (typep octet 'integer)) (assert (<= (integer-length octet) 8)) (let ((bitmask #b10000000) (template #b00000000)) ;; bitwise and the with the bitmask #b11000000 to extract the first two bits. ;; check if the first two bits are equal to the template #b10000000. (= (logand bitmask octet) template)))   (defun multi-byte-p (octet) "Return t if octet is a part of a multi-byte UTF-8 sequence. The multibyte pattern is 1xxx xxxx. A multi-byte can be either a lead byte or a trail byte." (assert (typep octet 'integer)) (assert (<= (integer-length octet) 8)) (let ((bitmask #b10000000) (template #b10000000)) ;; bitwise and the with the bitmask #b11000000 to extract the first two bits. ;; check if the first two bits are equal to the template #b10000000. (= (logand bitmask octet) template)))   (defun lead-byte-p (octet) "Return t if octet is one of the leading bytes of an UTF-8 sequence, nil otherwise. Allowed leading byte patterns are 0xxx xxxx, 110x xxxx, 1110 xxxx and 1111 0xxx." (assert (typep octet 'integer)) (assert (<= (integer-length octet) 8)) (let ((bitmasks (list #b10000000 #b11100000 #b11110000 #b11111000)) (templates (list #b00000000 #b11000000 #b11100000 #b11110000))) (some #'(lambda (a b) (= (logand a octet) b)) bitmasks templates)))   (defun n-trail-bytes (octet) "Take a leading utf-8 byte, return the number of continuation bytes 1-3." (assert (typep octet 'integer)) (assert (<= (integer-length octet) 8)) (let ((bitmasks (list #b10000000 #b11100000 #b11110000 #b11111000)) (templates (list #b00000000 #b11000000 #b11100000 #b11110000))) (loop for i from 0 to 3 when (= (nth i templates) (logand (nth i bitmasks) octet)) return i)))  
http://rosettacode.org/wiki/Use_another_language_to_call_a_function
Use another language to call a function
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. This task is inverse to the task Call foreign language function. Consider the following C program: #include <stdio.h>   extern int Query (char * Data, size_t * Length);   int main (int argc, char * argv []) { char Buffer [1024]; size_t Size = sizeof (Buffer);   if (0 == Query (Buffer, &Size)) { printf ("failed to call Query\n"); } else { char * Ptr = Buffer; while (Size-- > 0) putchar (*Ptr++); putchar ('\n'); } } Implement the missing Query function in your language, and let this C program call it. The function should place the string Here am I into the buffer which is passed to it as the parameter Data. The buffer size in bytes is passed as the parameter Length. When there is no room in the buffer, Query shall return 0. Otherwise it overwrites the beginning of Buffer, sets the number of overwritten bytes into Length and returns 1.
#Kotlin
Kotlin
// Kotlin Native v0.6   import kotlinx.cinterop.* import platform.posix.*   fun query(data: CPointer<ByteVar>, length: CPointer<size_tVar>): Int { val s = "Here am I" val strLen = s.length val bufferSize = length.pointed.value if (strLen > bufferSize) return 0 // buffer not large enough for (i in 0 until strLen) data[i] = s[i].toByte() length.pointed.value = strLen.signExtend<size_t>() return 1 }
http://rosettacode.org/wiki/Use_another_language_to_call_a_function
Use another language to call a function
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. This task is inverse to the task Call foreign language function. Consider the following C program: #include <stdio.h>   extern int Query (char * Data, size_t * Length);   int main (int argc, char * argv []) { char Buffer [1024]; size_t Size = sizeof (Buffer);   if (0 == Query (Buffer, &Size)) { printf ("failed to call Query\n"); } else { char * Ptr = Buffer; while (Size-- > 0) putchar (*Ptr++); putchar ('\n'); } } Implement the missing Query function in your language, and let this C program call it. The function should place the string Here am I into the buffer which is passed to it as the parameter Data. The buffer size in bytes is passed as the parameter Length. When there is no room in the buffer, Query shall return 0. Otherwise it overwrites the beginning of Buffer, sets the number of overwritten bytes into Length and returns 1.
#Lisaac
Lisaac
Section Header   + name := QUERY; - external := `#define main _query_main`; - external := `#define query Query`;   Section External   - query(buffer : NATIVE_ARRAY[CHARACTER], size : NATIVE_ARRAY[INTEGER]) : INTEGER <- ( + s : STRING_CONSTANT; + len, result : INTEGER; s := "Here am I"; len := s.count; (len > size.item(0)).if { result := 0; } else { 1.to len do { i : INTEGER; buffer.put (s @ i) to (i - 1); }; size.put len to 0; result := 1; }; result );   Section Public   - main <- ( + buffer : NATIVE_ARRAY[CHARACTER]; + size : NATIVE_ARRAY[INTEGER]; query(buffer, size); // need this to pull the query() method );
http://rosettacode.org/wiki/URL_parser
URL parser
URLs are strings with a simple syntax: scheme://[username:password@]domain[:port]/path?query_string#fragment_id Task Parse a well-formed URL to retrieve the relevant information:   scheme, domain, path, ... Note:   this task has nothing to do with URL encoding or URL decoding. According to the standards, the characters:    ! * ' ( ) ; : @ & = + $ , / ? % # [ ] only need to be percent-encoded   (%)   in case of possible confusion. Also note that the path, query and fragment are case sensitive, even if the scheme and domain are not. The way the returned information is provided (set of variables, array, structured, record, object,...) is language-dependent and left to the programmer, but the code should be clear enough to reuse. Extra credit is given for clear error diagnostics.   Here is the official standard:     https://tools.ietf.org/html/rfc3986,   and here is a simpler   BNF:     http://www.w3.org/Addressing/URL/5_URI_BNF.html. Test cases According to T. Berners-Lee foo://example.com:8042/over/there?name=ferret#nose     should parse into:   scheme = foo   domain = example.com   port = :8042   path = over/there   query = name=ferret   fragment = nose urn:example:animal:ferret:nose     should parse into:   scheme = urn   path = example:animal:ferret:nose other URLs that must be parsed include:   jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true   ftp://ftp.is.co.za/rfc/rfc1808.txt   http://www.ietf.org/rfc/rfc2396.txt#header1   ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two   mailto:[email protected]   news:comp.infosystems.www.servers.unix   tel:+1-816-555-1212   telnet://192.0.2.16:80/   urn:oasis:names:specification:docbook:dtd:xml:4.1.2
#JavaScript
JavaScript
(function (lstURL) {   var e = document.createElement('a'), lstKeys = [ 'hash', 'host', 'hostname', 'origin', 'pathname', 'port', 'protocol', 'search' ],   fnURLParse = function (strURL) { e.href = strURL;   return lstKeys.reduce( function (dct, k) { dct[k] = e[k]; return dct; }, {} ); };   return JSON.stringify( lstURL.map(fnURLParse), null, 2 );   })([ "foo://example.com:8042/over/there?name=ferret#nose", "urn:example:animal:ferret:nose", "jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true", "ftp://ftp.is.co.za/rfc/rfc1808.txt", "http://www.ietf.org/rfc/rfc2396.txt#header1", "ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two", "mailto:[email protected]", "news:comp.infosystems.www.servers.unix", "tel:+1-816-555-1212", "telnet://192.0.2.16:80/", "urn:oasis:names:specification:docbook:dtd:xml:4.1.2", "ssh://[email protected]", "https://bob:[email protected]/place", "http://example.com/?a=1&b=2+2&c=3&c=4&d=%65%6e%63%6F%64%65%64" ]);
http://rosettacode.org/wiki/URL_encoding
URL encoding
Task Provide a function or mechanism to convert a provided string into URL encoding representation. In URL encoding, special characters, control characters and extended characters are converted into a percent symbol followed by a two digit hexadecimal code, So a space character encodes into %20 within the string. For the purposes of this task, every character except 0-9, A-Z and a-z requires conversion, so the following characters all require conversion by default: ASCII control codes (Character ranges 00-1F hex (0-31 decimal) and 7F (127 decimal). ASCII symbols (Character ranges 32-47 decimal (20-2F hex)) ASCII symbols (Character ranges 58-64 decimal (3A-40 hex)) ASCII symbols (Character ranges 91-96 decimal (5B-60 hex)) ASCII symbols (Character ranges 123-126 decimal (7B-7E hex)) Extended characters with character codes of 128 decimal (80 hex) and above. Example The string "http://foo bar/" would be encoded as "http%3A%2F%2Ffoo%20bar%2F". Variations Lowercase escapes are legal, as in "http%3a%2f%2ffoo%20bar%2f". Some standards give different rules: RFC 3986, Uniform Resource Identifier (URI): Generic Syntax, section 2.3, says that "-._~" should not be encoded. HTML 5, section 4.10.22.5 URL-encoded form data, says to preserve "-._*", and to encode space " " to "+". The options below provide for utilization of an exception string, enabling preservation (non encoding) of particular characters to meet specific standards. Options It is permissible to use an exception string (containing a set of symbols that do not need to be converted). However, this is an optional feature and is not a requirement of this task. Related tasks   URL decoding   URL parser
#Crystal
Crystal
require "uri"   puts URI.encode("http://foo bar/") puts URI.encode("http://foo bar/", space_to_plus: true) puts URI.encode_www_form("http://foo bar/") puts URI.encode_www_form("http://foo bar/", space_to_plus: false)
http://rosettacode.org/wiki/URL_encoding
URL encoding
Task Provide a function or mechanism to convert a provided string into URL encoding representation. In URL encoding, special characters, control characters and extended characters are converted into a percent symbol followed by a two digit hexadecimal code, So a space character encodes into %20 within the string. For the purposes of this task, every character except 0-9, A-Z and a-z requires conversion, so the following characters all require conversion by default: ASCII control codes (Character ranges 00-1F hex (0-31 decimal) and 7F (127 decimal). ASCII symbols (Character ranges 32-47 decimal (20-2F hex)) ASCII symbols (Character ranges 58-64 decimal (3A-40 hex)) ASCII symbols (Character ranges 91-96 decimal (5B-60 hex)) ASCII symbols (Character ranges 123-126 decimal (7B-7E hex)) Extended characters with character codes of 128 decimal (80 hex) and above. Example The string "http://foo bar/" would be encoded as "http%3A%2F%2Ffoo%20bar%2F". Variations Lowercase escapes are legal, as in "http%3a%2f%2ffoo%20bar%2f". Some standards give different rules: RFC 3986, Uniform Resource Identifier (URI): Generic Syntax, section 2.3, says that "-._~" should not be encoded. HTML 5, section 4.10.22.5 URL-encoded form data, says to preserve "-._*", and to encode space " " to "+". The options below provide for utilization of an exception string, enabling preservation (non encoding) of particular characters to meet specific standards. Options It is permissible to use an exception string (containing a set of symbols that do not need to be converted). However, this is an optional feature and is not a requirement of this task. Related tasks   URL decoding   URL parser
#D
D
import std.stdio, std.uri;   void main() { writeln(encodeComponent("http://foo bar/")); }
http://rosettacode.org/wiki/Variables
Variables
Task Demonstrate a language's methods of:   variable declaration   initialization   assignment   datatypes   scope   referencing,     and   other variable related facilities
#DBL
DBL
; ; Variables examples for DBL version 4 by Dario B. ;   .DEFINE NR,10  ;const .DEFINE AP,"PIPPO"  ;const     RECORD CUSTOM COD, D5 NAME, A80 ZIP, D6 CITY, A80 ;-----------------------   RECORD   ALPHA, A5  ;alphanumeric NUMBR, D5  ;number DECML, F5.2  ;float NUMVE, 10D5  ;array of number NUMAR, [10,2]D5  ;array of number ALPV1, 10A8  ;array of alphanumeric ALPV2, [NR]A8  ;array of alphanumeric ALPA1, [10,2]A8  ;array of alphanumeric   NUMV, 3D3,100,200,300 ALPV, 2A3,'ABC','FGH','KLM' MSX, A9,"VARIABLES" MSG, A*,'Esempio di variabile autodimensionante'   PROC ;-----------------------------------------------------------------------   CLEAR ALPHA,NUMBR,DEML,NUMVE(1:10*5),NUMAR(1:10*2*5),ALPV1(1:10*8) CLEAR ALPV2(1:10*8),ALPA1(1:10*2*8)   ALPHA="PIPPO" NUMBR=10 DECML=20.55   CLEAR CUSTOM COD=1050 NAME='Dario Benenati' ZIP=27100 CITY="PAVIA"   NUMVE(1:10*5)= NUMVE(1)=1 SET NUMVE(2),NUMVE(3),NUMVE(4)=2   NUMAR(1:10*2*5)= NUMAR[1,1]=11 NUMAR[1,2]=12 NUMAR[2,1]=21 NUMAR[2,2]=22   ALPV1(1:10*8)= ALPV1(1)="PIPPO" APLV1(2)="PLUTO" APLV1(2)="ABCDEFGHIJKLMNOP"  ;ALPV(3)='IJKLMNOP'   ALPV2(1:10*8)=" " ALPV2[1]="PIPPO" ALPV2(2)="PLUTO" ALPV2[3](3:2)="FO" ALPV2[4](3,4)="FO"   SET ALPA1[1,1],ALPA1[1,2]="PLUTO" ALPA1[2,1](3:2)="FO" ALPA1[2,1](3,4)="FO"  ;.....................  
http://rosettacode.org/wiki/Variables
Variables
Task Demonstrate a language's methods of:   variable declaration   initialization   assignment   datatypes   scope   referencing,     and   other variable related facilities
#Delphi
Delphi
var i: Integer; s: string; o: TObject; begin i := 123; s := 'abc'; o := TObject.Create; try // ... finally o.Free; end; end;
http://rosettacode.org/wiki/Van_Eck_sequence
Van Eck sequence
The sequence is generated by following this pseudo-code: A: The first term is zero. Repeatedly apply: If the last term is *new* to the sequence so far then: B: The next term is zero. Otherwise: C: The next term is how far back this last term occured previously. Example Using A: 0 Using B: 0 0 Using C: 0 0 1 Using B: 0 0 1 0 Using C: (zero last occurred two steps back - before the one) 0 0 1 0 2 Using B: 0 0 1 0 2 0 Using C: (two last occurred two steps back - before the zero) 0 0 1 0 2 0 2 2 Using C: (two last occurred one step back) 0 0 1 0 2 0 2 2 1 Using C: (one last appeared six steps back) 0 0 1 0 2 0 2 2 1 6 ... Task Create a function/procedure/method/subroutine/... to generate the Van Eck sequence of numbers. Use it to display here, on this page: The first ten terms of the sequence. Terms 991 - to - 1000 of the sequence. References Don't Know (the Van Eck Sequence) - Numberphile video. Wikipedia Article: Van Eck's Sequence. OEIS sequence: A181391.
#FreeBASIC
FreeBASIC
  Const limite = 1000   Dim As Integer a(limite), n, m, i   For n = 0 To limite-1 For m = n-1 To 0 Step -1 If a(m) = a(n) Then a(n+1) = n-m: Exit For Next m Next n   Print "Secuencia de Van Eck:" &Chr(10) Print "Primeros 10 terminos: "; For i = 0 To 9 Print a(i) &" "; Next i Print Chr(10) & "Terminos 991 al 1000: "; For i = 990 To 999 Print a(i) &" "; Next i End  
http://rosettacode.org/wiki/Van_Eck_sequence
Van Eck sequence
The sequence is generated by following this pseudo-code: A: The first term is zero. Repeatedly apply: If the last term is *new* to the sequence so far then: B: The next term is zero. Otherwise: C: The next term is how far back this last term occured previously. Example Using A: 0 Using B: 0 0 Using C: 0 0 1 Using B: 0 0 1 0 Using C: (zero last occurred two steps back - before the one) 0 0 1 0 2 Using B: 0 0 1 0 2 0 Using C: (two last occurred two steps back - before the zero) 0 0 1 0 2 0 2 2 Using C: (two last occurred one step back) 0 0 1 0 2 0 2 2 1 Using C: (one last appeared six steps back) 0 0 1 0 2 0 2 2 1 6 ... Task Create a function/procedure/method/subroutine/... to generate the Van Eck sequence of numbers. Use it to display here, on this page: The first ten terms of the sequence. Terms 991 - to - 1000 of the sequence. References Don't Know (the Van Eck Sequence) - Numberphile video. Wikipedia Article: Van Eck's Sequence. OEIS sequence: A181391.
#F.C5.8Drmul.C3.A6
Fōrmulæ
package main   import "fmt"   func main() { const max = 1000 a := make([]int, max) // all zero by default for n := 0; n < max-1; n++ { for m := n - 1; m >= 0; m-- { if a[m] == a[n] { a[n+1] = n - m break } } } fmt.Println("The first ten terms of the Van Eck sequence are:") fmt.Println(a[:10]) fmt.Println("\nTerms 991 to 1000 of the sequence are:") fmt.Println(a[990:]) }
http://rosettacode.org/wiki/Vampire_number
Vampire number
A vampire number is a natural decimal number with an even number of digits,   that can be factored into two integers. These two factors are called the   fangs,   and must have the following properties:   they each contain half the number of the decimal digits of the original number   together they consist of exactly the same decimal digits as the original number   at most one of them has a trailing zero An example of a vampire number and its fangs:   1260 : (21, 60) Task Print the first   25   vampire numbers and their fangs. Check if the following numbers are vampire numbers and,   if so,   print them and their fangs: 16758243290880, 24959017348650, 14593825548650 Note that a vampire number can have more than one pair of fangs. See also numberphile.com. vampire search algorithm vampire numbers on OEIS
#PARI.2FGP
PARI/GP
fang(n)=my(v=digits(n),u=List());if(#v%2,return([]));fordiv(n,d,if(#Str(d)==#v/2 && #Str(n/d)==#v/2 && vecsort(v)==vecsort(concat(digits(d),digits(n/d))) && (d%10 || (n/d)%10), if(d^2>n,return(Vec(u))); listput(u, d))); Vec(u) k=25;forstep(d=4,6,2,for(n=10^(d-1),10^d-1,f=fang(n); for(i=1,#f,print(n" "f[i]" "n/f[i]); if(i==#f && k--==0,return)))) print();v=[16758243290880, 24959017348650, 14593825548650]; for(i=1,#v,f=fang(v[i]); for(j=1,#f, print(v[i]" "f[j]" "v[i]/f[j])))
http://rosettacode.org/wiki/Variadic_function
Variadic function
Task Create a function which takes in a variable number of arguments and prints each one on its own line. Also show, if possible in your language, how to call the function on a list of arguments constructed at runtime. Functions of this type are also known as Variadic Functions. Related task   Call a function
#Lasso
Lasso
define printArgs(...items) => stdoutnl(#items) define printEachArg(...) => with i in #rest do stdoutnl(#i)   printArgs('a', 2, (:3)) printEachArg('a', 2, (:3))
http://rosettacode.org/wiki/Variadic_function
Variadic function
Task Create a function which takes in a variable number of arguments and prints each one on its own line. Also show, if possible in your language, how to call the function on a list of arguments constructed at runtime. Functions of this type are also known as Variadic Functions. Related task   Call a function
#Logo
Logo
to varargs [:args] foreach :args [print ?] end   (varargs "Mary "had "a "little "lamb) apply "varargs [Mary had a little lamb]
http://rosettacode.org/wiki/Vector
Vector
Task Implement a Vector class (or a set of functions) that models a Physical Vector. The four basic operations and a pretty print function should be implemented. The Vector may be initialized in any reasonable way. Start and end points, and direction Angular coefficient and value (length) The four operations to be implemented are: Vector + Vector addition Vector - Vector subtraction Vector * scalar multiplication Vector / scalar division
#Ring
Ring
  # Project : Vector   decimals(1) vect1 = [5, 7] vect2 = [2, 3] vect3 = list(len(vect1))   for n = 1 to len(vect1) vect3[n] = vect1[n] + vect2[n] next showarray(vect3)   for n = 1 to len(vect1) vect3[n] = vect1[n] - vect2[n] next showarray(vect3)   for n = 1 to len(vect1) vect3[n] = vect1[n] * vect2[n] next showarray(vect3)   for n = 1 to len(vect1) vect3[n] = vect1[n] / 2 next showarray(vect3)   func showarray(vect3) see "[" svect = "" for n = 1 to len(vect3) svect = svect + vect3[n] + ", " next svect = left(svect, len(svect) - 2) see svect see "]" + nl  
http://rosettacode.org/wiki/Vector
Vector
Task Implement a Vector class (or a set of functions) that models a Physical Vector. The four basic operations and a pretty print function should be implemented. The Vector may be initialized in any reasonable way. Start and end points, and direction Angular coefficient and value (length) The four operations to be implemented are: Vector + Vector addition Vector - Vector subtraction Vector * scalar multiplication Vector / scalar division
#Ruby
Ruby
class Vector def self.polar(r, angle=0) new(r*Math.cos(angle), r*Math.sin(angle)) end   attr_reader :x, :y   def initialize(x, y) raise TypeError unless x.is_a?(Numeric) and y.is_a?(Numeric) @x, @y = x, y end   def +(other) raise TypeError if self.class != other.class self.class.new(@x + other.x, @y + other.y) end   def -@; self.class.new(-@x, -@y) end def -(other) self + (-other) end   def *(scalar) raise TypeError unless scalar.is_a?(Numeric) self.class.new(@x * scalar, @y * scalar) end   def /(scalar) raise TypeError unless scalar.is_a?(Numeric) and scalar.nonzero? self.class.new(@x / scalar, @y / scalar) end   def r; @r ||= Math.hypot(@x, @y) end def angle; @angle ||= Math.atan2(@y, @x) end def polar; [r, angle] end def rect; [@x, @y] end def to_s; "#{self.class}#{[@x, @y]}" end alias inspect to_s end   p v = Vector.new(1,1) #=> Vector[1, 1] p w = Vector.new(3,4) #=> Vector[3, 4] p v + w #=> Vector[4, 5] p v - w #=> Vector[-2, -3] p -v #=> Vector[-1, -1] p w * 5 #=> Vector[15, 20] p w / 2.0 #=> Vector[1.5, 2.0] p w.x #=> 3 p w.y #=> 4 p v.polar #=> [1.4142135623730951, 0.7853981633974483] p w.polar #=> [5.0, 0.9272952180016122] p z = Vector.polar(1, Math::PI/2) #=> Vector[6.123031769111886e-17, 1.0] p z.rect #=> [6.123031769111886e-17, 1.0] p z.polar #=> [1.0, 1.5707963267948966] p z = Vector.polar(-2, Math::PI/4) #=> Vector[-1.4142135623730951, -1.414213562373095] p z.polar #=> [2.0, -2.356194490192345]
http://rosettacode.org/wiki/Vigen%C3%A8re_cipher
Vigenère cipher
Task Implement a   Vigenère cypher,   both encryption and decryption. The program should handle keys and text of unequal length, and should capitalize everything and discard non-alphabetic characters. (If your program handles non-alphabetic characters in another way, make a note of it.) Related tasks   Caesar cipher   Rot-13   Substitution Cipher
#Ring
Ring
  # Project : Vigenère cipher   key = "LEMON" plaintext = "ATTACK AT DAWN" ciphertext = encrypt(plaintext, key) see "key = "+ key + nl see "plaintext = " + plaintext + nl see "ciphertext = " + ciphertext + nl see "decrypted = " + decrypt(ciphertext, key) + nl     func encrypt(plain, key) o = "" k = 0 plain = fnupper(plain) key = fnupper(key) for i = 1 to len(plain) n = ascii(plain[i]) if n >= 65 and n <= 90 o = o + char(65 + (n + ascii(key[k+1])) % 26) k = (k + 1) % len(key) ok next return o   func decrypt(cipher, key) o = "" k = 0 cipher = fnupper(cipher) key = fnupper(key) for i = 1 to len(cipher) n = ascii(cipher[i]) o = o + char(65 + (n + 26 - ascii(key[k+1])) % 26) k = (k + 1) % len(key) next return o   func fnupper(a) for aa = 1 to len(a) c = ascii(a[aa]) if c >= 97 and c <= 122 a[aa] = char(c-32) ok next return a  
http://rosettacode.org/wiki/Vigen%C3%A8re_cipher
Vigenère cipher
Task Implement a   Vigenère cypher,   both encryption and decryption. The program should handle keys and text of unequal length, and should capitalize everything and discard non-alphabetic characters. (If your program handles non-alphabetic characters in another way, make a note of it.) Related tasks   Caesar cipher   Rot-13   Substitution Cipher
#Ruby
Ruby
module VigenereCipher   BASE = 'A'.ord SIZE = 'Z'.ord - BASE + 1   def encrypt(text, key) crypt(text, key, :+) end   def decrypt(text, key) crypt(text, key, :-) end   def crypt(text, key, dir) text = text.upcase.gsub(/[^A-Z]/, '') key_iterator = key.upcase.gsub(/[^A-Z]/, '').chars.map{|c| c.ord - BASE}.cycle text.each_char.inject('') do |ciphertext, char| offset = key_iterator.next ciphertext << ((char.ord - BASE).send(dir, offset) % SIZE + BASE).chr end end   end
http://rosettacode.org/wiki/Vector_products
Vector products
A vector is defined as having three dimensions as being represented by an ordered collection of three numbers:   (X, Y, Z). If you imagine a graph with the   x   and   y   axis being at right angles to each other and having a third,   z   axis coming out of the page, then a triplet of numbers,   (X, Y, Z)   would represent a point in the region,   and a vector from the origin to the point. Given the vectors: A = (a1, a2, a3) B = (b1, b2, b3) C = (c1, c2, c3) then the following common vector products are defined: The dot product       (a scalar quantity) A • B = a1b1   +   a2b2   +   a3b3 The cross product       (a vector quantity) A x B = (a2b3  -   a3b2,     a3b1   -   a1b3,     a1b2   -   a2b1) The scalar triple product       (a scalar quantity) A • (B x C) The vector triple product       (a vector quantity) A x (B x C) Task Given the three vectors: a = ( 3, 4, 5) b = ( 4, 3, 5) c = (-5, -12, -13) Create a named function/subroutine/method to compute the dot product of two vectors. Create a function to compute the cross product of two vectors. Optionally create a function to compute the scalar triple product of three vectors. Optionally create a function to compute the vector triple product of three vectors. Compute and display: a • b Compute and display: a x b Compute and display: a • (b x c), the scalar triple product. Compute and display: a x (b x c), the vector triple product. References   A starting page on Wolfram MathWorld is   Vector Multiplication .   Wikipedia   dot product.   Wikipedia   cross product.   Wikipedia   triple product. Related tasks   Dot product   Quaternion type
#Erlang
Erlang
  -module(vector). -export([main/0]). vector_product(X,Y)-> [X1,X2,X3]=X, [Y1,Y2,Y3]=Y, Ans=[X2*Y3-X3*Y2,X3*Y1-X1*Y3,X1*Y2-X2*Y1], Ans. dot_product(X,Y)-> [X1,X2,X3]=X, [Y1,Y2,Y3]=Y, Ans=X1*Y1+X2*Y2+X3*Y3, io:fwrite("~p~n",[Ans]). main()-> {ok, A} = io:fread("Enter vector A : ", "~d ~d ~d"), {ok, B} = io:fread("Enter vector B : ", "~d ~d ~d"), {ok, C} = io:fread("Enter vector C : ", "~d ~d ~d"), dot_product(A,B), Ans=vector_product(A,B), io:fwrite("~p,~p,~p~n",Ans), dot_product(C,vector_product(A,B)), io:fwrite("~p,~p,~p~n",vector_product(C,vector_product(A,B))).  
http://rosettacode.org/wiki/Validate_International_Securities_Identification_Number
Validate International Securities Identification Number
An International Securities Identification Number (ISIN) is a unique international identifier for a financial security such as a stock or bond. Task Write a function or program that takes a string as input, and checks whether it is a valid ISIN. It is only valid if it has the correct format,   and   the embedded checksum is correct. Demonstrate that your code passes the test-cases listed below. Details The format of an ISIN is as follows: ┌───────────── a 2-character ISO country code (A-Z) │ ┌─────────── a 9-character security code (A-Z, 0-9) │ │        ┌── a checksum digit (0-9) AU0000XVGZA3 For this task, you may assume that any 2-character alphabetic sequence is a valid country code. The checksum can be validated as follows: Replace letters with digits, by converting each character from base 36 to base 10, e.g. AU0000XVGZA3 →1030000033311635103. Perform the Luhn test on this base-10 number. There is a separate task for this test: Luhn test of credit card numbers. You don't have to replicate the implementation of this test here   ───   you can just call the existing function from that task.   (Add a comment stating if you did this.) Test cases ISIN Validity Comment US0378331005 valid US0373831005 not valid The transposition typo is caught by the checksum constraint. U50378331005 not valid The substitution typo is caught by the format constraint. US03378331005 not valid The duplication typo is caught by the format constraint. AU0000XVGZA3 valid AU0000VXGZA3 valid Unfortunately, not all transposition typos are caught by the checksum constraint. FR0000988040 valid (The comments are just informational.   Your function should simply return a Boolean result.   See #Raku for a reference solution.) Related task: Luhn test of credit card numbers Also see Interactive online ISIN validator Wikipedia article: International Securities Identification Number
#jq
jq
# This filter may be applied to integers or integer-valued strings def luhntest: def digits: tostring | explode | map([.]|implode|tonumber); (digits | reverse) | ( [.[range(0;length;2)]] | add ) as $sum1 | [.[range(1;length;2)]] | (map( (2 * .) | if . > 9 then (digits|add) else . end) | add) as $sum2 | ($sum1 + $sum2) % 10 == 0;   def decodeBase36: # decode a single character def d1: explode[0] # "0" is 48; "A" is 65 | if . < 65 then . - 48 else . - 55 end; def chars: explode | map([.]|implode); chars | map(d1) | join("");   def is_ISIN: type == "string" and test("^(?<cc>[A-Z][A-Z])(?<sc>[0-9A-Z]{9})(?<cs>[0-9])$") and (decodeBase36 | luhntest);
http://rosettacode.org/wiki/Validate_International_Securities_Identification_Number
Validate International Securities Identification Number
An International Securities Identification Number (ISIN) is a unique international identifier for a financial security such as a stock or bond. Task Write a function or program that takes a string as input, and checks whether it is a valid ISIN. It is only valid if it has the correct format,   and   the embedded checksum is correct. Demonstrate that your code passes the test-cases listed below. Details The format of an ISIN is as follows: ┌───────────── a 2-character ISO country code (A-Z) │ ┌─────────── a 9-character security code (A-Z, 0-9) │ │        ┌── a checksum digit (0-9) AU0000XVGZA3 For this task, you may assume that any 2-character alphabetic sequence is a valid country code. The checksum can be validated as follows: Replace letters with digits, by converting each character from base 36 to base 10, e.g. AU0000XVGZA3 →1030000033311635103. Perform the Luhn test on this base-10 number. There is a separate task for this test: Luhn test of credit card numbers. You don't have to replicate the implementation of this test here   ───   you can just call the existing function from that task.   (Add a comment stating if you did this.) Test cases ISIN Validity Comment US0378331005 valid US0373831005 not valid The transposition typo is caught by the checksum constraint. U50378331005 not valid The substitution typo is caught by the format constraint. US03378331005 not valid The duplication typo is caught by the format constraint. AU0000XVGZA3 valid AU0000VXGZA3 valid Unfortunately, not all transposition typos are caught by the checksum constraint. FR0000988040 valid (The comments are just informational.   Your function should simply return a Boolean result.   See #Raku for a reference solution.) Related task: Luhn test of credit card numbers Also see Interactive online ISIN validator Wikipedia article: International Securities Identification Number
#Julia
Julia
using Printf   luhntest(x) = luhntest(parse(Int, x))   function checkISIN(inum::AbstractString) if length(inum) != 12 || !all(isalpha, inum[1:2]) return false end return parse.(Int, collect(inum), 36) |> join |> luhntest end   for inum in ["US0378331005", "US0373831005", "U50378331005", "US03378331005", "AU0000XVGZA3", "AU0000VXGZA3", "FR0000988040"] @printf("%-15s %5s\n", inum, ifelse(checkISIN(inum), "pass", "fail")) end
http://rosettacode.org/wiki/Van_der_Corput_sequence
Van der Corput sequence
When counting integers in binary, if you put a (binary) point to the righEasyLangt of the count then the column immediately to the left denotes a digit with a multiplier of 2 0 {\displaystyle 2^{0}} ; the digit in the next column to the left has a multiplier of 2 1 {\displaystyle 2^{1}} ; and so on. So in the following table: 0. 1. 10. 11. ... the binary number "10" is 1 × 2 1 + 0 × 2 0 {\displaystyle 1\times 2^{1}+0\times 2^{0}} . You can also have binary digits to the right of the “point”, just as in the decimal number system. In that case, the digit in the place immediately to the right of the point has a weight of 2 − 1 {\displaystyle 2^{-1}} , or 1 / 2 {\displaystyle 1/2} . The weight for the second column to the right of the point is 2 − 2 {\displaystyle 2^{-2}} or 1 / 4 {\displaystyle 1/4} . And so on. If you take the integer binary count of the first table, and reflect the digits about the binary point, you end up with the van der Corput sequence of numbers in base 2. .0 .1 .01 .11 ... The third member of the sequence, binary 0.01, is therefore 0 × 2 − 1 + 1 × 2 − 2 {\displaystyle 0\times 2^{-1}+1\times 2^{-2}} or 1 / 4 {\displaystyle 1/4} . Distribution of 2500 points each: Van der Corput (top) vs pseudorandom 0 ≤ x < 1 {\displaystyle 0\leq x<1} Monte Carlo simulations This sequence is also a superset of the numbers representable by the "fraction" field of an old IEEE floating point standard. In that standard, the "fraction" field represented the fractional part of a binary number beginning with "1." e.g. 1.101001101. Hint A hint at a way to generate members of the sequence is to modify a routine used to change the base of an integer: >>> def base10change(n, base): digits = [] while n: n,remainder = divmod(n, base) digits.insert(0, remainder) return digits   >>> base10change(11, 2) [1, 0, 1, 1] the above showing that 11 in decimal is 1 × 2 3 + 0 × 2 2 + 1 × 2 1 + 1 × 2 0 {\displaystyle 1\times 2^{3}+0\times 2^{2}+1\times 2^{1}+1\times 2^{0}} . Reflected this would become .1101 or 1 × 2 − 1 + 1 × 2 − 2 + 0 × 2 − 3 + 1 × 2 − 4 {\displaystyle 1\times 2^{-1}+1\times 2^{-2}+0\times 2^{-3}+1\times 2^{-4}} Task description Create a function/method/routine that given n, generates the n'th term of the van der Corput sequence in base 2. Use the function to compute and display the first ten members of the sequence. (The first member of the sequence is for n=0). As a stretch goal/extra credit, compute and show members of the sequence for bases other than 2. See also The Basic Low Discrepancy Sequences Non-decimal radices/Convert Van der Corput sequence
#Go
Go
package main   import "fmt"   func v2(n uint) (r float64) { p := .5 for n > 0 { if n&1 == 1 { r += p } p *= .5 n >>= 1 } return }   func newV(base uint) func(uint) float64 { invb := 1 / float64(base) return func(n uint) (r float64) { p := invb for n > 0 { r += p * float64(n%base) p *= invb n /= base } return } }   func main() { fmt.Println("Base 2:") for i := uint(0); i < 10; i++ { fmt.Println(i, v2(i)) } fmt.Println("Base 3:") v3 := newV(3) for i := uint(0); i < 10; i++ { fmt.Println(i, v3(i)) } }
http://rosettacode.org/wiki/URL_decoding
URL decoding
This task   (the reverse of   URL encoding   and distinct from   URL parser)   is to provide a function or mechanism to convert an URL-encoded string into its original unencoded form. Test cases   The encoded string   "http%3A%2F%2Ffoo%20bar%2F"   should be reverted to the unencoded form   "http://foo bar/".   The encoded string   "google.com/search?q=%60Abdu%27l-Bah%C3%A1"   should revert to the unencoded form   "google.com/search?q=`Abdu'l-Bahá".
#Cach.C3.A9_ObjectScript
Caché ObjectScript
USER>Write $ZConvert("http%3A%2F%2Ffoo%20bar%2F", "I", "URL") http://foo bar/
http://rosettacode.org/wiki/URL_decoding
URL decoding
This task   (the reverse of   URL encoding   and distinct from   URL parser)   is to provide a function or mechanism to convert an URL-encoded string into its original unencoded form. Test cases   The encoded string   "http%3A%2F%2Ffoo%20bar%2F"   should be reverted to the unencoded form   "http://foo bar/".   The encoded string   "google.com/search?q=%60Abdu%27l-Bah%C3%A1"   should revert to the unencoded form   "google.com/search?q=`Abdu'l-Bahá".
#Clojure
Clojure
(java.net.URLDecoder/decode "http%3A%2F%2Ffoo%20bar%2F")
http://rosettacode.org/wiki/UPC
UPC
Goal Convert UPC bar codes to decimal. Specifically: The UPC standard is actually a collection of standards -- physical standards, data format standards, product reference standards... Here,   in this task,   we will focus on some of the data format standards,   with an imaginary physical+electrical implementation which converts physical UPC bar codes to ASCII   (with spaces and   #   characters representing the presence or absence of ink). Sample input Below, we have a representation of ten different UPC-A bar codes read by our imaginary bar code reader: # # # ## # ## # ## ### ## ### ## #### # # # ## ## # # ## ## ### # ## ## ### # # # # # # ## ## # #### # # ## # ## # ## # # # ### # ### ## ## ### # # ### ### # # # # # # # # ### # # # # # # # # # # ## # ## # ## # ## # # #### ### ## # # # # ## ## ## ## # # # # ### # ## ## # # # ## ## # ### ## ## # # #### ## # # # # # ### ## # ## ## ### ## # ## # # ## # # ### # ## ## # # ### # ## ## # # # # # # # ## ## # # # # ## ## # # # # # #### # ## # #### #### # # ## # #### # # # # # ## ## # # ## ## # ### ## ## # # # # # # # # ### # # ### # # # # # # # # # ## ## # # ## ## ### # # # # # ### ## ## ### ## ### ### ## # ## ### ## # # # # ### ## ## # # #### # ## # #### # #### # # # # # ### # # ### # # # ### # # # # # # #### ## # #### # # ## ## ### #### # # # # ### # ### ### # # ### # # # ### # # Some of these were entered upside down,   and one entry has a timing error. Task Implement code to find the corresponding decimal representation of each, rejecting the error. Extra credit for handling the rows entered upside down   (the other option is to reject them). Notes Each digit is represented by 7 bits: 0: 0 0 0 1 1 0 1 1: 0 0 1 1 0 0 1 2: 0 0 1 0 0 1 1 3: 0 1 1 1 1 0 1 4: 0 1 0 0 0 1 1 5: 0 1 1 0 0 0 1 6: 0 1 0 1 1 1 1 7: 0 1 1 1 0 1 1 8: 0 1 1 0 1 1 1 9: 0 0 0 1 0 1 1 On the left hand side of the bar code a space represents a 0 and a # represents a 1. On the right hand side of the bar code, a # represents a 0 and a space represents a 1 Alternatively (for the above):   spaces always represent zeros and # characters always represent ones, but the representation is logically negated -- 1s and 0s are flipped -- on the right hand side of the bar code. The UPC-A bar code structure   It begins with at least 9 spaces   (which our imaginary bar code reader unfortunately doesn't always reproduce properly),   then has a     # #     sequence marking the start of the sequence,   then has the six "left hand" digits,   then has a   # #   sequence in the middle,   then has the six "right hand digits",   then has another   # #   (end sequence),   and finally,   then ends with nine trailing spaces   (which might be eaten by wiki edits, and in any event, were not quite captured correctly by our imaginary bar code reader). Finally, the last digit is a checksum digit which may be used to help detect errors. Verification Multiply each digit in the represented 12 digit sequence by the corresponding number in   (3,1,3,1,3,1,3,1,3,1,3,1)   and add the products. The sum (mod 10) must be 0   (must have a zero as its last digit)   if the UPC number has been read correctly.
#11l
11l
V LEFT_DIGITS = [ ‘ ## #’ = 0, ‘ ## #’ = 1, ‘ # ##’ = 2, ‘ #### #’ = 3, ‘ # ##’ = 4, ‘ ## #’ = 5, ‘ # ####’ = 6, ‘ ### ##’ = 7, ‘ ## ###’ = 8, ‘ # ##’ = 9 ]   V RIGHT_DIGITS = Dict(LEFT_DIGITS.items(), (k, v) -> (k.replace(‘ ’, ‘s’).replace(‘#’, ‘ ’).replace(‘s’, ‘#’), v))   V END_SENTINEL = ‘# #’ V MID_SENTINEL = ‘ # # ’   F decodeUPC(input) F decode(candidate) V pos = 0 V part = candidate[pos .+ :END_SENTINEL.len] I part == :END_SENTINEL pos += :END_SENTINEL.len E R (0B, [Int]())   [Int] output L 6 part = candidate[pos .+ 7] pos += 7   I part C :LEFT_DIGITS output [+]= :LEFT_DIGITS[part] E R (0B, output)   part = candidate[pos .+ :MID_SENTINEL.len] I part == :MID_SENTINEL pos += :MID_SENTINEL.len E R (0B, output)   L 6 part = candidate[pos .+ 7] pos += 7   I part C :RIGHT_DIGITS output [+]= :RIGHT_DIGITS[part] E R (0B, output)   part = candidate[pos .+ :END_SENTINEL.len] I part == :END_SENTINEL pos += :END_SENTINEL.len E R (0B, output)   V sum = 0 L(v) output I L.index % 2 == 0 sum += 3 * v E sum += v R (sum % 10 == 0, output)   V candidate = input.trim(‘ ’) V out = decode(candidate) I out[0] print(out[1]) E out = decode(reversed(candidate)) I out[0] print(out[1]‘ Upside down’) E I out[1].len == 12 print(‘Invalid checksum’) E print(‘Invalid digit(s)’)   V barcodes = [ ‘ # # # ## # ## # ## ### ## ### ## #### # # # ## ## # # ## ## ### # ## ## ### # # # ’, ‘ # # # ## ## # #### # # ## # ## # ## # # # ### # ### ## ## ### # # ### ### # # # ’, ‘ # # # # # ### # # # # # # # # # # ## # ## # ## # ## # # #### ### ## # # ’, ‘ # # ## ## ## ## # # # # ### # ## ## # # # ## ## # ### ## ## # # #### ## # # # ’, ‘ # # ### ## # ## ## ### ## # ## # # ## # # ### # ## ## # # ### # ## ## # # # ’, ‘ # # # # ## ## # # # # ## ## # # # # # #### # ## # #### #### # # ## # #### # # ’, ‘ # # # ## ## # # ## ## # ### ## ## # # # # # # # # ### # # ### # # # # # ’, ‘ # # # # ## ## # # ## ## ### # # # # # ### ## ## ### ## ### ### ## # ## ### ## # # ’, ‘ # # ### ## ## # # #### # ## # #### # #### # # # # # ### # # ### # # # ### # # # ’, ‘ # # # #### ## # #### # # ## ## ### #### # # # # ### # ### ### # # ### # # # ### # # ’ ]   L(barcode) barcodes decodeUPC(barcode)
http://rosettacode.org/wiki/Update_a_configuration_file
Update a configuration file
We have a configuration file as follows: # This is a configuration file in standard configuration file format # # Lines begininning with a hash or a semicolon are ignored by the application # program. Blank lines are also ignored by the application program. # The first word on each non comment line is the configuration option. # Remaining words or numbers on the line are configuration parameter # data fields. # Note that configuration option names are not case sensitive. However, # configuration parameter data is case sensitive and the lettercase must # be preserved. # This is a favourite fruit FAVOURITEFRUIT banana # This is a boolean that should be set NEEDSPEELING # This boolean is commented out ; SEEDSREMOVED # How many bananas we have NUMBEROFBANANAS 48 The task is to manipulate the configuration file as follows: Disable the needspeeling option (using a semicolon prefix) Enable the seedsremoved option by removing the semicolon and any leading whitespace Change the numberofbananas parameter to 1024 Enable (or create if it does not exist in the file) a parameter for numberofstrawberries with a value of 62000 Note that configuration option names are not case sensitive. This means that changes should be effected, regardless of the case. Options should always be disabled by prefixing them with a semicolon. Lines beginning with hash symbols should not be manipulated and left unchanged in the revised file. If a configuration option does not exist within the file (in either enabled or disabled form), it should be added during this update. Duplicate configuration option names in the file should be removed, leaving just the first entry. For the purpose of this task, the revised file should contain appropriate entries, whether enabled or not for needspeeling,seedsremoved,numberofbananas and numberofstrawberries.) The update should rewrite configuration option names in capital letters. However lines beginning with hashes and any parameter data must not be altered (eg the banana for favourite fruit must not become capitalized). The update process should also replace double semicolon prefixes with just a single semicolon (unless it is uncommenting the option, in which case it should remove all leading semicolons). Any lines beginning with a semicolon or groups of semicolons, but no following option should be removed, as should any leading or trailing whitespace on the lines. Whitespace between the option and parameters should consist only of a single space, and any non-ASCII extended characters, tabs characters, or control codes (other than end of line markers), should also be removed. Related tasks Read a configuration file
#Delphi
Delphi
  program uConfigFile;   {$APPTYPE CONSOLE}   uses System.SysUtils, uSettings;   const FileName = 'uConf.txt';   var Settings: TSettings;   procedure show(key: string; value: string); begin writeln(format('%14s = %s', [key, value])); end;   begin Settings := TSettings.Create; Settings.LoadFromFile(FileName); Settings['NEEDSPEELING'] := False; Settings['SEEDSREMOVED'] := True; Settings['NUMBEROFBANANAS'] := 1024; Settings['numberofstrawberries'] := 62000;   for var k in Settings.Keys do show(k, Settings[k]); Settings.SaveToFile(FileName); Settings.Free; Readln; end.
http://rosettacode.org/wiki/User_input/Text
User input/Text
User input/Text is part of Short Circuit's Console Program Basics selection. Task Input a string and the integer   75000   from the text console. See also: User input/Graphical
#Bracmat
Bracmat
( doit = out'"Enter a string" & get':?mystring & whl ' ( out'"Enter a number" & get':?mynumber & !mynumber:~# & out'"I said:\"a number\"!" ) & out$(mystring is !mystring \nmynumber is !mynumber \n) );
http://rosettacode.org/wiki/User_input/Text
User input/Text
User input/Text is part of Short Circuit's Console Program Basics selection. Task Input a string and the integer   75000   from the text console. See also: User input/Graphical
#C
C
#include <stdio.h> #include <stdlib.h>   int main(void) { // Get a string from stdin char str[BUFSIZ]; puts("Enter a string: "); fgets(str, sizeof(str), stdin);   // Get 75000 from stdin long num; char buf[BUFSIZ]; do { puts("Enter 75000: "); fgets(buf, sizeof(buf), stdin); num = strtol(buf, NULL, 10); } while (num != 75000);   return EXIT_SUCCESS; }
http://rosettacode.org/wiki/User_input/Graphical
User input/Graphical
In this task, the goal is to input a string and the integer 75000, from graphical user interface. See also: User input/Text
#Common_Lisp
Common Lisp
(capi:prompt-for-string "Enter a string:")
http://rosettacode.org/wiki/User_input/Graphical
User input/Graphical
In this task, the goal is to input a string and the integer 75000, from graphical user interface. See also: User input/Text
#Dart
Dart
import 'package:flutter/material.dart';   main() => runApp( OutputLabel() );   class OutputLabel extends StatefulWidget { @override _OutputLabelState createState() => _OutputLabelState(); }   class _OutputLabelState extends State<OutputLabel> { String output = "output"; // This will be displayed in an output text field   TextEditingController _stringInputController = TextEditingController(); // Allows us to get the text from a text field TextEditingController _numberInputController = TextEditingController();   @override Widget build( BuildContext context ) { return MaterialApp( debugShowCheckedModeBanner: false, // Disable debug banner in top right home: Scaffold ( // Scaffold provides a layout for the app body: Center ( // Everything in the center widget will be centered child: Column ( // All the widgets will be in a column children: <Widget> [ SizedBox( height: 25 ), // Space between top and text field   TextField ( // String input Text Field controller: _stringInputController, // Add input controller so we can grab text textAlign: TextAlign.center, // Center text decoration: InputDecoration( border: OutlineInputBorder(), labelText: 'Enter a string...'), // Border and default text ), // end TextField   SizedBox( height: 10 ), // Space between text fields   TextField ( // Number input Text Field controller: _numberInputController, // Add input controller so we can grab text textAlign: TextAlign.center, // Center text decoration: InputDecoration( border: OutlineInputBorder(), labelText: 'Enter 75000'), // Border and default text ), // end TextField   FlatButton ( // Submit Button child: Text('Submit Data'), // Button Text color: Colors.blue[400] // button color onPressed: () { // On pressed Callback for button setState( () { output = ''; // Reset output   int number; // Int to store number in   var stringInput = _stringInputController.text ?? ''; // Get the input from the first field, if it is null set it to an empty string   var numberString = _numberInputController.text ?? ''; // Get the input from the second field, if it is null set it to an empty string   if ( stringInput == '') { // If first field is empty output = 'Please enter something in field 1\n'; return; }   if (_numberInputController.text == '') { // If second field is empty output += 'Please enter something in field 2'; return; } else { // If we got an input in the second field   try { number = int.parse( numberString ); // Parse numberString into an int   if ( number == 75000 ) output = 'text output: $stringInput\nnumber: $number'; // Grabs the text from the input controllers and changes the string else output = '$number is not 75000!';   } on FormatException { // If a number is not entered in second field output = '$numberString is not a number!'; }   }   }); } ), // End FlatButton   Text( output ) // displays output   ] ) ) ) ); } }  
http://rosettacode.org/wiki/UTF-8_encode_and_decode
UTF-8 encode and decode
As described in UTF-8 and in Wikipedia, UTF-8 is a popular encoding of (multi-byte) Unicode code-points into eight-bit octets. The goal of this task is to write a encoder that takes a unicode code-point (an integer representing a unicode character) and returns a sequence of 1-4 bytes representing that character in the UTF-8 encoding. Then you have to write the corresponding decoder that takes a sequence of 1-4 UTF-8 encoded bytes and return the corresponding unicode character. Demonstrate the functionality of your encoder and decoder on the following five characters: Character Name Unicode UTF-8 encoding (hex) --------------------------------------------------------------------------------- A LATIN CAPITAL LETTER A U+0041 41 ö LATIN SMALL LETTER O WITH DIAERESIS U+00F6 C3 B6 Ж CYRILLIC CAPITAL LETTER ZHE U+0416 D0 96 € EURO SIGN U+20AC E2 82 AC 𝄞 MUSICAL SYMBOL G CLEF U+1D11E F0 9D 84 9E Provided below is a reference implementation in Common Lisp.
#D
D
import std.conv; import std.stdio;   immutable CHARS = ["A","ö","Ж","€","𝄞"];   void main() { writeln("Character Code-Point Code-Units"); foreach (c; CHARS) { auto bytes = cast(ubyte[]) c; //The raw bytes of a character can be accessed by casting auto unicode = cast(uint) to!dstring(c)[0]; //Convert from a UTF8 string to a UTF32 string, and cast the first character to a number writefln("%s  %7X [%(%X, %)]", c, unicode, bytes); } }
http://rosettacode.org/wiki/UTF-8_encode_and_decode
UTF-8 encode and decode
As described in UTF-8 and in Wikipedia, UTF-8 is a popular encoding of (multi-byte) Unicode code-points into eight-bit octets. The goal of this task is to write a encoder that takes a unicode code-point (an integer representing a unicode character) and returns a sequence of 1-4 bytes representing that character in the UTF-8 encoding. Then you have to write the corresponding decoder that takes a sequence of 1-4 UTF-8 encoded bytes and return the corresponding unicode character. Demonstrate the functionality of your encoder and decoder on the following five characters: Character Name Unicode UTF-8 encoding (hex) --------------------------------------------------------------------------------- A LATIN CAPITAL LETTER A U+0041 41 ö LATIN SMALL LETTER O WITH DIAERESIS U+00F6 C3 B6 Ж CYRILLIC CAPITAL LETTER ZHE U+0416 D0 96 € EURO SIGN U+20AC E2 82 AC 𝄞 MUSICAL SYMBOL G CLEF U+1D11E F0 9D 84 9E Provided below is a reference implementation in Common Lisp.
#Elena
Elena
import system'routines; import extensions;   extension op : String { string printAsString() { console.print(self," ") }   string printAsUTF8Array() { self.toByteArray().forEach:(b){ console.print(b.toString(16)," ") } }   string printAsUTF32() { self.toArray().forEach:(c){ console.print("U+",c.toInt().toString(16)," ") } } }   public program() { "A".printAsString().printAsUTF8Array().printAsUTF32(); console.printLine();   "ö".printAsString().printAsUTF8Array().printAsUTF32(); console.printLine();   "Ж".printAsString().printAsUTF8Array().printAsUTF32(); console.printLine();   "€".printAsString().printAsUTF8Array().printAsUTF32(); console.printLine();   "𝄞".printAsString().printAsUTF8Array().printAsUTF32(); console.printLine(); }
http://rosettacode.org/wiki/Use_another_language_to_call_a_function
Use another language to call a function
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. This task is inverse to the task Call foreign language function. Consider the following C program: #include <stdio.h>   extern int Query (char * Data, size_t * Length);   int main (int argc, char * argv []) { char Buffer [1024]; size_t Size = sizeof (Buffer);   if (0 == Query (Buffer, &Size)) { printf ("failed to call Query\n"); } else { char * Ptr = Buffer; while (Size-- > 0) putchar (*Ptr++); putchar ('\n'); } } Implement the missing Query function in your language, and let this C program call it. The function should place the string Here am I into the buffer which is passed to it as the parameter Data. The buffer size in bytes is passed as the parameter Length. When there is no room in the buffer, Query shall return 0. Otherwise it overwrites the beginning of Buffer, sets the number of overwritten bytes into Length and returns 1.
#Mercury
Mercury
:- module query. :- interface.   :- pred query(string::in, string::out) is det.   :- implementation.   query(_, "Hello, world!").   :- pragma foreign_export("C", query(in, out), "query").   :- pragma foreign_decl("C", " #include <string.h> int Query (char * Data, size_t * Length); "). :- pragma foreign_code("C", " int Query (char *Data, size_t *Length) { MR_String input, result; MR_allocate_aligned_string_msg(input, *Length, MR_ALLOC_ID); memmove(input, Data, *Length); query(input, &result); *Length = strlen(result); memmove(Data, result, *Length); return 1; } ").
http://rosettacode.org/wiki/Use_another_language_to_call_a_function
Use another language to call a function
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. This task is inverse to the task Call foreign language function. Consider the following C program: #include <stdio.h>   extern int Query (char * Data, size_t * Length);   int main (int argc, char * argv []) { char Buffer [1024]; size_t Size = sizeof (Buffer);   if (0 == Query (Buffer, &Size)) { printf ("failed to call Query\n"); } else { char * Ptr = Buffer; while (Size-- > 0) putchar (*Ptr++); putchar ('\n'); } } Implement the missing Query function in your language, and let this C program call it. The function should place the string Here am I into the buffer which is passed to it as the parameter Data. The buffer size in bytes is passed as the parameter Length. When there is no room in the buffer, Query shall return 0. Otherwise it overwrites the beginning of Buffer, sets the number of overwritten bytes into Length and returns 1.
#Nim
Nim
proc Query*(data: var array[1024, char], length: var cint): cint {.exportc.} = const text = "Here am I" if length < text.len: return 0   for i in 0 .. text.high: data[i] = text[i] length = text.len return 1
http://rosettacode.org/wiki/Use_another_language_to_call_a_function
Use another language to call a function
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. This task is inverse to the task Call foreign language function. Consider the following C program: #include <stdio.h>   extern int Query (char * Data, size_t * Length);   int main (int argc, char * argv []) { char Buffer [1024]; size_t Size = sizeof (Buffer);   if (0 == Query (Buffer, &Size)) { printf ("failed to call Query\n"); } else { char * Ptr = Buffer; while (Size-- > 0) putchar (*Ptr++); putchar ('\n'); } } Implement the missing Query function in your language, and let this C program call it. The function should place the string Here am I into the buffer which is passed to it as the parameter Data. The buffer size in bytes is passed as the parameter Length. When there is no room in the buffer, Query shall return 0. Otherwise it overwrites the beginning of Buffer, sets the number of overwritten bytes into Length and returns 1.
#OCaml
OCaml
#include <stdio.h> #include <string.h> #include <caml/mlvalues.h> #include <caml/callback.h>   extern int Query (char * Data, size_t * Length) { static value * closure_f = NULL; if (closure_f == NULL) { closure_f = caml_named_value("Query function cb"); } value ret = caml_callback(*closure_f, Val_unit); *Length = Int_val(Field(ret, 1)); strncpy(Data, String_val(Field(ret, 0)), *Length); return 1; }   int main (int argc, char * argv []) { char Buffer [1024]; unsigned Size = 0;   caml_main(argv); /* added from the original main */   if (0 == Query (Buffer, &Size)) { printf ("failed to call Query\n"); } else { char * Ptr = Buffer; printf("size: %d\n", Size); while (Size-- > 0) putchar (*Ptr++); putchar ('\n'); } }
http://rosettacode.org/wiki/URL_parser
URL parser
URLs are strings with a simple syntax: scheme://[username:password@]domain[:port]/path?query_string#fragment_id Task Parse a well-formed URL to retrieve the relevant information:   scheme, domain, path, ... Note:   this task has nothing to do with URL encoding or URL decoding. According to the standards, the characters:    ! * ' ( ) ; : @ & = + $ , / ? % # [ ] only need to be percent-encoded   (%)   in case of possible confusion. Also note that the path, query and fragment are case sensitive, even if the scheme and domain are not. The way the returned information is provided (set of variables, array, structured, record, object,...) is language-dependent and left to the programmer, but the code should be clear enough to reuse. Extra credit is given for clear error diagnostics.   Here is the official standard:     https://tools.ietf.org/html/rfc3986,   and here is a simpler   BNF:     http://www.w3.org/Addressing/URL/5_URI_BNF.html. Test cases According to T. Berners-Lee foo://example.com:8042/over/there?name=ferret#nose     should parse into:   scheme = foo   domain = example.com   port = :8042   path = over/there   query = name=ferret   fragment = nose urn:example:animal:ferret:nose     should parse into:   scheme = urn   path = example:animal:ferret:nose other URLs that must be parsed include:   jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true   ftp://ftp.is.co.za/rfc/rfc1808.txt   http://www.ietf.org/rfc/rfc2396.txt#header1   ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two   mailto:[email protected]   news:comp.infosystems.www.servers.unix   tel:+1-816-555-1212   telnet://192.0.2.16:80/   urn:oasis:names:specification:docbook:dtd:xml:4.1.2
#Julia
Julia
using Printf, URIParser   const FIELDS = names(URI)   function detailview(uri::URI, indentlen::Int=4) indent = " "^indentlen s = String[] for f in FIELDS d = string(getfield(uri, f))  !isempty(d) || continue f != :port || d != "0" || continue push!(s, @sprintf("%s%s:  %s", indent, string(f), d)) end join(s, "\n") end   test = ["foo://example.com:8042/over/there?name=ferret#nose", "urn:example:animal:ferret:nose", "jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true", "ftp://ftp.is.co.za/rfc/rfc1808.txt", "http://www.ietf.org/rfc/rfc2396.txt#header1", "ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two", "mailto:[email protected]", "news:comp.infosystems.www.servers.unix", "tel:+1-816-555-1212", "telnet://192.0.2.16:80/", "urn:oasis:names:specification:docbook:dtd:xml:4.1.2", "This is not a URI!", "ssh://[email protected]", "https://bob:[email protected]/place", "http://example.com/?a=1&b=2+2&c=3&c=4&d=%65%6e%63%6F%64%65%64"]   isfirst = true for st in test if isfirst isfirst = false else println() end println("Attempting to parse\n \"", st, "\" as a URI:") uri = try URI(st) catch println("URIParser failed to parse this URI, is it OK?") continue end print("This URI is parsable ") if isvalid(uri) println("and appears to be valid.") else println("but may be invalid.") end println(detailview(uri)) end  
http://rosettacode.org/wiki/URL_parser
URL parser
URLs are strings with a simple syntax: scheme://[username:password@]domain[:port]/path?query_string#fragment_id Task Parse a well-formed URL to retrieve the relevant information:   scheme, domain, path, ... Note:   this task has nothing to do with URL encoding or URL decoding. According to the standards, the characters:    ! * ' ( ) ; : @ & = + $ , / ? % # [ ] only need to be percent-encoded   (%)   in case of possible confusion. Also note that the path, query and fragment are case sensitive, even if the scheme and domain are not. The way the returned information is provided (set of variables, array, structured, record, object,...) is language-dependent and left to the programmer, but the code should be clear enough to reuse. Extra credit is given for clear error diagnostics.   Here is the official standard:     https://tools.ietf.org/html/rfc3986,   and here is a simpler   BNF:     http://www.w3.org/Addressing/URL/5_URI_BNF.html. Test cases According to T. Berners-Lee foo://example.com:8042/over/there?name=ferret#nose     should parse into:   scheme = foo   domain = example.com   port = :8042   path = over/there   query = name=ferret   fragment = nose urn:example:animal:ferret:nose     should parse into:   scheme = urn   path = example:animal:ferret:nose other URLs that must be parsed include:   jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true   ftp://ftp.is.co.za/rfc/rfc1808.txt   http://www.ietf.org/rfc/rfc2396.txt#header1   ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two   mailto:[email protected]   news:comp.infosystems.www.servers.unix   tel:+1-816-555-1212   telnet://192.0.2.16:80/   urn:oasis:names:specification:docbook:dtd:xml:4.1.2
#Kotlin
Kotlin
// version 1.1.2   import java.net.URL import java.net.MalformedURLException   fun parseUrl(url: String) { var u: URL var scheme: String try { u = URL(url) scheme = u.protocol } catch (ex: MalformedURLException) { val index = url.indexOf(':') scheme = url.take(index) u = URL("http" + url.drop(index)) } println("Parsing $url") println(" scheme = $scheme")   with(u) { if (userInfo != null) println(" userinfo = $userInfo") if (!host.isEmpty()) println(" domain = $host") if (port != -1) println(" port = $port") if (!path.isEmpty()) println(" path = $path") if (query != null) println(" query = $query") if (ref != null) println(" fragment = $ref") } println() }   fun main(args: Array<String>){ val urls = arrayOf( "foo://example.com:8042/over/there?name=ferret#nose", "urn:example:animal:ferret:nose", "jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true", "ftp://ftp.is.co.za/rfc/rfc1808.txt", "http://www.ietf.org/rfc/rfc2396.txt#header1", "ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two", "mailto:[email protected]", "news:comp.infosystems.www.servers.unix", "tel:+1-816-555-1212", "telnet://192.0.2.16:80/", "urn:oasis:names:specification:docbook:dtd:xml:4.1.2", "ssh://[email protected]", "https://bob:[email protected]/place", "http://example.com/?a=1&b=2+2&c=3&c=4&d=%65%6e%63%6F%64%65%64" ) for (url in urls) parseUrl(url) }