I am finishing some functions in a flutter project.
void code_shift_backward() {
var input_string = controller.text;
List<String> output_list = [];
var input_runes = input_string.runes.toList();
for (var rune in input_runes) {
var mutatedRune = rune--;
output_list.add(String.fromCharCode(mutatedRune));
}
var output_string = output_list.join("");
setState(() {
text_in_tree = output_string;
});
}
I give it the word wiggle and I expect vhffkd but it keeps giving wiggle
You have to change:
var mutatedRune = rune--;
to:
var mutatedRune = --rune;
Explanation:
rune-- assigns the value of rune to mutatedRune first, then reduces the value by one. It means mutatedRune and rune has the same value.
--rune reduces the value first, then assigns.
Read about Dart arithmetic operators for more details.
You can fix this by moving the -- to the front of rune.. This happens because putting the -- after the variable only updates the variable after that line.
void code_shift_backward() {
var input_string = controller.text;
List<String> output_list = [];
var input_runes = input_string.runes.toList();
for (var rune in input_runes) {
var mutatedRune = --rune;
output_list.add(String.fromCharCode(mutatedRune));
}
var output_string = output_list.join("");
setState(() {
text_in_tree = output_string;
});
}
For size, maybe:
String shiftBack(String input) =>
String.fromCharCodes([for (var c in input.runes) c - 1]);
Related
I have a variable named wordRandom and I would like to use a boolean array as in Java.
String[] words = {"yes", "no"};
String wordRandom = words[(int) (Math.random() * words.length )];
boolean[] letterFound = new boolean [wordRandom.length()];
For now, I have this in NodeJs
var words = ["yes", "no"];
var wordRandom = words[Math.floor(Math.random() * words.length)];
I am stuck on the boolean type ?! By searching on StackOverFlow below :
An array of booleans in javascript
I declare my variable as this?
var letterFound = new Array[wordRandom.length];
This is not good !
My code has an error message on the line -> var letterFound = new Array[wordRandom.length];
var readline = require("readline-sync");
var words = ["oui", "no"];
var wordRandom = words[Math.floor(Math.random() * words.length)];
var letterFound = new Array[wordRandom.length];
for(var i=0; i<wordRandom.length; i++){
if(letterFound[i]){
console.log(wordRandom.charAt(i));
} else {
console.log("-");
}
}
Thank you very much for your help.
In apps script I want to obtain formatted 'number' strings. The input is an unformatted number. With an earlier answer posted by #slandau, I thought I had found a solution by modifying his code (see code snippet). It works in codepen, but not when I am using apps script.
1. Does anyone know what went wrong here?
2. I noticed this code works except when entering a number ending in .0, in that case the return value is also .0 but should be .00. I would like some help fixing that too.
Thanks!
I have tried to look for type coercion issues, but wasn't able to get it down. I am fairly new to coding.
function commaFormatted(amount)
{
var delimiter = ","; // replace comma if desired
var a = amount.split('.', 2);
var preD = a[1]/(Math.pow(10,a[1].length-2));
var d = Math.round(preD);
var i = parseInt(a[0]);
if(isNaN(i)) { return ''; }
var minus = '';
if(i < 0) { minus = '-'; }
i = Math.abs(i);
var n = new String(i);
var a = [];
while(n.length > 3)
{
var nn = n.substr(n.length-3);
a.unshift(nn);
n = n.substr(0,n.length-3);
}
if(n.length > 0) { a.unshift(n); }
n = a.join(delimiter);
if(d.length < 1) { amount = n; }
else { amount = n + '.' + d; }
amount = minus + amount;
return amount;
}
console.log(commaFormatted('100000.3532'))
The expected result would be 100,000.35.
I am getting this in the IDE of codepen, but in GAS IDE is stops at the .split() method => not a function. When converting var a to a string = I am not getting ["100000", "3532"] when logging var a. Instead I am getting 100000 and was expecting 3532.
Based on this answer, your function can be rewritten to
function commaFormatted(amount)
{
var inputAmount;
if (typeof(amount) == 'string') {
inputAmount = amount;
} else if (typeof(amount) == 'float') {
inputAmount = amount.toString();
}
//--- we expect the input amount is a String
// to make is easier, round the decimal part first
var roundedAmount = parseFloat(amount).toFixed(2);
//--- now split it and add the commas
var parts = roundedAmount.split(".");
parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
return parts.join(".");
}
console.log(commaFormatted(100000.3532));
console.log(commaFormatted('1234567.3532'));
I am using the Flex SDK and able to capitalise the first letter of every word as follows:
textInput.text.toLowerCase().replace(/\b./g,function(...m):String{return m[0].toUpperCase()})
This works fine, however letters after punctuation are also being capitalised, which works in some cases (e.g. O'Neil) but not others (e.g. Connah'S Quay).
I want to have the code only look at letters at the start of a string and letters after a space. Can anyone provide the correct code to use in this instance please?
This snippet might help:
function firstLetterUpperCase(strData:String):String
{
var strArray:Array = strData.split(' ');
var newArray:Array = [];
for (var str:String in strArray)
{
newArray.push(strArray[str].charAt(0).toUpperCase() + strArray[str].slice(1));
}
return newArray.join(' ');
}
//testing
var strs = "Testing cases (e.g. o'Neil) and others (e.g. connah's quay)."
trace(firstLetterUpperCase(strs));
Result is:
//Testing Cases (e.g. O'Neil) And Others (e.g. Connah's Quay).
If you prefer, try this regex:
/(^| )./g
private function capitalise(s:String):String
{
var strArray:Array = s.split(' ');
var newArray:Array = new Array();
for each (var str:String in strArray)
newArray.push(str.charAt(0).toUpperCase()+str.slice(1));
return newArray.join(' ');
}
trace(capitalise("this is a test - o'Neil - connah's quay"));
// Output: This Is A Test - O'Neil - Connah's Quay
var test = "thIS is a test ansWER to stack OVERFlow";
function process(sentence) {
var words = sentence.split(" ");
var processed = '';
for(var i=0; i < words.length; i++) {
processed += words[i].substr(0,1).toUpperCase() +
words[i].substr(1).toLowerCase();
if(i < words.length-1) {
processed += " ";
}
}
return processed;
}
console.log(process(test));
var input = "i aM tHe kiNG";
capitalised = capitalize(input);
function capitalize(input)
{
var splited = input.split(" ");
//console.log(splited);
var output = Array();
for (i in splited)
{
//convert each letter into lower case
var temp = splited[i].toLowerCase();
//Convert the first char upper case and join with the rest letters of word.
temp = temp.charAt(0).toUpperCase() + temp.substring(1);
//store the word in the array
output.push(temp);
}
//join the words
return output.join(" ");
}
The output will be: I Am The King
I've been given the following exercise but can't seem to get it working.
//Remove duplicate characters in a
// given string keeping only the first occurrences.
// For example, if the input is ‘tree traversal’
// the output will be "tre avsl".
// ---------------------
var params = 'tree traversal word';
var removeDuplicates = function (string) {
return string;
};
// This function runs the application
// ---------------------
var run = function() {
// We execute the function returned here,
// passing params as arguments
return removeDuplicates;
};
What I've done -
var removeDuplicates = function (string) {
var word ='';
for(var i=0; i < string.length; i++){
if(string[i] == " "){
word += string[i] + " ";
}
else if(string.lastIndexOf(string[i]) == string.indexOf(string[i]))
{
word += string[i];
}
}
return word;
};
I'm not allowed to use replaceAll and when I create an inner for loop it doesn't work.
<script>
function removeDuplicates(string)
{
var result = [];
var i = null;
var length = string.length;
for (i = 0; i < length; i += 1)
{
var current = string.charAt(i);
if (result.indexOf(current) === -1)
{
result.push(current);
}
}
return result.join("");
}
function removeDuplicatesRegex(string)
{
return string.replace(/(.)(?=\1)/g, "");
}
var str = "tree traversal";
alert(removeDuplicates(str));
</script>
First of all, the run function should be returning removeDuplicates(params), right?
You're on the right lines, but need to think about this condition again:
else if(string.lastIndexOf(string[i]) == string.indexOf(string[i]))
With i = 0 and taking 'tree traversal word' as the example, lastIndexOf() is going to be returning 5 (the index of the 2nd 't'), whereas indexOf() will be returning 0.
Obviously this isn't what you want, because 't' hasn't yet been appended to word yet (but it is a repeated character, which is what your condition does actually test for).
Because you're gradually building up word, think about testing to see if the character string[i] exists in word already for each iteration of your for loop. If it doesn't, append it.
(maybe this will come in handy: http://www.w3schools.com/jsref/jsref_search.asp)
Good luck!
e.g. myfunc(from:c:\my\dir,to:c:\my\other\file.ext) ==> ..\other\file.ext .
new Uri() need not apply, unless there's a remedy for it returning URI format not Windows filename format. .LocalPath fails.
This should do what you want.
string firstDirectory = "c:\\my\\dir";
string secondDirectory = "c:\\my\\other\\file.ext";
var first = firstDirectory.Split('\\');
var second = secondDirectory.Split('\\');
var directoriesToGoBack = first.Except(second);
var directoriesToGoForward = second.Except(first);
StringBuilder directory = new StringBuilder();
bool initial = true;
foreach (string s in directoriesToGoBack)
{
if (initial)
{
initial = false;
} else
{
directory.Append('\\');
}
directory.Append("..");
}
foreach (string s in directoriesToGoForward)
{
directory.Append('\\');
directory.Append(s);
}
Console.WriteLine(directory.ToString());