I'm trying to convert strings to arrays then compare two arrays. If the same value needs to remove from both array. Then finally merge two arrays and find array length. Below is my code
String first_name = "siva";
String second_name = "lovee";
List<String> firstnameArray=new List();
List<String> secondnameArray=new List();
firstnameArray = first_name.split('');
secondnameArray = second_name.split('');
var totalcount=0;
for (int i = 0; i < first_name.length; i++) {
for (int j = 0; j < second_name.length; j++) {
if (firstnameArray[i] == secondnameArray[j]) {
print(firstnameArray[i] + "" + " == " + secondnameArray[j]);
firstnameArray.removeAt(i);
secondnameArray.removeAt(i);
break;
}
}
}
var finalList = new List.from(firstnameArray)..addAll(secondnameArray);
print(finalList);
print(finalList.length);
But always getting this error Unsupported operation: Cannot remove from a fixed-length list can you help me how to fix this issue. Thanks.
Seems like what you are trying to do is to find the length of unique characters in given two strings. Well, the Set type is perfect for this use-case. Here's an example of what you can do:
void main() {
String first = 'abigail';
String second = 'allie';
var unique = '$first$second'.split('').toSet();
print(unique);
}
This would give you an output of:
{a, b, i, g, l, e}
On which you may perform functions like .toList(), or .where() or .length.
You can ensure that firstnameArray, secondnameArray is not a fixed-length list by initializing it as below:
var firstnameArray = new List<String>.from(first_name.split(''));
var secondnameArray= new List<String>.from(second_name.split(''));
Thereby declaring firstnameArray, secondnameArray to be a mutable copy of input.
Related
I have a simple exercise in Coderbyte, it just want to have a function that's WordSplit(strArr) read the array of strings stored in strArr, For example I have two elements like ["hellocat", "apple,bat,cat,goodbye,hello,yellow,why"]
I just want to to determine if the first element in the input can be split into two words, where both words exist in the dictionary that is provided in the second input.
For example: the first element can be split into two words: hello and cat because both of those words are in the dictionary.
So the program should return the two words that exist in the dictionary separated by a comma, as this result hello,cat .
I've made a recursive solution below. It checks if the string to be split starts with any word in the dictionary. If it exists, the function is called again using a substring with that first word removed.
This function only works up to the first word that isn't in the dictionary since you did not specify the expected behavior when the inputted word is not made up of words in the dictionary. You could make it throw an exception perhaps, but please specify your expectation.
void main() {
print(wordSplit(["hellocat", "apple,bat,cat,goodbye,hello,yellow,why"]));
//hello,cat
}
String wordSplit(List<String> arg) {
String wordToSplit = arg[0];
String dict = arg[1];
List<String> parsedDict = arg[1].split(',');
for(String word in parsedDict) {
if(wordToSplit.startsWith(word)) {
//If the substring would be empty, don't do more recursion
if(word.length == wordToSplit.length) {
return word;
}
return word + ',' + wordSplit([wordToSplit.substring(word.length), dict]);
}
}
return wordToSplit;
}
#include <bits/stdc++.h>
using namespace std;
vector<string> converToWords(string dict) {
vector<string> res;
string s = "";
int n = dict.length();
for(int i=0; i<n; i++) {
if(dict[i] == ',') {
res.push_back(s);
s = "";
}
else s += dict[i];
}
res.push_back(s);
s = "";
return res;
}
string solve(string str[]) {
string result = "";
string word = str[0], dict = str[1];
int n = word.length();
vector<string> vs = converToWords(dict);
unordered_set<string> ust;
for(auto it: vs) ust.insert(it);
// for(auto i=ust.begin(); i!=ust.end(); i++){
// cout<<*i<<endl;
// }
string s = "";
for(int i=0; i<n; i++) {
s += word[i];
// cout<<s<<endl;
string temp = word.substr(i+1, n-(i+1));
// cout<<temp<<endl;
if(ust.find(s) != ust.end() && ust.find(temp) != ust.end()) {
cout<<s<<endl;
cout<<temp<<endl;
result += s+","+temp;
break;
}
temp = "";
}
return result;
}
int main() {
string arr[2];
cin>>arr[0]>>arr[1];
cout << solve(arr);
return 0;
}
I am actually working with maps in Dart and I couldn't figure out why the map variable in my example is behaving strangely or I am doing something wrong in my code.
Please can someone help me to debug the code, I have posted the code to reproduce the issue.
example.dart
void main() {
var data2 = {};
var data1 = {};
var floorDetails = new Map();
floorDetails.clear();
for (int i = 0; i < 2; i++) {
data2.clear();
data1.clear();
for (int j = 0; j < 2; j++) {
data1 = {
'flat${(i + 1) * 100 + (j + 1)}': {'flattype': "flat"},
};
data2.addAll(data1);
}
print('data2=$data2');
floorDetails['floor${(i+1)}'] = data2;
print('floorDetails = $floorDetails');
}
print(floorDetails.keys);
}
The output from the code is:
floorDetails = {
floor1: {
flat201: {flattype: flat},
flat202: {flattype: flat}
},
floor2: {
flat201: {flattype: flat},
flat202: {flattype: flat}
}
}
Actually I was expecting the output to be:
floorDetails = {
floor1: {
flat101: {flattype: flat},
flat102: {flattype: flat}
},
floor2: {
flat201: {flattype: flat},
flat202: {flattype: flat}
}
}
this is actually overwriting the values of all the keys inside the map floorDetails as per documentation for Map.addAll() method
void addAll(
Map<K, V> other
)
Adds all key-value pairs of other to this map.
If a key of other is already in this map, its value is overwritten.
The operation is equivalent to doing this[key] = value for each key and associated value in other. It iterates over other, which must therefore not change during the iteration.
although in the given example the keys are different but it is still overwriting the values.
Please, any help would be much appreciated.
Many Thanks,
Mahi
In the first iteration, here you assign data2
floorDetails['floor${(i+1)}'] = data2;
but the first line in the next iteration is
data2.clear();
which clears data2. This also clears the content of floorDetails['floor1']`, because it references the same map.
Either you create a new map, instead of clearing it by changing
data2.clear();
data1.clear();
to
data2 = {}; // or new Map()
data1 = {};
or create a copy of the map before assigning it
floorDetails['floor${(i+1)}'] = new Map.from(data2);
Map is an object and copied by reference. Only primitive types like bool, double, int, and String are copied by value.
how to return an array of unowned strings that all point to the same location in memory?
example:
init
var str = "ABC"
var unowned_string_array = repeat (str, 5)
def repeat (s: string, n: int): array of string
// code
and this array will contains 5 elements(same string "ABC"), all point to same location
The closest Vala code I could get is:
int main() {
var str = "ABC";
var unowned_string_array = repeat (str, 5);
return 0;
}
public (unowned string)[] repeat (string s, int n) {
var a = new (unowned string)[n];
for (var i = 0; i < n; i++)
// This sadly still duplicates the string,
// even though a should be an array of unowned strings
a[i] = s;
return a;
}
I'm not sure if the compiler understands the parenthesis here, it may think that I want to declare an unowned array of owned strings here ...
Update: It turns out the problem is that type inference will always create an owned variable (see nemequs comment).
There is even a bug report for this.
So this works just fine (no string duplication in the repeat function):
int main() {
var str = "ABC";
(unowned string)[] unowned_string_array = repeat (str, 5);
return 0;
}
public (unowned string)[] repeat (string s, int n) {
(unowned string)[] a = new (unowned string)[n];
for (var i = 0; i < n; i++)
// This sadly still duplicates the string,
// even though a should be an array of unowned strings
a[i] = s;
return a;
}
Which would be something like this in Genie:
[indent=4]
init
var str = "ABC"
unowned_string_array: array of (unowned string) = repeat (str, 5)
def repeat (s: string, n: int): array of (unowned string)
a: array of (unowned string) = new array of (unowned string)[n]
for var i = 1 to n
a[i] = s
return a
The Genie code has the additional problem of not compiling, due to the parser not being able to deduce what comes after the array of.
This seems to be a similar problem to what I already had with nested generic types.
I have reported this a Genie bug.
An array of Image Url path:
["http://cdncms.fonts.net/hero-images/FEX_Hero_Thumb.png ","http://cdncms.fonts.net/hero-images/Wilma_Hero_Thumb.png "]
asp.net mvc Controller :
public ActionResult Extract(string[] name)
{
//List<string> myList = name.ToList<string>();
for(int x = 0; x < name.Length; x++)
{
//string something = name[x];
var item = name[x];
Session["values"] = item;
}
char[] delimiter1 = new char[] { ',' }; // <-- Split on these
string[] array1 = Session["values"].ToString().Split(delimiter1, StringSplitOptions.RemoveEmptyEntries);
foreach (var item in array1)
{
string exts = Path.GetExtension(item); //illegal character
string strRealname = Path.GetFileName(item); illegal character
}
I know this problem due to the presence of [ character at the beginning and last .I have tried but not succeeded .Any idea how to remove this using split function in C#
Assuming that you have correctly identified the problem, you could do this before making it an array:
var values = Session["values"].ToString();
if(values.StartsWith("[")) values = values.Substring(1);
if(values.EndsWith("]")) values = values.Substring(0, values.Length - 1);
I'd like to know if there's any Dart function like PHP's strrev(). If not, could you please show my any source code how to make it on my own?
Thank you.
Lists can be reversed, so you can use this to reverse a String as well:
new String.fromCharCodes("input".charCodes.reversed.toList());
I haven't found one in the API, as a brand new Dart user (as of this afternoon). However, reversing a string is pretty easy to do in any language. Here's the typical O(n) solution in Dart form:
String reverse(String s) {
var chars = s.splitChars();
var len = s.length - 1;
var i = 0;
while (i < len) {
var tmp = chars[i];
chars[i] = chars[len];
chars[len] = tmp;
i++;
len--;
}
return Strings.concatAll(chars);
}
void main() {
var s = "dog";
print(s);
print(reverse(s));
}
May be a standardized reverse() method will be implemented in future in List (dart issue 2804), the following is about 8 to 10 times faster than the previous typical solution:
String reverse(String s) {
// null or empty
if (s == null|| s.length == 0)
return s;
List<int> charCodes = new List<int>();
for (int i = s.length-1; i>= 0; i-- )
charCodes.addLast(s.charCodeAt(i)) ;
return new String.fromCharCodes(charCodes);
}
try this instead of others.
String try(str) {
return str.split('').reversed.join('');
}
String theString = "reverse the string";
List<String> reslt = theString.split("");
List<String> reversedString = List.from(reslt.reversed);
String joinString = reversedString.join("");
print(joinString);
Ouput: gnirts eht esrever