Three digits real number in Pascal - freepascal

I have code in Free pascal, I have real number 3.285714287142857E+000 from a/b.
program threedigits;
var a,b:real;
begin
a:=23;
b:=7;
writeln(a/b);
end.
How to change the number to three digits after comma (3.286)?

Use 0:3
var a,b:real;
begin
a:=23;
b:=7;
writeln(a/b:0:3);
readln;
end.

Related

Use of function / return

I had the task to code the following:
Take a list of integers and returns the value of these numbers added up, but only if they are odd.
Example input: [1,5,3,2]
Output: 9
I did the code below and it worked perfectly.
numbers = [1,5,3,2]
print(numbers)
add_up_the_odds = []
for number in numbers:
if number % 2 == 1:
add_up_the_odds.append(number)
print(add_up_the_odds)
print(sum(add_up_the_odds))
Then I tried to re-code it using function definition / return:
def add_up_the_odds(numbers):
odds = []
for number in range(1,len(numbers)):
if number % 2 == 1:
odds.append(number)
return odds
numbers = [1,5,3,2]
print (sum(odds))
But I couldn’t make it working, anybody can help with that?
Note: I'm going to assume Python 3.x
It looks like you're defining your function, but never calling it.
When the interpreter finishes going through your function definition, the function is now there for you to use - but it never actually executes until you tell it to.
Between the last two lines in your code, you need to call add_up_the_odds() on your numbers array, and assign the result to the odds variable.
i.e. odds = add_up_the_odds(numbers)

Sentence-count function not returning total count

