How recurrsion works - c#-4.0

Hi I have a sample code here in which i am trying to shift the array by a given number of times.In output i want to print the final array generated after going through all the shifts.
public static void Main(string[] args)
{
int[] oldArray={1,2,3,4};
int[] newArray=Program.shiftRight(oldArray,3);
foreach(var item in newArray)
Console.Write(item+ " ");
}
public static int[] shiftRight(int[] arr,int times)
{
int[] demo = new int[arr.Length];
for (int i = 0; i < arr.Length; i++)
{
demo[(i+1) % demo.Length] = arr[i];
}
foreach(var item in demo)
Console.Write(item+ " ");
Console.WriteLine("");
times--;
if(times>0)
{
shiftRight(demo,times);
}
Console.WriteLine("\n");
return demo;
}
The output i am getting is
Hello, world!
4 1 2 3
3 4 1 2
2 3 4 1
4 1 2 3
can somebody explain why in main i am not getting output as "2 3 4 1"
but "4 1 2 3"?Thanks in advance.

Related

4 character string combination java

Good day,
I have to write a program that prints all permutations of the String "abcd" with the following restrictions:
the strings must always have 4 characters;
one character can be used more then once in a string;
"b" must always be followed by "a";
a string cannot have both "d" and "a"; and
the program must also print at the end the number of strings printed.
here is the working code i came up with so far.
Now i have to add code for :
"b" must always be followed by "a";
a string cannot have both "d" and "a";
Can someone help me with this ?
public class Combination2 {
public static void main(String[] args) {
String s = "abcd";
int count = 0;
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
for (int k = 0; k < 4; k++) {
for (int d = 0; d < 4; d++) {
String res = "" + s.charAt(i) + s.charAt(j) + s.charAt(k) + s.charAt(d);
count++;
System.out.println("" + res);
}
}
}
}
System.out.println("There are " + count + " combinations");
}
}
The simplest place to start would probably be to generate all permutations of the String "abcd" while ignoring the restrictions. Then once you have that figured out try and work on the restrictions.

Map value is not getting increased when it finds duplicate key. Please advise

I am new to Java.. Please help me to get required output for the below code.
Map value has to be counted when month value is repeated
Issue occurs due to 2 sublist which is executing on a different threads. Please advise if there is any modification needs to be done in this code in order to rectify map value to get counted.
int size = inputList.size();
int listSize = size/numberOfThreads;
List<String> tmplist1 = inputList.subList(0, listSize);
int count = listSize;
for (int i=0;i<numberOfThreads;i++)
{
if(listSize <= size) {
t1 = new TotalOrderThread();
t1.setInput(tmplist1);
Thread thread = new Thread(t1);
thread.start();
thread.join();
if(listSize < size)
tmplist1 = inputList.subList(listSize, listSize+count);
listSize=listSize+count;
}
*
Input:
123,03/04/2005
234,04/05/2005
567,03/04/2005
789,01/01/2005
Output:(month 4 is repeated twice but the value is not getting counted as 2). Please help to find out the mistake. Also, Is there anyway to print the month value as "MMM" format while iterating map?
4 1
5 1
1 1
4 1
*
Map<Integer,Integer> orderMap = new HashMap<>();
for(int i=0;i<this.input.size();i++)
{
String details = input.get(i);
String[] detailsarr = details.split(",");
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uuuu" ) ;
LocalDate id = LocalDate.parse(detailsarr[1], f);
int month = id.getMonthValue();
if(orderMap.containsKey(month))
{
int count = orderMap.get(month);
orderMap.put(month, count+1);
}
else
{
orderMap.put(month, 1);
}
}
for(Map.Entry<Integer,Integer> entry : orderMap.entrySet())
{
int month3 = entry.getKey();
int value = entry.getValue();
System.out.println(month3+ " " +value);
}
}
I tried your code like below. This one works.
Map<Integer,Integer> orderMap = new HashMap<>();
String[] input = {"123,03/04/2005", "234,04/05/2005", "567,03/04/2005", "789,01/01/2005"};
for(int i=0;i<input.length;i++)
{
String details = input[i];
String[] detailsarr = details.split(",");
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uuuu" ) ;
LocalDate id = LocalDate.parse(detailsarr[1], f);
int month = id.getMonthValue();
if(orderMap.containsKey(month))
{
int count = orderMap.get(month);
orderMap.put(month, count+1);
}
else
{
orderMap.put(month, 1);
}
}
for(Map.Entry<Integer,Integer> entry : orderMap.entrySet())
{
int month3 = entry.getKey();
int value = entry.getValue();
System.out.println(month3+ " " +value);
}

