generalizing a recurrence - recurrence

I'm not sure how could I write code for the following recurrence:
[a, b] --> [a, a*2/3, a*1/3+b*2/3, b];
[a, b, c] --> [a, a*2/3, a*1/3+b*2/3, b, b*2/3+ c/3, b/3+c*2/3, c]
that's it, takes a list, and expands that as in the example. I'm not sure how can I write code for that. Could someone please help me with that?

Pretty easy: takes a list as input, and produces a list as output.
public static <T extends Number> List<Double> expandThirds(List<T> input) {
List<Double> output = new ArrayList<Double>();
if(input.size() == 0)
return output;
output.add(input.get(0).doubleValue());
for(int i=0; i<input.size()-1; i++) {
double a = input.get(i).doubleValue();
double b = input.get(i+1).doubleValue();
output.add(a*2/3 + b/3);
output.add(a*3 + b*2/3);
output.add(b);
}
return output;
}

I think you can write like this:
double[] inputArray = new double[]{0.56,2.4,3.6};//pass you input array of size>1
List<Double> outList = new ArrayList<Double>();
//assuming minimum length of array = 2
for (int i=0; i<inputArray.length-1;i++){
permute(inputArray[i], inputArray[i+1], outList);
}
System.out.println(outList);
where generateRecurrance is private custom method as below:
private void generateRecurrance(double a, double b, List<Double> outList) {
outList.add(a);
outList.add(a*1/3+b*2/3);
outList.add(a*2/3+b*1/3);
outList.add(b);
}

Write a function to handle the first case, and call it mySequenceHelper. I won't write it here, but it should handle this case:
[a, b] --> [a*2/3+b/3, a*1/3+b*2/3, b];
Now write a function called mySequence, and have it pass each pair of numbers to mySequenceHelper, appending each set of results to a master list. Here is a simple one in java:
public List<Float> mySequence(List<Float> inputs) {
List<Float> toReturn = new LinkedList<Float>();
// Add the first term manually:
toReturn.add(inputs.get(0));
// For each pair of values in inputs, add the appropriate 3 terms
for (int i = 0; i < inputs.size() - 1; i++) {
toReturn.addAll(mySequenceHelper(inputs.get(i), inputs.get(i+1)));
}
return toReturn;
}

Related

find the index of item even there is duplication in Dart

I'm really confused on how I'm gonna find the index of item in array where there's a lot of duplicated words.
List<String> _words = "the quick brown fox jumps over the lazy dog".split(" ");
now I want to get the all the index in word "the" programmatically.
I expect a result of
List indexOfWords = _words.indexOfAll("the");
print(indexOfWords);
// [0, 6]
You can define indexOfAll as an extension method. I would implement it like this:
extension ListExtension<T> on List<T> {
List<int> indexOfAll(T item) => [
for (int i = 0; i < length; i++)
if (this[i] == item) i,
];
}
You can create an extension method. like this:
extension Occurrences on List {
List<int> indexOfAll(String pattern) {
List<int> indexes = [];
for (int i = 0; i < this.length; i++) {
if (this[i] == pattern) {
indexes.add(i);
}
}
return indexes;
}
}
then you can use it as function on your list
print(_words.indexOfAll("the")); // [0, 6]
I don't know if there is a direct solution for this job. To solve this problem I developed a function called GetIndexes() and it works successfully.
This example prints the following output to the console:
[the, quick, brown, fox, jumps, over, the, lazy, dog]
[3, 9, 15, 19, 25, 30, 34, 39]
The solution I developed is available below:
void main()
{
String text = "the quick brown fox jumps over the lazy dog";
var split = ' ';
List<int> indexes = [];
List<String> words;
words = text.split(split);
GetIndexes(text, split, indexes);
print(words);
print(indexes);
}
void GetIndexes(String text, var split, List<int> indexes)
{
int index = 0;
for(int i=0 ; i<text.length; ++i)
{
if(text[i] == split)
{
indexes.insert(index, i);
++index;
}
}
}

Check if element is the last value in fold function

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)...

Move elements in a List?

