I wanna write a method that merges the same values within an array via multiplication. I wanna do it with recursive.
Any sequence of numbers should be merged, if there are similar numbers withing it.
So for example if I have the numbers 1, 2, 5, 5, 4, it should become "1 2 25 4" or 5, 5, 5, 6 becomes ”125 6”.
Can anyone help?
This approach utilizes divide and conquer, and should run in O(n log n).
package edu.gwu.seas.cs6212.hw3;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.TreeMap;
public class Tester {
public static void main(String [] args){
System.out.println("Merging 1, 2, 5, 5, 4: ");
int [] originalArray = {1, 2, 5, 5, 4};
int [] mergedArray = mergeSequences(originalArray);
StringBuilder sb = new StringBuilder();
for(int element : mergedArray){
sb.append(element);
sb.append(",");
}
sb.deleteCharAt(sb.length()-1); //Remove final comma
System.out.println(sb.toString());
sb.delete(0, sb.length());
System.out.println("Merging 5, 5, 5, 6: ");
int [] originalArray2 = {5, 5, 5, 6};
int [] mergedArray2 = mergeSequences(originalArray2);
for(int element : mergedArray2){
sb.append(element);
sb.append(",");
}
sb.deleteCharAt(sb.length()-1); //Remove final comma
System.out.println(sb.toString());
}
private static int [] mergeSequences(int [] originalArray){
Map<Integer,Integer> indiciesMap = mergeDivideAndConquer(originalArray, 0, originalArray.length -1, new TreeMap<Integer,Integer>());
int indexCounter = 0;
List<Integer> mergedList = new ArrayList<Integer>();
Iterator<Entry<Integer, Integer>> it = indiciesMap.entrySet().iterator();
if(it.hasNext()){
while(it.hasNext()){
Entry<Integer,Integer> firstEntry = it.next();
int firstSequenceBeginIndex = firstEntry.getKey();
int firstSequenceEndIndex = firstEntry.getValue();
while(indexCounter < firstSequenceBeginIndex){
mergedList.add(originalArray[indexCounter]);
indexCounter++;
}
//Now we've reached first entry
int multiplicativeSum = 1;
while(indexCounter <= firstSequenceEndIndex){
multiplicativeSum *= originalArray[indexCounter];
indexCounter++;
}
mergedList.add(multiplicativeSum);
}
//Add remaining elements
while(indexCounter < originalArray.length){
mergedList.add(originalArray[indexCounter++]);
}
} else{
for(int element : originalArray){
mergedList.add(element);
}
}
return mergedList.stream().mapToInt(i -> i).toArray();
}
private static Map<Integer,Integer> findCrossingArray(final int [] originalArray, final int i, final int midpoint,
final int j, Map<Integer,Integer> indiciesMap){
int leftIndexOfSequence = -1;
for(int leftCounter = midpoint; leftCounter >= i; leftCounter--){
if(originalArray[leftCounter] == originalArray[midpoint]){
leftIndexOfSequence = leftCounter;
} else{
break;
}
}
int rightIndexOfSequence = midpoint;
for(int rightCounter = midpoint + 1; rightCounter <= j; rightCounter++){
if(originalArray[rightCounter] == originalArray[midpoint]){
rightIndexOfSequence = rightCounter;
} else{
break;
}
}
if(leftIndexOfSequence != -1 && leftIndexOfSequence != rightIndexOfSequence){
indiciesMap.put(leftIndexOfSequence, rightIndexOfSequence);
}
return indiciesMap;
}
private static Map<Integer,Integer> mergeDivideAndConquer(final int [] originalArray, final int i, final int j, Map<Integer,Integer> indiciesMap){
//Base case
if(j == i){
return indiciesMap;
}
//Divide recursively into smaller subproblems
int midpoint = Math.floorDiv((i + j),2);
Map<Integer,Integer> left = mergeDivideAndConquer(originalArray, i, midpoint, indiciesMap);
Map<Integer,Integer> right = mergeDivideAndConquer(originalArray, midpoint + 1, j, indiciesMap);
//Combine subsolutions
return findCrossingArray(originalArray, i, midpoint, j, indiciesMap);
}
}
Related
I have an assignment that needs me to find the smallest and second smallest value in an array but I can't manage to figure it out.
!New learner in dart
You can use Quickselect for Θ(n) time complexity:
int findKthSmallest(List<int> nums, int k) {
if (k <= 0 || k > nums.length) {
throw new ArgumentError("k must be positive and less than or equal to the size of nums.");
}
final n = nums.length - k;
int quickSelect(int left, int right) {
var pivot = nums[right];
var p = left;
for (var i = left; i < right; i++) {
if (nums[i] >= pivot) {
var temp = nums[i];
nums[i] = nums[p];
nums[p] = temp;
p++;
}
}
var temp = nums[right];
nums[right] = nums[p];
nums[p] = temp;
if (p > n) {
return quickSelect(left, p - 1);
} else if (p < n) {
return quickSelect(p + 1, right);
} else {
return nums[p];
}
}
return quickSelect(0, nums.length - 1);
}
void main() {
var nums = [5, 3, 1, 3, 2, 7, 9, 10];
var k = 2;
print('findKthSmallest(${nums}, ${k}): ${findKthSmallest([...nums], k)}');
}
Output:
findKthSmallest([5, 3, 1, 3, 2, 7, 9, 10], 2): 2
Hi Everyone, i am new to the programming world, can you please help me in finding second duplicate element in an array. i have tried but its not working.
public class FindSecondDuplicate {
public static void main(String[] args) {
int[] intArray = { 6,4,2,3,4,6,8};
int count=0;
Set<Integer> set=new LinkedHashSet<>();
for(int no:intArray)
{
if(set.add(no)==false)
{
count=count+1;
if(count==2)
{
System.out.println(no);
break;
}
}
else
{
set.add(no);
}
}
}
}
I think what you are trying to do can be accomplished using
public static void main(String[] args) {
int[] intArray = {6, 4, 2, 3, 4, 6, 8};
int count = 0;
Map<Integer, Integer> repeatCounter = new HashMap<>();
for (int i : intArray) {
if (repeatCounter.containsKey(i)) {
int repeatedNTimes = repeatCounter.get(i);
repeatCounter.put(i, repeatedNTimes + 1);
}else{
repeatCounter.put(i, 1);
}
}
for (int i : intArray) {
if (repeatCounter.get(i) == 2) {
count++;
if (count == 2) {
System.out.println(i);
break;
}
}
}
}
Find 2nd/3rd or any duplicate with Set Interface
public static void main(String[] args){
int[] array = {3, 12, 9, 3, 8, 3, 12, 4, 7, 8};
int find_duplicate = 3;
// Add all duplicates to set
Set<Integer> storeDuplicates = new LinkedHashSet<>();
for (int i = 0; i < array.length-1; i++){
for (int j = i+1; j < array.length; j++){
if (array[i] == array[j]){
storeDuplicates.add(array[i]);
}
}
}
// Traverse set for find the 2nd/3rd/any other duplicate
int count = 0;
for (int i : storeDuplicates){
count++;
if (count == find_duplicate) System.out.println(find_duplicate+" duplicate is : "+i);
}
}
Trying to get number of unique(non duplicated) numbers of an array via a static method.
For example the array is {1,1,2,4,5,5,7,78,89}
the output would be 7.
public class UniqueNumbes {
public static void main(String[] args) {
int[] test = {1, 2, 4, 5, 10, 30, 20, 1};
int num = numUnique(test);
System.out.println(num);
}
public static int numUnique(int[] list){
int count= 0;
int fin =list.length;
Arrays.sort(list);
for (int i = 0; i<=list.length; i++){
if(list[i]==list[i-1])
count++;
}
return fin-count;
}
}
Put everything in a set and return the size of the set.
import java.util.HashSet;
import java.util.Set;
public class UniqueNumbes {
public static void main(String[] args) {
int[] test = { 1, 2, 4, 5, 10, 30, 20, 1 };
int num = numUnique(test);
System.out.println(num);
}
public static int numUnique(int[] list) {
// java.util.Set
// "A collection that contains no duplicate elements."
Set<Integer> set = new HashSet<Integer>();
for (int i = 0; i < list.length; i++) {
set.add(list[i]);
}
return set.size();
}
}
A : [1, 2, 5, -7, 2, 3] The two sub-arrays are [1, 2, 5] [2, 3].
The answer is [1, 2, 5]as its sum is larger than [2, 3]
NOTE: If there is a tie, then compare with segment's length and return segment which has maximum length.
NOTE 2: If there is still a tie, then return the segment with minimum starting index.
I have written the code and its working for some cases but not for this one :
A : [ 1967513926, 1540383426, -1303455736, -521595368 ]
Your function returned the following :
1967513926
The expected returned value :
1967513926 1540383426
Here is my code
int* maxset(int* A, int n1, int *length_of_array) {
int greatin=0,greatout=0,greatin1=0,number1=0,number=0;
int n3,i,count=0,k,sum=0,max=0,ini=0,end=0;
for(i=0;i<n1;i++)
{
ini=end;
if(A[i]>=0)
{
count=1;
number++;
sum=sum+A[i];
if (sum>max )
{
max=sum;
greatout=i;
greatin=ini;
}
else if (sum==max && number>number1)
{
max=sum;
greatout=i;
greatin=ini;
}
}
else
{
sum=0;
end=i+1;
number1=number;
number=0;
}
}
if(count>0)
{
count=0;
n3=greatout-greatin+1;
*length_of_array=n3;
int * ret = (int *) malloc(sizeof(int) * *length_of_array);
for(i=greatin;count<n3;i++)
{
ret[count]=A[i];
count++;
}
return ret;
}
else
{
*length_of_array=0;
int * ret = (int *) malloc(sizeof(int) * *length_of_array);
return ret;
}
}
You are using int and when you add you overflow the limit 2,147,483,647
Here is a working program in python for your question:
def check(max_arr,curr):
if sum(curr) > sum(max_arr):
max_arr = curr
elif sum(curr) == sum(max_arr):
if len(curr) > len(max_arr):
max_arr = curr
elif len(curr) == len(max_arr):
if max_arr and (curr[0] > max_arr[0]):
max_arr = curr
return max_arr
def maxset(A):
curr = []
max_arr = []
for i in A:
if i >= 0:
curr.append(i)
else:
max_arr = check(max_arr,curr)
curr = []
max_arr = check(max_arr,curr)
return max_arr
import java.util.Scanner;
import java.util.Arrays;
public class P4 {
public static void main(String [] args) {
Scanner input = new Scanner(System.in);
final int NUMMONTHS = 12;
final int SORT = 12;
int [] plantHeight = new int[SORT];
int [] avgTemp = {46, 48, 49, 50, 51, 53, 54, 55, 56, 55, 51, 47};
int [] avgRain = {5, 3, 3, 1, 1, 0, 0, 0, 0, 1, 3, 4};
int[] newGrowth;
newGrowth = new int[NUMMONTHS];
int minTemp;
int maxTemp;
int minRain;
int j;
//prompt user input
System.out.println("Welcome to the 210 gardening planner!");
System.out.println("Enter minimum temperature for plant:");
minTemp = input.nextInt();
System.out.println("Enter maximum temperature for plant:");
maxTemp = input.nextInt();
System.out.println("Enter minimum rainfall for plant:");
minRain = input.nextInt();
System.out.println("Month" + "\t" + "Temp Rain Growth" + "\t" + "Plant Height");
//Calculate and print plant growth
for(j=0; j<NUMMONTHS; j++){
if(avgTemp[j] >= minTemp & maxTemp >= avgTemp[j]){
newGrowth[j] = avgRain[j] - minRain;
if(j == 0){
plantHeight[j] = newGrowth[j];
}else{
plantHeight[j] = newGrowth[j] + plantHeight[j-1];}
}
//if growth is zero, height remains same as previous
else{
newGrowth[j] = -1;
plantHeight[j] = plantHeight[j] - 1;
}
//plant height cannot be less than 0
if(plantHeight[j]< 0){
plantHeight[j] = 0;
}
plantHeight[j] = scan.nextInt();
System.out.print(j + "\t" + avgTemp[j] + " " + avgRain[j] + " ");
System.out.println(newGrowth[j] + " " + plantHeight[j]);
}
for (int i=0; i<plantHeight; i++) {
// find smallest element in elements i to plantHeight
int currentMin = plantHeight[i];
int minIndex = i;
for (int x=i+1; x < plantHeight; x++) {
if (plantHeight[x] < currentMin) {
currentMin = plantHeight[x];
minIndex = x;
}
}
if (minIndex != i) {
plantHeight[minIndex] = plantHeight[i];
plantHeight[i] = currentMin;
}
}
System.out.println(plantHeight[0]);
}
}
I made a graph of plant growth depending on rain and temperature, but I need some help storing the heights of the plant after each month and printing the tallest height. To do so, I'm trying to store each height into an array, then sorting the array in descending order to find the highest value and print it out.
You can use Arrays.sort() inbuild function to sort and the retrieve the last number.
Here is a simple example to explain sort. You can then implement in your code
int[] num = {4,3,6,2,9,3};
Arrays.sort(num);
for (int i: num) {
System.out.println(i);
}
int max = num[num.length - 1];
System.out.println(max); // max is 9
Demo of Arrays.sort()
Since you want maximum height and its corresponding month, it would be a better idea to use TreeMap and have height as key and month as value. Since it implements SortedMap so the key would be inserted in ascending order by default, you can then retrieve the last entry which would be the maximum height and its corresponding month.
TreeMap<Integer, Integer> map = new TreeMap<Integer, Integer>();
Random rand = new Random();
for (int i = 1; i < 13; i++) {
map.put(rand.nextInt(100), i);
}
/*for (Map.Entry<Integer, Integer> a: map.entrySet()) {
System.out.println(a.getKey() + " " + a.getValue());
}*/
Map.Entry<Integer, Integer> maxValues = map.lastEntry();
int maxHeight = maxValues.getKey();
int maxMonth = maxValues.getValue();
System.out.println(maxHeight + " " + maxMonth);
Demo of TreeMap
Instead of sorting, search for maxIndex:
int maxIndex = 0;
int currentMax = plantHeight[0];
for (int i=1; i<plantHeight; i++) {
if (plantHeight[i] > currentMax) {
maxIndex = i;
currentMax = plantHeight[i];
}
}
System.out.println(plantHeight[maxIndex]);
System.out.println(avgTemp[maxIndex]);
System.out.println(avtRain[maxIndex]);
To find both min and max:
int minIndex = 0;
int maxIndex = 0;
int currentMin = plantHeight[0];
int currentMax = currentMin;
for (int i=1; i<plantHeight; i++) {
if (plantHeight[i] < currentMin) {
minIndex = i;
currentMin = plantHeight[i];
}
else if (plantHeight[i] > currentMax) {
maxIndex = i;
currentMax = plantHeight[i];
}
}
System.out.println(plantHeight[minIndex]);
System.out.println(avgTemp[minIndex]);
System.out.println(avtRain[minIndex]);
System.out.println(plantHeight[maxIndex]);
System.out.println(avgTemp[maxIndex]);
System.out.println(avtRain[maxIndex]);