how to sort list of names satisfying below

The answer to be in any programing language satisfying following conditions
Only the first letter of each part of the name should be capital.
All the parts of the name except the last part should be represented by only two characters.
The first character should be the first letter of the part and should be capitalized.
The second character should be . .
example:
Input:
mahatma gandhi
Mohndas KaramChand gandhi
Output:
M. Gandhi
M. K. Gandhi
Please try if the following Java code can help you.
class Main {
public static void main(String[] args) {
String input = "mahatma gandhi\n" +
"Mohndas KaramChand gandhi\nVijay singh";
char[] chars = input.toLowerCase().toCharArray();
boolean found = false;
for (int i = 0; i < chars.length; i++) {
if (Character.isWhitespace(chars[i])) {
chars[i + 1] = Character.toUpperCase(chars[i + 1]);
}
}
chars[0] = Character.toUpperCase(chars[0]);
String output = String.valueOf(chars);
String[] parts1 = output.split("\n");
for (int i = 0; i < parts1.length; i++) {
String[] names = parts1[i].split(" ");
String[] initials = output.split(" ");
String lastname = names[names.length - 1];
for (int j = 0; j < names.length - 1; j++) {
initials[j] = names[j].substring(0, 1);
System.out.print(initials[j] + ".");
}
System.out.println(" " + lastname);
}
}
}
Output
M. Gandhi
M.K. Gandhi
V. Singh
You can try different versions of the input string, or change the program to read the string from a file or from the console. I hope it works for you.

Strange multi-threading output for different Platforms

