basically I want to be able to store a 2D array such as this
int [][] preferredMoves = {
{0,0}, {0, arrLength}, {length%2, arrLength},
{0, length%2}, {arrLength, 0}, {0, length%2},
{arrLength, arrLength}, {length%2, length%2},
{arrLength, length%2}, {length%2, 0}
};
In a single
int [] moves;
array.
I'm sure this is possible since I'm just storing a list..., but I can't seem to find information on this anywhere... or maybe its not possible?
EDIT
I am dealing with matrices.
I want to store the list in a single array to then return that array to use it elsewhere.
So then every time I call it, all I have to do is something like this...
int row = Computer.moves()[0];
int col = Computer.moves()[1];
I also need to loop through that single array, which contains the 2D array multiple times..
Not sure if this is what you meant,
but you could drop the internal { ... } to convert this to a one-dimensional array:
int [] moves = {
0, 0, 0, arrLength, length % 2, arrLength,
0, length % 2, arrLength, 0, 0, length % 2,
arrLength, arrLength, length % 2, length % 2,
arrLength, length % 2, length % 2, 0
};
And you can translate 2D indexes (i, j) to 1D index k using the formula:
k = i * 2 + j;
Janos' answer is probably what you want. Alternatively you could create a class, e.g. Pair, and store it in a Pair[] array.
Related
I have two arrays and I am trying to assign the values of one array, i.e. arrayOne[0] should be equal to the corresponding index in arrayTwo[0].
I am trying to do this using a forloop so that it loops through the the index of one array assigning the values sequentially.
so far I have:
for (int a =0; a< arrayOne.length; ++) {
// this sets the an int that loops through the value of the arrays(both arrayOne and arrayTwo are the same length)
I am lost however after this how to create the for loop which assigns index 0 = 0 and then incrementally step through this.
I know this is a very basic question but I am, as my name suggests, struggling to learn coding.
I am lost however after this how to create the for loop which assigns index 0 = 0 and then incrementally step through this.
There are many ways to copy arrays. But since you specifically asked for a for loop solution, just create a new array of the same size and use a for loop as shown to index them.
int [] a = {1,2,3,4,5,6,7};
int [] b = new int[a.length];
for (int i = 0; i < a.length; i++) {
b[i] = a[i]; // this copies element a[i] to b[i] where i is the index.
}
System.out.println(Arrays.toString(a));
System.out.println(Arrays.toString(b));
Prints
[1, 2, 3, 4, 5, 6, 7]
[1, 2, 3, 4, 5, 6, 7]
public static void main(String[] args) {
int[][] b = {{0, 0, 0, 1},
{0, 0, 1, 1},
{0, 1, 1, 1}};
int[] u = new int[b.length];
for (int i = 0; i < u.length; i++) {
for (int j = 0; j < b[i].length; j++) {
u[i] = u[i] +b[i][j];
}
System.out.println(u[i]);
}
}
What is the differences between written b[i].length; and b.length;
When i run this code with b[i].length; the output is 1,2,3.
When running with b.length; gives the output 0,1,2
Your array got 2 dimensions, thus it is an array of an array. If you use b.length you will get the amount of arrays that are stored within b
Your array could look like this:
int[][] b = {{1}, {1,2}, {1,2,3}};
So b is an array that contains 3 other arrays. b.length (in this case) will always be 3. If you use b[n].length, you will get the length of the array with index n within b. In my example above: b[0].length will be 1, b[1].length will be 2, b[2].length will be 3.
b.length gives you the length of array b which is 3 because it has three element: b[0] which is an array {0, 0, 0, 1}, b[1] which is an array {0, 0, 1, 1} and finally b[2] which is an array {0, 1, 1, 1}.
b[i].lenght gives you the length of element b[i] which is 4. The reason that you can use length method in b[i] is because b[i] is also array (b is an array of arrays so every element of b is an array of int's).
b[i].length will return 4 for every i because every element b[i] is an array of length 4 .However, note that b[i] doesn't need to have same length
for example if you had:
int[][] b = {{0, 0, 0, 1},{1, 1}};
Then here b.length returns you 2, b[0].length returns 4 and b[1].length returns 2.
In your code your have a 2d array.
/*This is an array of arrays*/
int[][] b = {
{0, 0, 0, 1},
{0, 0, 1, 1},
{0, 1, 1, 1}
};
This is an array to arrays.
b.length will return the amount of arrays in the main array
b[i].length will return the amount of elements in one specific array on index i
b.length return number all rows but b[i].length; return number column for row i
b.length is the number of rows in your matrix
b[i].length is the number of elements i-th row
b refers to an array of arrays.
b.length returns how many elements b has - in other words, how many "nested" arrays you have.
b[i].length returns how many elements b[i] has - in other words, the length of the nested array referred to by b[i].
I am trying to combine two arrays into one big array.
But I don't understand why it wont work.
Here's my code:
public class TestaCombine {
private int[] arrayX = new int[20];
private int[] arrayY = new int[6];
private int[] ratings;
public void getRanks(){
arrayX[0] = 3;
arrayX[1] = 4;
arrayX[2] = 2;
arrayX[3] = 6;
arrayX[4] = 2;
arrayX[5] = 5;
arrayY[0] = 9;
arrayY[1] = 7;
arrayY[2] = 5;
arrayY[3] = 10;
arrayY[4] = 6;
arrayY[5] = 8;
}
public void combine(){
ratings = new int[arrayX.length + arrayY.length];
System.arraycopy(arrayX, 0, ratings, 0, arrayX.length);
System.arraycopy(arrayY, 0, ratings, arrayX.length, arrayY.length);
Arrays.sort(ratings);
}
public void print(){
System.out.println(Arrays.toString(ratings));
}
public static void main(String[] args){
TestaCombine tc = new TestaCombine();
tc.getRanks();
tc.combine();
tc.print();
}
The output I am getting looks like this:
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 3, 4, 5, 5, 6, 6, 7, 8, 9, 10]
Don't understand where all the 0s comes from.
Note that the size of arrayX is 20. By default, ints have 0 value in Java. See the JLS - 4.12.5. Initial Values of Variables:
For type int, the default value is zero, that is, 0.
So when you do:
System.arraycopy(arrayX, 0, ratings, 0, arrayX.length);
It copies the zeros as well.
You're combining an array of size 6 with an array of size 20. The resulting array therefore has a size of 26.
But you've only specified 12 values, so the rest are filled in with values of 0. As you're sorting the collections, this also puts all the 0s at the start of the array.
It is because you have created one array with size of 20 and you only initialized 6 values within it, the rest of values where initialized during array initialization and they were all populated to 0's. When you combined array of size 20 and array of size 6 you received array of size 26 where 14 values are 0's
I would also like to recommend you apache commons libraries which contains nice set of tools for managing different collections.
I have seen acrosss in a company interview test this question, but i am not clear about the question first. Could you people clarify my doubt ?
Question : Write a program to sort an integer array which contains Only 0's,1's and 2's. Counting of elements not allowed, you are expected to do it in O(n) time complexity.
Ex Array : {2, 0, 1, 2, 1, 2, 1, 0, 2, 0}
Output to a linked list.
Remember the beginning of the list.
Remember the position where the 1s start.
Remember the end of the list.
Run through the whole array.
If you encounter a 0, add it to the first position of the linked list.
If you encounter a 1, add it after the position of the 1.
If you encounter a 2, add it at the end of the list.
HTH
Raku
Instead of blasting you with yet another unintelligible pseudo-code, I’ll give you the name of the problem: this problem is known as the Dutch national flag problem (first proposed by Edsgar Dijkstra) and can be solved by a three-ways merge (see the PHP code in the first answer which solves this, albeit very inefficiently).
A more efficient in-place solution of the threeways merge is described in Bentley’s and McIlroy’s seminal paper Engineering a Sort Function. It uses four indices to delimit the ranges of the intermediate array, which has the unsorted values in the middle, the 1s at both edges, and the 0s and 2s in-between:
After having established this invariant, the = parts (i.e. the 1s) are swapped back into the middle.
It depends what you mean by "no counting allowed".
One simple way to do this would be to have a new empty array, then look for 0's, appending them to the new array. Repeat for 1's then 2's and it's sorted in O(n) time.
But this is more-or-less a radix sort. It's like we're counting the 0's then 1's then 2's, so I'm not sure if this fits your criteria.
Edit: we could do this with only O(1) extra memory by keeping a pointer for our insertion point (starting at the start of the array), and scanning through the array for 0's, swapping each 0 with the element where the pointer is, and incrementing the pointer. Then repeat for 1's, 2's and it's still O(n).
Java implementation:
import java.util.Arrays;
public class Sort
{
public static void main(String[] args)
{
int[] array = {2, 0, 1, 2, 1, 2, 1, 0, 2, 0};
sort(array);
System.out.println(Arrays.toString(array));
}
public static void sort(int[] array)
{
int pointer = 0;
for(int i = 0; i < 3; i++)
{
for(int j = 0; j < array.length; j++)
{
if(array[j] == i)
{
int temp = array[pointer];
array[pointer] = array[j];
array[j] = temp;
pointer++;
}
}
}
}
}
Gives output:
[0, 0, 0, 1, 1, 1, 2, 2, 2, 2]
Sorry, it's php, but it seems O(n) and could be easily written in java :)
$arr = array(2, 0, 1, 2, 1, 2, 1, 0, 2, 0);
$tmp = array(array(),array(),array());
foreach($arr as $i){
$tmp[$i][] = $i;
}
print_r(array_merge($tmp[0],$tmp[1],$tmp[2]));
In O(n), pseudo-code:
def sort (src):
# Create an empty array, and set pointer to its start.
def dest as array[sizeof src]
pto = 0
# For every possible value.
for val in 0, 1, 2:
# Check every position in the source.
for pfrom ranges from 0 to sizeof(src):
# And transfer if matching (includes update of dest pointer).
if src[pfrom] is val:
dest[pto] = val
pto = pto + 1
# Return the new array (or transfer it back to the source if desired).
return dest
This is basically iterating over the source list three times, adding the elements if they match the value desired on this pass. But it's still O(n).
The equivalent Java code would be:
class Test {
public static int [] mySort (int [] src) {
int [] dest = new int[src.length];
int pto = 0;
for (int val = 0; val < 3; val++)
for (int pfrom = 0; pfrom < src.length; pfrom++)
if (src[pfrom] == val)
dest[pto++] = val;
return dest;
}
public static void main(String args[]) {
int [] arr1 = {2, 0, 1, 2, 1, 2, 1, 0, 2, 0};
int [] arr2 = mySort (arr1);
for (int i = 0; i < arr2.length; i++)
System.out.println ("Array[" + i + "] = " + arr2[i]);
}
}
which outputs:
Array[0] = 0
Array[1] = 0
Array[2] = 0
Array[3] = 1
Array[4] = 1
Array[5] = 1
Array[6] = 2
Array[7] = 2
Array[8] = 2
Array[9] = 2
But seriously, if a potential employer gave me this question, I'd state straight out that I could answer the question if they wish, but that the correct answer is to just use Array.sort. Then if, and only if, there is a performance problem with that method and the specific data sets, you could investigate a faster way.
And that faster way would almost certainly involve counting, despite what the requirements were. You don't hamstring your developers with arbitrary limitations. Requirements should specify what is required, not how.
If you answered this question to me in this way, I'd hire you on the spot.
This answer doesn't count the elements.
Because there are so few values in the array, just count how many of each type there are and use that to repopulate your array. We also make use of the fact that the values are consecutive from 0 up - making it match the typical java int loop.
public static void main(String[] args) throws Exception
{
Integer[] array = { 2, 0, 1, 2, 1, 2, 1, 0, 2, 0 };
List<Integer>[] elements = new ArrayList[3]; // To store the different element types
// Initialize the array with new lists
for (int i = 0; i < elements.length; i++) elements[i] = new ArrayList<Integer>();
// Populate the lists
for (int i : array) elements[i].add(i);
for (int i = 0, start = 0; i < elements.length; start += elements[i++].size())
System.arraycopy(elements[i].toArray(), 0, array, start, elements[i].size());
System.out.println(Arrays.toString(array));
}
Output:
[0, 0, 0, 1, 1, 1, 2, 2, 2, 2]
Push and Pull have a constant complexity!
Push each element into a priority queue
Pull each element to indices 0...n
(:
You can do it in one pass, placing each encountered element to it's final position:
void sort012(int* array, int len) {
int* p0 = array;
int* p2 = array + len;
for (int* p = array; p <= p2; ) {
if (*p == 0) {
std::swap(*p, *p0);
p0++;
p++;
} else if (*p == 2) {
std::swap(*p, *p2);
p2--;
} else {
p++;
}
}
}
Because there are so few values in the array, just count how many of each type there are and use that to repopulate your array. We also make use of the fact that the values are consecutive from 0 up - making it match the typical java int loop.
The whole sorting algorithm requires only three lines of code:
public static void main(String[] args)
{
int[] array = { 2, 0, 1, 2, 1, 2, 1, 0, 2, 0 };
// Line 1: Define some space to hold the totals
int[] counts = new int[3]; // To store the (3) different totals
// Line 2: Get the total of each type
for (int i : array) counts[i]++;
// Line 3: Write the appropriate number of each type consecutively back into the array:
for (int i = 0, start = 0; i < counts.length; start += counts[i++]) Arrays.fill(array, start, start + counts[i], i);
System.out.println(Arrays.toString(array));
}
Output:
[0, 0, 0, 1, 1, 1, 2, 2, 2, 2]
At no time did we refer to array.length, no care how long the array was. It iterated through the array touching each element just once, making this algorithm O(n) as required.
i have array values as like
String[] value = {"1","2","3", "4","5","6","7","8","9","10"};
suppose if i pass value "5" to tat array, it should be ordered as like
{"5","6","7","8","9","10",1","2","3","4"};...
how to do?plz anyone help?
thank u
What you need is called rotation. You can use Collections.rotate() method. Convert the array to a list and pass it to the method. This will rotate the array in place since the list is backed by the array:
String[] value = {"1","2","3", "4","5","6","7","8","9","10"};
Collections.rotate(Arrays.asList(value), 5);
The above code will rotate the array by a distance of 5. The resulting value array:
[6, 7, 8, 9, 10, 1, 2, 3, 4, 5]
Your question has two interpretations:
Rotate 5 steps, or
rotate the array so that 5 is the first element (regardless of where it is in the array).
Here is a solution for both alternatives:
import java.util.Arrays;
public class Test {
public static String[] rotateArray(String[] arr, int n) {
String[] rotated = new String[arr.length];
System.arraycopy(arr, n-1, rotated, 0, arr.length-n+1);
System.arraycopy(arr, 0, rotated, arr.length-n+1, n-1);
return rotated;
}
public static String[] rotateArrayTo(String[] arr, String head) {
for (int i = 0; i < arr.length; i++)
if (arr[i].equals(head))
return rotateArray(arr, i + 1);
throw new IllegalArgumentException("Could not find " + head);
}
public static void main(String[] args) {
String[] value = {"1","2","3","4","5","6","7","8","9","10"};
// Rotate so that it starts at 5:th element
value = rotateArray(value, 5);
System.out.println(Arrays.toString(value));
// Rotate so that it starts with element "7"
value = rotateArrayTo(value, "7");
System.out.println(Arrays.toString(value));
}
}
Output:
[5, 6, 7, 8, 9, 10, 1, 2, 3, 4]
[7, 8, 9, 10, 1, 2, 3, 4, 5, 6]
(ideone.com link)
first find the index of the entered value from the array..
and then in a loop move from the index to the final position.. and store these values in a new array.
after that, in the same result array, store the values from index 0 to the index of the entered value - 1.
You really don't need to store the values in a different array. Just find the index [say idx] of the value passed. And then start a loop from the start of the array and swap the values starting from idx.
For example -
idx = [some-value]
while [idx < arr.length]
temp = arr[i]
arr[i] = arr[idx]
arr[idx] = t
idx += 1
i += 1
Update:
I stand corrected by #aioobe. I simply worked out something for the 5th index - my bad. Here's something that works, if in case, you want to stay away from library functions -
private void slideLeft(String[] arr)
{
String t = arr[arr.length - 1];
String temp = null;
int next = -1;
for (int i = arr.length - 1; i >= 0; i--)
{
next = ( i == 0 ) ? arr.length - 1 : i - 1;
temp = arr[next];
arr[next] = t;
t = temp;
}
}
you'll need to call this method the number of times you need to shift the array members.
note: O(n^2) alert. not suitable for large shifts/arrays.