Moving number to the end in an array [duplicate] - java

This question already has answers here:
Adding a number to midpoint af an array [closed]
(3 answers)
Closed 9 years ago.
The code below I have set the midpoint of the array to five but now I want to move the midpoint to the very end and as it moves to the end the other numbers will go to the left to fill the gap. No arraylists aloud.
int mid = length/2;
for (int i = array.length-1 ; i> mid; i--) {
array[i] = array[i-1];
}
array[mid] = 5;

Something like this?
int mid = array.length/2;
for (int i = mid; i < array.length-1; i++)
{
int temp = array[i];
array[i] = array[i+1];
array[i+1] = temp;
}

public static void main(String[] args) {
int array[] = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int mid = array.length / 2;
array[mid] = 5;
// my code starts here...
int aux = mid; // aux isn't necessary if you can lost mid value
int backup = array[mid]; // save the middle value
for (; aux < array.length - 1; aux++) { //starting at middle until the end of array
// current pos receives the next value;
array[aux] = array[aux + 1];
}
array[array.length - 1] = backup; // restore the middle value at the end;
}
That code transforms [1, 2, 3, 4, 5, 6, 7, 8, 9] in [1, 2, 3, 4, 6, 7, 8, 9, 5].
Is it that you want?

Related

Move a certain number to the front of an array (Java)

I need help with a code where I have to put the number "7" at the front of the array using a random array of numbers. I use Math.random to generate the random numbers in each index. In any of these indexes, a number 7 may be generated.
import java.util.Arrays;
public class NumberShifter {
public static int[] Array(){
int[] array = new int[20];
int max = 10;
int min = 1;
int rand = 0;
int range = max - min +1;
for(int t = 0;t<=array.length-1;t++) {
rand = (int)(Math.random() * range) + min;
array[t] = rand;
}
return array;
}
}
Here's an example output for the code I have displayed (its all random numbers)
[9, 6, 3, 4, 4, 10, 7, 5, 2, 10, 3, 1, 8, 7, 4, 4, 10, 5, 9, 1]
There are two sevens in this array that have been generated randomly.
I would like to have the output where the sevens are at the front.
[7, 7, 3, 4, 4, 10, 9, 5, 2, 10, 3, 1, 8, 6, 4, 4, 10, 5, 9, 1]
How would I write the rest of my code so that I can achieve this?
P.S. I'm also in high school, so I'm sorry if I get something wrong!
Iterate the elements of the array and if they are 7 swap them with the next element at the beginning of the array, using another variable to keep track of the next index for swapping.
int index = 0;
for (int i = 0; i < array.length; i++) {
if (array[i] == 7) {
int tmp = array[i]; // actually not needed, we know it's 7
array[i] = array[index];
array[index] = tmp; // or just 7
index++;
}
}
I would actually start at the end and reserve the front for the sevens.
public static int[] Array() {
int[] array = new int[20];
int max = 10;
int min = 1;
int rand = 0;
int range = max - min + 1;
int sevensGoHere = 0;
for (int t = array.length - 1; t >= sevensGoHere;) {
rand = (int) (Math.random() * range) + min;
if (rand == 7) {
array[sevensGoHere++] = rand;
}
else {
array[t--] = rand;
}
}
return array;
}
By doing it on the fly you don't need to rearrange the array.

Replace every element with next greatest element (in ascending order, not replacing with -1)

