Get closest "1" to the left - java

I have a 2D Array:
{0, 0, 1, 1, 1},
{0, 0, 1, 1, 1},
{0, 0, 1, 1, 1},
{0, 1, 0, 0, 1}
and I am trying to see which row has the closest 1 to the left, in this case it is index 3. So we have to return 3 to console, but I don't know how to go about comparing the values, etc.
This is what I have tried so far:
int array[][] = {
{0, 0, 1, 1, 1},
{0, 0, 1, 1, 1},
{0, 0, 1, 1, 1},
{0, 1, 0, 0, 1}
};
int count = 0;
Map<Integer, Integer> countMap = new HashMap<>();
for(int i = 0; i < array.length; i++){
for(int j = 0; j < array[i].length; j++){
if(array[i][j] != 1){
count++;
}else{
System.out.println("index of i: " + i + ", index of j:" + j + ", count: " + count);
countMap.put(j, count);
count = 0;
break;
}
}
}
System.out.println();

You can try to iterate in a column wise manner and return result as soon as you encounter the first '1'. This way you don't need to spend extra computation iterating through the whole 2D matrix.
public class ClosestOne {
public static int closestOne(int[][] a) {
for(int i = 0; i < a[0].length; i++) {
for(int j = 0; j < a.length; j++) {
if(a[j][i] == 1) {
return j;
}
}
}
return -1;
}
public static void main(String[] args) {
int array[][] = {
{0, 0, 1, 1, 1},
{0, 0, 1, 1, 1},
{0, 0, 1, 1, 1},
{0, 1, 0, 0, 1}
};
int closestRow = closestOne(array);
if(closestRow == -1) {
System.out.println("'1' is not present in matrix!");
} else {
System.out.println("Closest '1' is in row: " + closestRow );
}
}
}

Using a HashMap is completely over-engineered here. Theoretically you do not need any kind of data structure since you calculate the values row-by-row anyways, but since you were using one, I thought I would use one, too.
Use a simple array instead of the Map, with the length of the original array (i.e. the rows). Fill that array with a number that is higher than any result can be, to be safe I used Integer.MAX_VALUE.
int[] firstIndex = new int[array.length];
//for all i in length of array:
firstIndex[i] = Integer.MAX_VALUE;
No iterate though your your 2d array like you are and overwrite the firstIndex if you find something that is better than the current value.
//for every row
//for ever column (col)
if (array[row][col] == 1 && col < firstIndex[row]) {
firstIndex[row] = col;
}
Then in the end look for the minimum value in that array.
int min = firstIndex[0];
for (int row = 1; row < firstIndex.length; row++) {
min = Integer.min(min, firstIndex[row]);
}
System.out.println(min);

It looks like you have already worked out the count to the first 1 on each row, you just need to decide which is the lowest after completing your loop. You don't need a map to do that, just check if the current row is better than the "best so far" and if it is then update the best.
There is actually no need for a count variable since j is the same thing, and i is the row.
int best = -1; // Initialize to -1 which is an invalid index
int bestCount = Integer.MAX_VALUE; // Initialize to a very bad best count.
for(int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
if (array[i][j] == 1 && j < bestCount) {
best = i; // the row
bestCount = j; // the '1'
break;
}
}
}
System.out.println("Closest 1 to left in row " + best);

Related

How to calculate the sum of each column in a 2D array?

