this is the pyramid problem which is :
Write a function that when given a number >= 0, returns an Array of ascending length subarrays.
pyramid(0) => [ ]
pyramid(1) => [ [1] ]
pyramid(2) => [ [1], [1, 1] ]
pyramid(3) => [ [1], [1, 1], [1, 1, 1] ]
the solution i wrote is :
List<List<int>> pyramid(int n) {
List<List<int>> bigList = [];
List<int> smallList = [];
for (int i = 0; i < n; i++) {
//1: i==1, i==2
smallList.add(1);
// bigList.add([smallList]); won't work because it takes only integers in parameters
List<List<int>> fixedList = [smallList];
print(fixedList);
bigList.addAll([smallList]);
print(bigList); // bigList,[[1]]
}
print(bigList);
return bigList;
}
void main() {
pyramid(3);
}
the output I get is not the one wanted, here is the output with the prints to know what happens in each iteration:
[[1]]
[[1]]
[[1, 1]]
[[1, 1], [1, 1]]
[[1, 1, 1]]
[[1, 1, 1], [1, 1, 1], [1, 1, 1]]
[[1, 1, 1], [1, 1, 1], [1, 1, 1]]
My question is: (and I am looking to find my mistake not the right answer)I dont understand why at the end of first iteration i=0, bigList has [1] as a first element. but has [1,1] as a first element in the end of the second iteration. why did the first element of bigList change. all I am doing is appending to the list. right?
List<List<Object>> makePyramid(int n) {
if (n < 1) return [];
var result = List.generate(n, (i) => List.filled(i+1, 1));
return result;
}
void main(List<String> args) {
List.generate(4, (i) => i).forEach((e) => print(makePyramid(e)));
}
Output:
[]
[[1]]
[[1], [1, 1]]
[[1], [1, 1], [1, 1, 1]]
Related
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]
}
}
Okay. I write an algorithm for show me all the permutations of a list of integers. But during the algorithm I got a problem to append a permuted list to my result list.
The code is the heap's algorithm. I got my finished permutation when size == 1. So a can append the permutated list V to my final list res. Here's the code:
The function for permutate the list
def permutations(V, size):
global res
if size == 1:
print(V)
res.append(V)
for i in range(0, size):
permutations(V, size-1)
if size % 2 == 1:
V[size-1], V[0] = V[0], V[size-1]
else:
V[i], V[size-1] = V[size-1], V[i]
A = [1,2,3]
res = []
permutation(A, len(A))
print(res)
And this is the output:
[1, 2, 3]
[2, 1, 3]
[3, 1, 2]
[1, 3, 2]
[2, 3, 1]
[3, 2, 1]
res: [[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]]
The printed permutations of V are all correct. But the list V append to my global res are not change. They are being append right after the print and the list append is different.
If you change the lines like this:
res.append(V)
|
|
v
D = [V[i] for i in range(len(V))]
res.append(D)
The results is correct on the final. Anyone can explain how can a printed list can be different from a appended list using the same variable.
Replace res.append(V) with res.append(list(V)) simply fixes your issue.
All V you appended to the res are references to the same object. This can be observed by printing the id of each element in the list:
for i in res:
print(id(i))
Hi i want to classify indexes of same rows in 2D numpy array. Is there any function to do it ?
Something like this :
a= [[1,2,3] , [2,3,4] , [5,6,7] ,[1,2,3] ,[1,2,3] , [2,3,4]]
then f(a) returns same row indexes [[0,3,4],[1,5],[2]]
I would appreciate for your solutions
Here's one to output list of arrays of row indices -
def classify_rows(a):
sidx = np.lexsort(a.T)
b = a[sidx]
m = ~(b[1:] == b[:-1]).all(1)
return np.split(sidx, np.flatnonzero(m)+1)
If you need a list of lists as output -
def classify_rows_list(a):
sidx = np.lexsort(a.T)
b = a[sidx]
m = np.concatenate(( [True], ~(b[1:] == b[:-1]).all(1), [True]))
l = sidx.tolist()
idx = np.flatnonzero(m)
return [l[i:j] for i,j in zip(idx[:-1],idx[1:])]
Sample run -
In [78]: a
Out[78]:
array([[1, 2, 3],
[2, 3, 4],
[5, 6, 7],
[1, 2, 3],
[1, 2, 3],
[2, 3, 4]])
In [79]: classify_rows(a)
Out[79]: [array([0, 3, 4]), array([1, 5]), array([2])]
In [80]: classify_rows_list(a)
Out[80]: [[0, 3, 4], [1, 5], [2]]
I am trying to make a list*list of all permutations from 1 to N
Example: perm(3, X). -> X = [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
I am instead getting
X = [1, 2, 3]
X = [1, 3, 2]
X = [2, 1, 3]
X = [2, 3, 1]
X = [3, 1, 2]
X = [3, 2, 1]
and having to keep hitting next. My question is how would I put all values of X into a list like the example run that I want. Here is my existing code:
permHelp([],[]).
permHelp(List,[H|Finish]):-delete(H,List,Rest),permHelp(Rest,Finish).
delete(X,[X|T],T).
delete(X,[H|T],[H|NT]):-delete(X,T,NT).
createList(0, L, L) :- !.
createList(N, R, L) :- N > 0, N1 is N-1, createList(N1, [N|R], L).
perm(N, X):- createList(N, [], L), permHelp(L, X).
perm(N, X):-
createList(N, [], L),
list_allperms(L, X).
With list_allperms/2 defined in another answer.
What you call permHelp should rather be called permutation.
Basically what I'm trying to do is, create a nestled list and set a value of one of its element as a function of other elements in the list.
>>> a = [[1]*5]*5
>>> a
[[1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1]]
>>> a[2][2] = a[0][2] + a[2][1]
>>> a
[[1, 1, 2, 1, 1], [1, 1, 2, 1, 1], [1, 1, 2, 1, 1], [1, 1, 2, 1, 1], [1, 1, 2, 1, 1]]
>>> a[3][2]
2
>>> a[4][2]
2
>>> a[4][4]
1
I just set the value of a[2][2] but the same value got set to every element in the 3rd column. What is going on exactly and how can I get the desired behavior?
What happens is that a ends up containing five references to the same sublist. When you change one sublist, they all change.
To see this, apply id() to each of the sublists:
>>> map(id, a)
[8189352, 8189352, 8189352, 8189352, 8189352]
As you can see, they all have the same ID, meaning they are the same object.
To fix, replace
a = [[1]*5]*5
with
a = [[1]*5 for _ in range(5)]
Now the sublists are independent objects:
>>> map(id, a)
[21086256, 18525680, 18524720, 19331112, 18431472]
The problem is your list a contains five references to the same list. You need to do something like this:
a = []
for _ in range(5):
a += [[1] * 5]