I am trying to solve this exercise, It seems easy this, but I can not understand the contraints -rules, It says:
the number may be represented on one or two hands;
if the number is represented on two hands, the larger number is given first
The rule number 2 I can not understand for example if it says 3, I have 3, 2+1, 1+2 (this not because its repeated), if it says 6 we have 6, 5+1, 4+2, 3+3, 2+4 + 1+5 but the correct output is 3, can someone guide me in this problem?? for 7 is 2, and 8 is 2, 9 is 1, and 10 is 1.
this is my code:
import java.util.Scanner;
class j1 {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int tot = 5;
int n = sc.nextInt();
int sum = 0;
int count = 1;
for (int i = 1; i <= tot; i++) {
for (int j = 1; j <= tot; j++) {
sum = i + j;
if (sum == n) {
System.out.println(i);
System.out.println(j);
count++;
}
}
}
System.out.println(count);
sc.close();
}
}
Its simple - if you are going to give the number using both the hands (2 hands) then you will first need to give the larger number which comprises the overall number -
eg for 7 (4+3 OR 5+2) when represented using 2 hands - give 4 first !
other option for 7 (3+4, 2+5) are invalid since it will make us to list the smaller number first which violates the rule #2
The number of the second hand must always be less than or equal to the number of the first hand. I believe the code below will work.
import java.util.Scanner;
class j1 {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int tot = 5;
int n = sc.nextInt();
int sum = 0;
int count = 1;
for (int i = 1; i <= tot; i++) {
for (int j = 1; j <= i; j++) {
sum = i + j;
if (sum == n) {
System.out.println(i);
System.out.println(j);
count++;
}
}
}
System.out.println(count);
sc.close();
}
}
Related
The task is to let the user input 10 numbers into an array. Then to print out how long the longest sequence of growing numbers is.
So for 1 8 45 6 5 4 5 8 10 65 the longest sequence would be 4 5 8 10 65, which is length = 5
public class Main {
public static void main(String[] args) {
int []a = new int[10];
int c = 1;
int max = 0;
for(int i=0; i<a.length; i++){
a[i] = In.readInt();
}
for(int i=0;i<a.length-1;i++){
if(a[i]<a[i+1]){
++c;
if(c>max){
max=c;
}
}else{
c=1;
}
}
Out.print("Length = " + max);
}
}
The program I'm submitting this to says this is only 75% correct and I can't for the life of me figure out why, it works with every combination of numbers I could come up with.
I think you are on the right track, a slight modification of the if condition inside your for-loop by moving the increment of c (which I have presumed stands for counter/count)? inside it should make it work with all test cases:
import java.util.Arrays;
import java.util.Scanner;
class Main {
public static void main(String[] args) {
int aLength = 10;
int a[] = new int[aLength];
System.out.printf("Enter %d integers separated by spaces: ", aLength);
try (Scanner scanner = new Scanner(System.in)) {
for (int i = 0; i < aLength; i++) {
a[i] = scanner.nextInt();
}
}
int maxLength = 1, counter = 1;
for (int i = 0; i < aLength - 1; i++) {
if (a[i] < a[i + 1]) {
counter++;
maxLength = Math.max(maxLength, counter);
} else {
counter = 1;
}
}
System.out.printf("Max length is %d\n", maxLength);
}
}
Example Usage:
Enter 10 integers separated by spaces: 1 8 45 6 5 4 5 8 10 65
Max length is 5
Note technically a subsequence/sequence does not have to be continuous (if you were looking the longest subsequence with growing numbers the answer would be 6, i.e., 1, 5, 4, 8, 10, 65) however from what your required output is i.e., 5, it is clear you are looking for the longest sub-array or continuous subsequence/sequence.
When I submit my code on Google Kickstart, I get a "wrong answer" for the 1st test set, even though the sample input and output match. I'm really not sure why Google does not accept the code.
The task is that given an array of N positive integers, find the number of K-countdowns, where a K-countdown is a contiguous subarray if it is of length K and contains the integers K, K-1, K-2, ..., 2, 1 in that order.
Input:
The first line of the input gives the number of test cases, T. T test cases follow. Each test case begins with a line containing the integers N and K. The second line contains N integers. The i-th integer is Ai.
Output:
For each test case, output one line containing Case #x: y, where x is the test case number (starting from 1) and y is the number of K-countdowns in her array.
Sample Input:
3
12 3
1 2 3 7 9 3 2 1 8 3 2 1
4 2
101 100 99 98
9 6
100 7 6 5 4 3 2 1 100
Sample Output:
Case #1: 2
Case #2: 0
Case #3: 1
My logic is pretty straightforward: I have a counter variable x which starts at K and decrements whenever an integer equals x. If a countdown is found (x=0 after decrementing) then the answer increases and x is set to equal K. Here is the crux of my code:
for(int i=0; i<n; i++) {
arr[i]=sc.nextLong();
if(arr[i]==x)
x--;
else
x=k;
if(x==0) {
ans++;
x=k;
}
}
Here is my entire code in case there are any trivial errors:
import java.util.Scanner;
public class Solution {
static int t;
static long n,k;
static long[] arr;
static Scanner sc=new Scanner(System.in);
public static void main(String[] args) {
t=sc.nextInt();
for(int i=1; i<=t; i++) {
n=sc.nextLong();
k=sc.nextLong();
System.out.println("Case #"+i+": "+solve());
}
sc.close();
}
public static long solve() {
long x=k;
long ans=0;
arr=new long[(int)n];
for(int i=0; i<n; i++) {
arr[i]=sc.nextLong();
if(arr[i]==x)
x--;
else
x=k;
if(x==0) {
ans++;
x=k;
}
}
return ans;
}
}
here is my cpp code which is running in o(n)
#include<bits/stdc++.h>
using namespace std;
int main(){
int t,m;
cin>>t;
m=t;
while(t--){
int n,k;
cin>>n>>k;
vector <int> v,v2;
for(int i=0;i<n;i++){
int tr;
cin>>tr;
v.push_back(tr);
}
for(int j=0;j<k;j++){
int tr=k-j;
v2.push_back(tr);
}
int fg=0;
for(int i=0;i<n;i++){
if(v[i]==k){
int count=0;
for(int j=0;j<k;j++){
if(v2[j]==v[i+j])
count++;
}
if(count==k)
fg++;
}
}
cout<<"Case #"<<m-t<<": "<<fg<<endl;
}
}
Suppose there is half of a countdown in the array and the following number is K.
Based on the code, that number will be neglected and so if there is a following countdown, it won't be counted. Here is what the main loop should look like:
for (int i = 0; i < n; i++) {
arr[i] = sc.nextLong();
if (arr[i] == x)
x--;
else if (arr[i] == k)
x = k-1;
else
x = k;
if (x == 0) {
ans++;
x = k;
}
}
Here is my Accepted code in java :
import java.util.*;
public class Solution {
public static int kCountDown(int [] nums, int k) {
int length = nums.length;
int endCounter = 0;
int result = 0;
for (int i=1; i<length; i++) {
if (nums[i - 1] - nums[i] == 1)
endCounter += 1;
else
endCounter = 0;
if (nums[i] == 1 && endCounter >= k - 1)
result += 1;
}
return result;
}
public static void main(String [] args) {
Scanner sc = new Scanner(System.in);
int test = sc.nextInt();
for (int t=1; t<=test; t++) {
int n = sc.nextInt();
int k = sc.nextInt();
int [] nums = new int [n];
for (int i=0; i<n; i++) {
nums[i] = sc.nextInt();
}
System.out.println("Case #" + t + ": " + kCountDown(nums, k));
}
}
}
Complexity is O(n) where n = length of the input array
This program is meant to display an array and compute prime numbers between 1 and whatever the user enters. On some IDEs that "Capture Output", the list of prime numbers will not "word-wrap". Instead, it will display one VERY long line of numbers. This can be handled by inserting a "line-feed" in the display code that is activated every 15 numbers. I have no clue how to do this, my code is below.
import java.util.Scanner;
import java.text.DecimalFormat;
public class Lab11avst {
public static void main(String[] args) {
// This main method needs additions for the 100 point version.
Scanner input = new Scanner(System.in);
System.out.print("Enter the primes upper bound ====>> ");
final int MAX = input.nextInt();
boolean primes[];
primes = new boolean[MAX];
computePrimes(primes);
displayPrimes(primes);
}
public static void computePrimes(boolean primes[]) {
System.out.println("\nCOMPUTING PRIME NUMBERS");
int newLine = 15;
int multiplicator = 1;
int list[] = new int[1000];
for (int k=2; k < primes.length; k++) {
primes[k] = true;
}
for (int k=2; k < primes.length; k++)
for (int x=2*k;x<primes.length;x+=k)
primes[x] = false;
}
public static void displayPrimes(boolean primes[]) {
DecimalFormat output = new DecimalFormat("0000");
System.out.println("\n\nPRIMES BETWEEN 1 AND " + primes.length);
int numPrimes = 0;
for (int k=2; k < primes.length; k++) {
if (numPrimes % 15 == 0) System.out.println("");
if (primes[k]) System.out.print(output.format(k) + " ");
++numPrimes;
}
}
}
If you have to proceed with your current method of computing prime numbers, then you can just keep track of how many primes have been printed, and add a line break for every 15 numbers. I suggest making a slight change to your displayPrimes() method:
public static void displayPrimes(boolean primes[]) {
DecimalFormat output = new DecimalFormat("0000");
System.out.println("\n\nPRIMES BETWEEN 1 AND " + primes.length);
int numPrimes = 0;
for (int k = 2; k < primes.length; k++) {
if (numPrimes % 15 == 0) System.out.println("");
if (primes[k]) System.out.print(output.format(k) + " ");
++numPrimes;
}
}
I use System.out.println here, which guarantees that the correct line break will be used for any platform.
However, a nicer way to approach the entire problem would be to just compute the actual prime numbers themselves, and then just iterate that array and display. Using this approach would require a complete refactor of code, maybe not what you want, and also probably too broad for a single question.
Let numPrimes indeed count the printed primes:
int numPrimes = 0;
for (int k = 2; k < primes.length; k++) {
if (primes[k]) {
if (numPrimes % 15 == 0) {
System.out.println();
}
System.out.print(output.format(k) + " ");
++numPrimes;
}
}
And \n is on Unix/Linux and MacOS, Windows uses \r\n:
System.out.println("\nCOMPUTING PRIME NUMBERS");
should be
System.out.println();
System.out.println("COMPUTING PRIME NUMBERS");
I'm a total beginner of java.
I have a homework to write a complete program that calculates the factorial of 50 using array.
I can't use any method like biginteger.
I can only use array because my professor wants us to understand the logic behind, I guess...
However, he didn't really teach us the detail of array, so I'm really confused here.
Basically, I'm trying to divide the big number and put it into array slot. So if the first array gets 235, I can divide it and extract the number and put it into one array slot. Then, put the remain next array slot. And repeat the process until I get the result (which is factorial of 50, and it's a huge number..)
I tried to understand what's the logic behind, but I really can't figure it out.. So far I have this on my mind.
import java.util.Scanner;
class Factorial
{
public static void main(String[] args)
{
int n;
Scanner kb = new Scanner(System.in);
System.out.println("Enter n");
n = kb.nextInt();
System.out.println(n +"! = " + fact(n));
}
public static int fact(int n)
{
int product = 1;
int[] a = new int[100];
a[0] = 1;
for (int j = 2; j < a.length; j++)
{
for(; n >= 1; n--)
{
product = product * n;
a[j-1] = n;
a[j] = a[j]/10;
a[j+1] = a[j]%10;
}
}
return product;
}
}
But it doesn't show me the factorial of 50.
it shows me 0 as the result, so apparently, it's not working.
I'm trying to use one method (fact()), but I'm not sure that's the right way to do.
My professor mentioned about using operator / and % to assign the number to the next slot of array repeatedly.
So I'm trying to use that for this homework.
Does anyone have an idea for this homework?
Please help me!
And sorry for the confusing instruction... I'm confused also, so please forgive me.
FYI: factorial of 50 is 30414093201713378043612608166064768844377641568960512000000000000
Try this.
static int[] fact(int n) {
int[] r = new int[100];
r[0] = 1;
for (int i = 1; i <= n; ++i) {
int carry = 0;
for (int j = 0; j < r.length; ++j) {
int x = r[j] * i + carry;
r[j] = x % 10;
carry = x / 10;
}
}
return r;
}
and
int[] result = fact(50);
int i = result.length - 1;
while (i > 0 && result[i] == 0)
--i;
while (i >= 0)
System.out.print(result[i--]);
System.out.println();
// -> 30414093201713378043612608166064768844377641568960512000000000000
Her's my result:
50 factorial - 30414093201713378043612608166064768844377641568960512000000000000
And here's the code. I hard coded an array of 100 digits. When printing, I skip the leading zeroes.
public class FactorialArray {
public static void main(String[] args) {
int n = 50;
System.out.print(n + " factorial - ");
int[] result = factorial(n);
boolean firstDigit = false;
for (int digit : result) {
if (digit > 0) {
firstDigit = true;
}
if (firstDigit) {
System.out.print(digit);
}
}
System.out.println();
}
private static int[] factorial(int n) {
int[] r = new int[100];
r[r.length - 1] = 1;
for (int i = 1; i <= n; i++) {
int carry = 0;
for (int j = r.length - 1; j >= 0; j--) {
int x = r[j] * i + carry;
r[j] = x % 10;
carry = x / 10;
}
}
return r;
}
}
How about:
public static BigInteger p(int numOfAllPerson) {
if (numOfAllPerson < 0) {
throw new IllegalArgumentException();
}
if (numOfAllPerson == 0) {
return BigInteger.ONE;
}
BigInteger retBigInt = BigInteger.ONE;
for (; numOfAllPerson > 0; numOfAllPerson--) {
retBigInt = retBigInt.multiply(BigInteger.valueOf(numOfAllPerson));
}
return retBigInt;
}
Please recall basic level of math how multiplication works?
2344
X 34
= (2344*4)*10^0 + (2344*3)*10^1 = ans
2344
X334
= (2344*4)*10^0 + (2344*3)*10^1 + (2344*3)*10^2= ans
So for m digits X n digits you need n list of string array.
Each time you multiply each digits with m. and store it.
After each step you will append 0,1,2,n-1 trailing zero(s) to that string.
Finally, sum all of n listed string. You know how to do that.
So up to this you know m*n
now it is very easy to compute 1*..........*49*50.
how about:
int[] arrayOfFifty = new int[50];
//populate the array with 1 to 50
for(int i = 1; i < 51; i++){
arrayOfFifty[i-1] = i;
}
//perform the factorial
long result = 1;
for(int i = 0; i < arrayOfFifty.length; i++){
result = arrayOfFifty[i] * result;
}
Did not test this. No idea how big the number is and if it would cause error due to the size of the number.
Updated. arrays use ".length" to measure the size.
I now updated result to long data type and it returns the following - which is obviously incorrect. This is a massive number and I'm not sure what your professor is trying to get at.
-3258495067890909184
I have this program that returns a factorial of N. For example, when entering 4,,, it will give 1! , 2! , 3!
How could I convert this to use nested loops?
public class OneForLoop
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter a number : ");
int N = input.nextInt();
int factorial = 1;
for(int i = 1; i < N; i++)
{
factorial *= i;
System.out.println(i + "! = " + factorial);
}
}
}
If written as nested loops it would look like this:
for (int i = 1; i < N; ++i)
{
int factorial = 1;
for (int j = 1; j <= i; ++j) {
factorial *= j;
}
System.out.println(i + "! = " + factorial);
}
Result:
Enter a number : 10
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720
7! = 5040
8! = 40320
9! = 362880
This program gives the same result as yours, it just takes longer to do so. What you have already is fine. Note also that the factorial function grows very quickly so an int will be too small to hold the result for even moderately large N.
If you want to include 10! in the result you need to change the condition for i < N to i <= N.
Right now you are calculating your factorial incrementally. Just recalculate it from scratch every time. Be advised that what you have now is better than what I'm posting, but this does follow your requirements.
public class TwoForLoops
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter a number : ");
int N = input.nextInt();
int factorial = 1;
for (int i = 1; i < N; ++i)
{
factorial = 1;
for(int j = 1; j <= i; j++)
{
factorial *= j;
}
System.out.println(i + "! = " + factorial);
}
}
}
Rather than just computing everything in a linear fashion, you could consider an inner loop which would do something like what you have in the outer loop. Is that what you are trying to achieve?
Would you consider recursion a nested loop?
public long factorial(int n)
{
if (n <= 1)
return 1;
else
return n * factorial(n - 1);
}
public static void main(String [] args)
{
//print factorials of numbers 1 to 10
for(int i = 1; i <= 10; i++)
System.out.println(factorial(i));
}