Strings in Julia - julia

I am playing with Julia and tried to run the following function. Can someone please tell me why I cannot see the last word "programming" in the terminal. Thanks
function prnt(st)
emptyArr = []
emptySt = ""
id = 1
for char in st
if (char != ' ' && char != '\n' && char != '\r')
emptySt = emptySt * char
else
print(emptySt)
emptySt = ""
end
end
end
prnt("this is programming")

i just added a little debugging println to see whats happening:
function prnt(st)
emptyArr = []
emptySt = ""
id = 1
for char in st
println(char) #debug statement
if (char != ' ' && char != '\n' && char != '\r')
emptySt = emptySt * char
else
print(emptySt)
emptySt = ""
end
end
end
the result was this:
julia> prnt("this is programming")
t
h
i
s
thisi
s
isp
r
o
g
r
a
m
m
i
n
g
adding a print(emptySt) at the end of the loop works fine:
function prnt(st)
emptyArr = []
emptySt = ""
id = 1
for char in st
if (char != ' ' && char != '\n' && char != '\r')
emptySt = emptySt * char
else
print(emptySt)
emptySt = ""
end
end
print(emptySt) #extra print here
end
and this is the result:
julia> prnt("this is programming")
thisisprogramming
an easier way to do this is using the replace function:
function prnt2(st)
println(replace(st,r" |\n|\r"=>"")) #using a regular expression (r"")
end
The result:
julia> prnt("this is programming")
thisisprogramming

Related

(Godot Engine) Compute string as PEMDAS

I've been trying to create a function in GDScript to process and calculate a string using PEMDAS rules. Below is my try on the subject. It can so far only use the MDAS rules:
Is there a better way to achieve such a function?
func _ready() -> void:
### USE CASES ###
print(Compute_String("1+2*3+3=")) # Output = 10
print(Compute_String("1+2*3*3=")) # Output = 19
print(Compute_String("1*2*3+3=")) # Output = 9
print(Compute_String("1+2+3*3=")) # Output = 12
print(Compute_String("5*2+7-3/2=")) # Output = 15.5
print(Compute_String("9+5.5*2.25=")) # Output = 21.375
print(Compute_String("5*2+7-3/2")) # Output = 1.#QNAN (Missing equals)
print(Compute_String("5*2+7-/2=")) # Output = 1.#QNAN (Adjacent operators)
print(Compute_String("*2+7-3/2=")) # Output = 1.#QNAN (Begins with operator)
print(Compute_String("")) # Output = 1.#QNAN (Empty)
print(Compute_String("=")) # Output = 1.#QNAN (Considered as empty)
print(Compute_String("1 +2=")) # Output = 1.#QNAN (Contains space)
print(Compute_String("(1+2)*3=")) # Output = 1.#QNAN (Parentheses not supported)
func Compute_String(_string: String) -> float:
var _result: float = NAN
var _elements: Array = []
if not _string.empty() and _string[_string.length() - 1] == "=":
var _current_element: String = ""
for _count in _string.length():
if _string[_count].is_valid_float() or _string[_count] == ".": _current_element += _string[_count]
else:
if _string[_count - 1].is_valid_float() and (_string[_count + 1].is_valid_float() if _string[_count] != "=" else true):
_elements.append_array([_current_element,_string[_count]]) ; _current_element = ""
else: return NAN
if not _elements.empty():
_elements.resize(_elements.size() - 1)
while _get_operators_count(_elements) != 0:
var _id: Array = [0, 0.0, 0.0]
if "*" in _elements:
_id = _add_adjacent(_elements, "*") ; _remove_adjacent(_elements, _id[0]) ; _elements.insert(_id[0] - 1, _id[1] * _id[2])
elif "/" in _elements:
_id = _add_adjacent(_elements, "/") ; _remove_adjacent(_elements, _id[0]) ; _elements.insert(_id[0] - 1, _id[1] / _id[2])
elif "+" in _elements:
_id = _add_adjacent(_elements, "+") ; _remove_adjacent(_elements, _id[0]) ; _elements.insert(_id[0] - 1, _id[1] + _id[2])
elif "-" in _elements:
_id = _add_adjacent(_elements, "-") ; _remove_adjacent(_elements, _id[0]) ; _elements.insert(_id[0] - 1, _id[1] - _id[2])
else: return NAN
if _elements.size() == 1: _result = _elements[0]
return _result
func _get_operators_count(_elements: Array) -> int:
var _result: int = 0 ; for _element in _elements: if not str(_element).is_valid_float(): _result += 1 ; return _result
func _add_adjacent(_elements: Array, _operator) -> Array:
return [_elements.find(_operator), float(_elements[_elements.find(_operator) - 1]), float(_elements[_elements.find(_operator) + 1])]
func _remove_adjacent(_elements: Array, _operator_idx: int) -> void:
_elements.remove(_operator_idx + 1) ; _elements.remove(_operator_idx) ; _elements.remove(_operator_idx - 1)

