I'm almost new at Java! I want to control if there are 4 consecutive elements in an array with 5 elements. Is there any way to do that? Can someone help me with that? Thanks! Consecutive like {2, 3, 4, 5}. If there is {3, 4, 2, 5} for example this is not consecutive.I want just a simple example if someone can help me.
I did this but I think this is incorrect:
public int katerTeNjepasnjeshme()
{
int[] numrat=new int[zar.length];
for(int i=0;i<zar.length;i++)
numrat[i]=zar[i].getValue();
int shuma=0;
for(int i=0;i<zar.length-1;i++)
{
if(zar[i+1].getValue()==(zar[i].getValue()+1))
Joptionpane.showMessageDialog(null,"Tere are cons elements");
}
Here's the general idea:
Keep a counter (initialized appropriately), to keep track of the number of consecutive elements as you iterate over the elements.
If the counter reaches 4, you have found 4 consecutive elements.
If you encounter an element that is not consecutive, then reset the counter to 1, and proceed to check the next element.
Here is a sample code snippet:
public static void findConsecutive()
{
int[] array = {1,2,3,5,6,7,8,10};
int counter = 1;
int i = 1;
for (i = 1; i < array.length; i++)
{
if (array[i] == (array[i-1] + 1))
{
counter++;
if (counter == 4)
{
System.out.println("Consecutive elements are at array index: " + (i - 3) + " to " + i);
break;
}
}
else
{
counter = 1;
}
}
}
i think something like that should work:
int[] mylist = new int[10];
for (int i = 0; i < myList.length; i++) {
int k = 1;
for (int j = 1; j < 5 j++) {
if (mylist[i] == mylist[i+j]-j) {
k++;
}
if (k=5) System.out.println("found");
}
}
As soon as you need to compare two elements of the array you should use proper bounds in the loop, otherwise you will get ArrayIndexOutOfBoundsException
boolean consequtive = true;
for (int i = 0; i < zar.length - 1; i++)
if (zar[i+1].getValue() != zar[i].getValue() + 1) {
consecutive = false;
break;
}
if (consequtive)
Joptionpane.showMessageDialog(null,"Tere are cons elements");
Related
I know the title is really bad but I spent like 10 minutes thinking of a way to describe my problem in a concise way and couldn't.
This program is supposed to create a numUnique() static method that returns the amount of unique numbers in an array. So, for example, if I have an array with {2, 4, 2, 7, 16, 4} the amount of unique numbers would be 4 (2, 4, 7 and 16).
I was writing the code to find the duplicates in my array, then I realized that I didn't know what to do with it when I had the duplicates, and I've been breaking my head trying to think of a solution but I can't.
Here is the code so far:
public class Unique {
public static void main(String[] args) {
int[] numbers = {1, 6, 2, 14, 6, 8, 2, 1, 23};
numUnique(numbers);
}
public static void numUnique(int[] array){
Arrays.sort(array);
for (int i = 0; i < array.length; i++) {
for (int j = i + 1; j < array.length; j++) {
if (array[i] == array[j])
//code here
}
}
}
}
My understanding is you to count (not return them all) the number of unique elements in the array. You are attempting to look all the way down, but it's enough to track the number of duplicates as you go. This code looks back to see if the current entry duplicates the previuos one (which works because you sorted, which was a good step).
import java.util.Arrays;
public class Unique {
public static void main(String[] args) {
int[] numbers = {
1,
6,
2,
14,
6,
8,
2,
1,
23
};
System.out.println(numUnique(numbers));
}
public static int numUnique(int[] array) {
Arrays.sort(array);
int dups = 0;
for (int i = 1; i < array.length; i++) {
if (array[i] == array[i - 1]) {
dups++;
}
}
return (array.length - dups);
}
}
If you want to keep the code that you have so far and sort the list, there are two options that seem to make sense. Where one is to return the number of unique integers, and the other is to return a list of the unique integers.
Returning the number of unique numbers:
public static int numUnique(int[] array) {
ArrayList<Integer> uniques = new ArrayList<>();
Arrays.sort(array);
uniques.add(array[0]);
int prev = array[0];
for (int i = 1; i < array.length; i++) {
if(array[i] != prev){
uniques.add(array[i]);
prev = array[i]
}
}
return uniques.size();
}
Returning the list of unique numbers, would simply require you to return the uniques list, without the .size().
If you want a array instead of a list, you will need to return the following:
return uniques.toArray(new Integer[list.size()]);
If you're using Arrays why not explore it further
private static long numUnique(int[] numbers) {
return Arrays.stream(numbers).distinct().count();
}
Keeping your code as it is:
If You want to know how many non-duplicates are in you array:
public static void numUnique(int[] array) {
Arrays.sort(array);
// Here, make a variable that keeps size of an array
int arrayLenght = array.length;
// Here is our counter:
int duplicates = 0;
for (int i = 0; i < array.length; i++) {
for (int j = i + 1; j < array.length; j++) {
if (array[i] == array[j])
// when you find duplicate, add 1 to our counter:
duplicates++;
}
}
//at the end you can count how many non-duplicates are in the array:
arrayLenght -= duplicates;
System.out.println("There are " + arrayLenght + " non duplicates in our array.");
}
Edit
This solution do not work in every situation.
I know this is not the most optimal way to do this, but the only i know hah:
public static void numUnique(int[] array) {
Arrays.sort(array);
int arrayLenght = array.length;
int duplicates = 0;
for (int i = 0; i < array.length; i++) {
//a little change in our second for-loop:
for (int j = 0; j < array.length; j++) {
if (array[i] == array[j]) {
//Here i'm just summing up the duplicates
duplicates ++;
}
}
// Aaand here, on a console, i print the value (array[i]) and how many duplicates does it have.
//to be exact, if the duplcicates rise only once so it's equal to 1, it means that there is no duplicate of this value (it found itself in the loop).
if (duplicates == 1) {
duplicates = 0;
}
System.out.println(array[i] + " have " + duplicates + "duplicates");
// And what is imporatnt We have to reset our duplication-container!
// so in further loops it will count duplicates for each value in array
duplicates = 0;
}
}
If you find another issue, ask me right away
For this particular problem I am attempting to remove redundant elements in an sorted array and replace them all with 0s at the end of the array. For example, if I had an array consisting of the int elements
1,3,3,4,4,5,6,6,7
My output array should be
1,3,4,5,6,7,0,0,0
My first attempt at the problem was to create a swapper in order to push all the 0s to the end of the list after removing the elements, but it won't seem to push the zeros to the end of the list. Here is my code.
public void implode(int[] ary)
{
int swapper = -1;
int[] newARY = new int[ary.length];
int current = -1;
for (int i = 0; i < ary.length; i++)
{
if (current != ary[i])
{
newARY[i] = ary[i];
current = ary[i];
}
}
for (int i = 0; i < ary.length; i++)
{
if (ary[i] == 0)
{
if (ary[i + 1] != 0)
{
swapper = ary[i + 1];
ary[i] = swapper;
ary[i + 1] = 0;
}
}
}
ary = newARY;
for (int i = 0; i < newARY.length; i++)
{
System.out.print(newARY[i] + " ");
}
}
The array im testing it with is,
int[] aryIn2 = {1, 1, 2, 3, 4, 4, 5, 6};
However, when outputting the imploded array, I receive this one.
1 0 2 3 4 0 5 6
Is there something I am missing?
Thanks in advance.
not an answer to your problem, but using (if possible) java streams can shorten your way:
int[] arr = {1,3,3,4,4,5,6,6,7};
// distinct
List<Integer> list = Arrays.stream(arr).distinct().boxed().collect(Collectors.toList());
// pad with zero's
while(list.size() < arr.length) {
list.add(0);
}
// display
System.out.println(list.stream().map(String::valueOf).collect(Collectors.joining(",")));
will output
1,3,4,5,6,7,0,0,0
Two issue with you code that I observed.
1) Your swapper logic is performing swapping on a different array than the one in which you had done modification earlier
2) You need to have this logic in a bubble-sort way, i.e. loop inside a loop
Below is a working modified sample code of your method. I have modified only the second for-loop logic
public void implode(int[] ary) {
int swapper = -1;
int[] newARY = new int[ary.length];
int current = -1;
for (int i = 0; i < ary.length; i++) {
if (current != ary[i]) {
newARY[i] = ary[i];
current = ary[i];
}
}
for (int i = 0; i < newARY.length - 1; i++) {
if (newARY[i] == 0 && newARY[i + 1] != 0) {
for (int j = i; (j + 1) < newARY.length; j++) {
swapper = newARY[j + 1];
newARY[j] = swapper;
newARY[j + 1] = 0;
}
}
}
for (int i = 0; i < newARY.length; i++) {
System.out.print(newARY[i] + " ");
}
}
In this first loop:
for (int i = 0; i < ary.length; i++) {
if (current != ary[i]) {
newARY[i] = ary[i];
current = ary[i];
}
}
You fill newARY with elements in ary with duplicated value turns to 0:
newARY: 1 0 2 3 4 0 5 6
However, in the second loop:
for (int i = 0; i < ary.length; i++)
{
if (ary[i] == 0)
{
if (ary[i + 1] != 0)
{
swapper = ary[i + 1];
ary[i] = swapper;
ary[i + 1] = 0;
}
}
}
You're modifying your original ary array. So the newARY is not updated.
However, your attempt to push 0 to the end of array also fail if there are more than two 0s consecutive. And it is also vulnerable to ArrayOutOfBoundIndexException since you try to read ary[i+1] without restriction on i
One simple and straight forward way to push 0s to the end of the array is to create new array with non-0s elements and fill 0s later:
int[] result = new int[ary.lenght];
int resultIndex = 0;
for (int i = 0; i < newARY.length; i++) {
if (newARY[i] != 0) {
result[resultIndex++] = newAry[i];
}
}
for (int i = resultIndex; i < newARY.length; i++) {
result[i] = 0;
}
// Print result array
Hint: Using above strategy, you can simplify your code. No need to create immediate array newARY. Just loop over the original array, push unique elements to the result array, then fill any slot left with 0s.
I'm working on a problem on leetcode (Two Sum):
Given an array of integers, return indices of the two numbers such
that they add up to a specific target.
You may assume that each input would have exactly one solution, and
you may not use the same element twice.
Example: Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
I tried my own solution and the array always showed [0,0]. So I tried a solution that they had after several tweeks and that still showed [0,0] when I put it in and it was the highest ranked solution. Is it me or is it leetcode?
Original Solution:
import java.util.Arrays;
public class Solution {
public int[] twoSum(int[] nums, int target) {
int[] indices = new int[2];
for(int i = 0; i < nums.length-1; i++)
{
for(int j = i+1; j < nums.length-1; j++)
{
if(target == (nums[i] + nums[j]))
{
indices[0] = i+1;
indices[1] = j+1;
}
}
}
return indices;
}
}
Leetcode Solution:
public class Solution {
public int[] twoSum(int[] nums, int target) {
int[] indices = new int[2];
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for(int i = 0; i < nums.length-1; i++)
{
if(map.containsKey(target - nums[i]))
{
indices[1] = i + 1;
indices[0] = map.get(target - nums[i]);
return indices;
}
map.put(nums[i], i + 1);
}
return indices;
}
}
I don't understand why neither of these will register ints in the indices array, it continually returns [0,0] for both solutions.
In my understanding your innerloop must not start with i+1, cause you have to check each index in your array. only if the index of the inner and outer loop match, you should skip it, cause you won't add the index with itself.
you must loop your array to the end (so i removed the -1 in the for-statement)
why are you returning i+1 and j+1 if you found a match? (so i removed this)
see my code. maybe it will be more clear, what im trying to say :-)
public class Solution {
public static void main(String[] args) {
Solution solution = new Solution();
int[] result = solution.twoSum(new int[] { 2, 7, 11, 15 }, 17);
System.out.println(result[0] + "/" + result[1]);
}
public int[] twoSum(int[] nums, int target) {
int[] indices = new int[2];
for (int i = 0; i < nums.length; i++) {
for (int j = 0; j < nums.length; j++) {
if (i == j) {
//do not use the same index for sum
continue;
}
if (target == (nums[i] + nums[j])) {
indices[0] = i;
indices[1] = j;
}
}
}
return indices;
}
}
The simplest way to loop through combinations of two within an array can be done as follows:
for(int i=0 ; i<nums.length-1 ; i++)
for(int j=i+1 ; j<nums.length ; j++)
if(nums[i]+nums[j]==target)
return new int[] {i, j};
return null; //in case there's no such case
I need for homework to get the most "popular" number in an array (the number in the highest frequency), and if there are several numbers with the same number of shows, get some number randomly.
After more then three hours of trying, and either searching the web, this is what I got:
public int getPopularNumber(){
int count = 1, tempCount;
int popular = array[0];
int temp = 0;
for ( int i = 0; i < (array.length - 1); i++ ){
if ( _buses[i] != null )
temp = array[i];
tempCount = 0;
for ( int j = 1; j < _buses.length; j++ ){
if ( array[j] != null && temp == array[j] )
tempCount++;
}
if ( tempCount > count ){
popular = temp;
count = tempCount;
}
}
return popular;
}
This code work, but don't take into account an important case- if there is more than one number with the same count of shows. Then it just get the first one.
for example: int[]a = {1, 2, 3, 4, 4, ,5 ,4 ,5 ,5}; The code will grab 4 since it shown first, and it's not random as it should be.
Another thing- since it's homework I can't use ArrayList/maps and stuff that we still didn't learn.
Any help would be appreciated.
Since they didn't give you any time complexity boundary, you can "brute force" the problem by scanning the the array N^2 times. (disclaimer, this is the most intuitive way of doing it, not the fastest or the most efficient in terms of memory and cpu).
Here is some psuedo-code:
Create another array with the same size as the original array, this will be the "occurrence array"
Zero its elements
For each index i in the original array, iterate the original array, and increment the element in the occurrence array at i each time the scan finds duplicates of the value stored in i in the original array.
Find the maximum in the occurrence array
Return the value stored in that index in the original array
This way you mimic the use of maps with just another array.
If you are not allowed to use collection then you can try below code :
public int getPopularNumber(){
int inputArr[] = {1, 2, 3, 4, 4, 5 ,4 ,5 ,5}; // given input array
int[] tempArr = new int[inputArr.length];
int[] maxValArr = new int[inputArr.length];
// tempArr will have number as index and count as no of occurrence
for( int i = 0 ; i < inputArr.length ; i++){
tempArr[inputArr[i]]++;
}
int maValue = 0;
// find out max count of occurrence (in this case 3 for value 4 and 5)
for( int j = 0 ; j < tempArr.length ; j++){
maValue = Math.max(maValue, tempArr[j]);
}
int l =0;
// maxValArr contains all value having maximum occurrence (in this case 4 and 5)
for( int k = 0 ; k < tempArr.length ; k++){
if(tempArr[k] == maValue){
maxValArr[l] = k;
l++;
}
}
return maxValArr[(int)(Math.random() * getArraySize(maxValArr))];
}
private int getArraySize(int[] arr) {
int size = 0;
for( int i =0; i < arr.length ; i++){
if(arr[i] == 0){
break;
}
size++;
}
return size;
}
that's hard as hell :D
After some trying, I guess I have it (If there will be 2 numbers with same frequency, it will return first found):
int mostPopNumber =0;
int tmpLastCount =0;
for (int i = 0; i < array.length-1; i++) {
int tmpActual = array[i];
int tmpCount=0;
for (int j = 0; j < array.length; j++) {
if(tmpActual == array[j]){
tmpCount++;
}
}
// >= for the last one
if(tmpCount > tmpLastCount){
tmpLastCount = tmpCount;
mostPopNumber = tmpActual;
}
}
return mostPopNumber;
--
Hah your code give me idea- you cant just remember last most popular number, btw I've found it solved there Find the most popular element in int[] array
:)
EDIT- after many, and many years :D, that works well :)
I've used 2D int and Integer array - you can also use just int array, but you will have to make more length array and copy actual values, Integer has default value null, so that's faster
Enjoy
public static void main(String[] args) {
//income array
int[] array= {1,1,1,1,50,10,20,20,2,2,2,2,20,20};
//associated unique numbers with frequency
int[][] uniQFreqArr = getUniqValues(array);
//print uniq numbers with it's frequency
for (int i = 0; i < uniQFreqArr.length; i++) {
System.out.println("Number: " + uniQFreqArr[i][0] + " found : " + uniQFreqArr[i][1]);
}
//get just most frequency founded numbers
int[][] maxFreqArray = getMaxFreqArray(uniQFreqArr);
//print just most frequency founded numbers
System.out.println("Most freq. values");
for (int i = 0; i < maxFreqArray.length; i++) {
System.out.println("Number: " + maxFreqArray[i][0] + " found : " + maxFreqArray[i][1]);
}
//get some of found values and print
int[] result = getRandomResult(maxFreqArray);
System.out.println("Found most frequency number: " + result[0] + " with count: " + result[1]);
}
//get associated array with unique numbers and it's frequency
static int[][] getUniqValues(int[] inArray){
//first time sort array
Arrays.sort(inArray);
//default value is null, not zero as in int (used bellow)
Integer[][] uniqArr = new Integer[inArray.length][2];
//counter and temp variable
int currUniqNumbers=1;
int actualNum = inArray[currUniqNumbers-1];
uniqArr[currUniqNumbers-1][0]=currUniqNumbers;
uniqArr[currUniqNumbers-1][1]=1;
for (int i = 1; i < inArray.length; i++) {
if(actualNum != inArray[i]){
uniqArr[currUniqNumbers][0]=inArray[i];
uniqArr[currUniqNumbers][1]=1;
actualNum = inArray[i];
currUniqNumbers++;
}else{
uniqArr[currUniqNumbers-1][1]++;
}
}
//get correctly lengthed array
int[][] ret = new int[currUniqNumbers][2];
for (int i = 0; i < uniqArr.length; i++) {
if(uniqArr[i][0] != null){
ret[i][0] = uniqArr[i][0];
ret[i][1] = uniqArr[i][1];
}else{
break;
}
}
return ret;
}
//found and return most frequency numbers
static int[][] getMaxFreqArray(int[][] inArray){
int maxFreq =0;
int foundedMaxValues = 0;
//filter- used sorted array, so you can decision about actual and next value from array
for (int i = 0; i < inArray.length; i++) {
if(inArray[i][1] > maxFreq){
maxFreq = inArray[i][1];
foundedMaxValues=1;
}else if(inArray[i][1] == maxFreq){
foundedMaxValues++;
}
}
//and again copy to correctly lengthed array
int[][] mostFreqArr = new int[foundedMaxValues][2];
int inArr= 0;
for (int i = 0; i < inArray.length; i++) {
if(inArray[i][1] == maxFreq){
mostFreqArr[inArr][0] = inArray[i][0];
mostFreqArr[inArr][1] = inArray[i][1];
inArr++;
}
}
return mostFreqArr;
}
//generate number from interval and get result value and it's frequency
static int[] getRandomResult(int[][] inArray){
int[]ret=new int[2];
int random = new Random().nextInt(inArray.length);
ret[0] = inArray[random][0];
ret[1] = inArray[random][1];
return ret;
}
The following is NOT a homework problem, it's just a set of problems that I've been working through for practice and I was wondering if anybody else could figure it out:
http://codingbat.com/prob/p159339
Return an array that contains exactly the same numbers as the given array, but rearranged so that every 3 is immediately followed by a 4. Do not move the 3's, but every other number may move. The array contains the same number of 3's and 4's, every 3 has a number after it that is not a 3 or 4, and a 3 appears in the array before any 4.
*SOLVED - here is my working code:
public int[] fix34(int...nums)
{
int[] returnArray = new int[nums.length];
//ASSIGN ARRAY
//We know that all 3's can't be moved, and after every 3 there
//will automatically be a 4
for(int i = 0; i<nums.length; i++)
{
if(nums[i] == 3)
{
returnArray[i] = 3;
returnArray[i+1] = 4;
}
}
//REBUILD ARRAY - UNMOVED INDEXES
//If a value was not moved/affected by the above, it will get placed into the array
//in the same position
for (int i = 0; i < nums.length; i++)
{
if (returnArray[i] != 3 && returnArray[i] != 4 && nums[i] != 3 && nums[i] != 4)
{
returnArray[i] = nums[i];
}
}
//REBUILD ARRAY - MOVED INDEXES
//changed values = 0 in returnArray, as a result, any time we hit a 0 we
//can simply assign the value that was in the 4's place in the nums array
OuterLoop: for (int i = 0; i < nums.length; i++)
{
if (returnArray[i] == 0)
{
for (int n = 0; n < returnArray.length; n++)
{
if (returnArray[n] == 4)
{
returnArray[i] = nums[n];
continue OuterLoop;
}
}
}
}
return returnArray;
}
I don't know java, but maybe I can help anyway. i dont want to give you the solution, but think of it like this:
you can move every number that isn't a 3. that's our only limit. that being said:
the only spots you need to change are the spots following 3s....so....every time you loop through, your program should be aware if it finds a spot after a 3 that isn't a 4....
it should also be aware if it finds any 4s not preceded by a 3......
during each loop, once it's found the location of each of those two things, you should know what to do.
Initialize all the variables
for(int i = 0; i<n-1; i++)
{
if(arr[i] == 3)
{
if(arr[i+1] == 4)
continue;
else
{
temp = 0;
while(arr[temp] != 4)
temp++;
//Write your own code here
}
//Complete the code
}
I have NOT provided the entire code. Try completing it as you said it was for your practice.
public int[] fix34(int[] nums) {
int[] arr = new int[nums.length];
int index = 0;
int tempVal= 0,j=0;
for(int i=0;i<nums.length;i++){
if(nums[i]==3){
arr[i] = nums[i];
index=i+1;
tempVal = nums[i+1];
j=index;
while(j<nums.length){
if(j<nums.length && nums[j]==4){
//System.out.println(j+"\t="+nums[j]);
nums[j]=tempVal;
nums[index] = 4;
break;
}
j++;
}
tempVal=0;
index=0;
}else{
arr[i] = nums[i];
}
}
index =0;
for(int i=0;i<nums.length;i++){
if(nums[i]==3 && nums[i+1]==4){
i+=1;
}else if(nums[i]==4){
index = i;
j=index;
while(j<nums.length){
if(nums[j]==3 && nums[j+1]!=4){
arr[index] = nums[j+1];
arr[j+1] = 4;
}
j++;
}
}
}
return arr;
}
Here's mine: A little overkill, but is always right, anyways i make 2 additional arrays and I make 2 passes in the loop putting the correct elements in the correct places. See Logic Below.
public int[] fix34(int[] nums) {
int index1 = 0;
int index2 = 0;
int index3 = 0;
int[] only4 = fours(nums); //holds all 4's in nums
int[] misc = new int[count4(nums)]; //will hold numbers after 3
for(int a = 0; a < nums.length - 1; a++){
if(nums[a] == 3){
misc[index1] = nums[a + 1]; //get it for later use
index1++;
nums[a + 1] = only4[index2]; //now the number after 3 is a 4, from the
index2++; //only4 array
}
}
for(int b = 1; b < nums.length; b++){
if(nums[b] == 4 && nums[b - 1] != 3){ //finds misplaced 4's
nums[b] = misc[index3]; //replaces lone 4's with the
index3++; //right hand side of each 3 original values.
}
}
return nums;
}
public int count4(int[] nums){
int cnt = 0;
for(int e : nums){
if(e == 4){
cnt++;
}
}
return cnt;
}
public int[] fours(int[] nums){
int index = 0;
int[] onlyFours = new int[count4(nums)]; //must set length
for(int e : nums){
if(e == 4){
onlyFours[index] = e;
index++;
}
}
return onlyFours;
}
I solved mine using two ArrayLists which contain the places of 3's and 4's.
I hope this helps.
public int[] fix34(int[] nums)
{
//Create a copy of nums to manipulate.
int[] ret = nums;
//Create two ArrayLists which carry corresponding places of 3 and 4;
ArrayList<Integer> threePositions = new ArrayList<Integer>();
ArrayList<Integer> fourPositions = new ArrayList<Integer>();
//Get the places of 3 and 4 and put them in the respective ArrayLists.
for (int i = 0; i < ret.length; i++)
{
if (ret[i] == 3)
{
threePositions.add(i);
}
if (ret[i] == 4)
{
fourPositions.add(i);
}
}
//Swap all ints right after the 3 with one of the 4s by using the referenced
//ArrayLists values.
for (int i = 0; i < threePositions.size(); i++)
{
int temp = ret[threePositions.get(i) + 1];
ret[threePositions.get(i) + 1] = ret[fourPositions.get(i)];
ret[fourPositions.get(i)] = temp;
}
//Return the ret array.
return ret;
}