I've a question to you.
https://stackoverflow.com/questions/14975968/vertical-arrangement-with-asterisk#=
The code which you shared this post is very good. I've an exam tomorrow. May you tell me the solution.
I edited int array in this program.
It's {-1, 2, 5, 3} but program is not printing (-1) value in which int array.
I want to When the loop read this minus value, it cross new line and print "*" and print the minus value to its underline.
Can you tell me how can i do that in Java?
Thank you.
https://i.stack.imgur.com/ESsVE.jpg
public static void main(String[] args) throws IOException {
int[] a = new int[] {-1,3,-4,2,5};
int[] tmp = a.clone();
Arrays.sort(tmp);
int max = tmp[tmp.length-1];
int low = tmp[0];
int last =max;
if(low<0) {
last=max-low;
}
for (int i = 0; i < last+1; i++) {
for (int j = 0; j < a.length; j++) {
if (i == last ) {
System.out.print(a[j]);
} else if(i<max){
if (i < max - a[j])
System.out.print(" ");
else
System.out.print("*");
}
else {
if (i < max - a[j] )
System.out.print("*");
else
System.out.print(" ");
}
}
System.out.println();
}
}
Related
Given an array A of 0s and 1s, we may change up to K values from 0 to 1.
Return the length of the longest (contiguous) subarray that contains only 1s.
Example 1:
Input: A = [1,1,1,0,0,0,1,1,1,1,0], K = 2
Output: 6
Explanation:
[1,1,1,0,0,1,1,1,1,1,1]
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
Example 2:
Input: A = [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], K = 3
Output: 10
Explanation:
[0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1]
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
Note:
1 <= A.length <= 20000
0 <= K <= A.length
A[i] is 0 or 1
https://leetcode.com/problems/max-consecutive-ones-iii/
This is the question link. On the first test case, I am getting output 9 but it should be 6. I can't figure out where it is going wrong?
public static int f(int arr[],int n,int tar)
{
int st=0,maxc=0,maxf=0;
//tar=tar+1;
for(int i=0;i<n;i++)
{
int se=i-st-maxc;
if(arr[i]==1)
maxc++;
while(i-st-maxc>tar)
{
maxf=Math.max(maxf, i-st);
st++;
}
}
return maxf+1;
}
public static void main(String[] args)
{
Scanner p=new Scanner(System.in);
int n,target;
n=p.nextInt();
target=p.nextInt();
int arr[]=new int[n];
for(int i=0;i<n;i++)
{
arr[i]=p.nextInt();
}
int ans=f(arr,n,target);
System.out.println(ans);
}
You do not need to provide the size of the array because you can get the size from the array.
If you use better variable names, the readability of the code will be better.
Also, you can use if statements in order to check changed values instead of counting.
This is example of the solution:
public static int longestOnes(int[] A, int K) {
var maxCount = 0;
for (int i = 0; i < A.length; i++) {
var count = 0;
var k = 0;
for (int j = i; j < A.length; j++) {
if (A[j] == 1) {
count++;
}
if (A[j] == 0) {
if (k >= K) {
if (count > maxCount) {
maxCount = count;
}
break;
}
count++;
k++;
}
}
}
return maxCount;
}
I have homework about arrays in Java and I am stuck on this question.
Fill in the body of the program below, which removes duplicate values from the sorted array input. Your solution should set the variable result to the number of values remaining after the duplicate values have been removed. For example, if input is (0,1,1,2,3,3,3,4,4), the first five values of input after removing the duplicates should be (0,1,2,3,4), and the value of result should be 5.
Here's my code:
import java.util.Scanner;
public class RemoveDups {
public static void main (String[] args) {
Scanner scan = new Scanner(System.in);
int[] input = 0,1,1,2,3,3,3,4,4;
int result;
int count = input[0];
result++;
String count1="";
int result2=0;
count1=count1+count;
input[0]=Integer.parseInt(count1);
count1="";
for (int j = 1; j <input.length-1;j++ ) {
if (count != input[j+1] && result2 == 0||count != input[j-1] &&result2==0 ) {
input[j] = count;
result++;
count = input[j + 1];
count1=count1+count;
input[j]=Integer.parseInt(count1);
count1="";
}
}
for (int i = 0; i < result; i++) {
System.out.println(input[i]);
}
}
}
}
I can't do this exercise. i have left always the last cell in array that is different from all another cells and this code not working for me.
public static int removeDuplicateElements(int arr[], int n){
if (n==0 || n==1){
return n;
}
int j = 0;
for (int i=0; i < n-1; i++){
if (arr[i] != arr[i+1]){
arr[j++] = arr[i];
}
}
arr[j++] = arr[n-1];
return j;
}
public static void main(String args []) {
int arr[] = {0,1,1,2,3,3,3,4,4};
int length = arr.length;
length = removeDuplicateElements(arr, length);
for (int i=0; i<length; i++)
System.out.print(arr[i]+" ");
}
Answer will be 0 1 2 3 4
Please refer following link.
Remove Duplicate Element in Array using separate index
I am not sure if you needed a filtered array or just the result value. The below will give you result value.
Since this is homework, I suggest you work on the below logic to create the non duplicate array.
int result = 1;
if(input == null || input.length == 0){
result = 0;
}
else{
for(int i = 1; i < input.length; i++){
if(input[i-1] != input[i]){
result++;
}
}
}
I am new to Java Programming (or programming infact).
I have an array which contains either 4 or 6 only. Given a number, either 4 or 6, find the highest sequential occurrence of the given number.
I need highest sequential occurrence count
Example: arr[{4,4,6,6,4,4,4,4,4,6}]
If the above array is given, and next input number is 4, the output should be 5. Because the number 4 has occurred sequentially 5 times.
public static void main(String[] args) throws IOException {
String arrayTK = br.readLine(); // Input is 4466444446
int[] inpArray = new int[10];
for (int i = 0; i < 10; i++) {
inpArray[i] = arrayTK.charAt(i) - '0';
}
int maxSequenceTimes = 0;
for (int j = 0; j < 10; j++) {
// Logic
}}
Any help would be greatly appreciated.
Edit
We will separate and count all sequences and then search in each sequence to know which sequence contain the biggest length.
int[] arr = {4,4,6,6,4,4,4,4,4,6};
boolean newSeq = false;
int diffrentSeq = 0;
int currentNumber;
//Get sequence numbers
for (int i = 0; i < arr.length; i++) {
currentNumber = arr[i];
if (i >= 1 && currentNumber != arr[i - 1])
newSeq = true;
else if (i == 0)
newSeq = true;
//It's new sequence!!
if (newSeq) {
diffrentSeq++;
newSeq = false;
}
}
System.out.println(diffrentSeq);
int[] maxSequencSize = new int[diffrentSeq];
int lastIndex = 0;
for (int i = 0; i < maxSequencSize.length; i++) {
int currentNum = arr[lastIndex];
for (int j = lastIndex; j < arr.length; j++) {
if (arr[j] == currentNum) {
maxSequencSize[i]++;
lastIndex = j + 1;
} else break;
}
}
System.out.println(max(maxSequencSize));
You need to get max value which act the max sequence length:
private static int max(int[] array){
int maxVal = 0;
for (int anArray : array) {
if (anArray > maxVal)
maxVal = anArray;
}
return maxVal;
}
String arrayTK = br.readLine(); // Input is 4466444446
Because your first input is a string, you don't need to convert it to an int array and if you are using you can use:
String arrayTK = "4466444446";
int result = Arrays.asList(arrayTK.replaceAll("(\\d)((?!\\1|$))", "$1;$2").split(";"))
.stream().max(Comparator.comparingInt(String::length)).get().length();
System.out.println(result);
Explanation :
arrayTK.replaceAll("(\\d)((?!\\1|$))", "$1;$2") put a separator between each two different numbers the result should be 44;66;44444;6
.split(";") split with this separator (i used ; in this case) the result is ["44", "66", "44444", "6"]
stream().max(Comparator.comparingInt(String::length)).get() get the max input
.length() to return the length of the result
Ideone demo
Edit
How I modify the same, to get count to any specific number. I mean, max sequential occurrence of number 4
In this case you can just add a filter .filter(t -> t.matches(number + "+")) which mean get only the numbers which match 4+ where 4 can be any number :
...
int number = 6;
int result = Arrays.asList(arrayTK.replaceAll("(\\d)((?!\\1|$))", "$1;$2").split(";"))
.stream()
.filter(t -> t.matches(number + "+"))
.max(Comparator.comparingInt(String::length)).get().length();
You need something like this:
import java.util.Scanner;
public class A {
public static void main(String[] args) {
Scanner br =new Scanner(System.in);
String str = br.next();
int arr[]=new int[str.length()];
for(int i=0;i<str.length();i++)
{
arr[i]=str.charAt(i)-'0';
//System.out.println(arr[i]);
}
int j=0;
int count=1,max=0;
for(int i=0;i<str.length();i++)
{
if(i==0){
j=arr[i];
}
else
{
if(arr[i]==j)
{
count++;
//System.out.println(" "+count);
}
else
{
if(max<count){
max=count;
}
count=1;
j=arr[i];
}
}
}
if(max<count){
max=count;
}
System.out.println(max);
}
}
That should do the work. Every time you find the matching value you start counting and when the streak is over you compare the length with the maximum length you have found so far.
public int logic(int[] inpArray, int num) {
int count = 0, max = 0
for(int i = 0; i < 10; ++i){
if(inpArray[i] == num) {
count++
else{
if(count > max)
max = count;
count = 0;
}
}
if (count > max)
max = count;
return max;
}
Ive been working on this assignment question for about 4 days now and I'm about to go crazy. We have specific directions to follow for this code;
"Your program should proceed as follows:
Display a welcome message.
Prompt the user for an integer which is 3. If the number entered is < 3. keep prompting the user until they enter a number 3 (use a do/while). This number will determine the size of the square array.
Fill the array as per pattern 1 and display it using printf to format the array.
Fill the same array as per pattern 2 and display it using printf t0 format the array.
Display a closing message."
Pattern:
I'm still stuck on pattern one. I tried to do first do a for loop which in it there's an if statement that checks if the column number is even or not, if it is, to print out the code backwards. The question also recommends using a while loop and a do/while loop...?
Also any tips on to how to go about the second patterns.
Here is my code.
import java.util.Scanner;
public class a3q33
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
int n;
do
{
System.out.println("How many rows/columns do you want your array to have? (Must be at least 3)");
n=keyboard.nextInt();
} while(n < 3);
int [][] arr = new int [n][n];
int i, j, k=1;
for(i=0;i<n;i++)
{
if(i % 2 != 0)
{
for(j=n;j>0;j--)
{
k = k+n;
arr[i][j]=k;
k--;
}
}
else
{
for(j=0;j<n;j++)
{
arr[i][j]=k;
k++;
}
}
}
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
System.out.printf(arr[i][j]+" ");
}
System.out.printf("");
System.out.println();
}
}
}
Any help would be greatly appreciated!
I assume that you meant "row" instead of "column" for the condition check given that the convention is arr[row][column]?
Also, the for loop in your code:
for(j=n;j>0;j--)
This will decrement the row/column index down to 1 and not 0. So you will miss one element at arr[0][...] or arr[...][0].
Also, j=n will be out of bound.
Instead, try using:
for(j=n-1;j>-1;j--)
It would be a good first steps to look into.
import java.util.Scanner;
public class a3q33{
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
int n;
do{
System.out.println("How many rows/columns do you want your array to have? (Must be at least 3)");
n=keyboard.nextInt();
} while(n < 3);
int count = 1;
int [][] arr = new int [n][n];
for(int i = 0;i<n; i++){
if(i%2==0){
for(int j = 0;j<n; j++){
arr [i][j] = count;
count++;
}
}
else{
for(int j = n-1;j>=0; j--){
arr [i][j] = count;
count++;
}
}
}
System.out.println("\nPattern 1 \n");
// print the array
for (int i = 0; i < n; i++){
for (int j = 0; j < n; j++){
System.out.printf("%d\t",arr[i][j]);
}
System.out.println();
}
// reset count back to 1 and fill the array in the same way only without the if/else
// for n = 5 for example this will produce [1, 2, 3, 4, 5 ]
// [6, 7, 8, 9, 10]
// [11,12, 13, 14, 15]
// [16,17, 18, 19, 20]
// [21,22, 23, 24, 25]
count = 1;
for(int i = 0;i<n; i++){
for(int j = 0;j<n; j++){
arr [i][j] = count;
count++;
}
}
// rotate arrays using arraycopy; for array at index 1 rotate by one, at index 2 by 2 and so on see
//http://stackoverflow.com/questions/31174840/how-to-rotate-an-array
//
for (int i = 1; i<n; i++){
int [] temp = new int [n];
for (int j = 0; j < n; j++) {
temp[(j + i) % n] = arr[i][j];
}
System.arraycopy(temp, 0, arr[i], 0, n);
arr[i]=temp;
}
System.out.println("\nPattern 2 \n");
// print the array
for (int i = 0; i < n; i++){
for (int j = 0; j < n; j++){
System.out.printf("%d\t",arr[i][j]);
}
System.out.println();
}
}
}
You can achieve this by checking the modulo:
for (int i = 0; i < n; i++) {
int start = i * n;
for (int j = 0; j < n; j++) {
arr[i][j] = i * n + ((i % 2 === 0) ? (j + 1) : (n - j));
}
}
I still can't get this right. The code in the bubble sort is incorrect. How can I get this right? What should I change or add to get the correct results? Thanks in advance. :)
import java.util.Random;
import java.util.Scanner;
public class HomeWork {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int choice;
int e;
Random t = new Random();
for (e = 1; e <= 5; e++) {
System.out.println(t.nextInt(1000));
}
System.out.println(" \n1: BUBBLE SORT ");
System.out.println(" 2: SELECTION SORT ");
System.out.println(" 3: QUICK SORT ");
System.out.println(" Choose a number from 1-3 ");
choice= s.nextInt();
if(choice == 1) {
System.out.print("You chose BUBBLE sort!");
int temp, q, w;
for(int i=0;i<w-1;i++) { //I think there is something wrong here in my bubble sort code.
// What should I add or change to make this correct?
for(int j=0;j<w-1-i;j++) {
if(q[j]>q[j+1]) {
temp = q[j];
q[j] = q[j+1];
q[j+1] = temp;
System.out.println(q[i]+""); // What should I change here to print the correct results?
} else if(choice == 2) {
System.out.print("You chose SELECTION sort!");
} else if(choice == 3) {
System.out.println("You chose QUICK sort!");
} else {
System.out.println("Not in the choices!");
}
}
}
}
}
}
I am still just a beginner. Please please help. Thanks in advance :)
Your problem is that you have not defined q or w--presumably you want them to be the array of numbers and its length. Furthermore, because your bubble sort does not automatically detect when the list has been sorted and stop then, it is more like a combined bubble/selection sort.
public static void main(String[] args) {
int a[] = { 1, 5, 100, 40, 80, 50 };
int length = a.length;
int temp;
for (int i = 0; i < length; i++) {
for (int j = 1; j < length - i; j++) {
if (a[j - 1] > a[j]) {
temp = a[j - 1];
a[j - 1] = a[j];
a[j] = temp;
}
}
}
for (int i = 0; i < a.length; i++) {
System.out.print(a[i] + " ");
}
}
Like the guy commented above, this the bubble sorting algorithm, and the guy above that, your Variable (w) is wrong, all wrong, and as a tip in the future, post the error, with the code, that's probably why you got a downvote and or because this is pretty simple.
Also forgive me, but i dont have eclipse, and am now coding in C++, but this should work
int x[] = new int[5]
Random t = new Random();
for (e = 1; e <= 5; e++) {
x[e] = t.nextInt(1000); // you didn't even assign any variables to sort, that's one problem, you just printed them.
} // and idk how you get random int's in java, but if this doesn't work, just make your own random int generator.
// There's LOTS of better ones than the one your using now.
int temp, q, w;
for(int i=0;i< 5;i++) {
for(int j=0;j<5-i;j++) {
if(q[j]>q[j+1]) {
temp = q[j-1];
q[j-1] = q[j];
q[j] = temp;
}
// Add 'else ifs' here
}
}
for (int i = 0; i < 5; i++) { // and this will print the results
System.out.print(q[i] + " ");
}
This should work, idk, not really experienced in java >.>, and btw there are tons of books that teach algorithm's, you should first look through your code really well, because of it's a simply mistake like now, these people on stack overflow aren't merciful, there all experience programmer that are really hard on you, but they are smart. (like me :D)
[EDIT] -btw, just merge this with your code, but here are some useful sites.
for random int's - http://www.javapractices.com/topic/TopicAction.do?Id=62
for bubble sort - http://examples.javacodegeeks.com/core-java/bubble-sort-algorithm-in-java-code-example/
public class BubbleSort {
public static void main(String[] args) {
int a[] = { 1, 5, 100, 40, 80, 50 };
int length = a.length;
int temp;
for (int i = 0; i < length; i++) {
for (int j = 1; j < length - i; j++) {
if (a[j - 1] > a[j]) {
temp = a[j - 1];
a[j - 1] = a[j];
a[j] = temp;
}
}
}
for (int i = 0; i < a.length; i++) {
System.out.print(a[i] + " ");
}
}
}