I'm new to Dart. I was trying to convert integer to roman. But It returns nothing. Can you guys help me? here is my code sample.
this code is from the Leetcode problem section.
class Solution {
String intToRoman(int num) {
List<int> numbers = [1,4,5,9,10,40,50,90,100,400,500,900,1000];
List<String> romans = ["I","IV","V","IX","X","XL","L","XC","C","CD","D","CM", "M"];
int index = romans.length - 1;
String roman = '';
for(num >0;numbers[index]<=num;){
roman += romans[index];
num -= numbers[index];
index -= 1;
}
return roman;
}
}
just change a little bit on the logic
.try on dartpad: https://dartpad.dev/?id
void main() {
print (intToRoman(30)); // result: XXX
}
String intToRoman(int num) {
List<int> numbers = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1];
List<String> romans = ["M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"];
String roman = '';
for (int i = 0; i < numbers.length; i++) {
while (num >= numbers[i]) {
roman += romans[i];
num -= numbers[i];
}
}
return roman;
}
This solution is based on Wiki:
class Solution {
/// digit: 3=Thousands(10³), 2=Hundreds(10²), 1=Tens(10), 0=Units(1)
/// Range for roman numerals: 1...3999
static final romanNumerals = <int,Map<int,String>>{
1 : {3:'M', 2:'C', 1:'X', 0:'I'},
2 : {3:'MM', 2:'CC', 1:'XX', 0:'II'},
3 : {3:'MMM', 2:'CCC', 1:'XXX', 0:'III'},
4 : {2:'CD', 1:'XL', 0:'IV'},
5 : {2:'D', 1:'L', 0:'V'},
6 : {2:'DC', 1:'LX', 0:'VI'},
7 : {2:'DCC', 1:'LXX', 0:'VII'},
8 : {2:'DCCC', 1:'LXXX', 0:'VIII'},
9 : {2:'CM', 1:'XC', 0:'IX'},
};
/* ---------------------------------------------------------------------------- */
Solution();
/* ---------------------------------------------------------------------------- */
String intToRoman(int number) {
if (number < 1 || number >= 4000) return '';
var list = number.toString().split('').map(int.parse).toList();
var buffer = StringBuffer();
final len = list.length;
for (var i = 0; i < len; i++) {
var digit = list[i];
if (digit == 0) continue;
buffer.write(romanNumerals[digit]![len - 1 - i]);
}
return buffer.toString();
}
/* ---------------------------------------------------------------------------- */
void intToRoman2(int number) {
print(intToRoman(number));
}
}
void main(List<String> args) {
Solution()
..intToRoman2(3)
..intToRoman2(58)
..intToRoman2(1994)
;
}
Output:
III
LVIII
MCMXCIV
This code was already sent to LeetCode with the following results:
Runtime: 1130 ms, faster than 27.96% of Dart online submissions for Integer to Roman.
Memory Usage: 150.5 MB, less than 44.09% of Dart online submissions for Integer to Roman.
why not use the simple way?
I use this extension to convert english numbers to persian numbers
extension StringExtensions on String {
String persianNumber() {
String number = this;
number = number.replaceAll("1", "۱");
number = number.replaceAll("2", "۲");
number = number.replaceAll("3", "۳");
number = number.replaceAll("4", "۴");
number = number.replaceAll("5", "۵");
number = number.replaceAll("6", "۶");
number = number.replaceAll("7", "۷");
number = number.replaceAll("8", "۸");
number = number.replaceAll("9", "۹");
number = number.replaceAll("0", "۰");
return number;
}
}
extension IntExtensions on int {
String persianNumber() {
String number = this.toString();
number = number.replaceAll("1", "۱");
number = number.replaceAll("2", "۲");
number = number.replaceAll("3", "۳");
number = number.replaceAll("4", "۴");
number = number.replaceAll("5", "۵");
number = number.replaceAll("6", "۶");
number = number.replaceAll("7", "۷");
number = number.replaceAll("8", "۸");
number = number.replaceAll("9", "۹");
number = number.replaceAll("0", "۰");
return number;
}
}
I have a String 'baseball' and I want to loop on this string and print the output like this:
'b',
'ba',
'bas',
'base',
'baseb',
'baseba',
'basebal',
'baseball'
Just loop through the string and concat the letters and print the result.
String str = "baseball";
String output = "";
for (var i = 0; i < str.length; i++) {
output += str[i];
print(output);
}
I'd create the incremental substrings. If you want to reuse the functionality, perhaps make it a synchronous generator:
Iterable<String> prefixes(String string, {int minLength = 1}) sync* {
for (var i = minLength; i <= string.length; i++) {
yield string.substring(0, i);
}
}
Then you can print them as you want:
for (var prefix in prefixes("baseball")) {
print(prefix);
}
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'm stuck on this common interview question using Dart. I need to return the most common character in a given string. I'm trying to create a map with a count for each character as the first step.
This is my progress so far:
main(List<String> arguments) {
maxChar('hello');
}
void maxChar(String word) {
Map<String, int> charMap = {};
int max = 0;
String maxChar = '';
word.split('').forEach((char) {
if(charMap.containsValue(char)) {
charMap[char]+1;
return;
} else {
charMap[char] = 1;
}
});
print(charMap);
}
Right now its not even counting the correct amount of the letter 'l'. It's outputting:
{h: 1, e: 1, l: 1, o: 1}
What am I doing wrong? Is there an easier way to return the most common character in a String in Dart?
Thanks!
EDIT:
Ok, I've solved it, but surely there is a more concise way of solving this problem. See my solution below:
main(List<String> arguments) {
print(max_char.maxChar('hello'));
}
String maxChar(String word) {
Map<String, int> charMap = {};
int max = -1;
String maxChar = '';
word.split('').forEach((char) {
if(charMap.containsKey(char)) {
charMap[char]++;
return;
} else {
charMap[char] = 1;
}
});
charMap.forEach((k,v) {
if(v > max) {
max = v;
maxChar = k;
}
});
return maxChar;
}
A shorter approach to counting the characters is definitely possible:
String charCount(String chars) {
int maxChar = -1;
int maxCount = 0;
var counts = <int, int>{};
for (var char in chars.runes) {
int count = counts.update(char, (n) => n + 1, ifAbsent: () => 1);
if (count > maxCount) {
maxCount = count;
maxChar = char;
}
}
return String.fromCharCode(maxChar);
}
If you just want to count the characters, you can remove all the lines mentioning maxCount and maxChar.
I use integers to represent the characters instead of strings. That's cheaper and just as precise, and it allows you to recognize and combine Unicode UTF-16 surrogates.
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