Currently working on an algorithm that replaces every element with the next greatest element, but unlike some other questions here, this one is not concerned with replacing values with -1 if no such number exists, and it must be in ascending order.
Given this input: {1, 5, -3, 2, 8, 4, 7, 10, 3, 11, 2 }
Have to get this output: 1 5 5 5 8 8 8 10 10 11 11
This is what I have so far:
class Playground {
static void nextGreatest(int arr[]) {
int size = arr.length;
// Initialize the next greatest element
int max_from_right = arr[size - 1];
// Replace all other elements with the next greatest
for (int i = 1; i < size; i++)
{
// Store the current element (needed later for
// updating the next greatest element)
int temp = arr[i];
// Replace current element with the next greatest
arr[i] = max_from_right;
// Update the greatest element, if needed
if(max_from_right < temp) {
max_from_right = temp;
}
}
}
// prints the array
static void printArray(int arr[])
{
for (int i=0; i < arr.length; i++)
System.out.print(arr[i]+" ");
}
public static void main (String[] args) {
int arr[] = {1, 5, -3, 2, 8, 4, 7, 10, 3, 11, 2 };
nextGreatest (arr);
printArray (arr);
}
}
And I get the following right now:
1 2 5 5 5 8 8 8 10 10 11
Thoughts?
Thanks
(Not sure I understand your question exactly, but based on the clarification from the comments here is my answer...)
Seems you just need to change the initial max initialization to the first element rather than the last element.
int currentMax = arr[0];
for (int i = 1; i < size; i++) {
int temp = arr[i];
arr[i] = currentMax;
if(currentMax < temp) {
currentMax = temp;
}
}
The solution ends up as For each index i, what is the maximum element seen so far.
Consider the following:
int currMax = -1;
int[] input = {1, 5, -3, 2, 8, 4, 7, 10, 3, 11, 2};
for (int i = 0; i < input.length; i++){
if (input[i] > currMax){ // if we find a new max element
currMax = input[i];
}
else if (input[i] < currMax){ // if value is less then max we replace it
input[i] = currMax;
}
}
System.out.println(Arrays.toString(input));
> [1, 5, 5, 5, 8, 8, 8, 10, 10, 11, 11]

Array swapLargest not passing all tests, BASIC JAVA

I've been trying to complete this problem for about 2 days now since it's the weekend and I can't contact any tutors at my school. I have made a loop that finds the highest value in a non-empty array and then swaps the lowest index of the highest number in that array with the last value in the array.
For example
swapLargest([1, 7, 5, 7, 4, 2]) → [1, 2, 5, 7, 4, 7]
but running it comes out as
[1, 7, 5, 7, 2, 4]
here is my code
int[] swapLargest(int[] a) {
int max = Integer.MIN_VALUE;
for(int i = 1; i <a.length; i++){ // starting from 0
if(a[i] > max){
max = a[i];
max = i;
}
}
int temp = a[max];
a[max]=a[a.length-1];
a[a.length-1] = temp;
return a;
}
and finally a link to the problem: http://codingbat.com/prob/p227094 if you'd like to test your results with mine. so far this would pass 4/11 tests.
I'm really new to programming, any tips would be appreciated.
Thanks!
You can store index of the max value in separate variable:
int[] swapLargest(int[] a) {
int max = Integer.MIN_VALUE;
int maxI = 0 ;
for(int i = 0; i < a.length; i++){
if(a[i] > max){
max = a[i];
maxI = i;
}
}
int temp = a[maxI];
a[maxI]=a[a.length-1];
a[a.length-1] = temp;
return a;
}

Returning the number of unique numbers in a sorted array [duplicate]