Character Arithmetic using only the Alphabet (A or a ...) in order

I am learning programming on my own at home. I'm interested in C right now and so, this is my first question. I have been trying to figure out why my code is not printing the right answer but I'm not sure what is wrong. I will attach the question and my code below. If some could help me figure out what I am doing wrong I'd be really grateful.
"Write a program that takes a string and displays it, replacing each of its
letters by the letter 13 spaces ahead in alphabetical order.
'z' becomes 'm' and 'Z' becomes 'M'. Case remains unaffected.
The output will be followed by a newline.
If the number of arguments is not 1, the program displays a newline."
I'm using command line arguments to read in a string "My horse is Amazing." and the expected output should be "Zl ubefr vf Nznmvat." but I am getting this as my output "Zå ubeÇr vÇ Nznçvat."
This is my code:
#include <stdio.h>
#include <string.h>
int main(int argc, char **argv[]){
char ch, str[100], newStr[100];
int i, len;
if(argc != 2){
printf("\n");
return (-1);
}
strcpy(str, argv[1]);
len = strlen(str);
printf("%s %d\n\n", str, len);
for (i = 0; i < len; i++)
{
ch = str[i];
if ((ch >= 65) && (ch <= 90)){
ch = ch + 13;
if(ch > 90){
ch = ch - 90;
ch = ch + 64;
}
}else if ((ch >= 97) && (ch <= 122)){
ch = ch + 13;
if(ch > 122){
ch = ch - 122;
ch = ch + 96;
}
}
newStr[i] = ch;
}
printf("%s \n", newStr);
return 0;
}
ch is a signed 1-byte variable, meaning it can only represent values between -128 and 127. Adding 13 to y results in a value outside of that range.

Finding all possible permutations of the characters in a set of strings using recursion