I'm writing a program so that it computes and prints the sum of each column of the array. The given data looks like this:
int[][] data = {{3, 2, 5},
{1, 4, 4, 8, 13},
{9, 1, 0, 2},
{0, 2, 6, 3, -1, -8}};
Ideally, it should output the results 13, 9, 15, 13, 12, -8. But since some of the rows have different lengths, when I run my program, it outputs 13, 9, 15 and gives me an ArrayIndexOutOfBoundsException. And I really don't know how to fix it.
Here is my code:
public class ColumnSums
{
public static void main(String[] args) {
//The given data
int[][] data = {{3, 2, 5},
{1, 4, 4, 8, 13},
{9, 1, 0, 2},
{0, 2, 6, 3, -1, -8}};
//Determine the number of data in the longest row
int LongestRow = 0;
for ( int row=0; row < data.length; row++){
if ( data[row].length > LongestRow ){
LongestRow = data[row].length;
}
}
System.out.println("The longest row in the array contains " + LongestRow + " values"); //Testing
//Save each row's length into a new array (columnTotal)
int[] columnTotal = new int[4];
//Scan through the original data again
//Record each row's length into a new array (columnTotal)
System.out.println("The lengths of each row are: ");
for ( int i = 0; i < data.length; i++){
columnTotal[i] = data[i].length;
System.out.println(columnTotal[i]); //Testing
}
// Create an array to store all the sums of column
int ColumnSums[] = new int[LongestRow];
System.out.println("The sums of each column are: ");
for ( int i = 0; i < LongestRow; i++ ){
int sum = 0;
for (int j = 0; j < data.length; j++) {
sum = sum + data[j][i];
}
ColumnSums[i] = sum;
System.out.println("Column " + i + ": " + ColumnSums[i]); //Testing
}
}
}
Thanks for your time!!!
You basically just need to loop through the columns until the counter is out of bounds for every row. No need to loop through ahead of time to find the longest row.
public static ArrayList<Integer> getCollumnSum() {
int[][] data = {{3, 2, 5},
{1, 4, 4, 8, 13},
{9, 1, 0, 2},
{0, 2, 6, 3, -1, -8}};
int col = 0;
ArrayList<Integer> totals = new ArrayList<Integer>();
while (true) {
int total = 0;
boolean dataInCol = false;
for (int i = 0; i < data.length; i++) {
if (col < data[i].length) {
total += data[i][col];
dataInCol = true;
}
}
col += 1;
if (dataInCol) {
totals.add(total);
} else {
break;
}
}
return totals;
}
Output:
[13, 9, 15, 13, 12, -8]
To read a 2D array your loops should be
for(int i = 0; i < array.length; ++i){
for(int j = 0; j < array[i].length; ++j){
System.out.println(array[i][j]);
}
}
See the use of for(int j = 0; j < array[i].length; ++j) to use the current row length.
With this, you will prevent this ArrayIndexOutOfBoundsException
I am open to question if you need. Just post a comment !
I have altered your code to fit your needs
int[][] data = {{3, 2, 5},
{1, 4, 4, 8, 13},
{9, 1, 0, 2},
{0, 2, 6, 3, -1, -8}};
int longestRow = 0;
for ( int row=0; row < data.length; row++){
if ( data[row].length > longestRow ){
longestRow = data[row].length;
}
}
System.out.println("The longest row in the array contains " + longestRow + " values");
Here, no need for columnTotal as I can't notice any use of it. It maybe your program need. Anyway, you can print the length of each row directly as below.
System.out.println("The lengths of each row are: ");
for ( int i = 0; i < data.length; i++){
System.out.println("Row " + i + " is " + data[i].length);
}
You can't get the sum of each column at each inner loop, because the sum of each column will be obtained after the both loops finish. Therefore, the variable sum is useless. So, it would be like below
int columnSums[] = new int[longestRow];
for ( int i = 0; i < data.length; i++ ){
for (int j = 0; j < data[i].length; j++){
columnSums[j] +=data[i][j];
}
}
Finally, you can print the sum of each column as below
System.out.println("The sums of each column are: ");
for (int i = 0; i < columnSums.length; i++) {
System.out.println("Column " + i + ": " + columnSums[i]);
}
After running the code, the output would be:
The longest row in the array contains 6 values
The lengths of each row are:
Row 0 is 3
Row 1 is 5
Row 2 is 4
Row 3 is 6
The sums of each column are:
Column 0: 13
Column 1: 9
Column 2: 15
Column 3: 13
Column 4: 12
Column 5: -8

How can I find three of the same numbers in a row?

