I want To build a Program in which i want Multiple inputs in integers and Reverse it .. how Can I Do that in Dart?
I tried of strings But Don't Know About Integers
You can do something like this:
import 'dart:io';
void main() {
print('Input integers (q to stop):');
final integers = <int>[];
while (true) {
// Reads input from the user.
final input = stdin.readLineSync()!;
// Check to see if the user is done inputting numbers.
if (input == 'q') {
break;
}
// Try to convert the String to an int. If input isn't a
// valid integer, int.tryParse(input) == null.
final integer = int.tryParse(input);
if (integer != null) {
integers.add(integer);
}
}
print('Original order: $integers');
// Reversing a List in Dart is simple: just call integers.reverse
// to get an Iterable with the elements of integers in reversed order.
// Calling integers.reverse.toList() will convert the Iterable to a List
// so it's possible to print the entire list at once.
print('Reversed order: ${integers.reversed.toList()}');
}
Example:
Input integers (q to stop):
1
2
3
r
4
5
q
Original order: [1, 2, 3, 4, 5]
Reversed order: [5, 4, 3, 2, 1]
Related
import 'dart:io';
void main() {
int? n = int.parse(stdin.readLineSync()!);
print("value of n: $n and run time type: ${n.runtimeType}");
List<int> list1 = [];
for (int i = 0; i < n; i++) {
list1.insert(i, int.parse(stdin.readLineSync()!));
}
print("List 1: $list1");
}
This is my code.
If I take in put like that:
5
1
2
3
4
5
it gives output:
value of n: 5 and run time type: int
List 1: [1, 2, 3, 4, 5]
I want to take input like:
5
1 2 3 4 5
and want the same output. But I do not find any resources for that. Please help me.
You can split the string by using space as delimiter and then use map to parse each string into an int.
This way don't need to know number of elements beforehand but if it's necessary to get exactly n number of elements in list then you can use Iterable.take() method.
List<int> list1 = stdin
.readLineSync()
?.split(RegExp(r'\s+'))
.map((e) => int.parse(e))
.take(n)
.toList() ??
List<int>.empty();
Is there a method we use to reach the desired number in an array given in dart language.. I can do this for binary ones, but I can't do it for a code that finds the sum of 3 or more elements
For example
Input: candidates = [10,1,2,7,6,1,5], target = 8
Output:
[
[1,1,6],
[1,2,5],
[1,7],
[2,6]
]
this is the my code i have done until now
void main() {
var candidates = [10, 1, 2, 7, 6, 1, 5], target = 8;
var answer = [];
for (int i = 0; i < candidates.length; i++) {
for (int j = 0; j < candidates.length; j++) {
if (candidates[i] + candidates[j] == target && i != j && i < j) {
answer.add([candidates[i], candidates[j]]);
}
}
}
}
I am sure this can be done more efficient but since the solution is for some Leetcode assignment, I don't really want to spend too much time on optimizations.
I have tried added some comments in the code which explains my way of doing it:
void main() {
getSumLists([10, 1, 2, 7, 6, 1, 5], 8).forEach(print);
// [5, 1, 2]
// [1, 6, 1]
// [1, 7]
// [6, 2]
getSumLists([2, 5, 2, 1, 2], 5).forEach(print);
// [2, 1, 2]
// [5]
}
Iterable<List<int>> getSumLists(
List<int> candidates,
int target, {
List<int>? tempAnswer,
int sum = 0,
}) sync* {
// We cannot use default value in parameter since that makes list const
final tempAnswerNullChecked = tempAnswer ?? [];
if (sum == target) {
// We got a result we can return.
// OPTIMIZATION: If you know the returned list from each found result is not
// being used between found results, you can remove the `.toList()` part.
yield tempAnswerNullChecked.toList();
} else if (sum > target) {
// No need to search further in this branch since we are over the target
return;
}
// Make a copy so we don't destroy the input list but also so it works even
// if provided list as input is non-growing / non-modifiable
final newCandidates = candidates.toList();
while (newCandidates.isNotEmpty) {
// We take numbers from the end of the list since that is more efficient.
final number = newCandidates.removeLast();
// Recursive call where we return all results we are going to find given
// the new parameters
yield* getSumLists(
newCandidates,
target,
tempAnswer: tempAnswerNullChecked..add(number),
sum: sum + number,
);
// Instead of creating a new tempAnswerNullChecked, we just reuse it and
// make sure we remove any value we are temporary adding
tempAnswerNullChecked.removeLast();
// Ensure we don't get duplicate combinations. So if we have checked the
// number `1` we remove all `1` so we don't try the second `1`.
newCandidates.removeWhere((element) => element == number);
}
}
I am using fold on an array which hasn't been assign to a variable and want to check whether the element is the last value. With a conventional for loop I can do this:
List<int> ints = [1, 2, 3];
int sum = 0;
for (int num in ints]) {
if (num != ints.last) {
sum = sum + num;
}
}
print(sum);
Is it possible to do this with fold instead?
int foldSum = [1, 2, 3].fold(0, (int prev, element) => prev + element);
print(foldSum);
I can't find any way of check when fold is at the last value. Note: this is a simplified example of my problem and the reason the list isn't assigned to a variable (allowing me to use .last) is because it is the result of a call to .map().
For completeness, below is the actual code (which won't obviously won't be runnable in isolation but will help illustrate my problem) I am trying to convert to use .map and .fold:
String get fieldsToSqlInsert {
String val = "";
for (Column column in columns) {
if (data.containsKey(column.name)) {
val = '$val "${data[column.name]}"';
} else {
val = "$val NULL";
}
if (column != columns.last) {
val = "$val,";
}
}
return val;
}
But it doesn't work because I don't know how to check when fold is at the final element:
String get fieldsToSqlInsert => columns
.map((column) =>
data.containsKey(column.name) ? data[column.name] : "NULL")
.fold("", (val, column) => column != columns.last ? "$val," : val);
If you simply want to exclude the last element from further calculation, you can just use take to do so:
String get fieldsToSqlInsert => columns.take(columns.length - 1)...
I would like to get the second to last item in a List, similarly than with getter last.
I tried the following :
final list = [1, 2, 3, 4, 5];
final secondToLast = (list..removeLast()).last; // Mutates the List
However it mutates the List.
There is many options available (however you should make sure that list is not null and has at least 2 elements) :
final list = [1, 2, 3, 4, 5];
// Works only for Lists
final secondToLast = list[list.length - 2];
final secondToLast = list.reversed.elementAt(1);
final secondToLast = list.reversed.skip(1).first;
// Works for any Iterable
final secondToLast = list.elementAt(list.length - 2);
To get something similar to last, you can write an extension on Iterable :
extension CustomIterable<T> on Iterable<T> {
T? get secondToLast {
return this == null || length < 2 ? null : elementAt(length - 2);
}
}
I need to parse an array of 32 bit ints (little endian), from an array of u8s, however the next int only exists if the 31st bit of the current int is set. If the rest don't exist then the rest of the array should be set to zeroes. I'm not sure how to go about conditionally parsing the next element.
Lets say the field is 4 bytes long. Then the result of the parse_field function would be that the 4 bytes would be parsed with le_u32, and that would be the first element in the [u32; 8] array. If however, this field's 31st bit is set. Then there exists another 4 bytes that is also like this field and it goes in the next element in the array. If it is not set then the function must return, the array with the rest of the elements set to zero. And this continue for each existing field.
For example for the following input:
0x8000000a
0x8000000b
...
You would get [0x8000000a, 0x8000000b, 0, 0, 0, 0, 0, 0]
But if the input is
0x8000000a
0x8000000b
0x8000000c
0x8000000d
0x8000000e
....
Then you would get [0x8000000a, 0x8000000b, 0x8000000c, 0x8000000d, 0x8000000e, 0, 0, 0]
extern crate nom;
use nom::*;
#[derive(Clone, Copy, Debug)]
struct Derp {
field: [u32; 8]
}
named!(parse_field<[u32; 8]>,
// what do I do here
);
named!(parse_derp<Derp>,
do_parse!(
field: parse_field >>
(Derp {
field: field
})
)
);
fn main() {
let temp = [0x0a, 0x00, 0x00, 0x80, 0x0b, 0x00, 0x00, 0x80];
println!("{:?}", parse_derp(&temp));
}
Also is it possibly better to use a Vec here?
Here is a parser that matches the last u32 of your input:
named!(last_u32<u32>,
verify!(le_u32, |n:u32| (n & 0b1) != 0) // Matches iff the 31st bit is set
);
you can then use it like this:
named!(parse_field<Vec<u32>>,
map!(
many_till!(le_u32, last_u32),
|(mut v,n)| { v.push(n); v } // Add the last u32 to the vector
)
);