So i've been trying to create a sentence-count function which will cycle through the following 'story':
let story = 'Last weekend, I took literally the most beautiful bike ride of my life. The route is called "The 9W to Nyack" and it actually stretches all the way from Riverside Park in Manhattan to South Nyack, New Jersey. It\'s really an adventure from beginning to end! It is a 48 mile loop and it basically took me an entire day. I stopped at Riverbank State Park to take some extremely artsy photos. It was a short stop, though, because I had a really long way left to go. After a quick photo op at the very popular Little Red Lighthouse, I began my trek across the George Washington Bridge into New Jersey. The GW is actually very long - 4,760 feet! I was already very tired by the time I got to the other side. An hour later, I reached Greenbrook Nature Sanctuary, an extremely beautiful park along the coast of the Hudson. Something that was very surprising to me was that near the end of the route you actually cross back into New York! At this point, you are very close to the end.';
And I realise the problem I'm having but I cannot find a way around this. Basically I want my code to return a the total sCount below but seeing as I've returned my sCount after my loop, it's only adding and returning the one count as a total:
const sentenceTotal = (word) => {
let sCount = 0;
if (word[word.length-1] === "." || word[word.length-1] === "!" || word[word.length-1] === "?") {
sCount += 1;
};
return sCount;
};
// console.log(sentenceTotal(story)) returns '1'.
I've tried multiple ways around this, such as returning sentenceTotal(word) instead of sCount but console.log will just log the function name.
I can make it return the correct sCount total if I remove the function element of it, but that's not what I want.
I don't see any loop or iterator which would go through story to count the number of occurrences of ., ?, or !.
Having recently tackled "counting sentences" myself I know it is a non-trivial problem with many edge cases.
For a simple use-case though you can use split and a regular expression;
story.split(/[?!.]/).length
So you could wrap that in your function like so:
const sentenceTotal = (word) => {
return word.split(/[?.!]/).length
};
let story = 'Last weekend, I took literally the most beautiful bike ride of my life. The route is called "The 9W to Nyack" and it actually stretches all the way from Riverside Park in Manhattan to South Nyack, New Jersey. It\'s really an adventure from beginning to end! It is a 48 mile loop and it basically took me an entire day. I stopped at Riverbank State Park to take some extremely artsy photos. It was a short stop, though, because I had a really long way left to go. After a quick photo op at the very popular Little Red Lighthouse, I began my trek across the George Washington Bridge into New Jersey. The GW is actually very long - 4,760 feet! I was already very tired by the time I got to the other side. An hour later, I reached Greenbrook Nature Sanctuary, an extremely beautiful park along the coast of the Hudson. Something that was very surprising to me was that near the end of the route you actually cross back into New York! At this point, you are very close to the end.';
sentenceTotal(story)
=> 13
There a several strange things about you question so I'll do it in 3 steps :
First step : The syntax.
What you wrote is the assignement to a const of an anonymous variable. So what it does is :
Create a const name 'sentenceCount'
To this const, assign the anonymous function (words) => {...}
Now you have this : sentenceCount(words){...}
And that's all. Because what you wrote : ()=>{} is not the calling of a function, but the declaration of an anonym function, you should read this : https://www.w3schools.com/js/js_function_definition.asp
If you want a global total, you must have a global total variable(not constant) so that the total isn't lost. So :
let sCount = 0; //<-- have sCount as a global variable not a const
function isEndOfSentence(word) {
if (word[word.length-1] === "." || word[word.length-1] === "!" || word[word.length-1] === "?") {
sCount += 1;
};
};
If you are forbidden from using a global variable (and it's best to not do so), then you have to register the total as a return of your function and store the total in the calling 'CountWords(sentence)' function.
function isEndOfSentence(words) {...}
callingFunction(){
//decalaration
let total;
//...inside your loop
total += isEndOfSentence(currentWord)
}
The algorithm
Can you provide more context as how you use you function ?
If your goal is to count the words until there is a delimiter to mark the end of a sentence, your function will not be of great usage .
As it is written, your function will only ever be able to return 0 or 1. As it does the following :
The function is called.
It create a var called sCount and set it to 0
It increment or not sCount
It return sCount so 1 or 0
It's basically a 'isEndOfSentence' function that would return a boolean. It's usage should be in an algorithm like :
// var totalSentence = 0
// for each word
// if(isEndOfSentence(word))
// totalSentence + totalSentence = 1
// endfor
Also this comes back to just counting the punctuation to count the number of sentence.
The quick and small solution
Also I tried specifically to keep the program in an algorithm explicit form since I guess that's what you're dealing with.
But I feel that you wanted to write something small and with as little characters as possible so for your information, there are faster way of doing this with a tool called regex and the native JS 'split(separator)' function of a string.
A regex is a description of a string that it can match to and when used can return those match. And it can be used in JS to split a string:
story.split(/[?!.]/) //<-- will return an array of the sentences of your story.
story.split(/[?!.]/).length //<-- will return the number of element of the array of the sentences of your story, so the sentence count
That does what you wanted but with one line of code. But If you want to be smart about you problem, remember that I said
Also this comes back to just counting the punctuation to count the number of sentence.
So we'll just do that right ?
story.match(/(\.\.\.)|[.?!]/g).length
Have fun here ;) : https://regexr.com/
I hope that helps you ! Good luck !

How to replace numbered list elements with an identifier containing the number