I have an array something like the following.
int[][] myArray =
{{1, 2, 3, 0, 0, 1}
{1, 0, 4, 4, 0, 1}
{1, 2, 4, 3, 4, 0}
{2, 2, 0, 0, 2, 2}
{3, 0, 0, 3, 0, 0}
{4, 2, 3, 0, 0, 0}}
It would say that one had won because of the 1s in the three 1s in the first column. Two would not win because they are not in a "row".
I want to do some sort of win checking so that it finds three of the same number in a row, diagonal or column. Sort of like tic-tac-toe but with a larger grid. Before I used a messy set of if statements and goto statements. (It was written in Basic.) I have tried using a system where it found the directions from the last placed piece, in which there is a number of the same, but it didn't work properly. How can I do this in an easy and maintainable way?
Tried code:
private static boolean checkBoardCombinations(int[][] board, int inputX, int inputY) {
int currentPlayer = board[inputX-1][inputY-1];
boolean[][] directions = new boolean[3][3];
for(int y = 0; y >= -2; y--){
for(int x = 0; x >= -2; x--){
if(inputX+x >= 0 && inputX+x <= 7 && inputY+y >= 0 && inputY+y <= 7
&& (board[inputX+x][inputY+y] == currentPlayer)){
//System.out.printf("X: %s Y: %s", inputX+x, inputY+y);
directions[x+2][y+2] = true;
}
else{
directions[x+2][y+2] = false;
}
//System.out.printf("X: %s Y: %s B: %s,", inputX+x, inputY+y, directions[x+2][y+2]);
}
//System.out.println();
}
/*
for(int x = 0; x <= 2; x++){
for(int y = 0; y <= 2; y++){
System.out.print(directions[x][y] + " ");
}
System.out.println();
}
*/
return false;
}
Supposing the number of players are known, you can iterate over all the players one by one, and check if any player is forming a connection of required length or not.
Such code would look like following:
private int[][] grid; // Your array of size ROWS x COLUMNS
private final int ROWS = 6, COLUMNS = 6;
private final int CONSECUTIVE_CONNECTION_REQUIRED = 3;
// Returns true if given playerType is forming a connection, else false.
public boolean checkGrid(int playerType)
{
// Check downward
for (int i = 0; i <= ROWS - CONSECUTIVE_CONNECTION_REQUIRED; i++)
{
for (int j = 0; j < COLUMNS; j++)
{
int counter = 0;
for (int k = i; k < CONSECUTIVE_CONNECTION_REQUIRED + i; k++)
{
if (grid[k][j] == playerType)
counter++;
}
if (counter == CONSECUTIVE_CONNECTION_REQUIRED)
return true;
}
}
// Check across
for (int i = 0; i <= COLUMNS - CONSECUTIVE_CONNECTION_REQUIRED; i++)
{
for (int j = 0; j < ROWS; j++)
{
int counter = 0;
for (int k = i; k < CONSECUTIVE_CONNECTION_REQUIRED + i; k++)
{
if (grid[j][k] == playerType)
counter++;
}
if (counter == CONSECUTIVE_CONNECTION_REQUIRED)
return true;
}
}
// Check left to right diagonally
for (int i = 0; i <= ROWS - CONSECUTIVE_CONNECTION_REQUIRED; i++)
{
for (int j = 0; j <= COLUMNS - CONSECUTIVE_CONNECTION_REQUIRED; j++)
{
int counter = 0;
for (int k = i, m = j; k < CONSECUTIVE_CONNECTION_REQUIRED + i; k++, m++)
{
if (grid[k][m] == playerType)
counter++;
}
if (counter == CONSECUTIVE_CONNECTION_REQUIRED)
return true;
}
}
// Check right to left diagonally
for (int i = 0; i <= ROWS - CONSECUTIVE_CONNECTION_REQUIRED; i++)
{
for (int j = COLUMNS - 1; j >= COLUMNS - CONSECUTIVE_CONNECTION_REQUIRED; j--)
{
int counter = 0;
for (int k = i, m = j; k < CONSECUTIVE_CONNECTION_REQUIRED + i; k++, m--)
{
if (grid[k][m] == playerType)
counter++;
}
if (counter == CONSECUTIVE_CONNECTION_REQUIRED)
return true;
}
}
return false;
}
Where playerType is 0, 1, 2, 3 and so on...
You can use checkGrid() method like following:
for(int i = MIN_PLAYER_NUMBER; i <= MAX_PLAYER_NUMBER; i++)
{
if(checkGrid(i))
{
// Player i is forming the connection!!!
}
}
But if you don't want to iterate over your grid this many times, then drop your two dimensional array, and use a graph with adjacency list representation. Write a proper API for that which lets you make changes in your particular representation easily, and you can then find if any player is making a connection of particular length in the graph or not, in less iterations.
Although you already accepted an answer I thought to also submit you my answer for diversity :)
public static void main (String[] args)
{
int[][] myArray =
{{1, 2, 3, 0, 0, 1},
{1, 0, 4, 4, 0, 1},
{1, 2, 4, 3, 4, 0},
{2, 2, 0, 0, 2, 2},
{3, 0, 0, 3, 0, 0},
{4, 2, 3, 0, 0, 0}};
System.out.println(testForWinner(myArray));
}
/**
* Returns -1 if no winner
*/
static int testForWinner(int[][] ar) {
for(int i=0; i<ar.length; i++) {
for(int j=0; j<ar[i].length; j++) {
if(checkNext(ar, i, j, 0, 1, 1)) { //Check the element in the next column
return ar[i][j];
}
for(int k=-1; k<=1; k++) { //Check the three adjacent elements in the next row
if(checkNext(ar, i, j, 1, k, 1)) {
return ar[i][j];
}
}
}
}
return -1;
}
/**
* Step number `step` starting at `ar[i][j]` in direction `(di, dj)`.
* If we made 3 steps we have a winner
*/
static boolean checkNext(int[][] ar, int i, int j, int di, int dj, int step) {
if(step==3) {
return true;
}
if(i+di<0 || i+di>ar.length-1 || j+dj<0 || j+dj>ar[i].length-1) {
return false;
}
if(ar[i+di][j+dj]==ar[i][j]) {
return checkNext(ar, i+di, j+dj, di, dj, step+1);
}
return false;
}
See it in action: http://ideone.com/Ou2sRh

