Sort numbers inside string - flutter

I have a string that consists of few numbers. First number is the number of the row, remaining are numbers in this row.(Array but string, kind of). The problem is that remaining numbers are unsorted, and I want to find the clearest way of sorting them without creating new List and sorting everything there.
String unsorted = '9, 12, 14, 11, 2, 10';
print(unsorted.sort()); // '9, 2, 10, 11, 12, 14'

You cant really avoid converting to a list of numbers if you want to sort it.
void main() {
print(sortNumString('9, 12, 14, 11, 2, 10')); // 2, 9, 10, 11, 12, 14
}
String sortNumString(String numString, [String separator = ', ']) =>
(numString.split(separator).map(int.parse).toList()..sort())
.join(separator);
The .. means to return the previous thing, the list, since sort returns void.

I'm not exactly experienced when it comes to dart programming language but this is what i came up with.
void main() {
var unsorted = "9, 12, 14, 11, 2, 10";
var nums_int = unsorted.split(", ").map(int.parse).toList();
nums_int.sort();
for (var n in nums_int) {
stdout.write(n.toString() + ", ");
}
}
That should give the expected output: "2, 9, 10, 11, 12, 14"
Hope this helps.

Related

Efficient way to get a subsequence with a precondition in Swift

I have an ordered sequence of numbers, let's say something like
0, 1, 2, 3, 5, 6, 11, 12, 15, 20
Given a number N, how could I get a sequence that starts from the last number that is smaller than N? For example, if N = 7, I'd like to get back
6, 11, 12, 15, 20
Please note that this sequence will get very big and new numbers will be appended.
drop(while:) seemed like a good candidate, but in the example above it would also drop 6 so I can't use it.
For huge sorted arrays the most efficient way is binary search. It cuts the array in half until the index was found.
extension RandomAccessCollection where Element : Comparable {
func lastIndex(before value: Element) -> Index {
var slice : SubSequence = self[...]
while !slice.isEmpty {
let middle = slice.index(slice.startIndex, offsetBy: slice.count / 2)
if value < slice[middle] {
slice = slice[..<middle]
} else {
slice = slice[index(after: middle)...]
}
}
return slice.startIndex == self.startIndex ? startIndex : index(before: slice.startIndex)
}
}
let array = [0, 1, 2, 3, 5, 6, 11, 12, 15, 20]
let index = array.lastIndex(before: 7)
print(array[index...])

Best way to find the largest amount of consecutive integers in a sorted array in swift, preferably not using a for loop

Given an array of integers for example let array = [1, 3, 4, 7, 8, 9, 12, 14, 15]
What is the best way of finding the largest amount of consecutive integers preferably without using a for-in loop. If we would pass this array into a function it would return 3 as '7, 8, 9' is the largest amount of consecutive integers.
let array = [1, 3, 4, 7, 8, 9, 12, 14, 15]
func getMaxConsecutives(from array: [Int]) -> Int {
var maxCount = 1
var tempMaxCount = 1
var currentNumber = array[0]
for number in array {
if currentNumber == number - 1 {
tempMaxCount += 1
maxCount = tempMaxCount > maxCount ? tempMaxCount : maxCount
currentNumber = number
} else {
tempMaxCount = 1
currentNumber = number
}
}
return maxCount
}
getMaxConsecutives(from: array)
This works as intended but I would like a more efficient solution something that is not O(n).
I appreciate any creative answers.
You can do it like this:
let array = [1, 3, 4, 7, 8, 9, 12, 14, 15]
if let maxCount = IndexSet(array).rangeView.max(by: {$0.count < $1.count})?.count {
print("The largest amount of consecutive integers: \(maxCount)")
//prints 3
}
I think I can write it more tightly (basically as a one-liner):
let array = [1, 3, 4, 7, 8, 9, 12, 14, 15]
let (_,_,result) = array.reduce((-1000,1,0)) {
$1 == $0.0+1 ? ($1,$0.1+1,max($0.2,$0.1+1)) : ($1,1,$0.2)
}
print(result) // 3
But we are still looping through the entire array — so that we are O(n) — and there is no way to avoid that. After all, think about what your eye does as it scans the array looking for the answer: it scans the whole array.
(One way to achieve some savings: You could short-circuit the loop when we are not in the middle of a run and the maximum run so far is longer than what remains of the array! But the gain might not be significant.)

Flutter Get closest timestamp to now from List