This question already has answers here:
How to efficiently remove duplicates from an array without using Set
(48 answers)
Closed 7 years ago.
I was asked to write a method that accepts a sorted array, removes any duplicate elements found in the array and then places a 0 at the end of the array for every duplicate element found.
It is also supposed to return the number of unique elements found in the array.
Here is my method:
public static int removeDups(int[] arr) {
int j = 0;
int i = 1;
int numDups = 0;
while(i < arr.length) {
if (arr[i] == arr[j]) {
i++;
numDups++;
}
else {
arr[++j] = arr[i++];
}
}
for (int k = j+1; k < arr.length; k++) {
arr[k] = 0;
}
return (j);
}
It successfully finds all the duplicate numbers in the array and places the correct number of 0s at the end, but it doesn't always return the correct value for the number of unique elements.
For example, for the array:
{ 6 10 19 21 23 26 27 36 38 45 }
the number of unique elements should be 10, but it returns 9.
What am I doing wrong?
As it can be seen, j is used as the index of the last unique element.
In an array, i'th index is actually the i + 1'th element counted from 1.
So, you have to return j + 1 instead of j from your method.
Here is a solution to your problem. It keeps track of two pointers, one which only advances when a value gets written to the array, and the other which touches every element of the array in sequential order. When one or more duplicates are encountered, the second pointer keeps advancing, while the first pointer stays put, waiting to write a non-duplicate value. Finally, the code iterates over the remainder of the array from the first pointer, writing out zeroes until the end.
public static int removeDups(int[] arr) {
if (arr == null) {
return null;
}
if (arr.length == 0 || arr.length == 1) {
return arr;
}
int prevIndex = 0;
for (int i=1; i < arr.length; ++i) {
if (arr[prevIndex] != arr[i]) {
arr[prevIndex+1] = arr[i];
++prevIndex;
}
}
for (int i=prevIndex+1; i < arr.length; ++i) {
arr[i] = 0;
}
return prevIndex+1;
}
int[] arr = {1, 2, 3, 3, 4, 5, 6, 6, 6, 10};
removeDups(arr);
System.out.println(Arrays.toString(arr));
Output:
[1, 2, 3, 4, 5, 6, 10, 0, 0, 0]
This code has been tested using IntelliJ and it appears to be working.
Try this!
static int getUniqueElements(int [] sortedArr){
int duplicateCount = 0;
int [] tempArr = sortedArr;
int j=0;
boolean isNewValue = true;
for(int i=1;i<tempArr.length;i++){
if(sortedArr[j] != tempArr[i]){
isNewValue = true;
sortedArr[++j] = tempArr[i];
}else{
if(isNewValue){
isNewValue = false;
duplicateCount++;
}
}
}
for(j++;j<sortedArr.length;j++){
sortedArr[j] = 0;
duplicateCount++;
}
return (sortedArr.length-duplicateCount);
}
public static void main(String[] args) {
int[] arr = {1, 3, 3, 3, 3, 6, 6, 7, 8, 8};
System.out.println("Unique Count:"+ getUniqueElements(arr));
System.out.println(Arrays.toString(arr));
}
OutPut:
Unique Count:2
[1, 3, 6, 7, 8, 0, 0, 0, 0, 0]
Since in the given array 1,7 are unique.
Note: tried with your example array {6, 10, 19, 21, 23 ,26 ,27 ,36 ,38, 45 } also
My solution is as(assuming elements can repeat only twice):
public static int removeDups(int[] arr) {
int i = 0;
int numDups = 0;
while (i < arr.length - 1 - numDups) {
if (arr[i] == arr[i + 1]) {
numDups++;
for (int m = i + 1; m < arr.length - numDups; m++) {
arr[m] = arr[m + 1];
}
arr[arr.length - numDups] = 0;
}
i++;
}
return arr.length-numDups;
}