Move 0's to end of array

I need to move all 0's in an array to the end of the array.
Example: [1, 10, 0, 5, 7] should result in [1, 10, 5, 7, 0].
I am open to doing a reverse loop or a regular loop.
I cannot create a new array.
Here is what I have so far:
for (int i = arr.length; i <= 0; --i) {
if (arr[i] != 0) {
arr[i] = arr.length - 1;
}
}
Thanks!
SIZE(n) where n = arr.size, retain ordering:
Create an array that is the same size as the initial array you need to remove 0s from. Iterate over the original array and add each element to the new array provided it is not 0. When you encounter a 0, count it. Now, when you've reached the end of the first array, simply add the counted number of 0s to the end of the array. And, even simpler, since Java initializes arrays to 0, you can forget about adding the zeroes at the end.
Edit
Since you have added the additional constraint of not being able to create a new array, we need to take a slightly different approach than the one I've suggested above.
SIZE(1)
I assume the array needs to remain in the same order as it was before the 0s were moved to the end. If this is not the case there is another trivial solution as detailed in Brads answer: initialize a "last zero" index to the last element of the array and then iterate backwards swapping any zeros with the index of the last zero which is decremented each time you perform a swap or see a zero.
SIZE(1), retain ordering:
To move the 0s to the end without duplicating the array and keeping the elements in the proper order, you can do exactly as I've suggested without duplicating the array but keeping two indices over the same array.
Start with two indices over the array. Instead of copying the element to the new array if it is not zero, leave it where it is and increment both indices. When you reach a zero, increment only one index. Now, if the two indices are not the same, and you are not looking at a 0, swap current element the location of the index that has fallen behind (due to encountered 0s). In both cases, increment the other index provided the current element is not 0.
It will look something like this:
int max = arr.length;
for (int i = 0, int j = 0; j < max; j++) {
if (arr[j] != 0) {
if (i < j) {
swap(arr, i, j);
}
i++
}
}
Running this on:
{ 1, 2, 0, 0, 0, 3, 4, 0, 5, 0 }
yeilds:
{ 1, 2, 3, 4, 5, 0, 0, 0, 0, 0 }
I made a fully working version for anyone who's curious.
Two choices come to mind
Create a new array of the same size, then Iterate over your current array and only populate the new array with values. Then fill the remaining entries in the new array with "zeros"
Without creating a new array you can iterate over your current array backwards and when you encounter a "zero" swap it with the last element of your array. You'll need to keep a count of the number of "zero" elements swapped so that when you swap for a second time, you swap with the last-1 element, and so forth.
[Edit] 7 years after originally posting to address the "ordering" issue and "last element is zero" issues left in the comments
public class MyClass {
public static void main(String[] args) {
int[] elements = new int[] {1,0,2,0,3,0};
int lastIndex = elements.length-1;
// loop backwards looking for zeroes
for(int i = lastIndex; i >=0; i--) {
if(elements[i] == 0) {
// found a zero, so loop forwards from here
for(int j = i; j < lastIndex; j++) {
if(elements[j+1] == 0 || j == lastIndex) {
// either at the end of the array, or we've run into another zero near the end
break;
}
else {
// bubble up the zero we found one element at a time to push it to the end
int temp = elements[j+1];
elements[j+1] = elements[j];
elements[j] = temp;
}
}
}
}
System.out.println(Arrays.toString(elements));
}
}
Gives you...
[1, 2, 3, 0, 0, 0]
Basic solution is to establish an inductive hypothesis that the subarray can be kept solved. Then extend the subarray by one element and maintain the hypothesis. In that case there are two branches - if next element is zero, do nothing. If next element is non-zero, swap it with the first zero in the row.
Anyway, the solution (in C# though) after this idea is optimized looks like this:
void MoveZeros(int[] a)
{
int i = 0;
for (int j = 0; j < a.Length; j++)
if (a[j] != 0)
a[i++] = a[j];
while (i < a.Length)
a[i++] = 0;
}
There is a bit of thinking that leads to this solution, starting from the inductive solution which can be formally proven correct. If you're interested, the whole analysis is here: Moving Zero Values to the End of the Array
var size = 10;
var elemnts = [0, 0, 1, 4, 5, 0,-1];
var pos = 0;
for (var i = 0; i < elemnts.length; i++) {
if (elemnts[i] != 0) {
elemnts[pos] = elemnts[i];
pos++;
console.log(elemnts[i]);
}
}
for (var i = pos; i < elemnts.length; i++) {
elemnts[pos++] = 0;
console.log(elemnts[pos]);
}
int arrNew[] = new int[arr.length];
int index = 0;
for(int i=0;i<arr.length;i++){
if(arr[i]!=0){
arrNew[index]=arr[i];
index++;
}
}
Since the array of int's is initialized to zero(according to the language spec). this will have the effect you want, and will move everything else up sequentially.
Edit: Based on your edit that you cannot use a new array this answer doesnt cover your requirements. You would instead need to check for a zero(starting at the end of the array and working to the start) and swap with the last element of the array and then decrease the index of your last-nonzero element that you would then swap with next. Ex:
int lastZero = arr.length - 1;
if(arr[i] == 0){
//perform swap and decrement lastZero by 1 I will leave this part up to you
}
/// <summary>
/// From a given array send al zeros to the end (C# solution)
/// </summary>
/// <param name="numbersArray">The array of numbers</param>
/// <returns>Array with zeros at the end</returns>
public static int[] SendZerosToEnd(int[] numbersArray)
{
// Edge case if the array is null or is not long enough then we do
// something in this case we return the same array with no changes
// You can always decide to return an exception as well
if (numbersArray == null ||
numbersArray.Length < 2)
{
return numbersArray;
}
// We keep track of our second pointer and the last element index
int secondIndex = numbersArray.Length - 2,
lastIndex = secondIndex;
for (int i = secondIndex; i >= 0; i--)
{
secondIndex = i;
if (numbersArray[i] == 0)
{
// While our pointer reaches the end or the next element
// is a zero we swap elements
while (secondIndex != lastIndex ||
numbersArray[secondIndex + 1] != 0)
{
numbersArray[secondIndex] = numbersArray[secondIndex + 1];
numbersArray[secondIndex + 1] = 0;
++secondIndex;
}
// This solution is like having two pointers
// Also if we look at the solution you do not pass more than
// 2 times actual array will be resume as O(N) complexity
}
}
// We return the same array with no new one created
return numbersArray;
}
In case if question adds following condition.
Time complexity must be O(n) - You can iterate only once.
Extra
space complexity must be O(1) - You cannot create extra array.
Then following implementation will work fine.
Steps to be followed :
Iterate through array & maintain a count of non-zero elements.
Whenever we encounter a non-zero element put at count location in array & also increase the count.
Once array is iterated completely put the zeros at end of array till the count reach to original length of array.
public static void main(String args[]) {
int[] array = { 1, 0, 3, 0, 0, 4, 0, 6, 0, 9 };
// Maintaining count of non zero elements
int count = -1;
// Iterating through array and copying non zero elements in front of array.
for (int i = 0; i < array.length; i++) {
if (array[i] != 0)
array[++count] = array[i];
}
// Replacing end elements with zero
while (count < array.length - 1)
array[++count] = 0;
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
}
Time complexity = O(n), Space Complexity = O(1)
import java.util.Scanner;
public class ShiftZeroesToBack {
int[] array;
void shiftZeroes(int[] array) {
int previousK = 0;
int firstTime = 0;
for(int k = 0; k < array.length - 1; k++) {
if(array[k] == 0 && array[k + 1] != 0 && firstTime != 0) {
int temp = array[previousK];
array[previousK] = array[k + 1];
array[k + 1] = temp;
previousK = previousK + 1;
continue;
}
if(array[k] == 0 && array[k + 1] != 0) {
int temp = array[k];
array[k] = array[k + 1];
array[k + 1] = temp;
continue;
}
if(array[k] == 0 && array[k + 1] == 0) {
if(firstTime == 0) {
previousK = k;
firstTime = 1;
}
}
}
}
int[] input(Scanner scanner, int size) {
array = new int[size];
for(int i = 0; i < size; i++) {
array[i] = scanner.nextInt();
}
return array;
}
void print() {
System.out.println();
for(int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
System.out.println();
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
ShiftZeroesToBack sztb = new ShiftZeroesToBack();
System.out.print("Enter Size of Array\t");
int size = scanner.nextInt();
int[] input = sztb.input(scanner, size);
sztb.shiftZeroes(input);
sztb.print();
}
}
let's say we have an array
[5,4,0,0,6,7,0,8,9]
Let's assume we have array elements between 0-100, now our goal is to move all 0's at the end of the array.
now hold 0 from the array and check it with non zero element if any non zero element found swap with that element and so on, at the end of the loop we will find the solution.
here is the code
for (int i = 0; i < outputArr.length; i++)
{
for (int j = i+1; j < outputArr.length; j++)
{
if(outputArr[i]==0 && outputArr[j]!=0){
int temp = outputArr[i];
outputArr[i] = outputArr[j];
outputArr[j] = temp;
}
}
print outputArr[i]....
}
output:
[5,4,6,7,8,9,0,0,0]
Here is how i have implemented this.
Time complexity: O(n) and Space Complexity: O(1)
Below is the code snippet:
int arr[] = {0, 1, 0, 0, 2, 3, 0, 4, 0};
int i=0, k = 0;
int n = sizeof(arr)/sizeof(arr[0]);
for(i = 0; i<n; i++)
{
if(arr[i]==0)
continue;
arr[k++]=arr[i];
}
for(i=k;i<n;i++)
{
arr[i]=0;
}
output: {1, 2, 3, 4, 0, 0, 0, 0, 0}
Explanation: using another variable k to hold index location, non-zero elements are shifted to the front while maintaining the order. After traversing the array, non-zero elements are shifted to the front of array and another loop starting from k is used to override the remaining positions with zeros.
This is my code with 2 for loops:
int [] arr = {0, 4, 2, 0, 0, 1, 0, 1, 5, 0, 9,};
int temp;
for (int i = 0; i < arr.length; i++)
{
if (arr[i] == 0)
{
for (int j = i + 1; j < arr.length; j++)
{
if (arr[j] != 0)
{
temp = arr[j];
arr[j] = arr[i];
arr[i] = temp;
break;
}
}
}
}
System.out.println(Arrays.toString(arr));
output: [4, 2, 1, 1, 5, 9, 0, 0, 0, 0, 0]
public static void main(String[] args) {
Integer a[] = {10,0,0,0,6,0,0,0,70,6,7,8,0,4,0};
int flag = 0;int count =0;
for(int i=0;i<a.length;i++) {
if(a[i]==0 ) {
flag=1;
count++;
}else if(a[i]!=0) {
flag=0;
}
if(flag==0 && count>0 && a[i]!=0) {
a[i-count] = a[i];
a[i]=0;
}
}
}
This is One method of Moving the zeroes to the end of the array.
public class SeparateZeroes1 {
public static void main(String[] args) {
int[] a = {0,1,0,3,0,0,345,12,0,13};
movezeroes(a);
}
static void movezeroes(int[] a) {
int lastNonZeroIndex = 0;
// If the current element is not 0, then we need to
// append it just in front of last non 0 element we found.
for (int i = 0; i < a.length; i++) {
if (a[i] != 0 ) {
a[lastNonZeroIndex++] = a[i];
}
}//for
// We just need to fill remaining array with 0's.
for (int i = lastNonZeroIndex; i < a.length; i++) {
a[i] = 0;
}
System.out.println( lastNonZeroIndex );
System.out.println(Arrays.toString(a));
}
}
This is very simple in Python. We will do it with list comprehension
a =[0,1,0,3,0,0,345,12,0,13]
def fix(a):
return ([x for x in a if x != 0] + [x for x in a if x ==0])
print(fix(a))
int[] nums = { 3, 1, 2, 5, 4, 6, 3, 2, 1, 6, 7, 9, 3, 8, 0, 4, 2, 4, 6, 4 };
List<Integer> list1 = new ArrayList<>();
List<Integer> list2 = new ArrayList<>();
for (int i = 0; i < nums.length; i++) {
if (nums[i] == 3) {
list1.add(nums[i]);
} else if (nums[i] != 3) {
list2.add(nums[i]);
}
}
List<Integer> finalList = new ArrayList<>(list2);
finalList.addAll(list1);
}
}
int[] nums = {3,1,2,5,4,6,3,2,1,6,7,9,3,8,0,4,2,4,6,4};
int i = 0;
for(int j = 0, s = nums.length; j < s;) {
if(nums[j] == 3)
j++;
else {
int temp = nums[i];
nums[i] = nums[j];``
nums[j] = temp;
i ++;
j ++;
}
}
For Integer array it can be as simple as
Integer[] numbers = { 1, 10, 0, 5, 7 };
Arrays.sort(numbers, Comparator.comparing(n -> n == 0));
For int array :
int[] numbers = { 1, 10, 0, 5, 7 };
numbers = IntStream.of(numbers).boxed()
.sorted(Comparator.comparing(n -> n == 0))
.mapToInt(i->i).toArray();
Output of both:
[1, 10, 5, 7, 0]
Lets say, you have an array like
int a[] = {0,3,0,4,5,6,0};
Then you can sort it like,
for(int i=0;i<a.length;i++){
for(int j=i+1;j<a.length;j++){
if(a[i]==0 && a[j]!=0){
a[i]==a[j];
a[j]=0;
}
}
}
public void test1(){
int [] arr = {0,1,0,4,0,3,2};
System.out.println("Lenght of array is " + arr.length);
for(int i=0; i < arr.length; i++){
for(int j=0; j < arr.length - i - 1; j++){
if(arr[j] == 0){
int temp = arr[j];
arr[j] = arr[arr.length - i - 1];
arr[arr.length - i - 1] = temp;
}
}
}
for(int x = 0; x < arr.length; x++){
System.out.println(arr[x]);
}
}
Have a look at this function code:
vector<int> Solution::solve(vector<int> &arr) {
int count = 0;
for (int i = 0; i < arr.size(); i++)
if (arr[i] != 0)
arr[count++] = arr[i];
while (count < arr.size())
arr[count++] = 0;
return arr;
}
import java.io.*;
import java.util.*;
class Solution {
public static int[] moveZerosToEnd(int[] arr) {
int j = 0;
for(int i = 0; i < arr.length; i++) {
if(arr[i] != 0) {
swap(arr, i, j);
j++;
}
}
return arr;
}
private static void swap(int arr[], int i, int j){
int temp = arr[j];
arr[j] = arr[i];
arr[i] = temp;
}
public static void main(String[] args) {
int arr[] =new int[] {1, 10, 0, 2, 8, 3, 0, 0, 6, 4, 0, 5, 7, 0 };
System.out.println(Arrays.toString(moveZerosToEnd(arr)));
}
}
Reimplemented this in Python:
Pythonic way:
lst = [ 1, 2, 0, 0, 0, 3, 4, 0, 5, 0 ]
for i, val in enumerate(lst):
if lst[i] == 0:
lst.pop(i)
lst.append(0)
print("{}".format(lst))
#dcow's implementation in python:
lst = [ 1, 2, 0, 0, 0, 3, 4, 0, 5, 0 ]
i = 0 # init the index value
for j in range(len(lst)): # using the length of list as the range
if lst[j] != 0:
if i < j:
lst[i], lst[j] = lst[j], lst[i] # swap the 2 elems.
i += 1
print("{}".format(lst))
a = [ 1, 2, 0, 0, 0, 3, 4, 0, 5, 0 ]
count = 0
for i in range(len(a)):
if a[i] != 0:
a[count], a[i] = a[i], a[count]
count += 1
print(a)
#op [1, 2, 3, 4, 5, 0, 0, 0, 0, 0]