I have gotten amazing help here today!
I'm trying to do something else. I have a numbered list of questions in a Google Doc, and I'd like to replace the numbers with something else.
For example, I'd like to replace the numbers in a list such as:
The Earth is closest to the Sun in which month of the year?
~July
~June
=January
~March
~September
In Australia (in the Southern Hemisphere), when are the days the shortest and the nights the longest?
~in late December
~in late March
=in late June
~in late April
~days and nights are pretty much the same length throughout the year in Australia
With:
::Q09:: The Earth is closest to the Sun in which month of the year?
~July
~June
=January
~March
~September
::Q11:: In Australia (in the Southern Hemisphere), when are the days the shortest and the nights the longest?
~in late December
~in late March
=in late June
~in late April
~days and nights are pretty much the same length throughout the year in Australia
I've tried using suggestions from previous posts but have come up only with things such as the following, which doesn't seem to work.
Thank you for being here!!!
function questionName2(){
var body = DocumentApp.getActiveDocument().getBody();
var text = body.editAsText();
var pattern = "^[1-9]";
var found = body.findText(pattern);
var matchPosition = found.getStartOffset();
while(found){
text.insertText(matchPosition,'::Q0');
found = body.findText(pattern, found);
}
}
Regular expressions
Text.findText(searchPattern) uses a string that will be parsed as a regular expression using Google's RE2 library for the searchPattern. Using a string in this way requires we add an extra backslash whenever we are removing special meaning from a character, such as matching the period after the question number, or using a character matching set like \d for digits.
^\\s*\\d+?\\. will match a set of digits, of any non-zero length, that begin a line, with any length (including zero) of leading white space. \d is for digits, + is one or more, and the combination +? makes the match lazy. The lazy part is not required here, but it's my habit to default to lazy to avoid bugs. An alternative would be \d{1,2} to specifically match 1 to 2 digits.
To extract just the digits from the matched text, we can use a JavaScript RegExp object. Unlike the Doc regular expression, this regular expression will not require extra backslashes and will allow us to use capture groups using parentheses.
^\s*(\d+?)\. is almost the same as above, except no extraneous slashes and we will now "save" the digits so we can use them in our replacement string. We mark what we want to save using parentheses. Because this will be a normal JavaScript regular expression literal, we will wrap the whole thing in slashes: /^\s*(\d+?)\./, but the starting and ending / are just to indicate this is a RegExp literal.
text elements and text strings
Text.findText can return more than just the exact match we asked for: it returns the entire element that contains the text plus indices for what the regular expression matched. In order to perform search and replace with capture groups, we have to use the indices to delete the old text and then insert the new text.
The following assignments get us all the data we need to do the search and replace: first the element, then the start & stop indices, and finally extracting the matched text string using slice (note that slice uses an exclusive end, whereas the Doc API uses an inclusive end, hence the +1).
var found = DocumentApp.getActiveDocument().getBody().findText(pattern);
var matchStart = found.getStartOffset();
var matchEnd = found.getEndOffsetInclusive();
var matchElement = found.getElement().asText();
var matchText = matchElement.getText().slice(matchStart, matchEnd + 1);
Caveats
As Tanaike pointed out in the comments, this assumes the numbering is not List Items, which automatically generates numbers, but numbers you typed in manually. If you are using an automatically generated list of numbers, the API does not allow you to edit the format of the numbering.
This answer also assumes that in the example, when you mapped "9." to "::Q09::" and "10." to "::Q11::", that the mapping of 10 to 11 was a typo. If this was intended, please update the question to clarify the rules for why the numbering might change.
Also assumed is that the numbers are supposed to be less than 100, given the example zero padding of "Q09". The example should be flexible enough to allow you to update this to a different padding scheme if needed.
Full example
Since the question did not use any V8 features, this assumes the older Rhino environment.
/**
* Replaces "1." with "::Q01::"
*/
function updateQuestionNumbering(){
var text = DocumentApp.getActiveDocument().getBody();
var pattern = "^\\s*\\d+?\\.";
var found = text.findText(pattern);
while(found){
var matchStart = found.getStartOffset();
var matchEnd = found.getEndOffsetInclusive();
var matchElement = found.getElement().asText();
var matchText = matchElement.getText().slice(matchStart, matchEnd + 1);
matchElement.deleteText(matchStart, matchEnd);
matchElement.insertText(matchStart, matchText.replace(/^\s*(\d+?)\./, replacer));
found = text.findText(pattern, found);
}
/**
* #param {string} _ - full match (ignored)
* #param {string} number - the sequence of digits matched
*/
function replacer(_, number) {
return "::Q" + padStart(number, 2, "0") + "::";
}
// use String.prototype.padStart() in V8 environment
// above usage would become `number.padStart(2, "0")`
function padStart(string, targetLength, padString) {
while (string.length < targetLength) string = padString + string;
return string;
}
}

How to improve performance for REGEXP string matching in MySQL?