How to get the closest timestamp to now from List?
I got a List of timestamps and I want to determine the closest timestamp in the future to current timestamp.
How can I achieve that?
Something like this? I am not sure how you are representing your timestamps so I have made the example by using DateTime objects:
void main() {
final dateTimes = <DateTime>[
DateTime(2020, 8, 1),
DateTime(2020, 8, 5),
DateTime(2020, 7, 13),
DateTime(2020, 7, 18),
DateTime(2020, 8, 15),
DateTime(2020, 8, 20)
];
final now = DateTime(2020, 7, 14);
final closetsDateTimeToNow = dateTimes.reduce(
(a, b) => a.difference(now).abs() < b.difference(now).abs() ? a : b);
print(closetsDateTimeToNow); // 2020-07-13 00:00:00.000
}
Note, the solution finds the closets timestamp in the list and looks both in the past and future.

The ten's digit and unit's digit of numbers

I have this code
int[,] array = new int[,]{ {34, 21, 32, 41, 25},
{14 ,42, 43, 14, 31},
{54, 45, 52, 42, 23},
{33, 15, 51, 31, 35},
{21, 52, 33, 13, 23} };
for (int i = 0; i < array.GetLength(1); i++)
{
for (int j = 0; j < array.GetLength(0); j++)
{
Console.Write(array[i, j] + " ");
}
Console.WriteLine();
}
and i need to find a specific number ( the treasure ).
For each value the ten's digit represents the row number and the unit's digit represents the column number of the cell containing the next clue.
Starting in the upper left corner (at 1,1), i have to use the clues to guide me search of the array. (The first three clues are 11, 34, 42).
The treasure is a cell whose value is the same as its coordinates.
The program should output the cells it visits during its search.
I did the simply way:
Console.WriteLine("The next clue is: {0}", array[0, 0]);
Console.WriteLine("The next clue is: {0}", array[2, 3]);
Console.WriteLine("The next clue is: {0}", array[3, 2]);
Console.WriteLine("The next clue is: {0}", array[0, 4]);
and so on, but the problem is, that if I change the array to set another route the program will output the wrong way. So the solution needs to be dynamic and find the treasure regardless of the array content.
My problem is that i don't know how to do to find the ten's digit of the numbers and the unit's digit.
Can anyone please help me with this?
To illustrate my comment: code below and Fiddle
(I've added a HashSet<int> to track which cells have already been visited and avoid ending up with an infinite loop)
int[,] array = new int[,]
{
{34, 21, 32, 41, 25},
{14 ,42, 43, 14, 31},
{54, 45, 52, 42, 23},
{33, 15, 51, 31, 35},
{21, 52, 33, 13, 23}
};
int currentCoordinates = 11;
bool treasureFound = false;
var visitedCells = new HashSet<int>();
while (!treasureFound && !visitedCells.Contains(currentCoordinates))
{
int currentRowIndex = currentCoordinates / 10;
int currentColumnIndex = currentCoordinates % 10;
int nextCoordinates = array[currentRowIndex - 1, currentColumnIndex - 1];
if (nextCoordinates == currentCoordinates)
{
treasureFound = true;
}
else
{
visitedCells.Add(currentCoordinates);
currentCoordinates = nextCoordinates;
}
}
if (treasureFound)
{
Console.WriteLine($"Treasure found in cell {currentCoordinates}");
}
else
{
Console.WriteLine("No treasure");
}

how to use removeObjectsInArray in swift

I have two arrays
var availableIndex: Int[] = [0, 1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 12, 13, 14]
var answerIndex: Int[] = [1, 3, 10, 8]
I want to remove 1, 3, 10, 8 from availableIndex array. I've seen the documentation how to achieve that using removeObjectsInArray
availableIndex.removeObjectsInArray(answerIndex)
but I can't use that method, it gave me an error. I have no idea where's my fault. Sorry if my bad English
edit:
here is the error 'Int[]' does not have a member named 'removeObjectsInArray'
The proper Swifty way to do this is
availableIndex = availableIndex.filter { value in
!answerIndex.contains(value)
}
(will create a new filtered array only with values not contained in answerIndex)
Of course, a better solution would be to convert answerIndex into a Set.
removeObjectsInArray is defined only on Obj-C mutable arrays (NSMutableArray).
An Obj-C workaround is to define the array directly as NSMutableArray
var availableIndex: NSMutableArray = [0, 1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 12, 13, 14]
var answerIndex: Int[] = [1, 3, 10, 8]
availableIndex.removeObjectsInArray(answerIndex)
It's also possible to do it like that:
availableIndex.removeAll(where: { answerIndex.contains($0) })