Printing Column

I'm having a problem printing columns. When the code reaches "100" it stops reading what is below it because it's empty:
public class Column{
public static void main( String[] arg )
{
int[][] uneven =
{ { 1, 3, 100, 6, 7, 8, 9, 10},
{ 0, 2},
{ 0, 2, 4, 5},
{ 0, 2, 4, 6, 7},
{ 0, 1, 4, 5 },
{ 0, 1, 2, 3, 4, 5, 6 }};
for ( int col=0; col < uneven.length; col++ )
{
System.out.print("Col " + col + ": ");
for( int row=0; row < uneven.length; row++ )
System.out.print( uneven[row][col] + " ");
System.out.println();
}
}
}
What should I do so that it will continue reading the column?
To print a variable length 2-D array, your inner loop runs from 0 to the current row length : -
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) { // Closely see inner loop
System.out.println(arr[i][j]);
}
}
arr[i] is the current row. And arr[i].length gives the number of columns in that row.
You can infer it like this: -
arr is a 2-D array.
So, each element of your arr is a 1-D array.
So, arr[i] is a 1-D array. Which represents each row.
To get number of columns in each row, you do arr[i].length
Now, you can apply the same thing in your problem.
Actually, your for loop is running wrongly. Your outer loop is running from col = 0 to col < uneven.length, but it should run from: - row = 0 to row < uneven.length
So, your for loop should be like: -
for ( int row=0; row < uneven.length; row++ )
{
System.out.print("Row " + row + ": ");
for( int col=0; col < uneven[row].length; col++ ) {
System.out.print( uneven[row][col] + " ");
}
System.out.println();
}
UPDATED : -
Ok, I got your question wrong first. If you want to print column wise, you can use this code: -
int[][] uneven =
{ { 1, 3, 100, 6, 7, 8, 9, 10},
{ 0, 2},
{ 0, 2, 4, 5},
{ 0, 2, 4, 6, 7},
{ 0, 1, 4, 5 },
{ 0, 1, 2, 3, 4, 5, 6 }};
int max = -1;
for ( int row = 0; row < uneven.length; row++ ) {
if (uneven[row].length > max) {
max = uneven[row].length;
}
}
System.out.println(max);
for (int i = 0; i < max; i++) {
for (int j = 0; j < uneven.length; j++) {
if (uneven[j].length <= i) {
continue;
}
System.out.print(uneven[j][i] + " ");
}
System.out.println();
}
First you need to find the max among all number of columns in each row.
Then run the loop again, from 0 to max columns. Now, since you have a lop for columns, now you need another one for rows. And that will be your inner loop.
Now, in inner loop, you cannot just print the array element at the (j, i) index, because the current row might not have max number of columns. So, you need to put an if-condition to check that.
Replace:
for( int row=0; row < uneven.length; row++ )
with:
for( int row=0; row < uneven[col].length; row++ )

