How to output the contents of a DList as an array to the console? - d

I'm just started to learn Dlang.
Need to output DList!int as an array - [1, 2, 3].
import std.stdio : writeln;
import std.container.dlist : DList;
void main()
{
DList!int list;
list.insertFront(1);
list.insertBack([2, 3]);
writeln(list); // prints DList!int(7F50A689A000)
}

You were very close. You just needed the [] to make a Range out of it, and then the writeln() line would work as you expected:
writeln(list[]); // prints [1, 2, 3]

Related

Generate a random list based on limited items with spock-genesis

I use spock-genesis and would like to have an infinite lists generator parametrized with a list of values. A generated item should be a list that contains at most the list of parametrized values in random order.
Some invariants are:
def 'list generator'() {
expect:
xs.size() <= 3
xs.findAll({x -> x == 1}).size() <= 1
xs.findAll({x -> x == 2}).size() <= 1
xs.findAll({x -> x == 3}).size() <= 1
where:
xs << listGen([1, 2, 3])
}
I'm about to write own Generator implementation but there is chance I overthink something and it's possible to compose such generator with already existing spock-genesis units.
Try this
List listGen(List list) {
list.subsequences()
.collect { it.permutations() }
.inject([[]]) { result, subseq -> result + subseq }
}
The result of listGen([1, 2, 3]) will be:
[[], [1], [1, 2, 3], [3, 2, 1], [2, 1, 3], [3, 1, 2], [1, 3, 2], [2, 3, 1], [2], [3, 2], [2, 3], [2, 1], [1, 2], [3], [1, 3], [3, 1]]
Your test passes with this implementation.
UPD:
As per the OP clarifications below in the comments, they expect the permutations to be random, so here is the line of code that will do that using spock-genesis any:
where:
xs << Gen.any(listGen([1, 2, 3])).take(42).collect() // I assume 42 here should be random as well then
I'm not quite sure what you want, is just a list of every possible permutation of the list [1,2,3]? If so then this should be enough.
[1, 2, 3].permutations()
With #Dmitry Khamitov help I've come up with spock-genesis generator
package spock.genesis.generators.composites
import groovy.transform.CompileStatic
import spock.genesis.generators.Generator
import spock.genesis.generators.UnmodifiableIterator
import spock.genesis.generators.values.RandomElementGenerator
/** A lazy infinite {#code Generator} that returns a random subset of elements from a source Collection
* #warning O(n!) time complexity. Starts being too expensive with lists 10+ elements
* #param < E > the generated type
*/
#CompileStatic
class ListSubsetGenerator<E> extends Generator<List<E>> {
final RandomElementGenerator<List<E>> valueSource
ListSubsetGenerator(Collection<E> source) {
this.valueSource = new RandomElementGenerator<>(getListsSource(source))
}
private List<List<E>> getListsSource(Collection<E> source) {
source.toList().subsequences()
.collect { it.permutations() }
.inject([[]]) { result, subseq ->
result.addAll(subseq)
result
} as List<List<E>>
}
#Override
UnmodifiableIterator<List<E>> iterator() {
new UnmodifiableIterator<List<E>>() {
private final Iterator<List<E>> source = valueSource.iterator()
#Override
boolean hasNext() {
source.hasNext()
}
#Override
List<E> next() {
source.next()
}
}
}
#Override
Generator<List<E>> seed(Long seed) {
super.seed(seed)
valueSource.seed(seed)
this
}
}
Here are some tests:
class ListSubsetGeneratorTest extends Specification {
#Iterations(100)
def 'test invariants'() {
expect:
xs.size() <= 3
xs.findAll({x -> x == 1}).size() <= 1
xs.findAll({x -> x == 2}).size() <= 1
xs.findAll({x -> x == 3}).size() <= 1
xs.every { [1, 2, 3].contains(it) }
where:
xs << new ListSubsetGenerator([1, 2, 3])
}
def 'setting seed produces the same sequences for different generators'() {
given:
def elements = ['a', 'b', 'c', 'd']
def xs = new ListSubsetGenerator(elements).seed(seed).take(100).realized
def ys = new ListSubsetGenerator(elements).seed(seed).take(100).realized
expect:
xs == ys
where:
seed << [Long.MIN_VALUE, 100, Long.MAX_VALUE]
}
}

What is the use of returning [...list] in Dart?

In Dart programming language, sometimes I see functions returning a list in pair of brackets with triple dots [...list]. For example:
class IntList {
List<int> _integerList = [1, 2, 3, 4, 5];
List<int> get integerList {
return [..._integerList];
}
}
So what is the difference between return integerList; and the above return statement?
Any help is really appreciated. Thank you.
For this particular case there is no difference. ... is the spread operator. This allows you to insert multiple elements into a collection.
For example:
var list = [1, 2, 3];
var list2 = [0, ...list];
print(list2)
Output:
[0, 1, 2, 3]
So doing return [..._integerList]; is the exact same as return integerList;, other than that it creates a new list.
var list = [1, 2, 3];
print(list.hashCode);
print([...list].hashCode);
This code shows that they are different List objects when the spread operator is used because of the output of different hash codes.