I executed the following code on Ubuntu 14.04 and CentOS 7 using gcc compiler but the strange thing is that it shows different output for same inputs. There are two issues that I'm unable to solve.
I always get 0 in sum(in main function) for the very first multiplication (1*1).
Completely unexpected output for Ubuntu.
Here is the code and both the outputs.
Code
#include<stdio.h>
#include<pthread.h>
#include<stdlib.h>
#define N 15
struct matrix
{
int num1, num2;
};
void* multiply(void *c);
int main()
{
int i, j, rows, cols, a[N][N], b[N][N], sum, k, final, res[N][N],*ptr;
pthread_t t1, t2;
struct matrix m1;
ptr=∑
printf("Enter the number of rows: ");
scanf("%d", &rows);
printf("Enter the number of cols: ");
scanf("%d", &cols);
for(i = 0; i < rows; i++)
{
for(j = 0; j < cols; j++)
{
printf("Enter the value at: a[%d][%d] : ", i, j);
scanf("%d", &a[i][j]);
}
}
for(i = 0; i < rows; i++)
{
for(j = 0; j < cols; j++)
{
printf("Enter the value at: b[%d][%d] : ", i, j);
scanf("%d", &b[i][j]);
}
}
for(i = 0; i < rows; i++)
{
for(j = 0; j < cols; j++)
{
final = 0;
for(k = 0; k < rows; k++)
{
m1.num1 = a[i][k];
m1.num2 = b[k][j];
pthread_create(&t1, NULL, (void*)multiply,(void*)&m1);
pthread_join(t1, (void**)&ptr);
sum=*ptr;
printf("\t%d",sum);
final += sum;
res[i][j] = final;
}
printf("\n");
}
}
printf("The result is :\n");
for(i = 0; i < rows; i++)
{
for(j = 0; j < cols; j++)
{
printf("%d\t", res[i][j]);
}
printf("\n");
}
return 0;
}
void* multiply(void *c)
{
struct matrix *m;
m = (struct matrix *)c;
int p = 0;
p = m->num1 * m->num2;
printf("\t%d * %d = %d",m->num1,m->num2,p);
pthread_exit((void*)&p);
}
Output for execution on Ubuntu
Enter the number of rows: 2
Enter the number of cols: 2
Enter the value at: a[0][0] : 1
Enter the value at: a[0][1] : 2
Enter the value at: a[1][0] : 3
Enter the value at: a[1][1] : 4
Enter the value at: b[0][0] : 1
Enter the value at: b[0][1] : 2
Enter the value at: b[1][0] : 3
Enter the value at: b[1][1] : 4
1 * 1 = 1 0 2 * 3 = 6 32648
1 * 2 = 2 32648 2 * 4 = 8 32648
3 * 1 = 3 32648 4 * 3 = 12 32648
3 * 2 = 6 32648 4 * 4 = 16 32648
The result is :
32648 65296
65296 65296
Output for execution on CentOS
Enter the number of rows: 2
Enter the number of cols: 2
Enter the value at: a[0][0] : 1
Enter the value at: a[0][1] : 2
Enter the value at: a[1][0] : 3
Enter the value at: a[1][1] : 4
Enter the value at: b[0][0] : 1
Enter the value at: b[0][1] : 2
Enter the value at: b[1][0] : 3
Enter the value at: b[1][1] : 4
1 * 1 = 1 0 2 * 3 = 6 6
1 * 2 = 2 2 2 * 4 = 8 8
3 * 1 = 3 2 4 * 3 = 12 4
3 * 2 = 6 3 4 * 4 = 16 16
The result is :
6 10
15 22
The multiply function is returning a pointer to a local variable p, and the lifetime of the local variable finishes as soon as the function ends.
The easiest solution here is not to use the return value, but to reserve a place for the result in the struct matrix that is passed to multiply(), because that structure is allocated within main. Change the definition of struct multiply:
struct matrix
{
int num1, num2;
int product;
};
Change multiply() to put the result here:
void *multiply(void *c)
{
struct matrix *m = c;
m->product = m->num1 * m->num2;
printf("\t%d * %d = %d", m->num1, m->num2, m->product);
return NULL;
}
Change main() to retrieve the result from there:
pthread_create(&t1, NULL, multiply, &m1);
pthread_join(t1, NULL);
sum = m1.product;
(Side note: that variable sum has a confusing name, since it doesn't hold a sum!)

How to count letters, digits, spaces in a string

I'm working on a code to count the amount of spaces/digits/letters inside a given input using a loop. I am trying to use the .isdigit() and .isalpha() method to see if each letter in the string is a letter or number, and if true, adding it to the count. My code looks perfect to me, but when I run it, I only get the count for length and spaces (Which is not using the .isspace() method)
Perhaps I am messing up when updating the count within my loop but again.. it all looks good to me, could anyone help steer me in the right direction?
def main():
sentence = input('Enter a sentence: ')
printStats(sentence)
def printStats(input):
print('Statistics on your sentence: ')
print(' Characters:', charCount(input))
print(' Letters:', letterCount(input))
print(' Digits:', digitCount(input))
print(' Spaces:', spaceCount(input))
def charCount(input):
for char in input:
return len(input)
#Section below is where I need help
def letterCount(input):
count=0
for letter in input:
if input.isalpha():
count += 1
return count
def digitCount(input):
count=0
for digit in input:
if input.isdigit():
count += 1
return count
#Section above is where I need help
def spaceCount(input):
for space in input:
return input.count(" ")
main()
Thanks for your time
package com.drools;
public class TEST {
public static void main(String[] args) {
int charCount = 0;
int digitCount = 0;
String word = "NEW YORK 1";
String data[];
int k = 0;
data = word.split("");
int data1 = word.length();
char temp;
for (int i1 = 0; i1 < word.length(); i1++) {
temp = word.charAt(i1);
if (Character.isLetter(temp)) {
charCount++;
} else if (Character.isDigit(temp)) {
digitCount++;
for (int i = 0; i < data.length; i++) {
if (data[i].equals(" ")) {
k++;
}
}
System.out.println("total count "+ data1 + "||number of spaces in the entire word "+ k + " ||characters " + charCount+ " || digits" + digitCount);
}
}}
}
**Out put:**
total count 10||number of spaces in the entire word 2 ||characters 7 || digits1
You need to do letter.isalpha() and digit.isdigit() instead of calling them on the entire input.
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class LettersDigitsSpace {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Pattern pletter = Pattern.compile("[a-zA-Z]");
Pattern pdigit = Pattern.compile("\\d");
Pattern pwhitespace = Pattern.compile("\\s");
System.out.println();
System.out.println("-------------------------------------------------");
System.out.println("--- Letters, Digits, and White Spaces counter ---");
System.out.println("-------------------------------------------------");
System.out.println();
System.out.println("Enter String: ");
String val = input.nextLine();
Matcher mletter = pletter.matcher(val);
Matcher mdigit = pdigit.matcher(val);
Matcher mspace = pwhitespace.matcher(val);
int countl = 0, countd = 0, counts = 0;
while (mletter.find()) {
countl++;
}
while (mdigit.find()) {
countd++;
}
while (mspace.find()) {
counts++;
}
System.out.println("\nLetter count: "+countl+"\nDigit count: " + countd + "\nWhite Space count: " + counts);
}
}

Resources