Using an array of arrays (int[][]), create a method to find all cycles within a given permutation [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
So I can just use standard arrays for this, nothing else. I have to find a way to make a method that finds all the cycles in the given permutation and returns them as an array object of arrays. Then I have to place the lowest of each array as the first entry of the array. Then sort them by lowest.
I can't use arraylists or sets or anything.
EDIT: By cycles I mean take the integer value of the initial object and locate the index value that it corresponds to. Take that integer value at that index and do the same. Continue doing this until it points back to an object that's already been referenced.
An example: [0, 4, 2, 8, 7, 9, 1, 6, 5, 3]
would be these cycles : [0] [4, 8, 5, 7, 6, 9, 3, 2] [1]
and return this: [0], [1], [2, 4, 8, 5, 7, 6, 9, 3]
or
This array: [2, 4, 8, 1, 5, 3, 9, 0, 7, 6]
would be these cycles : [2, 8, 7, 0] [4, 5, 3, 1] [9, 6]
and return this : [0, 2, 8, 7], [1, 4, 5, 3], [6, 9]
I am so lost, any help would be wonderful. thanks ahead of time!
Don't ask why I took the time to do this.
EDIT: Totally working now
public class Main {
public Main()
{
}
public static void main(String[] args)
{
int array[] = {0, 4, 2, 8, 7, 9, 1, 6, 5, 3};
Main m = new Main();
int[][] cycles = m.getCycles(array);
for (int i = 0; i < cycles.length; i++)
{
System.out.print("[");
for (int j = 0; j < cycles[i].length; j++)
{
System.out.print(cycles[i][j]);
if (j < cycles[i].length - 1)
System.out.print(", ");
}
System.out.println("]");
}
System.out.println("end debug");
}
public int[][] getCycles(int[] array)
{
int[][] cycles = new int[array.length][array.length];
// initialize the cycles to all -1s, cuz they'll never be in the array
for (int i = 0; i < cycles.length; i++)
{
for (int j = 0; j < cycles[i].length; j++)
{
cycles[i][j] = -1;
}
}
int i = 0;
do {
int nextElement = array[i];
int j = 0;
do {
cycles[i][j] = nextElement;
nextElement = array[nextElement];
j++;
} while (!elementInArray(cycles[i], nextElement) && j < array.length);
i++;
} while (!arrayHasCycled(array, cycles) && i < array.length);
cycles = removeNegativeOnes(cycles, i);
for (i = 0; i < cycles.length; i++)
{
pushForward(cycles[i]);
}
return cycles;
}
public boolean elementInArray(int[] array, int element)
{
for (int i = 0; i < array.length; i++)
{
if( array[i] == element)
return true;
}
return false;
}
public int[][] removeNegativeOnes(int[][] cycles, int numCycles)
{
int [][] newCycles = new int[numCycles][];
for (int i = 0; i < numCycles; i++)
{
int realLenOfCycle = indexOf(-1, cycles[i]);
newCycles[i] = new int[realLenOfCycle];
for (int j = 0; j < newCycles[i].length; j++)
{
newCycles[i][j] = cycles[i][j];
}
}
return newCycles;
}
public int indexOf(int element, int[] array)
{
int index = -1;
for (int i = 0; i < array.length; i++)
{
if (array[i] == element)
return i;
}
return index;
}
public boolean arrayHasCycled(int[] array, int[][] cycles)
{
for (int i = 0; i < array.length; i++)
{
boolean cycleHasValue = false;
for (int j = 0; j < cycles.length; j++)
{
for (int k = 0; k < cycles[j].length; k++)
{
if (cycles[j][k] == array[i])
cycleHasValue = true;
}
}
if (!cycleHasValue)
return false;
}
return true;
}
public void pushForward(int [] array)
{
int lastElement = array[array.length - 1];
for (int i = array.length - 1; i > 0; i--)
{
array[i] = array[i - 1];
}
array[0] = lastElement;
}
}
Output:
[0]
[1, 4, 7, 6]
[2]
[3, 8, 5, 9]
From what I understand, you're asked us to create a code which executes the following algorithm:
Create a one-dimensional array of integers, array
For each element in that array, nextElement do the following:
Create a new one-dimensional array, currCycle that will be added to a two-dimensional array, cycles.
Set the first element of that array to nextElement.
nextElement then becomes array[nextElement]
If nextElement is already in currCycle, continue onto the next element of array
Check if all the elements of array are in cycles, and if so, stop executing this algorithm.
Finally, return the cycles as a two-dimensional array with the index that was being used instead of the element at that index, which is what the current array consists of. To accomplish this, just cyclically (in the normal sense) push each element of the array forward one index.
This doesn't follow your examples exactly, but I think you may have malformed your examples, for instance:
An example: [0, 4, 2, 8, 7, 9, 1, 6, 5, 3]
would be these cycles : [0] [4, 8, 5, 7, 6, 9, 3, 2] [1]
and return this: [0], [1], [2, 4, 8, 5, 7, 6, 9, 3]
The first element 0 is 0, so when you get 0, it's already in the current cycle, so go to the next element, the element at index 1, which is 4. Once you're at 4 go to the fourth element, which is 7 not 8!
0 1 2 3 4
[0, 4, 2, 8, 7...

Categories

Resources