To merage two array
Dear all
class IntArray {
private int data[];
public IntArray (int d[]) {
data=d;
How to merge two array with method:
public IntArray merge(IntArray b)
I try to find out the length of IntArray with b.length but unsucced.
Does this help?
public class FileMerge {
public static void main(String args[]){
int []File1 = {3, 7, 8, 11, 15};
System.out.println();
System.out.print("File 1 is "+File1.length+":");
for (int i=0; i <File1.length; i++) System.out.print(" "+File1[ i ]);
int []File2 = {2, 6, 8, 12};
System.out.println();
System.out.print("File 2 is "+File2.length+":");
for (int i=0; i <File2.length; i++) System.out.print(" "+File2[ i ]);
// merge one from one file then one from the other
int j = 0;
int []File3 = new int[File1.length + File2.length];
for (int i=0; i <File3.length; i++){
if(i < File2.length) File3[j++]=File2[ i ];
if(i < File1.length) File3[j++]=File1[ i ];
System.out.println();
System.out.print("File 3 is "+File3.length+":");
for (int i=0; i <File3.length; i++) System.out.print(" "+File3[ i ]);
// merge all of File1 then all of File2 after this
for (int i=0; i <File1.length; i++){
File3[i] = File1;
for (int i=0; i <File2.length; i++){
File3[File2.length+i+1] = File2[i];
System.out.println();
System.out.print("File 3 is "+File3.length+":");
for (int i=0; i <File3.length; i++) System.out.print(" "+File3[ i ]);
// sort it with built in function
java.util.Arrays.sort(File3);
System.out.println();
System.out.print("File 3 sorted is "+File3.length+":");
for (int i=0; i <File3.length; i++) System.out.print(" "+File3[ i ]);
// re-merge
j = 0;
File3 = new int[File1.length + File2.length];
for (int i=0; i <File3.length; i++){
if(i < File2.length) File3[j++]=File2[ i ];
if(i < File1.length) File3[j++]=File1[ i ];
// bubble sort it
for(int i=0; i <File3.length-1; i++) {
for(j=i+1; j <File3.length; j++) {
if(File3[i] < File3[j]){
int temp = File3[i];
File3[i] = File3[j];
File3[j] = temp;
} // and print it
System.out.println();
System.out.print("File 3 reverse sorted is "+File3.length+":");
for (int i=0; i <File3.length; i++) System.out.print(" "+File3[ i ]);
} // main
} // end class
Similar Messages
-
About combing two array into one
Hi all,
I post a questiona bout converting an array of integer into char (byte) array and I got a solution already http://forums.ni.com/t5/LabVIEW/how-to-display-char-code-properly/m-p/2596087#M780368
However, I enouther another problem while dealing with an array of U16 type. I would like to extract the high and low byte from numbers (U16) stored in array. I extract the high and low byte for each U16 number and convert them as char, concatenate them to a string. Repeat this process for each element in the array so to get a big string with each element is a char for high and low byte. My code is enclosed as follows
It works fine but I am concerning the speed. Is that any other way to do it fast and don't use loop (in real case, I will deal with pretty big array many times, efficiency is a problem). Note that the high and low bytes array extracted from the original array with the module Split number.vi, but how can I combine these two array in one code with data arranged as high-low-high-low ... ? Thanks.
Solved!
Go to Solution.PKIM wrote:
However, I enouther another problem while dealing with an array of U16 type. I would like to extract the high and low byte from numbers (U16) stored in array. I extract the high and low byte for each U16 number and convert them as char, concatenate them to a string. Repeat this process for each element in the array so to get a big string with each element is a char for high and low byte. My code is enclosed as follows
It works fine but I am concerning the speed. Is that any other way to do it fast and don't use loop (in real case, I will deal with pretty big array many times, efficiency is a problem). Note that the high and low bytes array extracted from the original array with the module Split number.vi, but how can I combine these two array in one code with data arranged as high-low-high-low ... ? Thanks.
You need to be more clear.
Looking at the code, you are dealing with I16, not U16. Also your index array primitives could be replaced by autoindexing. Your use of the feedback node only makes sense if you want to append strings forever with stale data, thus growing data structures without limits. If you only want to convert the current data, remove the feedback mode and use a "concatenate strings" with a single input. A for loop is one of the most efficient data structures and using it is not a problem. One way or another the code needs top oerate on all data.
All that said, I agree with Tim that most likely all you need to do is insert a typecast after the "to I16" and eliminate all other code.
LabVIEW Champion . Do more with less code and in less time . -
Two array objects compareTo:
Have two arrays: ttt and ppp. I have to have a method to compare them.
public int compareTo(object ob)
both of the arrays are int type and both have super long numbers in them.
ThanksActually, the reflection api is pretty fast since
JDK1.4.0...No. Reflection could not be fast. In J2SDK1.4 it seems to be faster then in previous releases. But improvments do not include array operations. So here are some results of simple benchmark:
bash-2.05a$ /usr/java/jdk1.3.1_04/bin/java TestArray
Result for reflect copiing (3 elements, 1000000 times): 4915ms
Result for system copiing (3 elements, 1000000 times): 460ms
Result for pure java copiing (3 elements, 1000000 times): 137ms
bash-2.05a$
bash-2.05a$ /usr/java/j2sdk1.4.0_01/bin/java TestArray
Result for reflect copiing (3 elements, 1000000 times): 6082ms
Result for system copiing (3 elements, 1000000 times): 491ms
Result for pure java copiing (3 elements, 1000000 times): 115ms
bash-2.05a$
bash-2.05a$ /usr/java/j2sdk1.4.1/bin/java TestArray
Result for reflect copiing (3 elements, 1000000 times): 5738ms
Result for system copiing (3 elements, 1000000 times): 497ms
Result for pure java copiing (3 elements, 1000000 times): 157ms
bash-2.05a$
As you can see, in new Java reflect operations on arrays are even slower then in jdk1.3.1. System copiing is good alternative for pure java (element by element) copiing, espetially for big arrays. And here is the code of this benchmark, test it on your PC also:
import java.lang.reflect.*;
public class TestArray {
static void doNothing(){}
static int field;
public static void main(String[] args) throws Exception {
final int COUNT = 3, TIMES = 1000*1000;
final String[] arr1 = new String[COUNT];
final String[] arr2 = new String[COUNT];
long time = -System.currentTimeMillis();
for(int i=TIMES; i-->0;)
copyReflect(arr1, arr2, COUNT);
time += System.currentTimeMillis();
System.out.println("Result for reflect copiing ("+COUNT+" elements, "+TIMES+" times): "+time+"ms");
long time = -System.currentTimeMillis();
for(int i=TIMES; i-->0;)
copySystem(arr1, arr2, COUNT);
time += System.currentTimeMillis();
System.out.println("Result for system copiing ("+COUNT+" elements, "+TIMES+" times): "+time+"ms");
long time = -System.currentTimeMillis();
for(int i=TIMES; i-->0;)
copyPureJava(arr1, arr2, COUNT);
time += System.currentTimeMillis();
System.out.println("Result for pure java copiing ("+COUNT+" elements, "+TIMES+" times): "+time+"ms");
private static void copyReflect(Object src, Object dst, int count) {
for(int i=count; i-->0; ) Array.set(dst, i, Array.get(src, i));
private static void copySystem(Object src, Object dst, int count) {
System.arraycopy(src, 0, dst, 0, count);
private static void copyPureJava(String[] src, String[] dst, int count) {
for(int i=count; i-->0; ) dst[i] = src; -
A lot of time to multiply two arrays
Hello!
I want to multiply two arrays. The size of the two arrays is 1568x1568. I use to do it a AxB.vi block....but it spends a huge time, almost 17 seconds, when a operation like this have to be done it less than in a second.
I 've attached an example of the multiplication of two arrays with this size, you have to wait 16 seconds to obatin the result.
Someone know how i can do this multiplication as far as possible?I have to use another block.....for example....formula node and make iterations (or in this way you spend the same time?)
Thank you very much
LarsonNomis wrote:
On my system (P4, 2.6GHz, 1GB Ram Win2K), the example runs in 19 seconds in LV7.0 but in 7.1 it runs in 300mS!
No idea why - perhaps the AxB function was rewritten for 7.1
Yes the matrix operations got a big makeover in LabVIEW 7.1 and are MUCH faster as demonstrated here.
On my 1.6GHz PentiumM laptop, the difference is not that big, but still about 10x.
LabVIEW 7.0: 3700ms
LabVIEW 7.1: 360ms
Time to upgrade!
LabVIEW Champion . Do more with less code and in less time . -
User defined func: Unavble to merge two arrays in result list
Hi
I am trying to merge two arrays on the basis of "FEE" element in the input file;
Actually there is an Attribute Name and Value pair array coming in the input file which has 5 pairs already(Notification + 100 , oversize + 8 etc.) see example below;
<m0:Fees>ZB9</m0:Fees>
<m:Attribute>
<m0:Attributename>NOTIFICATION</m0:Attributename>
<m0:Attributevalue>100</m0:Attributevalue>
</m:Attribute>
<m:Attribute>
<m0:Attributename>OVERSIZE</m0:Attributename>
<m0:Attributevalue>8</m0:Attributevalue>
</m:Attribute>
<m:Attribute>
<m0:Attributename>OVERWEIGHT</m0:Attributename>
<m0:Attributevalue>108</m0:Attributevalue>
</m:Attribute>
<m:Attribute>
<m0:Attributename>SIGNATURE</m0:Attributename>
<m0:Attributevalue>294</m0:Attributevalue>
</m:Attribute>
<m:Attribute>
<m0:Attributename>RTS</m0:Attributename>
<m0:Attributevalue>8</m0:Attributevalue>
</m:Attribute>
The condition is:
CASE 1. If the FEE doesn't exist in the file then only the Atrribute Name and Value in added to the Array
CASE 2 If FEE exist then add all the Atrribute Name and Value pairs as well as in the last index of Array add String "Fee" in Attributename and String "ZB9" in Attributevalue.
CASE 1 is working fine.
but in CASE 2 even if i m taking an output array of length Attributename +1 and Attributevalue +1 and trying to add "Fee" and "ZB9" respectively, it never happens.
Please have a look at the code below;
//write your code here
public void ud_Attributename(String[] Fees,String[] Attributename,ResultList result,Container container){
String attribute_copy[]=new String[Attributename.length+1];
String attribute_name[]=new String[Attributename.length];
String array_copy1[]=new String[Attributename.length+1];
//int len =Attributename.length;
if(Fees[0]!=null)
if(Fees[0].equals("ZB0"))
Fees[0]="01";
else if(Fees[0].equals("ZB5"))
Fees[0]="02";
else if(Fees[0].equals("ZB6"))
Fees[0]="03";
else if(Fees[0].equals("ZB9"))
Fees[0]="04";
try{
if((Fees[0]=="01")||(Fees[0]=="02")||(Fees[0]=="03")||(Fees[0]=="04"))
for(int x=0;x<=Attributename.length;x++)
if(x==Attributename.length)
array_copy1[x]="Fee";
else{
array_copy1[x]=Attributename[x];
result.addValue(array_copy1[x]);
else
for(int i=0;i<=len;i++)
attribute_name<i>=Attributename[i+1];
result.addValue(attribute_name<i>);
}catch(Exception e)
{e.printStackTrace();}
Same way i've used for Attributevalue.
But the result is
<ATTRIBUTEPAIR>
<PAIR>
<NAME>NOTIFICATION</NAME>
<VALUE>04</VALUE>
</PAIR>
<PAIR>
<NAME>OVERSIZE</NAME>
<VALUE>8</VALUE>
</PAIR>
<PAIR>
<NAME>OVERWEIGHT</NAME>
<VALUE>108</VALUE>
</PAIR>
<PAIR>
<NAME>SIGNATURE</NAME>
<VALUE>294</VALUE>
</PAIR>
<PAIR>
<NAME>RTS</NAME>
<VALUE>8</VALUE>
</PAIR>
</ATTRIBUTEPAIR>
Please suggest where i am wrong. ur help is very much appreciated.
Thnks in advancethis is i am doing now
//write your code here
String attribute_copy[]=new String[Attributename.length+1];
String attribute_name[]=new String[Attributename.length];
String attribute_name1[]={"Fee"};
//String[] Attributename.copyTo(attribute_name1,0);
//String[] attribute_name1 = (String[]) Attributename.Clone();
//String fees;
String array_copy1[]=new String[Attributename.length];
int len =Attributename.length;
for(int y=0;y<len;y++){
array_copy1[y]=Attributename[y];
if(Fees[0]!=null)
if(Fees[0].equals("ZB0"))
Fees[0]="01";
else if(Fees[0].equals("ZB5"))
Fees[0]="02";
else if(Fees[0].equals("ZB6"))
Fees[0]="03";
else if(Fees[0].equals("ZB9"))
Fees[0]="04";
else if(Fees[0].equals("ZA1"))
Fees[0]="05";
else if(Fees[0].equals("ZA2"))
Fees[0]="06";
try{
if((Fees[0]=="01")||(Fees[0]=="02")||(Fees[0]=="03")||(Fees[0]=="04")||(Fees[0]=="05")||(Fees[0]=="06"))
int j=0;
for(int a=0;a<=len;a++)
if(j==0&&attribute_copy[j]==null)
attribute_copy[j]="Fee";
else
//int b=-1;
for(int i=0;i<=len;i++)
if(i==j)
//i=i-1;
attribute_copy[j]=array_copy1[i-1];
break;
else{
continue;}
result.addValue(attribute_copy[j]);
j+=1;
else
for(int i=0;i<=len;i++)
attribute_name<i>=Attributename[i+1];
result.addValue(attribute_name<i>);
}catch(Exception e)
{e.printStackTrace();}
and the result in queue is
SUPPRESS
[FEE]
[NOTIFICATION]
[NOTIFICATION]
[OVERSIZE]
[OVERSIZE]
[OVERWEIGHT]
[OVERWEIGHT]
[SIGNATURE]
[SIGNATURE]
[RTS]
[RTS]
but in the output i m getting
<ATTRIBUTEPAIR>
<REF_HANDLE>0001</REF_HANDLE>
<PAIR>
<NAME>Fee</NAME>
<VALUE>04</VALUE>
</PAIR>
<PAIR>
<NAME>OVERSIZE</NAME>
<VALUE>8</VALUE>
</PAIR>
<PAIR>
<NAME>OVERWEIGHT</NAME>
<VALUE>108</VALUE>
</PAIR>
<PAIR>
<NAME>SIGNATURE</NAME>
<VALUE>294</VALUE>
</PAIR>
<PAIR>
<NAME>RTS</NAME>
<VALUE>8</VALUE>
</PAIR>
</ATTRIBUTEPAIR>
Notification is missing. -
Read from .txt file and output the content as two arrays
I am using the contoured move to control the x-y stage. The trajectory datas for x and y axis are generated using my interpolation program and it is stored in a .txt file as two columns. What I want to do is read .txt file and output the content of this file as two arrays. Is there anyone has any ideas? Thanks, the .txt file is attached.
Attachments:
R.75.txt 172 KBHi Awen,
This is quite easy to do, you can merely use the "read from spreadsheet file" function to get a 2D array (2 columns and n rows) and then use the index array function to get whatever row/colums you want..
Hope the attached VI helps you
When my feet touch the ground each morning the devil thinks "bloody hell... He's up again!"
Attachments:
read sprdsheet file.vi 27 KB -
I have two arrays of points, when i plot them there´s an intersection point, but this point doesn´t belong to any arrays. I need to find the both value of this point, X and Y. I attached my problem in a very simple example. Thanks.
Attachments:
arrays_plot.vi 25 KBAlthough this doesn't directly answer your question , I've attached a VI that will hopefully give you a start and point you in the right direction. It generates a Boolean array that indicates between which indecies an intersection has taken place. Then, all you need to do is use triganometry to work out exactly what the intersection point is.
Copyright © 2004-2015 Christopher G. Relf. Some Rights Reserved. This posting is licensed under a Creative Commons Attribution 2.5 License.
Attachments:
2x1D_Array_Intersections.vi 36 KB -
Can;t find what is wrong. Trying to add elements in two arrays
Hello everyone
I'm trying to take as input two numbers, convert them to arrays and add all the element of the array one by one. I want the result to be the sum of every element of the array. Let's say array1={1,2,3,4} and array2={2,6,4,3} I want the final result to be 3877.
If the sum of one element of the array is greater than nine, then I would put zero and add 1 to the element on the left.
Here is the code:
import javax.swing.JOptionPane;
public class Main {
public static void main(String[] args) {
String numberOne = JOptionPane.showInputDialog
("Enter the first number: ");
String numberTwo = JOptionPane.showInputDialog
("Enter the second number: ");
//compare string length and make them equal length
int[]n1 = toArray(numberOne); // my first array
int[]n2 = toArray(numberTwo); // my second array
//call the method that ads both strings
int[]finalArray = arrSum(n1,n2);
JOptionPane.showMessageDialog(null, "The sum of the two numbers is: "
+ finalArray);
}//end of main
//method to create an array from a string
public static int[] toArray(String str)
int[]arr = new int[str.length()];
arr[0]=0;
for (int i=1; i<str.length(); i++)
arr= Character.digit(str.charAt(i),10);
return arr;
}//end of toArray
//method to add arrays by elements
public static int[]arrSum (int[]arr1, int[]arr2){
for (int i = arr1.length-1; i >=1; i--)
int sum = arr1[i] + arr2[i];
if (sum > 9)
{ sum -= 10;
arr1[i-1]++;
return arr1;
}//end of arrSum method
}Edited by: designbc01 on Feb 16, 2010 1:15 AMThe best advice I can give you is to break your problem up into smaller pieces. First, focus on a method that converts an input String into an array. When you have that working perfectly, then focus on creating a method that "adds" two arrays with the logic you described. When you have that working perfectly, then combine the two different pieces.
Why does your for loop in toArray( ) start with 1? The first index of a String, array, or pretty much anything else, is zero. -
Check two array collection items
hi guys
how to check two array collection items so that if any change
in any of the item i can update the datagrid
i already had refresh problem
any idea
karthik.kIf the AC is made [Bindable] and if it is being used as a
dataProvider for the DG changes to the AC should be reflected
automatically in the DG.
If you are trying to feed two AC into a DG and really want to
or need to do something manually, you can have a handler for the
collectionChange event and do the work there.
See FB3 help sys (or LiveDocs online) on
changeCollection. -
I am trying to add two arrays together, it does not seem as if the arrays are broken up into more than one index. I have attached my code. If the array is broken up into indexes I would like to add each corresponding index, but I think the array is all in just one index and if so I was wondering how would I break it into indexes. Thanks
Attachments:
SimpleTest x1.vi 336 KBSince you are "transposing" and later work with 1D array, I assume you want to read the first column of the file.
Why do you need a sequence stacked 5 frames deep, local variables, 5 instances of the same boolean diagram constant and 5 path conststants of which some are identical??? None of this is needed!
All you need is probably something along the lines of the following picture, which probably does something similar to what you want. Still, we are probably still jumping through too many flaming hoops. Note that the execution order is uniquely defined by the wiring alone, no sequence needed! Can you take a step back and tell us what you are actually trying to achieve with all this? How many columns are in the file? Only one?
Message Edited by altenbach on 01-27-2009 04:02 PM
LabVIEW Champion . Do more with less code and in less time .
Attachments:
AddArraysFromFile.png 13 KB -
Writing two arrays to a Excel Spreadsheet
Guru's
I am trying to take information from two arrays and write them to a spreadsheet. One array generates the headers information for the columns, the other array is a random number generator. The number of columns and rows are input from the front panel. The first column of the chart is time at some multiple (interval) input from the front panel
The problem I am having is timing the data out of the loop at the same time so they write together. One loop writes first and the other is left out. The data is going out to an excel spreadsheet. The data is correct for the headers and the columns, but won't write together.
I have only been using LabView for six weeks and have spent a good portion of this weekend working on this problem.
Attached are screen shots and the .vi of the problem. Explanations of each loop are writen in the block diagram.
Thank you for your time and help!!
Newbie2
Attachments:
writing to excel problem.doc 195 KB
Writing to excel problem.vi 27 KBFirst let's talk about the code flaws:
Placing a text decoration over a path constant does not turn it into a valid path constant.
All your controls belong outside the loop, because it would be really bad if they could change during running of the loop. This is also less work, because LabVIEW does not need to re-inspect the control during each iteration.
Your while loop should be a FOR loop because the number of iteration can be calculated before the loop starts. This eliminates checking for termination.
You are not writing any excel files. You are just writing an ASCII table, but you possibly force excel to open it via a fake file extension. (this might be OK, but make sure to NEVER save it later as excel or the file structure would change dramatically).
"# of rows" and "# of machines" should be integers (blue).
Don't be afraid to brance a wire. You don't need any local variables if you do so.
To determine the order in which the segments are written to the file can be determined by dataflow if you wire it correctly. Wire the path to the write function that needs to write first. Then use the path output of this function and wire it to the next instance. Now the second instance must wait until the first one is finished.
(Currently you are branching the path wire, and the execution order is random!)
LabVIEW Champion . Do more with less code and in less time . -
How to join two arrays together?
I have the following type
type TVarcharArr is table of varchar(4000) index by binary_integer;I have a procedure that passes in two separate arrays as:
p_account_number in TVarcharArr,
p_product_system_code in TVarcharArrThese arrays are related (they will have the same number of elements), the contents would be as follows:
Account Number Product System Code
123 ABC
456 DEF
789 GHII can use TABLE(CAST to turn each of these arrays into a table, but how do I join these two arrays together so that they become a single table with two columns? Or if I CAST them as TABLEs, how can I join these two tables together - is there some way of using the index to facilitate the join?
Cheers
RichardYou are right, I do need to convert the arrays first to use TABLE(CAST, and I do have my concerns about the use of rownum.
Here's the test case I built to test what I'm doing, incorporating the rownum solution:
declare
type TVarcharArr is table of varchar(4000) index by binary_integer;
v_arr TVarcharArr;
v_tab tchartab := tchartab();
v_arr2 TVarcharArr;
v_tab2 tchartab := tchartab();
begin
v_arr(1) := 'ABC';
v_arr(2) := 'DEF';
v_arr(3) := 'GHI';
v_arr2(1) := '123';
v_arr2(2) := '456';
v_arr2(3) := '789';
v_tab.extend(v_arr.Count);
for i in v_arr.first .. v_arr.last
loop
v_tab(i) := v_arr(i);
end loop;
v_tab2.extend(v_arr2.Count);
for i in v_arr2.first .. v_arr2.last
loop
v_tab2(i) := v_arr2(i);
end loop;
for rec in (with w_acct as
(select rownum rn, a.column_value acol
from table(cast(v_tab as tchartab)) a
w_prod as
(select rownum rn, b.column_value bcol
from table(cast(v_tab2 as tchartab)) b
select acol,bcol
from w_acct a,
w_prod b
where a.rn = b.rn) loop
DBMS_OUTPUT.PUT_LINE ( 'rec = ' || rec.acol || '|'|| rec.bcol );
null;
end loop;
end;It does return the correct result - but can it be trusted to be consistent - does the rownum in an array suffer the same problems as the rownum from a regular select? I'm guessing it's too risky to find out.
In essence, I'm getting two arrays and I'm trying to join them together so that I can CAST them as a table. (And I know the real question is why isn't it just one array of records with two elements - but sometimes you have to work with what you're given) -
How to combine two arrays?
HI. Can anyone help me?I need to make waveform graph that shows channels' on and off states. I have done a program which works fine for one channel. Now I want to have the other channel in the same picture. I just can't plot those two signals in same picture. Is there any way to combine these two arrays so line 1 would show channel 1 state and line 2 would show channel 2 state? And it would be great if those extra lines wouldn't show at all in the chart. I know I should some how move bits of one array to the other array,but it should remain 1-D. I attach the code here. If there is(and I bet there is) a better way to do this, please tell me.
Mika
Attachments:
Channelsstate.vi 31 KBWould this do?
Message Edited by devchander on 02-06-2008 04:44 AM
Attachments:
dig_graph_21.vi 16 KB -
Find Intersection of two array elements in Oracle 9i
How to find intersection of two arrays in pl/sql for Oracle 9i.
it is feasible in 11g using given code but this code is not working in 9i please help....
DECLARE
abc LIST := list(1,2,3,4);
def LIST := list(4,5,6,7);
BEGIN
dbms_output.put_line(format_list(abc MULTISET EXCEPT def));
END;
Thanks in advance.... :)Argh. Never mind. My coordinates were reversed.
People that made my data set specified the coordinates as lat/long and I didn't question it. I can now see that Oracle expects long/lat instead, so my example works now. -
Printing every possible pair combination of elements in two arrays??
Hi there,
I'm trying to implement the problem of printing every possible pair combination of elements in two arrays. The pattern I have in mind is very simple, I just don't know how to implement it. Here's an example:
g[3] = {'A', 'B', 'C'}
h[3] = {1, 2, 3}
...code...??
Expected Output:
A = 1
B = 2
C = 3
A = 1
B = 3
C = 2
A = 2
B = 1
C = 3
A = 2
B = 3
C = 1
A = 3
B = 1
C = 2
A = 3
B = 2
C = 1
The code should work for any array size, as long as both arrays are the same size. Anybody know how to code this??
Cheers,
Seannot a big fan of Java recursion, unless tail recursion, otherwise you are bound to have out of stack error. Here is some generic permutation method I wrote a while back:
It is generic enough, should serve your purpose.
* The method returns all permutations of given objects. The input array is a two-dimensionary, with the 1st dimension being
* the number of buckets (or distributions), and the 2nd dimension contains all possible items for each of the buckets.
* When constructing the actual all permutations, the following logic is used:
* take the following example:
* 1 2 3
* a d f
* b e g
* c
* has 3 buckets (distributions): 1st one has 3 items, 2nd has 2 items and 3rd has 2 items as well.
* All possible permutaions are:
* a d f
* a d g
* a e f
* a e g
* b d f
* b d g
* b e f
* b e g
* c d f
* c d g
* c e f
* c e g
* You can see the pattern, every possiblity of 3rd bucket is repeated once, every possiblity of 2nd bucket is repeated twice,
* and that of 1st is 4. The number of repetition has a pattern to it, ie: the multiplication of permutation of all the
* args after the current one.
* Therefore: 1st bucket has 2*2 = 4 repetition, 2nd has 2*1 = 2 repetition while 3rd being the last one only has 1.
* The method returns another two-dimensional array, with the 1st dimension represent the number of permutations, and the 2nd
* dimension being the actual permutation.
* Note that this method does not purposely filter out duplicated items in each of given buckets in the items, therefore, if
* is any duplicates, then the output permutations will contain duplicates as well. If filtering is needed, use
* filterDuplicates(Obejct[][] items) first before calling this method.
public static Object[][] returnPermutation(Object[][] items)
int numberOfPermutations = 1;
int i;
int repeatNum = 1;
int m = 0;
for(i=0;i<items.length;i++)
numberOfPermutations = numberOfPermutations * items.length;
int[] dimension = {numberOfPermutations, items.length};
Object[][] out = (Object[][])Array.newInstance(items.getClass().getComponentType().getComponentType(), dimension);
for(i=(items.length-1);i>=0;i--)
m = 0;
while(m<numberOfPermutations)
for(int k=0;k<items[i].length;k++)
for(int l=0;l<repeatNum;l++)
out[m][i] = items[i][k];
m++;
repeatNum = repeatNum*items[i].length;
return out;
/* This method will filter out any duplicate object in each bucket of the items
public static Object[][] filterDuplicates(Object[][] items)
int i;
Class objectClassType = items.getClass().getComponentType().getComponentType();
HashSet filter = new HashSet();
int[] dimension = {items.length, 0};
Object[][] out = (Object[][])Array.newInstance(objectClassType, dimension);
for(i=0;i<items.length;i++)
filter.addAll(Arrays.asList(items[i]));
out[i] = filter.toArray((Object[])Array.newInstance(objectClassType, filter.size()));
filter.clear();
return out;
Maybe you are looking for
-
How to modify changes of table control data in PAI
I have a table control where the columns are brought by dict fields.I am able to bring data into table control through an itab. Now what i want is whenever user edits data in table control and clicks on save button the corresponding changes should be
-
Cancel Vendor Credit Memo - Reg.
Dear Experts, We have posted vendor credit memo through MIRO. The details are as, T-Code : MIRO Transaction : Credit Memo Reference : PO Qty : 0.232 MT Amount : INR 50000/- Tax amount : 0/-(ZERO) Document Date : 16.11.09 Posting Date : 17.02.2010 Now
-
Finder is not recognizing external drive
Yesterday, (Mar 28,2012) Finder was listing my external drive but when I went to eject the drive, it no longer showed in Finder. I cannot eject the drive properly. It is showing on my Desktop. I've done a disk utility verfy disk and it is recognized
-
Logical Systems for client 000 and 001
I've just install solman 7.0 ehp1 sr1 and am going to create a new client from 001. Do I need to create logical systems for clients 000 and 001? Do I need to creat rfc's for these? Thanks, Daniel
-
My ipad2 is Not charging anymore! what to do?
please i Need help.. what should i do??