difficulty with arrays

I am a bit stuck so if anyone has a spare moment it would be a great help for me. I am using eclipse and the program is compiling and running. but there is a runtime error.
in the array {2, 1, 1, 2, 3, 3, 2, 2, 2, 1} I want to print {2, 2, 2} which is the numbers with the highest repeating times in the array. What I am getting is:
0
1
0
0
3
0
2
2
0
Thank you guys and here is my code.
public class SameIndexInArray
{
public static void main(String[] args)
{
int[] array = {2, 1, 1, 2, 3, 3, 2, 2, 2, 1};
int[] subarray = new int[array.length]; //store the values should be {2, 2, 2}
int max = 1;
int total = 1;
for(int i=0; i<array.length-1; i++)
{
if(array[i] != array[i + 1])
{
max = 1;
}
else if(array[i] == array[i + 1])
{
max++;
total = max;
subarray[i] = array[i]; // here is the issue
}
System.out.println(subarray[i]);
}
//System.out.println(total);
}
}
You only store facultatively into subarray, so you should define a separate counter (let's say j) for subarray index counting, and say subarray[j++] = array[i]. And, you shouldn't output subarray for each index of array, so move that println into the second if clause.
see if this works
int[] array = {2, 1, 1, 2, 3, 3, 2, 2, 2, 1};
int frequency = 0;
int num = 0;
for(int i=0; i<array.length-1; i++)
{
int lfreq = 1;
int lnum = array[i];
while(array[i] == array[i+1]){
lfreq++;
i++;
}
if(lfreq >= frequency){
frequency = lfreq;
num = lnum;
}
}
int[] subarray = new int[frequency];
for(int i=0; i < frequency; i++)
subarray[i] = num;
System.out.println(Arrays.toString(subarray));
You need to use another index but "i"
you can't relate to 2 arrays with the same index
Your problem is that all values in subarray are initialized with 0 and you only edit the values when there is an actual sequence, starting with the second element.
The whole subarray is unneccessary. Just save the start index and the length of the subquery ;)
What I mean is something like this:
int[] array = {2, 1, 1, 2, 3, 3, 2, 2, 2, 1};
int startIndex = 0;
int length = 0;
int longestIndex = 0;
int longestLength = 0;
for(int i=0; i<array.length-1; i++)
{
if(array[i] != array[i + 1])
{
if (length > longestLength) {
longestLength = length;
longestIndex = startIndex;
}
startIndex = i;
length = 1;
}
else if(array[i] == array[i + 1])
{
length++;
}
}
if (length > longestLength) {
longestLength = length;
longestIndex = startIndex;
}
Now you that you know where your longest sequence starts and how long it is you can build your new array:
int[] sequence = new int[longestLength];
for (int i = 0; i < longestLength; i++) {
sequence[i] = array[i + startIndex];
}
Thats because you are inserting at an index position "i" into subarray.
For example,
The second time the loop runs.
array[1] == array[2] is true and
subarray[i] = array[i];
runs. So at this moment the contents of subarray is {0,1,0,0,0,0,0,0,0}. Note that arrays are initialized to 0 by default.
This is how you could do it.
int[] array = {2, 1, 1, 2, 3, 3, 2, 2, 2, 1};
//store the values should be {2, 2, 2}
int max = 1;
int total = 1;
int value = 0;
for(int i=0; i<array.length-1; i++)
{
if(array[i] != array[i + 1])
{
max = 1;
}
else if(array[i] == array[i + 1])
{
max++;
total = max;
value = array[i];
}
}
int[] subarray = new int[total];
for(int i=0; i<total; i++)
subarray[i] = value;
public static void main(String[] args) {
int[] ar = { 2, 1, 1, 2, 3, 3, 2, 2, 2, 1 };
int max=0,
maxStart=0,
count=1;
for(int i=1; i<ar.length; i++) {
if (ar[i-1] == ar[i]) {
count++;
if(count > max) {
max = count;
maxStart = i-count+1;
}
}else {
count=1;
}
}
System.out.println("Sub array begins from " + maxStart);
for(int i = maxStart; i < maxStart + max; i++) {
System.out.print(ar[i] + " ");
}
}

Categories

Resources