Preface:
I've done quite a bit of (re)searching on this, and found the following SO post/answer: https://stackoverflow.com/a/5361490/6095216 which was pretty close to what I'm looking for. The same code, but with somewhat more helpful comments, appears here: http://thenoyes.com/littlenoise/?p=136 .
Problem Description:
I need to split 1 column of MySQL TEXT data into multiple columns, where the original data has this format (N <= 7):
{"field1":"value1","field2":"value2",...,"fieldN":"valueN"}
As you might guess, I only need to extract the values, putting each one into a separate (predefined) column. The problem is that the number and order of the fields is not guaranteed to be the same for all records. Thus, solutions using SUBSTR/LOCATE, etc. don't work, and I need to use regular expressions. Another restriction is that 3rd party libraries such as LIB_MYSQLUDF_PREG (suggested in the answer from my 1st link above) cannot be used.
Solution/Progress so far:
I've modified the code from the above links such that it returns the first/shortest match, left-to-right; otherwise, NULL is returned. I also refactored it a bit and made the identifiers more reader/maintainer-friendly :)
Here's my version:
CREATE FUNCTION REGEXP_EXTRACT_SHORTEST(string TEXT, exp TEXT)
RETURNS TEXT DETERMINISTIC
BEGIN
DECLARE adjustStart, adjustEnd BOOLEAN DEFAULT TRUE;
DECLARE startInd INT DEFAULT 1;
DECLARE endInd, strLen INT;
DECLARE candidate TEXT;
IF string NOT REGEXP exp THEN
RETURN NULL;
END IF;
IF LEFT(exp, 1) = '^' THEN
SET adjustStart = FALSE;
ELSE
SET exp = CONCAT('^', exp);
END IF;
IF RIGHT(exp, 1) = '$' THEN
SET adjustEnd = FALSE;
ELSE
SET exp = CONCAT(exp, '$');
END IF;
SET strLen = LENGTH(string);
StartIndLoop: WHILE (startInd <= strLen) DO
IF adjustEnd THEN
SET endInd = startInd;
ELSE
SET endInd = strLen;
END IF;
EndIndLoop: WHILE (endInd <= strLen) DO
SET candidate = SUBSTRING(string FROM startInd FOR (endInd - startInd + 1));
IF candidate REGEXP exp THEN
RETURN candidate;
END IF;
IF adjustEnd THEN
SET endInd = endInd + 1;
ELSE
LEAVE EndIndLoop;
END IF;
END WHILE EndIndLoop;
IF adjustStart THEN
SET startInd = startInd + 1;
ELSE
LEAVE StartIndLoop;
END IF;
END WHILE StartIndLoop;
RETURN NULL;
END;
I then added a helper function to avoid having to repeat the regex pattern, which, as you can see from above, is the same for all the fields. Here is that function (I left my attempt to use a lookbehind - unsupported in MySQL - as a comment):
CREATE FUNCTION GET_MY_FLD_VAL(inputStr TEXT, fldName TEXT)
RETURNS TEXT DETERMINISTIC
BEGIN
DECLARE valPattern TEXT DEFAULT '"[^"]+"'; /* MySQL doesn't support lookaround :( '(?<=^.{1})"[^"]+"'*/
DECLARE fldNamePat TEXT DEFAULT CONCAT('"', fldName, '":');
DECLARE discardLen INT UNSIGNED DEFAULT LENGTH(fldNamePat) + 2;
DECLARE matchResult TEXT DEFAULT REGEXP_EXTRACT_SHORTEST(inputStr, CONCAT(fldNamePat, valPattern));
RETURN SUBSTRING(matchResult FROM discardLen FOR LENGTH(matchResult) - discardLen);
END;
Currently, all I'm trying to do is a simple SELECT query using the above code. It works correctly, BUT IT. IS. SLOOOOOOOW... There are only 7 fields/columns to split into, max (not all records have all 7)! Limited to 20 records, it takes about 3 minutes - and I have about 40,000 records total (not very much for a database, right?!) :)
And so, finally, we get to the actual question: [how] can the above algorithm/code (pretty much a brute search at this point) be improved SIGNIFICANTLY performance-wise, such that it can be run on the actual database in a reasonable amount of time? I started looking into the major known pattern-matching algorithms, but quickly got lost trying to figure out what would be appropriate here, in large part due to the number of available options and their respective restrictions, conditions for use, etc. Plus, it seems like implementing one of these in SQL just to see if it would help, might be a lot of work.
Note: this is my first post ever(!), so please let me know (nicely) if something is not clear, etc. and I will do my best to fix it. Thanks in advance.
I was able to solve this by parsing the JSON, as suggested by tadman and Matt Raines above. Being new to the concept of JSON, I just didn't realize it could be done this way at all...a little embarrassing, but lesson learned!
Anyway, I used the get_option function in the common_schema framework: https://code.google.com/archive/p/common-schema/ (found through this post, which also demonstrates how to use the function: Parse JSON in MySQL ). As a result, my INSERT query took about 15 minutes to run, vs the 30+ hours it would've taken with the REGEXP solution. Thanks, and until next time! :)
Don't do it in SQL; do it in PHP or some other language that has builtin tools for parsing JSON.

