Im a programming student and im having alot of trouble with this question:
"complete a static method multiplesOf which takes two int parameters, number and count. The method body must return an int array containing the first count multiples of number. For example,
multiplesOf(5, 4) should return the array { 5, 10, 15, 20 }
multiplesOf(11, 3) should return the array { 11, 22, 33 }
multiplesOf(1, 15) should return the array { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }
You must not use System.out.print or System.out.println in your method."
This is my current code:
public static void main(String[] args) {
multiplesOf(5,4);
}
public static int[] multiplesOf (int number, int count) {
int[] a = new int[count];
a[0]= number;
for(int i = 0; i<count; i++) {
a[i] = (a[i]*count);
}
return a;
}
Ive been trying to figure out why the array "a" still only has the values 0,1,2,3
Try:
public static int[] multiplesOf(int number, int count) {
int[] a = new int[count];
for(int i = 1; i <= count; i++) {
a[i - 1] = number * i;
}
return a;
}
a[0] = number;
for(int i = 1; i<count; i++)
{
a[i] = (i+1)*number;
}
try this
public static int[] multiplesOf (int number, int count)
{
int[] a = new int[count];
a[0] = number;
for(int i = 1; i<count; i++)
{
a[i] = number * (i + 1);
}
return a;
}
output
[5, 10, 15, 20]
public static int[] multiplesOf(int number, int count) {
int[] a = new int[count];
for (int i = 0; i < count; i++) {
a[i] = (number * (i+1));
}
return a;
}
use this
public static int[] multiplesOf (int number, int count) {
int[] a = new int[count];
for(int i = 1; i<=count; i++) {
//a[i-1] beacuse we started iterating array at i=1
a[i-1] = (i*number);
}
return a;
}
multiplesOf(5, 4) returns -> the array { 5, 10, 15, 20 }
Related
Suppose my input array is [15,20,12]
The required answer is a 2D array
The Required is output is as followed
[12
20
20 12
15
15 12
15 20
15 20 12
]
Not clear if it's homework or practical case. This is how would I solve it using Guava PowerSet:
public static void main(String[] args) {
Integer input[] = {15,20,12};
List<Integer> rev = Lists.reverse(Arrays.asList(input));
Set<Integer> indices = IntStream.range(0, input.length).boxed().collect(ImmutableSet.toImmutableSet());
Object output[] = Sets.powerSet(indices).stream()
.filter(indexset -> !indexset.isEmpty())
.map(indexset -> indexset.stream().map(i -> rev.get(i)).collect(Collectors.collectingAndThen(toList(), Lists::reverse)))
.map(List::toArray)
.toArray();
System.out.println(Arrays.deepToString(output));
}
Disclaimer:
This is my original work. No part of the solution has been copied from anywhere.
My solution works perfectly for 3 elements. However, this needs to be improved to work for arrays of other sizes. Despite this, I am publishing it so that OP or anyone else can extend this solution to work for an array of any size.
This question is close to the power set except for the fact that a power set can not have duplicate elements. If this exception is removed from this question, there are many solutions available e.g. at 1, 2, 3 etc.
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] arr = { 15, 20, 12 };
System.out.println(Arrays.deepToString(subsets(arr)));
}
public static int[][] subsets(int input[]) {
int[][] subarrs = new int[(int) Math.pow(2, input.length) - 1][input.length];
int[] indices = { 0 };
subsetsHelper(input, subarrs, 0, 0, 0, indices);
return subarrs;
}
private static void subsetsHelper(int input[], int[][] subarrs, int index, int i, int j, int[] indices) {
if (i == input.length) {
subarrs[index] = input;
return;
}
int[] subarr = new int[indices.length];
for (int x = 0; x < subarr.length; x++) {
subarr[x] = input[indices[x]];
}
subarrs[index] = subarr;
if (j == input.length - 1) {
subsetsHelper(input, subarrs, index + 1, i + 1, i + 1, new int[] { i + 1 });
} else {
subsetsHelper(input, subarrs, index + 1, i, j + 1, new int[] { i, j + 1 });
}
}
}
Output:
[[15], [15, 20], [15, 12], [20], [20, 12], [12], [15, 20, 12]]
Here you go.
public static void main(String[] args) {
int[] nums= {15, 20, 12};
int[][] subsets = subsets(nums);
for (int i = 1; i < subsets.length; i++) {
System.out.println(Arrays.toString(subsets[i]));
}
}
public static int[][] subsets(int input[]) {
List<List<Integer>> list = new ArrayList<>();
subsetsHelper(list, new ArrayList<>(), input, 0);
return convertListToArray(list);
}
private static void subsetsHelper(List<List<Integer>> list , List<Integer> resultList, int [] nums, int start){
list.add(new ArrayList<>(resultList));
for(int i = start; i < nums.length; i++){
// add element
resultList.add(nums[i]);
// Explore
subsetsHelper(list, resultList, nums, i + 1);
// remove
resultList.remove(resultList.size() - 1);
}
}
private static int[][] convertListToArray(List<List<Integer>> list) {
int[][] array = new int[list.size()][];
for (int i = 0; i < array.length; i++) {
array[i] = new int[list.get(i).size()];
}
for(int i=0; i<list.size(); i++){
for (int j = 0; j < list.get(i).size(); j++) {
array[i][j] = list.get(i).get(j);
}
}
return array;
}
1.As each recursion call will represent subset here, add resultList(see recursion code above) to the list of subsets in each call.
2.Iterate over elements of a set.
3.In each iteration
Add elements to the list
explore(recursion) and make start = i+1 to go through remaining elements of the array.
Remove element from the list
Output:
[15]
[15, 20]
[15, 20, 12]
[15, 12]
[20]
[20, 12]
[12]
public static int[][]returnallsub(int arr[], int si){
if(si==arr.length)
{int[][]ret=new int [1][0];
return ret;
}
int [][]rss =returnallsub(arr,si+1);
int [][]tss=new int[rss.length*2][];
int i=0;
for(;i<rss.length;i++) {
tss[i]=new int [rss[i].length];
}
int k=0;
for(;k<rss.length;k++) {
tss[i]=new int [rss[k].length+1];
i++;
}
int j=0;
for(i=0;i<rss.length;i++) {
for(j=0;j<rss[i].length;j++){
tss[i][j]=rss[i][j];
}
}
for(k=i;k<tss.length;k++) {
tss[k][0]=arr[si];
}
int r=i;
for(i=0;i<rss.length;i++) {
for(j=0;j<rss[i].length;j++){
tss[r][j+1]=rss[i][j];
}
r++;
}
return tss;
}
public static int[][] subsets(int arr[]) {
int start=0;
return returnallsub( arr,0);
}
}
Im Swedish so maybe I did give the wrong title.
I have two arrays of different size:
{2, 5, 10, 13}
{5, 7, 5, 22, 44, 75}
I want to add each element and put it in a third array.
So the result should be {7, 12, 15, 25, 44, 75}
I have manage to done some code.
I get an exeption of out of bounds.
I think the problem is that I can´t add a non existing element.
But how can I solve it?
public static void main(String[] args) {
int[] samling = {1, 2, 4, 3, 8};
int[] samling2 = {1, 2, 4, 3, 8, 8, 3};
int[] svar = concateArrays(samling, samling2);
for(int i=0; i < svar.length; i++)
System.out.println("Ny Array " + svar[i]);
}
public static int[] concateArrays(int[] samling, int[] samling2)
{
int sum = samling.length + samling2.length;
int[] total = new int[sum];
for(int i=0; i < total.length; i++){
//if (samling2.length != 0) // || samling.length != 0)
total[i] = samling[i] + samling2[i];
}
return total;
}
The length of the output array shouldn't be the sum of lengths of the input arrays, it should be the length of the longer input array. And before accessing an element of either input array, you must check the current index i is a valid index of that array.
public static int[] concateArrays(int[] samling, int[] samling2)
{
int[] total = new int[Math.max(samling.length,samling2.length)];
for(int i=0; i < total.length; i++) {
total[i] = (i < samling.length ? samling[i] : 0) +
(i < samling2.length ? samling2[i] : 0);
}
return total;
}
You can use one loop to loop over both arrays simultaneously.
You first need to check which array is the longest, and make a new array:
int[] arr = new int[longest];
Then you need to walk over the array. In this example, I assume the latter array is always the longest.
for (int i = 0; i < samling2.length; i++) {
int totalValue = samling[i];
if (i < samling.length) {
totalValue += samling2[i];
}
arr[i] = totalValue;
}
You can make an array of length equal to max of the two arrays you have. Then you can add the elements from both arrays if the specific index exist in both arrays else simply copy the index from the array which contain that index.
See the following code to get a better picture
import java.io.*;
class GFG {
public static void main(String[] args) {
int[] samling = {1, 2, 4, 3, 8};
int[] samling2 = {1, 2, 4, 3, 8, 8, 3};
int[] svar = concateArrays(samling, samling2);
System.out.println("Ny Array :");
for(int i=0; i < svar.length; i++)
System.out.print(svar[i] + " ");
}
public static int[] concateArrays(int[] samling, int[] samling2)
{
int len = 0;
if (samling.length > samling2.length)
len = samling.length;
else
len = samling2.length;
int[] total = new int[len];
for(int i=0; i < len; i++){
if (i >= samling2.length) {
total[i] = samling[i];
}else if( i >= samling.length) {
total[i] = samling2[i];
}else{
total[i] = samling2[i] + samling[i];
}
}
return total;
}
}
Another variant, with no need for a conditional operation in each iteration of the copying loop:
public static int[] concateArrays(int[] samling, int[] samling2)
{
// max length of the two arrays
int maxLen = Math.max(samling.length,samling2.length);
// decide which of the inputs is shorter and which is longer
int[] shorter = maxLen == samling.length ? samling2 : samling;
int[] longer = maxLen == samling.length ? samling : samling2;
int[] total = new int[maxLen];
// add both as long as there are elements in the shorter
for(int i=0; i < shorter.length; i++) {
total[i] = shorter[i] + longer[i];
}
// copy the remainder of the longer
for(int i=shorter.length; i < longer.length; i++) {
total[i] = longer[i];
}
return total;
}
You can try this :
public static int[] concateArrays(int[] samling, int[] samling2)
{
int minLength = samling.length;
int[] array = null;
if (samling2.length > samling.length) {
array = samling2;
} else {
minLength = samling2.length;
array = samling;
}
for (int i = 0; i < minLength; i++) {
array[i] = samling[i] + samling2[i];
}
return array;
}
This problem is about sequences of positive integers a1,a2,…,aN. A subsequence of a sequence is anything obtained by dropping some of the elements. For example, 3,7,11,3 is a subsequence of 6,3,11,5,7,4,3,11,5,3 , but 3,3,7 is not a subsequence of 6,3,11,5,7,4,3,11,5,3 .
A fully dividing sequence is a sequence a1,a2,…,aN where ai divides aj whenever i < j. For example, 3,15,60,720 is a fully dividing sequence.
Given a sequence of integers your aim is to find the length of the longest fully dividing subsequence of this sequence.
Consider the sequence 2,3,7,8,14,39,145,76,320
It has a fully dividing sequence of length 3, namely 2,8,320, but none of length 4 or greater.
Consider the sequence 2,11,16,12,36,60,71,17,29,144,288,129,432,993 .
It has two fully dividing subsequences of length 5 - (2,12,36,144,288) or (2,12,36,144,432).
To solve this problem, I have written the following code:
import java.util.Scanner;
class DivSeq {
private int n, input[];
void accept() {
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
input = new int[n];
for(int i = 0; i<n; i++)
input[i] = sc.nextInt();
sc.close();
}
int size(int a[]) {
//this function returns the number of non zero entries in an array
int ctr = 0;
for(int i = 0; i<a.length; i++) {
if(a[i]==0)
break;
else
ctr++;
}
return ctr;
}
int sequence() {
int subseq[], pvrseq[], seq[], j, a = 1, q, k = 1, f = 0;
subseq = new int [n];
pvrseq = new int [n];
seq = new int [n];
for(int i = 0; i<n-1; i++) {
k = 1;
for(int c = 0; c<seq.length; c++)
seq[c] = 0;
//seq has been initialized, now inserting 1st value
seq[0] = input[i];
//creating the sequence
for(j = i+1; j<n; j++) {
if(input[j]%input[i]==0)
seq[k++] = input[j];
}
//if size of sequence is 1, then there is no use of checking it
if(size(seq)<2)
continue;
subseq[0] = seq[0];
a = 1;
while(a<size(seq)-1) {
k = 2;
for(int p = a; p<size(seq)-1; p++) {
//initial value of subsequence
if(subseq[1] == 0)
subseq[1] = seq[p];
//creating the subsequence
for(q = p+1; q<size(seq); q++) {
if(seq[q]%seq[p]==0) {
subseq[k++] = seq[q];
p = q-1;
f = 1;
break;
}
}
if(f==1 && q==size(seq)-1)
break;
}
//checking the size of subsequence and previous sequence
if(size(pvrseq)<size(subseq)) {
for(int y = 0; y<subseq.length; y++)
pvrseq[y] = subseq[y];
for(int y = 1; y<subseq.length; y++)
subseq[y] = 0;
}
a++;
}
}
return size(pvrseq);
}
public static void main(String [] args) {
DivSeq obj = new DivSeq();
obj.accept();
System.out.println(obj.sequence());
}
}
This code solves some of the test cases that it is supposed to solve.
case 1: 2,3,7,8,14,39,145,76,320
desired output = 3
case 2: 2,11,16,12,36,60,71,17,29,144,288,129,432,993
desired output = 5
Rest of the test cases are invisible.
However, it does not solve all of them and I cannot understand why. It manages to meet only 4/11 test cases (including case 1 and case 2).
#LuCio and #Aldert I found an alternate way to solve the problem. Here is the code:
import java.util.Scanner;
class DivSeqUpdated {
private int n, input[], weight[];
void accept() {
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
input = new int[n];
weight = new int[n];
for(int i = 0; i<n; i++)
input[i] = sc.nextInt();
sc.close();
}
int max(int x, int y) {
return x<y?y:x;
}
int sequence(int src, int a[], int n) {
if(weight[src]==-1) {
int i, tmp = 0;
for(i = src+1; i<n; i++) {
if(a[i]%a[src]==0)
tmp = max(tmp, sequence(i,a,n));
}
weight[src] = tmp+1;
}
return weight[src];
}
public static void main(String [] args) {
DivSeqUpdated obj = new DivSeqUpdated();
obj.accept();
for(int i = 0; i<obj.n; i++)
obj.weight[i] = -1;
int tmp = 0;
for(int i = 0; i<obj.n; i++)
tmp = obj.max(tmp, obj.sequence(i,obj.input,obj.n));
System.out.println(tmp);
}
}
It gives a result of 11/11 tests which solves the issue. I hope this can help other users as well.
I would take a recursive approach to determine the longest subsequence of a sequence.
protected static int[] subsequence(int[] seq) {
int[] longestSub = new int[0];
for (int i = 0; i < seq.length; i++) {
int[] subAtI = subseq(subarray(seq, i));
if (longestSub.length < subAtI.length) {
longestSub = subAtI;
}
}
return longestSub;
}
private static int[] subseq(int[] seq) {
if (seq.length == 1) {
return seq;
}
int[] longestSub = new int[0];
int current = seq[0];
for (int i = 1; i < seq.length; i++) {
int number = seq[i];
if (number > 0 && current > 0 && number % current == 0) {
int[] subAtI = subseq(subarray(seq, i));
if (longestSub.length < subAtI.length) {
longestSub = subAtI;
}
}
}
return concat(current, longestSub);
}
private static int[] concat(int current, int[] sub) {
int[] result = new int[sub.length + 1];
result[0] = current;
System.arraycopy(sub, 0, result, 1, sub.length);
return result;
}
private static int[] subarray(int[] seq, int i) {
int length = seq.length - i;
int[] result = new int[length];
System.arraycopy(seq, i, result, 0, length);
return result;
}
For a sequence iterate over each integer (seq[i]) and determine the subsequence for that integer (subsequence(subarray(seq, i))). The longest subsequence is the result.
Applying that to some example from the question:
public static void main(String[] args) throws IOException {
printLongestSub(new int[] { 2, 11, 16, 12, 36, 60, 71, 17, 29, 144, 288, 129, 432, 993 }); // [2, 12, 36, 144, 288]
printLongestSub(new int[] { 2, 3, 7, 8, 14, 39, 145, 76, 320 }); // [2, 8, 320]
printLongestSub(new int[] { 2 }); // [2]
printLongestSub(new int[] { 2, 5 }); // [2]
printLongestSub(new int[] { 5, 6, 12 }); // [6, 12]
printLongestSub(new int[] { 5, 6, 12, 11, 33, 99 }); // [11, 33, 99]
}
private static void printLongestSub(int[] seq) {
System.out.println(Arrays.toString(subsequence(seq)));
}
I tried:
public static void main(String[] args) {
int array [] = {2, 5, 1, 4, 7, 9, 0};
for (int i = 0; i < array.length-2; i++) {
swapNum(array[i], array[i+2]);
System.out.println(Arrays.toString(array));
}
System.out.println(Arrays.toString(array));
}
public static void swapNum(int a, int b){
int tmp = a;
a = b;
b = tmp;
}
But found that it is not swapping values. Then I took help from here
https://codereview.stackexchange.com/questions/86016/left-shifting-an-array-of-ints
public void anotherTry() {
int nums [] = {4, 5, 2, 1, 6, 8};
for (int i = 0, start = 0; i < nums.length; i++) {
if (i == 0)
start = nums[i];
if (i == (nums.length - 1)) {
nums[i] = start;
break;
}
nums[i+2] = nums[i];
System.out.println(Arrays.toString(nums));
}
System.out.println(Arrays.toString(nums));
}
Its gives array out of bound of exception.
Where I am wrong?
Role of start variable. If start always will be equal to nums[i]?
You can't swap values like that in Java. However, since you are using an array and want to swap values within the array, you can rewrite your swap method to work with indexes:
public static void main(String[] args) {
int array [] = {2, 5, 1, 4, 7, 9, 0};
for (int i = 0; i < array.length-2; i++) {
swapNum(array, i, i+2);
System.out.println(Arrays.toString(array));
}
System.out.println(Arrays.toString(array));
}
public static void swapNum(int[] values, int i, int j){
int tmp = values[i];
values[i] = values[j];
values[j] = tmp;
}
I got the largest number and smallest number from the string. But how do I find second largest number and third largest number in this java code from this problem? which code should i use? Please explain
public class Problem1
{
public static void main(String[] args) {
int a[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
// int b[] = { 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 };
Problem1 app = new Problem1();
app.scrambleArray(a);
app.print(a);
// Usage enable assertions: -ea to VM arguments
int result = app.findInt(a, 10);
assert (result == 10) :
String.format("Expected <10> but was <%d>", result);
result = app.findInt(a, 11);
assert (result == -1) :
String.format("Expected <-1> but was <%d>", result);
System.out.printf("Largest Number is : %d%n", app.getMax(a));
app.print(app.reverseArray(a));
}
public void scrambleArray(int[] a) {
for (int i = 0; i < a.length; i++) {
int pos = new Random().nextInt(a.length);
int tmp = a[i];
a[i] = a[pos];
a[pos] = tmp;
}
}
public void print(int[] a) {
System.out.println(Arrays.toString(a));
}
public int getMax(int[] a) {
int max = a[0];
for (int i = 1; i < a.length; i++) {
max = Math.max(a[i], max);
}
return max;
}
public int findInt(int[] a, int value) {
int result = -1;
for (int i : a) {
if (value == i) {
result = value;
break;
}
}
return result;
}
public int[] reverseArray(int[] a) {
int[] results = new int[a.length];
for (int i = 0, idx = a.length - 1; i < a.length; i++, idx--) {
results[i] = a[idx];
}
return results;
}
}
Use Arrays.sort() method to sort your integer array
int a[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
Arrays.sort(a);
System.out.println("largest value: " + a[a.length - 1]);
System.out.println("second largest: " + a[a.length - 2]);
The prior answer is generally a good solution. The exception is if the number of elements in the array is very big and performance matters. In that case, it may be faster to keep the N largest elements in a sorted set, and avoid sorting the whole list:
public int[] getNLargest(int[] in, int n){
TreeSet<Integer> large = new TreeSet<Integer>();
for(int i : in){
if(large.size() < n){
large.add(i);
} else if(i > large.first().intValue()){
large.remove(large.first());
large.add(i);
}
}
int[] result = new int[large.size()];
int index = 0;
for(Integer i : large){
result[index] = i.intValue();
index++;
}
return result;
}
import java.util.*;
public class SecondLargestInArray
{
public static void main(String[] args)
{
int arr[] = {14,46,47,86,92,52,48,36,66,85,92};
int largest = arr[0];
int secondLargest = arr[0];
System.out.println("The given array is:" );
for (int i = 0; i < arr.length; i++)
{
System.out.print(arr[i]+"\t");
}
for (int i = 0; i < arr.length; i++)
{
if (arr[i] > largest)
{
secondLargest = largest;
largest = arr[i];
}
else if((arr[i]<largest && arr[i]>secondLargest) || largest==secondLargest)
{
secondLargest=arr[i];
}
}
System.out.println("\nLargest number is:" + largest);
System.out.println("\nSecond largest number is:" + secondLargest);
}
}