How make a List of ArrayList in Java? - list

I'm trying to make a list of lists, but I noticed that my list ends up empty at the end of the loop.
ArrayList<ArrayList<Integer>> list_of_lists = new ArrayList<ArrayList<Integer>>();
List<Integer> list = new ArrayList<Integer>();
for(int x = 0; x < 5; x++) {
for(int y = 0; y < 2; y++) {
list.add(x);
list.add(y);
list_of_lists.add((ArrayList<Integer>) list);
System.out.println(list_of_lists);
list.clear();
}
}
System.out.println(list_of_lists);
But, in console the result is:
[[0, 0]]
[[0, 1], [0, 1]]
[[1, 0], [1, 0], [1, 0]]
[[1, 1], [1, 1], [1, 1], [1, 1]]
[[2, 0], [2, 0], [2, 0], [2, 0], [2, 0]]
[[2, 1], [2, 1], [2, 1], [2, 1], [2, 1], [2, 1]]
[[3, 0], [3, 0], [3, 0], [3, 0], [3, 0], [3, 0], [3, 0]]
[[3, 1], [3, 1], [3, 1], [3, 1], [3, 1], [3, 1], [3, 1], [3, 1]]
[[4, 0], [4, 0], [4, 0], [4, 0], [4, 0], [4, 0], [4, 0], [4, 0], [4, 0]]
[[4, 1], [4, 1], [4, 1], [4, 1], [4, 1], [4, 1], [4, 1], [4, 1], [4, 1], [4, 1]]
[[], [], [], [], [], [], [], [], [], []]
Why, the final is a empy list insteed of :
[[0, 0], [0, 1], [1, 0], [1, 1], [2, 0], [2, 1], [3, 0], [3, 1], [4, 0], [4, 1]]
It's with each other instead of two separate lists. My code was linking one list to another

The reason for being the last list empty is that Java stores everything in the form of references i.e in the form of memory address and manipulates them in the same way.
Hence ,the ArrayList object list is also a reference.
So
1) Everytime the inner loop is run a reference to list object is added to the ArrayList list_of_lists.
2) Hence each time the list is manipulated the list_of_lists stores the value of list as many times as the inner loop is run i.e. the list is added to it.
Hence Each time System.out.println(list_of_lists) is called
1) it prints list same no of times it is added to list_of_lists.
2) the list is cleared with list.clear() after that which makes all the references to list empty.
You can also check this code to get list_of_lists at each iteration to get a clear picture of what is happening.
ArrayList<ArrayList<Integer>> list_of_lists = new ArrayList<ArrayList<Integer>>();
List<Integer> list = new ArrayList<Integer>();
for(int x = 0; x < 5; x++) {
for(int y = 0; y < 2; y++) {
list.add(x);
list.add(y);
list_of_lists.add((ArrayList<Integer>) list);
System.out.println(list_of_lists);
list.clear();
}
System.out.println(list_of_lists); //composes of empty lists
//the same of times list is added to it
}
System.out.println(list_of_lists);
**Solution:*
To create a List of Lists you have to allocate memory each time new list is added to list_of_lists:
ArrayList<ArrayList<Integer>> list_of_lists = new
ArrayList<ArrayList<Integer>>();
List<Integer> list;
for(int x = 0; x < 5; x++) {
for(int y = 0; y < 2; y++) {
list = new ArrayList<>();
list.add(x);
list.add(y);
list_of_lists.add((ArrayList<Integer>) list);
System.out.println(list_of_lists);
// list.clear();
}
}
System.out.println(list_of_lists);
}

It's because all your sublists points to the same instance. You should create new instance for each pair of numbers instead of reusing list. Check the code below
ArrayList<ArrayList<Integer>> list_of_lists = new ArrayList<ArrayList<Integer>>();
List<Integer> list;
for(int x = 0; x < 5; x++) {
for(int y = 0; y < 2; y++) {
list = new ArrayList<Integer>();
list.add(x);
list.add(y);
list_of_lists.add((ArrayList<Integer>) list);
System.out.println(list_of_lists);
//list.clear();
}
}
System.out.println(list_of_lists);
The output will be
[[0, 0]]
[[0, 0], [0, 1]]
[[0, 0], [0, 1], [1, 0]]
[[0, 0], [0, 1], [1, 0], [1, 1]]
[[0, 0], [0, 1], [1, 0], [1, 1], [2, 0]]
[[0, 0], [0, 1], [1, 0], [1, 1], [2, 0], [2, 1]]
[[0, 0], [0, 1], [1, 0], [1, 1], [2, 0], [2, 1], [3, 0]]
[[0, 0], [0, 1], [1, 0], [1, 1], [2, 0], [2, 1], [3, 0], [3, 1]]
[[0, 0], [0, 1], [1, 0], [1, 1], [2, 0], [2, 1], [3, 0], [3, 1], [4, 0]]
[[0, 0], [0, 1], [1, 0], [1, 1], [2, 0], [2, 1], [3, 0], [3, 1], [4, 0], [4, 1]]
[[0, 0], [0, 1], [1, 0], [1, 1], [2, 0], [2, 1], [3, 0], [3, 1], [4, 0], [4, 1]]