I have this set of (Greek) strings:
ἸἼΙἹἽ,
ῇηἤήῃὴῆἡἠἢᾖἥἣῄἦᾗᾐἧᾔᾑ,
σς,
οὸόὀὄὅὂ,
ὺὖυῦύὐὑὔΰϋὕὗὓὒῢ
I'd like to find all possible permutations of the characters in these 5 strings. For example, Ἰῇσοὺ, Ἰῇσοὖ, Ἰῇσου, etc. I know it should involve recursion since the number of strings is not fixed but I'm a beginner and I'm completely dumbfounded by recursion.
I did the following in Python and it does give me all combinations of the characters in each string. But I need the 'ἸἼΙἹἽ' to always come first, 'ῇηἤήῃὴῆἡἠἢᾖἥἣῄἦᾗᾐἧᾔᾑ' second,'σς' third, etc.
# -*- coding: utf-8 -*-
def Gen( wd, pos, chars ):
if pos < len( chars ):
for c in chars:
for l in c:
Gen( wd + l, pos + 1, chars )
else:
print wd
chars = [ u'ἸἼΙἹἽ', u'ῇηἤήῃὴῆἡἠἢᾖἥἣῄἦᾗᾐἧᾔᾑ', u'σς', u'οὸόὀὄὅὂ', u'ὺὖυῦύὐὑὔΰϋὕὗὓὒῢ' ]
Gen( "", 0, chars )
Thanks for the help everybody. My mind is completely blown. Recursion! Here's what I ended up doing in Python:
# -*- coding: utf-8 -*-
s = [ u'ἸἼΙἹἽ', u'ῇηἤήῃὴῆἡἠἢᾖἥἣῄἦᾗᾐἧᾔᾑ', u'σς', u'οὸόὀὄὅὂ', u'ὺὖυῦύὐὑὔΰϋὕὗὓὒῢ' ]
results = []
def recur( wd, strings ):
index = 0
if index < len( strings ):
for c in strings[ index ]:
recur( wd + c, strings[ index + 1: ] )
else:
results.append( wd )
def main():
recur( '', s )
for r in results:
print r.encode( 'utf-8' )
main()
You create a char array which will contain the string you want to work with
char str[] = "ABC";
then you get the length of the string int n = strlen(str); and lastly you permutate.
You make a new function which will contain the input string, starting index of the string and ending index of the string.
Check if the starting index (int s) equals the ending index (int e)
if it does, that means you're done, if not you go into a loop where you go from start (s) to end (e), swap the values, recurse, swap again to backtrack.
An example in C++:
#include <stdio.h>
#include <string.h>
void swap(char *i, char *j)
{
char temp;
temp = *i;
*i = *j;
*j = temp;
}
void permutate(char *str, int start, int end)
{
int i;
if (start == end)
printf("%s\n", str);
else
{
for (i = start; i <= end; i++)
{
swap((str + start), (str + i));
permutate(str, start + 1, end);
swap((str + start), (str + i)); //backtrack
}
}
}
int main()
{
char str[] = "ABC";
int n = strlen(str);
permutate(str, 0, n - 1);
return 0;
}
I'm not that familliar with Python, but I've found something that might help in your case:
def comb(first_str, second_str):
if not first_str:
yield second_str
return
if not second_str:
yield first_str
return
for result in comb(first_str[1:], second_str):
yield first_str[0] + result
for result in comb(first_str, second_str[1:]):
yield second_str[0] + result
>>> for result in comb("ἸἼΙἹἽ", "ῇηἤήῃὴῆἡἠἢᾖἥἣῄἦᾗᾐἧᾔᾑ"):
print(result)
Just write down the five nested loops. In pseudocode,
for a in "ἸἼΙἹἽ"
for b in "ῇηἤήῃὴῆἡἠἢᾖἥἣῄἦᾗᾐἧᾔᾑ"
for c in "σς"
for d in "οὸόὀὄὅὂ"
for e in "ὺὖυῦύὐὑὔΰϋὕὗὓὒῢ"
emit [a,b,c,d,e]
To encode these five loops with recursion, so it's good for any number of input strings, again in pseudocode,
g(list-of-strings) =
| case list-of-strings
| of empty --> end-of-processing
| of (first-string AND rest-of-strings) -->
for each ch in first-string
DO g(rest-of-strings)
Now you only need to figure out where to hold each current first-string's character ch and how to combine them all while at the end-of-processing (basically, your two options are a global accumulator, or an argument to a function invocation).

Solving QT's QString arg() ambiguity

There is an issue using QString::arg() when a string contains a digit right after a place marker. It's not clear from the QString::arg() function description what would happen in case of such a replacement:
QString("String for replacement %1234").arg("blah");
Will this result in "String for replacement blah234" or "String for replacement blah34"?
I looked in the QT's source code to answer this question. It seems that the algorithm which looks for place markers is 'greedy' and it would take both digits in the example above.
Here is the source of the QT's function which is used inside the QString::arg() (QT 4.8.4):
static ArgEscapeData findArgEscapes(const QString &s)
{
const QChar *uc_begin = s.unicode();
const QChar *uc_end = uc_begin + s.length();
ArgEscapeData d;
d.min_escape = INT_MAX;
d.occurrences = 0;
d.escape_len = 0;
d.locale_occurrences = 0;
const QChar *c = uc_begin;
while (c != uc_end) {
while (c != uc_end && c->unicode() != '%')
++c;
if (c == uc_end)
break;
const QChar *escape_start = c;
if (++c == uc_end)
break;
bool locale_arg = false;
if (c->unicode() == 'L') {
locale_arg = true;
if (++c == uc_end)
break;
}
if (c->digitValue() == -1)
continue;
int escape = c->digitValue();
++c;
if (c != uc_end && c->digitValue() != -1) {
escape = (10 * escape) + c->digitValue();
++c;
}
if (escape > d.min_escape)
continue;
if (escape < d.min_escape) {
d.min_escape = escape;
d.occurrences = 0;
d.escape_len = 0;
d.locale_occurrences = 0;
}
++d.occurrences;
if (locale_arg)
++d.locale_occurrences;
d.escape_len += c - escape_start;
}
return d;
}
Is there a better way of solving such an ambiguity than always using a 2-digit place markers?
Since you can only use %1 to %99 as markers and you can skip marker numbers you can write:
QString("String for replacement %10234").arg("blah");
to output String for replacement blah234
Qt help states for arg(const QString & a, int fieldWidth = 0, QChar fillChar = QLatin1Char( ' ' ))
Returns a copy of this string with the lowest numbered place marker replaced by string a, i.e., %1, %2, ..., %99.
...
Place marker numbers must be in the range 1 to 99.
Therefore, what you're seeing is, by definition, correct; the first two numbers will be replaced. If you're wanting "String for replacement blah234", then you could define the string as: -
QString("String for replacement %1%2").arg("blah").arg(234);
I have the same issue, but the order answers not looks like a good way for me.
I have resolve the ambiguity in this way.
QString myString= QString("ConcatenatedNumbers%0123").arg(66,3,10, QChar('0'));
The string will be:
ConcatenatedNumbers06623

