I've been working in a little Java project but I can't figure out how to overwrite the elements of an array based on the values on another array.
Basically I have two arrays: repeated[] = {1,4,0,0,0,3,0,0} and hand[] = {1,2,2,2,2,6,6,6} and I use repeated[] to count the amount of times a number appears on hand[], and if it is between 3 and 7 it should overwrite the corresponding element in hand[] with a zero but I keep getting this output {1,0,0,2,2,6,0,6} when it should give me {1,0,0,0,0,0,0,0}. What am I doing wrong?
public static void main(String[] args) {
int repeated[] = {1,4,0,0,0,3,0,0};
int hand[] = {1,2,2,2,2,6,6,6};
for(int z=0;z<repeated.length;z++){
if(repeated[z]>=3 && repeated[z]<8){
for(int f:hand){
if(hand[f]==(z+1)){
hand[f]=0;
} } } }
for(int e:hand){
System.out.print(e+",");
}
}
First, the value in repeated is offset by one (because Java arrays start at index zero). Next, you need to test if the value is >= 3 (because 6 only appears 3 times). And, you could use Arrays.toString(int[]) to print your array. Something like,
public static void main(String[] args) {
int repeated[] = { 1, 4, 0, 0, 0, 3, 0, 0 };
int hand[] = { 1, 2, 2, 2, 2, 6, 6, 6 };
for (int z = 0; z < repeated.length; z++) {
if (repeated[hand[z] - 1] >= 3) {
hand[z] = 0;
}
}
System.out.println(Arrays.toString(hand));
}
Output is
[1, 0, 0, 0, 0, 0, 0, 0]
Related
I ran into an issue I can't seem to solve, and all the searches I do are not completely relevant to the issue I am having, and trying to implement those things to solve my issue still doesn't work. I've spent an hour trying to find another question or post somewhere that would help but can't seem to find any specific to my issue (unless Google just doesn't want to work today).
I am trying to create a method that returns an array of all of the odd numbers between 1 and n, say in this example 1 to 255.
I tried the following (here is the method currently):
import java.util.Arrays;
public class BasicJava: {
public Integer[] arrayOfOdds() {
int n = 255;
Integer[] odds = new Integer[(n+1)/2];
for(int i = 1; i < n+1; i+=2) {
odds[i/2] = i;
}
return odds;
}
}
Main Method:
import java.util.Arrays;
public class BasicJavaTest {
public static void main(String[] args) {
BasicJava test = new BasicJava();
System.out.println(Arrays.toString(test.arrayOfOdds()));
}
}
I tried using an array to do the same thing before switching to using an ArrayList (I like other data structures more than I do arrays) and converting to an array and got the same output (I will just put part of the output array to not use too much space):
[0, 1, 0, 3, 0, 5, 0, 7, 0, 9, 0, 11, 0, 13, 0, 15, 0, 17, 0, 19, 0, 21, 0, 23, 0, 25, 0, 27, 0, 29, 0, 31, 0]
What do I need to resolve this issue?
If I just wanted to print all of the odds between 1 and N using the same for loop and if statement, I would get the correct output.
Thank you
You can do this is linear time complexity and without using an ArrayList.
Your final output will always have n/2 elements so your array size can be fixed at the same. In the next step you can simply populate the values in your array.
FYR code:
int[] arr = new int[((n+1)/2)];
for(int i = 0, e = 1; i < arr.length; e += 2, i++) {
arr[i] = e;
}
You can use IntStream like this.
static int[] arrayOfOdds() {
return IntStream.iterate(1, i -> i + 2)
.takeWhile(i -> i < 256)
.toArray();
}
public static void main(String[] args) {
System.out.println(Arrays.toString(arrayOfOdds()));
}
output:
[1, 3, 5, 7, 9, 11, 13, 15, ... , 251, 253, 255]
int N = 255;
Integer[] array = new Integer[(N+1)/2];
for (int j = 1; j < N+1; j+=2) {
array[j/2] = j;
}
System.out.println(Arrays.toString(array));
You don't need to add condition to check for each integer.
Here is a simple trick to create odds number:
Start with 1 and increase 2 for next element. ( 1,3,5...)
public static void main(String[] args) {
List<Integer> arr = getOddList(255);
System.out.print(arr);
}
private static List<Integer> getOddList(int n) {
List<Integer> nums = new ArrayList<>();
for (int i = 1; i < n; i = i + 2) {
nums.add(i);
}
return nums;
}
//Output [1, 3, 5, 7, 9, 11...
hello to all you code geniuses on here
ill try to explain my problem as simply as i can
image1
To produce image1, lets say an array like below is required, keeping in mind that the numbers are placed left to right in the first row, then go backwards in the second row, and if you added more numbers, it would create a third row.
int[] something = {1, 2, 3, 2, 1, 2, 1, 3, 3, 1, 1, 2}
so i want to make to make a "map" of the layout, like this desired output below.
2 1 1 3 3 1
1 2 3 2 1 2
and then from there i would want to find the total for each column, so like this.
2 1 1 3 3 1
1 2 3 2 1 2
..................
3 3 4 5 4 3
(and i then want to make store this layout and sum within another array)
hopefully that all made sense, if so,
how could i go about doing this?
thanks heaps : )
Seems like you can use a two-dimensional array data structure to solve this:
int[][] something = new int[][]{
{2, 1, 1, 3, 3, 1},
{1, 2, 3, 2, 1, 2}
};
int totalForColomn1 = something[0][0] + something [1][0];
int totalForColomn2 = something[0][1] + something [1][1];
// ...
int totoalForColomn6 = something[0][5] + something [1][5];
If you could only use one-dimensional array:
int[] something = new int[] {2, 1, 1, 3, 3, 1, 4, 2, 3, 2, 1, 2};
int row_size = 6;
int totalForColomn1 = something[0] + something[0 + row_size];
int totalForColomn2 = something[1] + something[1 + row_size];
// ...
int totalForColomn6 = something[5] + something[5 + row_size];
Remember to keep a consistant row_size by putting those undecided element to 0.
In this case, you should init your array like:
int[] something = new int[] {0, 0, 0, 0, 1, 4, 1, 2, 3, 2, 1, 1};
So If I am reading this correctly if L is the length of your array you want to add the nth and L-1-nth element of the array and store the result in an array. I through this together quickly so I did not handle what happens if the input array is of odd length (your question did not specify).
import java.util.Arrays;
public class App {
public static void main(String[] args) {
int[] something = {1, 2, 3, 2, 1, 2, 1, 3, 3, 1, 1, 2};
System.out.println(Arrays.toString(addValues(something)));
}
public static int [] addValues(int [] input){
int[] output = new int[input.length / 2];
for(int i = 0; i<input.length/2; i++){
output[i] = input[i] + input[input.length -1 - i ];
}
return output;
}
}
EDIT:
I think this will work for the case where the are an arbitrary number of rows.
The main insite into how this work is in the grid below.
0 1 2 3 4 5 :row 0
11 10 9 8 7 6 :row 1
12 13 14 15 16 17:row 2
23 22 21 20 19 18:row 3
So whether the output index is going up or down is determined by the row number and every time we hit an input index that is the same size as our output array we need to stay at the same output index.
import java.util.Arrays;
public class App {
public static void main(String[] args) {
int[] something = { 1, 2, 3, 2, 1, 2, 1, 3, 3, 1, 1, 2 };
System.out.println(Arrays.toString(addValues(something, 6)));
}
public static int[] addValues(int[] input, int row_lenth) {
int[] output = new int[row_lenth];
int output_index = 0;
for (int i = 0; i < input.length; i++) {
if (i % row_lenth != 0) {
if ((i / row_lenth) % 2 == 0) {
output_index++;
} else {
output_index--;
}
}
output[output_index] += input[i];
}
return output;
}
}
import java.util.Scanner;
public class Stckoverq {
public static void main(String args[]) {
Scanner sn = new Scanner(System.in);
System.out.print("What is the size of array? ");
int size = sn.nextInt();
System.out.print("What is length of the row?");
int len = sn.nextInt();
int ind = 0, i = 0, j = 0;
//variable 'ind' is for getting the element from arr[] array at index ind
int rac[][] = new int[size/len][len];
//variable 'i' and 'j' is for storing rows and column elements respectively in array rac[]
int arr[] = new int[size];
System.out.println("Enter array elements: ");
for(int k=0;k<size;k++)
arr[k] = sn.nextInt();
while(ind!=arr.length)
{
if(j==len) {
j=0; //Reset column index
i++; //Increase row index
}
rac[i][j] = arr[ind];
ind++;
j++; //Increase column index
}
//Now print the rows and columns................
for(int r =0;r<size/len;r++) {
for(int c=0;c<len;c++)
System.out.print(rac[r][c]+"\t");
System.out.println();
}
int sum[] = new int[len];
//this array sum[] is used to store sum of all row elements.
int s = 0;
for(int c=0;c<len;c++) {
for(int r =0;r<size/len;r++)
s += rac[r][c];
sum[c] = s;
s = 0;
}
for(int x: sum)
System.out.print(x+"\t");
}
}
I have the following array:
int [] mi_array= {9,4,0,0,4,0,3,0,1,8,0};
I want to order the numbers other than 0 on the left, and the 0s on the right, but I find that the function steps on one of the numbers.
The output must be
{9,4,4,3,1,8,0,0,0,0,0}
public class Array {
public static void main(String[] args) {
int [] mi_array= {9,4,4,3,1,8,0,0,0,0,0};
int x=0;
int y=mi_array.length-1;
for (int i=0;i<mi_array.length;i++)
if(mi_array[i]!=0) {
mi_array[x]=mi_array[i];
x++;
}
else {
mi_array[y]=mi_array[i];
y--;
}
for (int i=0;i<mi_array.length;i++)
System.out.println(mi_array[i]);
System.out.println(x);
}
}
Try this.
int[] mi_array = {9, 4, 0, 0, 4, 0, 3, 0, 1, 8, 0};
for (int i = 0, j = i + 1, s = mi_array.length; j < s;)
if (mi_array[i] == 0) {
mi_array[i] = mi_array[j];
mi_array[j] = 0;
++j;
} else if (++i >= j)
j = i + 1;
System.out.println(Arrays.toString(mi_array));
// -> [9, 4, 4, 3, 1, 8, 0, 0, 0, 0, 0]
You can use filter and IntStream.concat to merge the parts of the array that are not 0 with the parts that are.
final int[] mi_array = { 9, 4, 0, 0, 4, 0, 3, 0, 1, 8, 0 };
final int[] result = IntStream.concat(Arrays.stream(mi_array).filter(i -> i != 0),
Arrays.stream(mi_array).filter(i -> i == 0)).toArray();
System.out.println(Arrays.toString(result));
Demo!
You can also do this:
final int[] mi_array = { 9, 4, 0, 0, 4, 0, 3, 0, 1, 8, 0 };
final int[] result = new int[mi_array.length];
final AtomicInteger idx = new AtomicInteger();
Arrays.stream(mi_array).filter(i -> i != 0).forEach(val -> result[idx.getAndIncrement()] = val);
System.out.println(Arrays.toString(result));
Your primary problem here is that you overwrite numbers you haven't already covered.
if (mi_array[i] != 0) {
mi_array[x] = mi_array[i];
x++;
}
x can never exceed i in this code; it starts at 0 just like i does, and increments at most by 1 every loop (and i increments by 1 every loop). So, no problem here; at 'worst' this is mi_array[i] = mi_array[i]; which does nothing.
however...
} else {
mi_array[y]=mi_array[i];
y--;
}
This is much more problematic. Given inputs {9,4,0,0,4,0,3,0,1,8,0};, when i is 2, then mi_array[i] is 0, thus this code runs. y is still 10, so this will end up running: mi_array[10] = 0;. The second 0 occurs when i is 3, and ends up running: mi_array[9] = 0;. And at that point, the 8 at index 9? You deleted it. It cannot be recovered.
The solution
The dumb solution is to make a copy of the array; edit the copy, refer to the original (which you won't change at all). You don't actually end up needing a copy; this code will write every number back, so just make a new array of the same size and write in that.
A slightly more elegant solution will not write 0s at all. Instead, it just writes the non-zeroes (as that code cannot overwrite anything, as shown before), and then at the end, overwrite the rest with zeroes. Now you don't need a copy.
O(n), two-pointer approach:
public static void shiftZeroesRight(int[] array) {
int notZeroPos;
for (int i = 0; i < array.length; i++) {
if (array[i] != 0)
continue;
notZeroPos = i + 1;
while (notZeroPos < array.length && array[notZeroPos] == 0)
++notZeroPos;
if (notZeroPos >= array.length)
break;
array[i] = array[notZeroPos];
array[notZeroPos] = 0;
}
}
At 0th index value is 4, so I have to check the value at index 4 and square it and place the value at 0th index without using a temp array:
Index 0 1 2 3 4
Values 4 3 1 2 0
================
Result 0 4 9 1 16
Now I am getting the first two values right, but the last three are not right. My code is as below:
static void Index(int arr[], int n) {
for(int i=0;i<n;i++) {
int index = arr[i];
int value = arr[index];
arr[i]=value*value;
}
}
Below is the output that I am getting:
Original Array
4 3 1 2 0
Array after Squaring
0 4 16 256 0
Can anyone help me out here as to what am I doing wrong?
Assuming the numbers are within range [0, 46341), we can store both the old and the new values in the array during the process (as 32 bits are enough). Then after the first loop we do another one to discard the old values and square the new ones.
// assume array[i] is within range [0, 46341) for any i
static void f(int[] array) {
for (int i = 0; i < array.length; i++) {
int j = array[i] & 0xffff; // get old value
array[i] = array[j] << 16 | j; // put new and old values
}
for (int i = 0; i < array.length; i++) {
int j = array[i] >>> 16; // get new value
array[i] = j * j; // put new value squared
}
}
NOTE: This approach is valid only if length of array is less than 10.
I have completed this code using only one loop without using any extra space.
Although, I have set a flag to run the complete loop twice.
If you do not have any constraint of using one loop, you can avoid using the flag and simply use two loops.
Approach:
Index 0 1 2 3 4
Values 4 3 1 2 0
Updated value 04 23 31 12 40
You must have got the idea what I did here.
I put the values at tens place whose square is to be displayed.
Now you have to just have to iterate once more and put the square of tens place at that index
Here's the code:
void sq(int arr[], int n){
bool flag = false;
for(int i=0; i<n; i++){
if(!flag){
if(arr[arr[i]] < 10){
arr[i] += (arr[arr[i]] * 10);
}
else{
arr[i] += ((arr[arr[i]]%10) * 10);
}
}
if(i==n-1 && !flag){
i=0;
flag = true;
}
if(flag)
arr[i] = (arr[i]/10) * (arr[i]/10);
}
}
It is in C++.
The problem is you are changing the values in your original array. In you current implementation this is how your array changes on each iteration:
{4, 3, 1, 2, 0}
{0, 3, 1, 2, 0}
{0, 4, 1, 2, 0}
{0, 4, 16, 2, 0}
{0, 4, 16, 256, 0}
The problem is you still need the values stored in the original array for each iteration. So the solution is to leave the original array untouched and put your values into a new array.
public static void index(int arr[]) {
int[] arr2 = new int[arr.length];
for(int i=0;i<arr.length;i++) {
int index = arr[i];
int value = arr[index];
arr2[i]=value*value;
}
}
Values of arr2 in revised process:
{0, 0, 0, 0, 0}
{0, 0, 0, 0, 0}
{0, 4, 0, 0, 0}
{0, 4, 9, 0, 0}
{0, 4, 9, 1, 0}
{0, 4, 9, 1, 16}
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.