Is there a Dart utility for converting a flat list into a nested one?

It's a common problem here, but I couldn't find any simplified methods for Dart in particular - how can I convert a list like this
[1, 2, 3, 4, 5, 6]
into a list like this
[[1, 2], [3,4], [5,6]]
assuming there are no extra elements after this?
Dart Quiver package is a set of utility libraries for Dart that makes using many Dart libraries easier and more convenient or adds additional functionality (https://github.com/google/quiver-dart).
You can use the partition function from quiver iterables library as follows.
import 'package:quiver/iterables.dart';
main() {
var list = [1, 2, 3, 4, 5, 6];
# Use partition function to segment lists into chunks of size 2
var newList = partition<int>(list, 2);
print (newList);
}
Result [[1, 2], [3,4], [5,6]]
var list = [1, 2, 3, 4];
List<int> temp = [];
List<List<int>> newList = list.fold<List<List<int>>>([], (newList, i) {
if (temp.length < 2) {
temp.add(i);
}
if (temp.length >= 2) {
List<int> newValue = new List<int>.from(temp);
newList.add(newValue);
temp.clear();
}
return newList;
});
print(newList);

Printing part of list starting from end and "loop" back to beginning not working

>>> mylist = [ 1, 2, 3 , 5, 'd']
>>> print 'mylist[-1:2] = ',mylist[-1:2]
output is an empty list: []
I am testing around with lists and from what I have so far understood from tutorials made me think the output would be [d, 1, 2]
Can anyone please help me out why isn't that the output?
To understand why your code returns an empty list, it is important to note how accessing list elements in python works. Indexing with : on a python list (or slicing) works like this:
a_list[start:stop:step]
stop must always be greater than start for the list indexing/slicing to work.
When you access an element in the list by using a negative number as the index, say a_list[-1], python adds the length of the list to it and gives you what you want. For ex:
a_list = [1, 2, 3, 4, 5]
a_list[-1] == a[5 - 1]
So when you do mylist[-1:2] it actually means mylist[4:2]. This violates start < stop condition. And hence returns an empty list.
This is what you are looking for:
[mylist[-1]] + mylist[:2]
Slicing with negative numbers (see string slicing) does not make the list a ringbuffer. It's just another way of pointing to an element in the list. So, what you ask for is really: The list beginning at index 4 and ending at index 2. Doesn't make sense, hence you get nothing.
Slicing does not work that way in python. Instead, I suggest creating your own defined function, like below:
>>> def loop(list, start, end):
... array = []
... for k in range(start, end+1):
... array.append(list[k])
... return array
...
>>> x = [1, 2, 3, 4, 5]
>>> desired_output = [5, 1, 2, 3]
>>> loop(x, -1, 2)
[5, 1, 2, 3]
>>> loop(x, -1, 2) == desired_output
True
>>>
This loops over the list, and adds each value of the list to another array, which it then returns.
Or, you can add them together using the following code:
[x[-1]] + x[:2]

Index of item in a list of a list in python

I got the following problem:
I'm writing a script for Ensight (a program for visualizing CFD computations) in python.
The program Ensight gives me a list for the time values like:
print ensight.query(ensight.TIMEVALS)['timevalues']
[[0, 0.0], [1, 9.99e-07], [2, 1.99e-06], [3, 0.0003],etc.]
Where the first value in every list is the timestep and the second value the actual time at this timestep. Now I want to ask somehow for timestep '2' and want to know the corresponding second value of the list. Therefore if I could just find the index of the timestep I could easily have the corresponding time value.
EDIT\\
It solved it now like this:
time_values = ensight.query(ensight.TIMEVALS)['timevalues']
for start,sublist in enumerate(time_values):
if step_start in sublist:
index_begin = start
for end,sublist in enumerate(time_values):
if step_stop in sublist:
index_end = end
Maybe this is what you want?
print ensight.query(ensight.TIMEVALS)['timevalues'][1][1]
That should print the 9.99e-07 as it is the second value in the second list included in your main list.
I'm just wondering why you have 3 opening and just 2 closing brackets. Is this a typo?
[[ [..].. ]
If you have a list like myList = [[0, 0.0], [1, 9.99e-07], [2, 1.99e-06], [3, 0.0003],etc.]
you can access the first nested list with myList[0] resulting in [0, 0.0]
To access the second value in that list you can use myList[0][1]
Set n to the required timestep value
>>> n=2
>>> print [list[1] for list in ensight.query(ensight.TIMEVALS)['timevalues'] if list[0]=n ]
this can also be extended in your case
>>> from=2
>>> to=100
>>> print [list[1] for list in ensight.query(ensight.TIMEVALS)['timevalues'] if (list[0]>from && list[0]<to) ]
>>> l = ensight.query(ensight.TIMEVALS)['timevalues']
>>> print l
[[0, 0.0], [1, 9.99e-07], [2, 1.99e-06], [3, 0.0003]]
>>> _d = {int(ele[0]): ele[1] for ele in l}
>>> print _d[2]
1.99e-o6