I got trapped in the very basic way of sorting the protection of arraylist- I would like to change the solution of PolyGenialBerecents for this question. I am trying, like, instead of printing them, I am pushing them into an array list.
My code: Output: But when I changed it The type of ArrayList type of integer [] of the given string, as follows, I am getting unnecessary output. Changed Code Output : Does anyone help me Tell me what I'm doing ... Thanks, Sarah Your error is there: Keep in mind, arrays are objects and have a reference that you save the same array Therefore, before you add it you must clone the
Public class exam {Fixed Array List & lt; String & gt; Combination; Public stationary zero main (string array []) {integer [] A3 = {1, 2, 3, 4, 5}; Comb (A3, 2); } Public static zero comb (integer [] item, int a) {Arrays.sort (item); Combination = New Arrestist & lt; String & gt; (); ArrayList & LT; String & gt; C1 = New Arrestist & lt; String & gt; (); C1 = kcomb (item, 0, k, new integer []]; System.out.println ("from the comb"); For (string x: c1) {System.out.println (x); }} Public stable Array list & lt; String & gt; Kcomb (integer [] item, int n, int k, integer [] arr) {if (k == 0) {combinations.add (Arrays.toString (arr)); } Else {for (int i = n; i & lt; = items.length - k; i ++) {arr [arr.length - k] = item [i]; Kcomb (item, I + 1, k - 1, arr); }} Return combination; }}
from comb [1, 2] [1, 3] [1, 4] [ 1, 5] [2, 3] [2, 4] [2, 5] [3, 4] [3, 5] [4, 5]
Public Class Exam {Fixed Array List & lt; Integer [] & gt; Combination; Public stationary zero main (string array []) {integer [] A3 = {1, 2, 3, 4, 5}; Comb (A3, 2); } Public static zero comb (integer [] item, int a) {Arrays.sort (item); Combination = New Arrestist & lt; Integer [] & gt; (); ArrayList & LT; Integer [] & gt; C1 = New Arrestist & lt; Integer [] & gt; (); C1 = kcomb (item, 0, k, new integer []]; System.out.println ("from the comb"); For (integer [] x: c1) {System.out.println (Arrays.toString (x)); }} Public Stable Arrestist & lt; Integer [] & gt; Kcomb (integer [object], int n, int k, integer [] arr) {if (k == 0) {combinations.add (arr); } Else {for (int i = n; i & lt; = items.length - k; i ++) {arr [arr.length - k] = item [i]; Kcomb (item, I + 1, k - 1, arr); }} Return combination; }}
from comb [4, 5] [4, 5] [4, 5] [ 4, 5] [4, 5] [4, 5] [4, 5] [4, 5] [4, 5] [4, 5]
combinations.add (arr); You are always working on the same array
arr .
arr in the context of ArrayList and then change the array values later. You always get the value of the final combination for every other combination, because you are working on the same array all the time.
arr to get a new reference to having your reference of each string as ArrayList code strings being irreversible Before the code was working.
No comments:
Post a Comment