FFT implementation in Verilog : Error using nested for loop

This post is related to the my previous post related to FFT.
FFT implemetation in Verilog: Assigning Wire input to Register type array
I want to assign output of first stage to input of second stage of FFT butterfly modules. I have to re-order the output of first stage according to input of second stage. Here is my code to implement the swapping.
always# (posedge y_ndd[0] or posedge J)
begin
if(J==1'b1)
begin
for (idx=0; idx<N/2; idx=idx+1)
begin
IN[2*idx] <= X[idx*2*X_WDTH+: 2*X_WDTH];
IN[2*idx+1] <= X[(idx+N/2)*2*X_WDTH+: 2*X_WDTH];
end
end
else
begin
level=level+1;
modulecount=0;
for(jj=0;jj<N;jj=jj+(2**(level+1)))
begin
for (jx=jj; jx<jj+(2**level); jx=jx+1)//jj+(2**level)
begin
IN[modulecount] <=OUT[jx];
IN[modulecount+1] <=OUT[jx+(2**level)];
modulecount=modulecount+1;
end
end
end
end
When I synthesize this, It gives 2 errors.
ERROR:Xst:891 - "Network.v" line 161: For Statement is only supported when the new step evaluation is constant increment or decrement of the loop variable.
ERROR:Xst:2634 - "Network.v" line 161: For loop stop condition should depend on loop variable or be static.
Can't we use non-constant increment and non-static stop coditions?
If that so, how we handle this.
Any help is appreciated.
Thanks in advance.
Synthesis tools unroll loops in order to synthesize the circuit. Therefore, only loops that iterate a constant number of times, whose constant is known at compile/elaboration time are synthetisable.
When the stop value is not known, you can assume a maximum number of iterations and use that as the stop condition. Then add the original stop condition as a conditional statement inside the loop:
for (jx=jj; jx < MAX_LOOP_ITERATION; jx=jx+1)//jj+(2**level)
begin
if (jx<jj+(2**level)) // <---------- Add stop condition here
begin
IN[modulecount] <=OUT[jx];
IN[modulecount+1] <=OUT[jx+(2**level)];
modulecount=modulecount+1;
end
end
If N is not a constant, the outer loop should also be fixed using a similar conditional statement. You also need to fix the increment value and each time add a constant value. Use a conditional statement to check if jj==jj+(2**(level+1))
Obviously, you need to be careful as a high max number may increase your worst case delay and the minimum clock cycle time.
//ll,level,K has to be declare.
always# (posedge y_ndd[0] or posedge J)
begin
if(J==1'b1)
begin
for (idx=0; idx<N/2; idx=idx+1)
begin
IN[2*idx] <= X[idx*2*X_WDTH+: 2*X_WDTH];
IN[2*idx+1] <= X[(idx+N/2)*2*X_WDTH+: 2*X_WDTH];
end
end
else
begin
ll=ll+1;
modulecount=0;
for(level=0;level<K;level=level+1) //K time you need to execute
begin
if(ll==level)
begin
for(jj=0;jj<N;jj=jj+(2**(level+1)))
begin
for (jx=jj; jx<jj+(2**level); jx=jx+1)
begin
IN[modulecount] <=OUT[jx];
IN[modulecount+1] <=OUT[jx+(2**level)];
modulecount=modulecount+1;
end
end
end
end
//ll=ll+1;
end
end
You can try this. It has to work. But problem is outer loop will execute K times.