Consider: ['A', 'B', 'C']
I'd like to do
list.move("B", -1);
list.move("A", 1);
resulting in ["B", "C", "A"].
Is there some sort of one liner to move items in a listin Dart? Obviously could do this manually in a few lines just curious if there is some easier way.
There is indeed no built-in way to do this.
Since the list keeps the same length, the most efficient approach would move the elements in-place rather than remove an element and then insert it again. The latter requires moving all later elements as well, where doing it in-place only requires moving the elements between from and to.
Example:
extension MoveElement<T> on List<T> {
void move(T element, int offset) {
var from = indexOf(element);
if (from < 0) return; // Or throw, whatever you want.
var to = from + offset;
// Check to position is valid. Or cap it at 0/length - 1.
RangeError.checkValidIndex(to, this, "target position", length);
element = this[from];
if (from < to) {
this.setRange(from, to, this, from + 1);
} else {
this.setRange(to + 1, from + 1, this, to);
}
this[to] = element;
}
}
I would probably prefer a more general "move" function like:
extension MoveElement<T> on List<T> {
void move(int from, int to) {
RangeError.checkValidIndex(from, this, "from", length);
RangeError.checkValidIndex(to, this, "to", length);
var element = this[from];
if (from < to) {
this.setRange(from, to, this, from + 1);
} else {
this.setRange(to + 1, from + 1, this, to);
}
this[to] = element;
}
}
and then build the "find element, then move it relative to where it was" on top of that.
linear? I don't think there is any. In any case, a sample code here:
extension on List<String> {
void move(String element, int shift) {
if (contains(element)) {
final curPos = indexOf(element);
final newPos = curPos + shift;
if (newPos >= 0 && newPos < length) {
removeAt(curPos);
insert(newPos, element);
}
}
}
}
void main(List<String> args) {
var list = ['A', 'B', 'C', 'D', 'E', 'F'];
print(list);
list.move('B', 2);
print(list);
list.move('B', -3);
print(list);
}
Result:
[A, B, C, D, E, F]
[A, C, D, B, E, F]
[B, A, C, D, E, F]

flutter how to generate random numbers without duplication

Is there any way to generate random numbers without duplication?
For instance I want to generate 50 random numbers from 1 to 100 no duplication, any way to do this or do I have to check every time incoming number is already created or not?
you can use shuffle as following code.
import 'dart:math';
var list = new List<int>.generate(10, (int index) => index); // [0, 1, 4]
list.shuffle();
print(list);
You can use Set. Each object can occur only once when using it. Just try this:
Set<int> setOfInts = Set();
while (setOfInts.length < 50) {
setOfInts.add(Random().nextInt(range) + 1);
}
You can read the documentation here: Set Doc
Here is an alternative that avoids creating an array of all the possible values, and avoids repeatedly looping until no collision occurs. It may be useful when there is a large range to select from.
import 'dart:math';
class RandomList {
static final _random = new Random();
static List<int> uniqueSample({int limit, int n}) {
final List<int> sortedResult = [];
final List<int> result = [];
for (int i = 0; i < n; i++) {
int rn = _random.nextInt(limit - i); // We select from a smaller list of available numbers each time
// Increment the number so that it picks from the remaining list of available numbers
int j = 0;
for (; j < sortedResult.length && sortedResult[j] <= rn; j++) rn++;
sortedResult.insert(j, rn);
result.add(rn);
}
return result;
}
}
I haven't tested it exhaustively but it seems to work.

Rotate/Shift a list in Dartlang?

Is there a better/faster way in Dart to rotate a list?
List<Object> rotate(List<Object> l, int i) {
i = i % l.length;
List<Object> x = l.sublist(i);
x.addAll(l.sublist(0, i));
return x;
}
Could be simplified a bit
List<Object> rotate(List<Object> list, int v) {
if(list == null || list.isEmpty) return list;
var i = v % list.length;
return list.sublist(i)..addAll(list.sublist(0, i));
}
If you want to shift instead of rotate you can simply use the removeAt function:
List<int> list = [ 1, 2, 3 ];
int firstElement = list.removeAt(0);
print(list); // [ 2, 3 ]
print(firstElement); // 1
From the docs:
Removes the object at position [index] from this list.
This method reduces the length of this by one and moves all later objects down by one position.
Returns the removed value.
The [index] must be in the range 0 ≤ index < length. The list must be growable.
Here are some more useful JS shims.

Resources