Related

How to update numpy column where column condition met?

If I have the following:
import numpy as np
a = np.array([[0, 1],
[1, 3],
[4, 4]])
And want to update the column value if a column condition is met. For example if the 2nd column value is greater than 2, then replace only that column value with 9.
a = [[0, 1],
[1, 9],
[4, 9]]
I would have thought this would work, but it updates all the values in that row.
a[a[:,1] > 2] = 9
But it replaces all the values in the row.
a =[[0, 1],
[9, 9],
[9, 9]]
I'm guessing I'm missing some understanding of how the boolean indexing is being created here.
You need:
import numpy as np
a = np.array([[0, 1],
[1, 3],
[4, 4]])
a[:,1]= np.where(a[:,1]>2, 9, a[:,1])
print(a)
Output:
array([[0, 1],
[1, 9],
[4, 9]])
why your code not working
try printing out print(a[a[:,1] > 2])
it will give output as:
[[1 3]
[4 4]]
It will check for 2nd index if it is greater than 2 it will return an entire row.

Skipping list of lists elements

I have this nested list:
list = [[1, 2, 3, 4],
[2, 7, 2, 1],
[3, 3, 7, 5],
[4, 4, 1, 7]]
And I'm trying to skip the first list of this nested list, and the first element of each list. I want it to become like this:
list = [[7, 2, 1],
[3, 7, 5],
[4, 1, 7]]
So far I have this:
% skip first list in list of lists
skip_first_list([_|Tail], Tail).
% attemping to skip first element in each of the lists
skip_first_list([[_ | HeadTail] | Tail], X) :-
skip_first_list(Tail, R),
append(R, [HeadTail], X).
Which does not produce the correct result:
?- skip_first_list([[1, 2, 3, 4], [2, 7, 2, 1], [3, 3, 7, 5], [4, 4, 1, 7]], X).
X = [[2, 7, 2, 1], [3, 3, 7, 5], [4, 4, 1, 7]] ;
X = [[3, 3, 7, 5], [4, 4, 1, 7], [2, 3, 4]] ;
X = [[4, 4, 1, 7], [7, 2, 1], [2, 3, 4]] ;
X = [[3, 7, 5], [7, 2, 1], [2, 3, 4]] ;
false.
Whereas I'm after this answer:
X = [[7, 2, 1], [3, 7, 5], [4, 1, 7]]
My result so far seems to be showing I'm appending in a reverse/incorrect order, How can I fix this? I don't really understand what order Prolog evaluates expressions. Any any would be appreciated.
Well the specification is that you provide a list of lists and that:
the first sublist is ignored (not part of the output); and
that for the remaining sublists, all heads are ignored as well.
So we better split this into two predicates:
remove_heads/2, which removes the heads of all sublists; and
remove_upper_left/2 which remove the first sublist, and then uses the above predicate to pop the heads of the sublists.
We can perform remove_heads/2 for instance with recursion:
remove_heads([],[]).
remove_heads([[_|H]|T],[H|T2]) :-
remove_heads(T,T2).
finally our remove_upper_left/2 simply ignores the head of the list, and makes a call to remove_heads with the tail:
remove_upper_left([_|T],T2) :-
remove_heads(T,T2).
Or in full:
remove_heads([],[]).
remove_heads([[_|H]|T],[H|T2]) :-
remove_heads(T,T2).
remove_upper_left([_|T],T2) :-
remove_heads(T,T2).
This then produces:
?- remove_upper_left([[1, 2, 3, 4], [2, 7, 2, 1], [3, 3, 7, 5], [4, 4, 1, 7]],X).
X = [[7, 2, 1], [3, 7, 5], [4, 1, 7]].
and works in the opposite direction as well:
?- remove_upper_left(X, [[1, 2, 3, 4], [2, 7, 2, 1], [3, 3, 7, 5], [4, 4, 1, 7]]).
X = [_G1364, [_G1370, 1, 2, 3, 4], [_G1376, 2, 7, 2, 1], [_G1382, 3, 3, 7, 5], [_G1388, 4, 4, 1|...]].
So here it prepends a variable to every list, and prepends a variable (possibly a sublist) to the output.
Furthermore we have here two predicates at the price of one: we can also use remove_heads/2 in the future if we want to pop the heads of all the sublists in a list of lists.

How can I correct my list format?