Is there a way to format a String in Flex

Is it possible to do something like this:
var s:String = format("%20d %-10s %s", time, type, message);
In languages like C, C++, C#, Python, and Perl there is something similar to my example, but I can't seem to find it for Flex.
I don't want to create special class Formatter for every string that I want to format.
You probably are looking for mx.utils.StringUtil.substitute(). Works similar to .NET String.Format().
For Example:
StringUtil.substitute("Hello {0}", ["World"]);
Adobe Livedocs for StringUtil class
Found this script that implements sprintf - and that's exactly what I was looking for. Thanks to Manish Jethani!
/* sprintf(3) implementation in ActionScript 3.0.
*
* Author: Manish Jethani (manish.jethani#gmail.com)
* Date: April 3, 2006
* Version: 0.1
*
* Copyright (c) 2006 Manish Jethani
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package
{
/* sprintf(3) implementation in ActionScript 3.0.
*
* http://www.die.net/doc/linux/man/man3/sprintf.3.html
*
* The following flags are supported: '#', '0', '-', '+'
*
* Field widths are fully supported. '*' is not supported.
*
* Precision is supported except one difference from the standard: for an
* explicit precision of 0 and a result string of "0", the output is "0"
* instead of an empty string.
*
* Length modifiers are not supported.
*
* The following conversion specifiers are supported: 'd', 'i', 'o', 'u', 'x',
* 'X', 'f', 'F', 'c', 's', '%'
*
* Report bugs to manish.jethani#gmail.com
*/
public function sprintf(format:String, ... args):String
{
var result:String = "";
var length:int = format.length;
for (var i:int = 0; i < length; i++)
{
var c:String = format.charAt(i);
if (c == "%")
{
var pastFieldWidth:Boolean = false;
var pastFlags:Boolean = false;
var flagAlternateForm:Boolean = false;
var flagZeroPad:Boolean = false;
var flagLeftJustify:Boolean = false;
var flagSpace:Boolean = false;
var flagSign:Boolean = false;
var fieldWidth:String = "";
var precision:String = "";
c = format.charAt(++i);
while (c != "d"
&& c != "i"
&& c != "o"
&& c != "u"
&& c != "x"
&& c != "X"
&& c != "f"
&& c != "F"
&& c != "c"
&& c != "s"
&& c != "%")
{
if (!pastFlags)
{
if (!flagAlternateForm && c == "#")
flagAlternateForm = true;
else if (!flagZeroPad && c == "0")
flagZeroPad = true;
else if (!flagLeftJustify && c == "-")
flagLeftJustify = true;
else if (!flagSpace && c == " ")
flagSpace = true;
else if (!flagSign && c == "+")
flagSign = true;
else
pastFlags = true;
}
if (!pastFieldWidth && c == ".")
{
pastFlags = true;
pastFieldWidth = true;
c = format.charAt(++i);
continue;
}
if (pastFlags)
{
if (!pastFieldWidth)
fieldWidth += c;
else
precision += c;
}
c = format.charAt(++i);
}
switch (c)
{
case "d":
case "i":
var next:* = args.shift();
var str:String = String(Math.abs(int(next)));
if (precision != "")
str = leftPad(str, int(precision), "0");
if (int(next) < 0)
str = "-" + str;
else if (flagSign && int(next) >= 0)
str = "+" + str;
if (fieldWidth != "")
{
if (flagLeftJustify)
str = rightPad(str, int(fieldWidth));
else if (flagZeroPad && precision == "")
str = leftPad(str, int(fieldWidth), "0");
else
str = leftPad(str, int(fieldWidth));
}
result += str;
break;
case "o":
var next:* = args.shift();
var str:String = uint(next).toString(8);
if (flagAlternateForm && str != "0")
str = "0" + str;
if (precision != "")
str = leftPad(str, int(precision), "0");
if (fieldWidth != "")
{
if (flagLeftJustify)
str = rightPad(str, int(fieldWidth));
else if (flagZeroPad && precision == "")
str = leftPad(str, int(fieldWidth), "0");
else
str = leftPad(str, int(fieldWidth));
}
result += str;
break;
case "u":
var next:* = args.shift();
var str:String = uint(next).toString(10);
if (precision != "")
str = leftPad(str, int(precision), "0");
if (fieldWidth != "")
{
if (flagLeftJustify)
str = rightPad(str, int(fieldWidth));
else if (flagZeroPad && precision == "")
str = leftPad(str, int(fieldWidth), "0");
else
str = leftPad(str, int(fieldWidth));
}
result += str;
break;
case "X":
var capitalise:Boolean = true;
case "x":
var next:* = args.shift();
var str:String = uint(next).toString(16);
if (precision != "")
str = leftPad(str, int(precision), "0");
var prepend:Boolean = flagAlternateForm && uint(next) != 0;
if (fieldWidth != "" && !flagLeftJustify
&& flagZeroPad && precision == "")
str = leftPad(str, prepend
? int(fieldWidth) - 2 : int(fieldWidth), "0");
if (prepend)
str = "0x" + str;
if (fieldWidth != "")
{
if (flagLeftJustify)
str = rightPad(str, int(fieldWidth));
else
str = leftPad(str, int(fieldWidth));
}
if (capitalise)
str = str.toUpperCase();
result += str;
break;
case "f":
case "F":
var next:* = args.shift();
var str:String = Math.abs(Number(next)).toFixed(
precision != "" ? int(precision) : 6);
if (int(next) < 0)
str = "-" + str;
else if (flagSign && int(next) >= 0)
str = "+" + str;
if (flagAlternateForm && str.indexOf(".") == -1)
str += ".";
if (fieldWidth != "")
{
if (flagLeftJustify)
str = rightPad(str, int(fieldWidth));
else if (flagZeroPad && precision == "")
str = leftPad(str, int(fieldWidth), "0");
else
str = leftPad(str, int(fieldWidth));
}
result += str;
break;
case "c":
var next:* = args.shift();
var str:String = String.fromCharCode(int(next));
if (fieldWidth != "")
{
if (flagLeftJustify)
str = rightPad(str, int(fieldWidth));
else
str = leftPad(str, int(fieldWidth));
}
result += str;
break;
case "s":
var next:* = args.shift();
var str:String = String(next);
if (precision != "")
str = str.substring(0, int(precision));
if (fieldWidth != "")
{
if (flagLeftJustify)
str = rightPad(str, int(fieldWidth));
else
str = leftPad(str, int(fieldWidth));
}
result += str;
break;
case "%":
result += "%";
}
}
else
{
result += c;
}
}
return result;
}
}
// Private functions
function leftPad(source:String, targetLength:int, padChar:String = " "):String
{
if (source.length < targetLength)
{
var padding:String = "";
while (padding.length + source.length < targetLength)
padding += padChar;
return padding + source;
}
return source;
}
function rightPad(source:String, targetLength:int, padChar:String = " "):String
{
while (source.length < targetLength)
source += padChar;
return source;
}
The printf-as3 project sounds like it should fit your needs

Resources