first I write a test code:
a = [-0.2364, 2.2524, 8.4896,'a']
l = []
for i,each in enumerate(a,start=1):
l.append(["{}, {}".format(i,each)])
lst = str(l).translate(None, "'")
print lst
and the output is ok
[[1, -0.2364], [2, 2.2524], [3, 8.4896], [4, a]]
This is what I want like add serial number for each item in a list. And then I try use httplib read data and replace test list a.
a = response.read()
l = []
for i,each in enumerate(a,start=1):
l.append(["{}, {}".format(i,each)])
lst = str(l).translate(None, "'")
print a
print lst
But output is changed like :
[-0.035308122832456316]
[[1, [], [2, -], [3, 0], [4, .], [5, 0], [6, 3], [7, 5], [8, 3], [9, 0], [10, 8], [11, 1], [12, 2], [13, 2], [14, 8], [15, 3], [16, 2], [17, 4], [18, 5], [19, 6], [20, 3], [21, 1], [22, 6], [23, ]]]
lista seems ok. but outputlst is not what I expected.For this case I trying to get output like:
[-0.035308122832456316]
[[1,-0.035308122832456316]]
how can I fix this?Thanks!
As I mentioned above if a is a string '[-0.035308122832456316]' or even with multiple list values like this a = '[-0.035308122832456316,89427873479875]' simply use below code and it will work fine for you.
import ast
a = response.read()
a = ast.literal_eval(a) #Convert String representation of list to list
l = []
for i,each in enumerate(a,start=1):
l.append(["{}, {}".format(i,each)])
lst = str(l).translate(None, "'")
print a
print lst
Try working with a dictionary instead of a list:
a = [-0.2364, 2.2524, 8.4896, 'a']
l = {}
for i, each in enumerate(a, start=1):
l[i] = each
print l
To simulate your indication that a is a list with 1 item:
a = [-0.035308122832456316]
l = {}
for i, each in enumerate(a, start=1):
l[i] = each
print l
If, as others have indicated, that a is a string with value "[-0.035308122832456316]", then convert it to a list:
a = "[-0.035308122832456316]"
if isinstance(a, str):
a = [a[1:-1]]
l = {}
for i, each in enumerate(a, start=1):
l[i] = each
print l

Generate Successive Number Pairs - Prolog

I have some code that takes a given list of pairs of numbers and solves for chains of 7. However, it takes an obnoxious amount of time to solve for even one (well, i haven't solved for 1 yet and it has been a large amount of time). I was wondering if there was a better/more efficient way of coding this.
Here's what I did, with out the numbers in the list "L". (the list looks like such: L= [[1,2],[2,3],...])
length(L,LEN),
interval(N1,1,LEN),
interval(N2,1,LEN),
interval(N3,1,LEN),
interval(N4,1,LEN),
interval(N5,1,LEN),
interval(N6,1,LEN),
interval(N7,1,LEN),
nth1(N1,L,A),
nth1(N2,L,B),
nth1(N3,L,C),
nth1(N4,L,D),
nth1(N5,L,E),
nth1(N6,L,F),
nth1(N7,L,G),
nth1(2,A,A2),
nth1(1,B,B1),
A2 = B1,
nth1(2,B,B2),
nth1(1,C,C1),
B2 = C1,
nth1(2,C,C2),
nth1(1,D,D1),
C2 = D1,
nth1(2,D,D2),
nth1(1,E,E1),
D2 = E1,
nth1(2,E,E2),
nth1(1,F,F1),
E2 = F1,
nth1(2,F,F2),
nth1(1,G,G1),
F2 = G1,
nth1(2,G,G2),
nth1(1,A,A1),
G2 = A1,
R = (A,B,C,D,E,F,G).
If I understand your intention correctly, you can write this shorter as
use_module(library(clpfd)).
q(L,R) :-
[A,B,C,D,E,F,G] ins 1 .. 7,
R = [[A,B],[B,C],[C,D],[D,E],[E,F],[F,G],[G,A]],
permutation(L, R),
label([A,B,C,D,E,F,G]).
Example:
3 ?- q([[1,7],[2,3],[5,4],[3,1],[7,6],[6,5],[4,2]],X).
X = [[1, 7], [7, 6], [6, 5], [5, 4], [4, 2], [2, 3], [3, 1]] ;
X = [[2, 3], [3, 1], [1, 7], [7, 6], [6, 5], [5, 4], [4, 2]] ;
X = [[5, 4], [4, 2], [2, 3], [3, 1], [1, 7], [7, 6], [6, 5]] ;
X = [[3, 1], [1, 7], [7, 6], [6, 5], [5, 4], [4, 2], [2, 3]] ;
X = [[7, 6], [6, 5], [5, 4], [4, 2], [2, 3], [3, 1], [1, 7]] ;
X = [[6, 5], [5, 4], [4, 2], [2, 3], [3, 1], [1, 7], [7, 6]] ;
X = [[4, 2], [2, 3], [3, 1], [1, 7], [7, 6], [6, 5], [5, 4]] ;
false.
But your question is really unclear.
update: We can create the kind of lists we use above, of any length, with
vars(N, Vars):-
length(Vars, N).
pairs(Vars, N, Pairs):- % assuming vars(N, Vars)
N #> 0,
append(Vars,[A],[A|B]), % |B| = N
maplist( pair, Vars, B, Pairs).
pair( A, B, [A,B]).
Such that q/2 can be generalized as
gen_q(L,R) :-
length( L, N),
vars( N, Vars),
Vars ins 1 .. N,
pairs( Vars, N, R),
permutation(L, R),
label(Vars).
But computational feasibility of this for larger inputs is another matter entirely. The brute force of permutation/2 may have to be replaced with something more specific.
Also, the N results produced comprise a clear pattern; there's no need to re-enter the search to produce them all after the first one is found.

Permutation Prolog

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.