Code for creating string in a loop to report numbers - string

I created a code that functions as it is supposed to. I determined the escape function to be -1 for the user to exit the program and used if/else to only add the sum of positive integers.
I know that I have to save the numbers that pass the if statement (only positive numbers) and the only way that I can think of doing this is through a String.
Unfortunately, whenever I attempt to add a string as part of the while loop, it will print the statement over and over again when I only want a single line.
I'm also struggling to set the user input to a single line. I know it has everything to do with the .nextLine() command, but if I pull it outside the brackets (which I've attempted to do) then it reads as an error.
Actually, a source about conversion of Strings to characters or inputs to Strings would be very helpful as well. It's apparent that this is where a good portion of my understanding is lacking.
public static void main(String args[])
{
int userNum = 0;
int sum = 0;
Scanner s = new Scanner(System.in);
String str3;
System.out.print("Enter positive integers (to exit enter -1):\n ");
//Loop for adding sum with exit -1
while(userNum != -1){
//condition to only calculate positive numbers user entered
if(userNum > 0){
//calculation of all positive numbers user entered
sum += userNum;
str3 = String.valueOf(userNum);}
userNum = s.nextInt();
}
System.out.println("The values of the sum are: " + str3);
System.out.println("The Sum: " + sum);
}
}
I'm hoping for the user input to be printed,
Enter positive integers (to exit enter -1): _ _ ___//with the user
input in the same row.
And...
values from string to read out on same line, not multiple lines.

The variable str needs to be initialized as:
String str3 = "";
and in the loop, each entered number must be concatenated to str.
int userNum = 0;
int sum = 0;
Scanner s = new Scanner(System.in);
String str3 = "";
System.out.print("Enter positive integers (to exit enter -1):\n ");
while (userNum != -1) {
userNum = s.nextInt();
if (userNum > 0) {
sum += userNum;
str3 += " " + userNum;
}
}
System.out.println("The values of the sum are: " + str3);
System.out.println("The Sum: " + sum);

Related

Remove duplicate string elements C++

The problem consists of finding all permutations using k out of n digits. I'm able to find all the permutations, but I'm struggling trying to erase duplicates. I can successfully compare and find the duplicates, but erasing them is what I'm struggling to do. I have a feeling I'm missing something simple but I don't know what it is.
Any help would be greatly appreciated. I've been staring at this for a week.
Here is the code that I've got right now.
void getPermutations(int n, int k)
{
string str = "";
//fill string with numbers <= n
for(int i = 0; i < n; i++)
{
str += to_string(i); //convert numbers to string
}
string tempStr = "";
string outputStr = "";
do {
tempStr = str.substr(0, k);
int compareResult = tempStr.compare(0, k, outputStr, 0, k);
if (compareResult == 0)
{
cout << "| same | ";
outputStr.erase(k,k);
}
outputStr = tempStr;
cout << outputStr << " ";
} while (next_permutation(str.begin(), str.end()));
}
I think what you meant to do was to erase the contents of tempStr, not outputStr.
The call to erase is not exactly right. Its first argument marks the starting position of your erasing, and the second argument tells how many characters to erase. So if you want to erase the whole string, the first argument should be...
You actually don't have to erase anything. After you get it working your way, try to do it without erasing!
Good Luck!

Arduino does not return the desired output via serial port

I would like to send a list of elements inside a structure via serial port but the output produced by Arduino is abnormal.
A little help? What is the reason for this abnormal output?
const int menu_max_item = 20;
int menu_num_item = 0;
typedef struct item_menu{
String text;
void (*func)(void);
} t_item_menu;
t_item_menu arr_menu[menu_max_item];
void menu_add_item(String txt, void (*f)(void)){
arr_menu[menu_num_item].text = txt;
arr_menu[menu_num_item].func = f;
menu_num_item++;
}
void fn_nd_function(){
Serial.println('test');
}
void print_menu_lcd(){
for(int x = 0; x < 4 && x < menu_num_item; x++){
lcd.setCursor(0,x);
lcd.print(arr_menu[x].text);
}
}
void setup(){
Serial.begin(9600);
for(int i = 0; i < 2; i++) menu_add_item("item " + i, fn_nd_function);
}
void loop() {
print_menu_lcd();
delay(1000);
}
Real output
item
tem
em
Desired output
item 1
item 2
item 3
You have a couple of errors...
This code:
void fn_nd_function(){
Serial.println('test');
}
test is NOT a single character is it? So why do you have it in single quotes?
But more importantly this which is the cause of your bad output:
menu_add_item("item " + i, fn_nd_function);
"item" + i is NOT how you concatenate a number to the end of the character string "item". This is C++ not Java or Python. You'll have to build that string separately. Please don't be tempted to use the String class as that can cause other issues.
What is happening now is that you are passing "item" which is a pointer to the character array stored somewhere in memory holding the characters 'i', 't', 'e' and 'm'. When you add 1 to that pointer you end up with a pointer pointing to the 't' and when you add 2 you end up with a pointer pointing to the 'e'. So when you print from those pointers you only get the part after what that pointer points to.
You need to have a line ahead of that to build the string first. Something along the lines of:
char str[7] = "item "; // Note the two spaces to leave room for the digit
str[5] = i + '0'; // Add '0' to convert single digit to ascii
menu_add_item(str, fn_nd_function);

Reduce a string when it has a pair

Shil has a string S , consisting of N lowercase English letters. In one operation, he can delete any pair of adjacent letters with same value. For example, string "aabcc" would become either "aab" or "bcc" after operation.
Shil wants to reduce S as much as possible. To do this, he will repeat the above operation as many times as it can be performed. Help Shil out by finding and printing 's non-reducible form!
If the final string is empty, print Empty String; otherwise, print the final non-reducible string.
Sample Input 0
aaabccddd
Sample Output 0
abd
Sample Input 1
baab
Sample Output 1
Empty String
Sample Input 2
aa
Sample Output 2
Empty String
Explanation
Sample Case 0: Shil can perform the following sequence of operations to get the final string:
Thus, we print .
Sample Case 1: Shil can perform the following sequence of operations to get the final string: aaabccddd -> abccddd
abccddd -> abddd
abddd -> abd
Thus we print abd
Sample case 1: baab -> bb
bb -> Empty String.
in my code in the while loop when i assign s[i] to str[i].the value of s[i] is not getting assigned to str[i].the str[i] has a garbage value.
my code :
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
string s;
cin>>s;
int len = s.length();
int len1 = 0;
string str;
for(int i = 0;i < len-1;i++){
if(s[i]!= '*'){
for(int j=i+1;j < len;j++){
if(s[j] != '*'){
if(s[i] == s[j]){
s[i] = s[j] = '*';
}
}
}
}
}
int i = 0;
while(i<len){
if(s[i] != '*'){
str[len1] = s[i];
len1++;
}
i++;
}
if(len1 != 0){
cout<<str;
}
else{
cout<<"Empty String";
}
return 0;
}
#include <iostream>
using namespace std;
int main(){
string s,tempS;
bool condition = false;
cin >> s;
tempS = s;
while(condition==false){
for(int i=1; i<s.size(); i++){
if(s[i]==s[i-1]){
s.erase(s.begin()+i-1, s.begin()+i+1);
}
}
if(tempS == s){
condition = true;
} else{
tempS = s;
}
}
if(s.size()==0){
cout << "Empty String" ;
} else{
cout << s;
}
return 0;
}
the first while loop keeps on modifying the string until and unless it becomes equal to temp (which is equal to the string pre-modification)
It is comparing the adjacent elements if they are equal or not and then deleting them both.
As soon as string becomes equal to temp after modifications, string has reached it's most reduced state !

Finding minimum moves required for making 2 strings equal

This is a question from one of the online coding challenge (which has completed).
I just need some logic for this as to how to approach.
Problem Statement:
We have two strings A and B with the same super set of characters. We need to change these strings to obtain two equal strings. In each move we can perform one of the following operations:
1. swap two consecutive characters of a string
2. swap the first and the last characters of a string
A move can be performed on either string.
What is the minimum number of moves that we need in order to obtain two equal strings?
Input Format and Constraints:
The first and the second line of the input contains two strings A and B. It is guaranteed that the superset their characters are equal.
1 <= length(A) = length(B) <= 2000
All the input characters are between 'a' and 'z'
Output Format:
Print the minimum number of moves to the only line of the output
Sample input:
aab
baa
Sample output:
1
Explanation:
Swap the first and last character of the string aab to convert it to baa. The two strings are now equal.
EDIT : Here is my first try, but I'm getting wrong output. Can someone guide me what is wrong in my approach.
int minStringMoves(char* a, char* b) {
int length, pos, i, j, moves=0;
char *ptr;
length = strlen(a);
for(i=0;i<length;i++) {
// Find the first occurrence of b[i] in a
ptr = strchr(a,b[i]);
pos = ptr - a;
// If its the last element, swap with the first
if(i==0 && pos == length-1) {
swap(&a[0], &a[length-1]);
moves++;
}
// Else swap from current index till pos
else {
for(j=pos;j>i;j--) {
swap(&a[j],&a[j-1]);
moves++;
}
}
// If equal, break
if(strcmp(a,b) == 0)
break;
}
return moves;
}
Take a look at this example:
aaaaaaaaab
abaaaaaaaa
Your solution: 8
aaaaaaaaab -> aaaaaaaaba -> aaaaaaabaa -> aaaaaabaaa -> aaaaabaaaa ->
aaaabaaaaa -> aaabaaaaaa -> aabaaaaaaa -> abaaaaaaaa
Proper solution: 2
aaaaaaaaab -> baaaaaaaaa -> abaaaaaaaa
You should check if swapping in the other direction would give you better result.
But sometimes you will also ruin the previous part of the string. eg:
caaaaaaaab
cbaaaaaaaa
caaaaaaaab -> baaaaaaaac -> abaaaaaaac
You need another swap here to put back the 'c' to the first place.
The proper algorithm is probably even more complex, but you can see now what's wrong in your solution.
The A* algorithm might work for this problem.
The initial node will be the original string.
The goal node will be the target string.
Each child of a node will be all possible transformations of that string.
The current cost g(x) is simply the number of transformations thus far.
The heuristic h(x) is half the number of characters in the wrong position.
Since h(x) is admissible (because a single transformation can't put more than 2 characters in their correct positions), the path to the target string will give the least number of transformations possible.
However, an elementary implementation will likely be too slow. Calculating all possible transformations of a string would be rather expensive.
Note that there's a lot of similarity between a node's siblings (its parent's children) and its children. So you may be able to just calculate all transformations of the original string and, from there, simply copy and recalculate data involving changed characters.
You can use dynamic programming. Go over all swap possibilities while storing all the intermediate results along with the minimal number of steps that took you to get there. Actually, you are going to calculate the minimum number of steps for every possible target string that can be obtained by applying given rules for a number times. Once you calculate it all, you can print the minimum number of steps, which is needed to take you to the target string. Here's the sample code in JavaScript, and its usage for "aab" and "baa" examples:
function swap(str, i, j) {
var s = str.split("");
s[i] = str[j];
s[j] = str[i];
return s.join("");
}
function calcMinimumSteps(current, stepsCount)
{
if (typeof(memory[current]) !== "undefined") {
if (memory[current] > stepsCount) {
memory[current] = stepsCount;
} else if (memory[current] < stepsCount) {
stepsCount = memory[current];
}
} else {
memory[current] = stepsCount;
calcMinimumSteps(swap(current, 0, current.length-1), stepsCount+1);
for (var i = 0; i < current.length - 1; ++i) {
calcMinimumSteps(swap(current, i, i + 1), stepsCount+1);
}
}
}
var memory = {};
calcMinimumSteps("aab", 0);
alert("Minimum steps count: " + memory["baa"]);
Here is the ruby logic for this problem, copy this code in to rb file and execute.
str1 = "education" #Sample first string
str2 = "cnatdeiou" #Sample second string
moves_count = 0
no_swap = 0
count = str1.length - 1
def ends_swap(str1,str2)
str2 = swap_strings(str2,str2.length-1,0)
return str2
end
def swap_strings(str2,cp,np)
current_string = str2[cp]
new_string = str2[np]
str2[cp] = new_string
str2[np] = current_string
return str2
end
def consecutive_swap(str,current_position, target_position)
counter=0
diff = current_position > target_position ? -1 : 1
while current_position!=target_position
new_position = current_position + diff
str = swap_strings(str,current_position,new_position)
# p "-------"
# p "CP: #{current_position} NP: #{new_position} TP: #{target_position} String: #{str}"
current_position+=diff
counter+=1
end
return counter,str
end
while(str1 != str2 && count!=0)
counter = 1
if str1[-1]==str2[0]
# p "cross match"
str2 = ends_swap(str1,str2)
else
# p "No match for #{str2}-- Count: #{count}, TC: #{str1[count]}, CP: #{str2.index(str1[count])}"
str = str2[0..count]
cp = str.rindex(str1[count])
tp = count
counter, str2 = consecutive_swap(str2,cp,tp)
count-=1
end
moves_count+=counter
# p "Step: #{moves_count}"
# p str2
end
p "Total moves: #{moves_count}"
Please feel free to suggest any improvements in this code.
Try this code. Hope this will help you.
public class TwoStringIdentical {
static int lcs(String str1, String str2, int m, int n) {
int L[][] = new int[m + 1][n + 1];
int i, j;
for (i = 0; i <= m; i++) {
for (j = 0; j <= n; j++) {
if (i == 0 || j == 0)
L[i][j] = 0;
else if (str1.charAt(i - 1) == str2.charAt(j - 1))
L[i][j] = L[i - 1][j - 1] + 1;
else
L[i][j] = Math.max(L[i - 1][j], L[i][j - 1]);
}
}
return L[m][n];
}
static void printMinTransformation(String str1, String str2) {
int m = str1.length();
int n = str2.length();
int len = lcs(str1, str2, m, n);
System.out.println((m - len)+(n - len));
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String str1 = scan.nextLine();
String str2 = scan.nextLine();
printMinTransformation("asdfg", "sdfg");
}
}

How do I convert from Integer Queue to String?

OK, so I have this very simple, very inefficient program, but that's alright, the only thing that I would like to know is how to print the first five numbers of the queue as zeros without changing the values of ssn1 through ssn5.
For example I would like to print 000001111, and not 111111111, but still have those values stored in the queue. Could someone help me with that? I simply would like to hide them.
I am trying to convert the integers of the queue into a string, create a substring, and then print the dummyint five time followed by the substring.
import java.util.*;
public class SSNQueue {
public static void main (String args[]) {
Scanner scan = new Scanner(System.in);
Queue<Integer> ssn = new LinkedList<Integer>();
int Dummyssn = 0;
System.out.println("Please enter each digit number of SSN");
System.out.print("Enter digit number 1: ");
int ssn1 = scan.nextInt();
System.out.print("Enter digit number 2: ");
int ssn2 = scan.nextInt();
System.out.print("Enter digit number 3: ");
int ssn3 = scan.nextInt();
System.out.print("Enter digit number 4: ");
int ssn4 = scan.nextInt();
System.out.print("Enter digit number 5: ");
int ssn5 = scan.nextInt();
System.out.print("Enter digit number 6: ");
int ssn6 = scan.nextInt();
System.out.print("Enter digit number 7: ");
int ssn7 = scan.nextInt();
System.out.print("Enter digit number 8: ");
int ssn8 = scan.nextInt();
System.out.print("Enter digit number 9: ");
int ssn9 = scan.nextInt();
ssn.add(ssn1);
ssn.add(ssn2);
ssn.add(ssn3);
ssn.add(ssn4);
ssn.add(ssn5);
ssn.add(ssn6);
ssn.add(ssn7);
ssn.add(ssn8);
ssn.add(ssn9);
Integer.toString(ssn);
String Subssn = ssn.substring(5);
System.out.println("The SSN is:" + ssn);
System.out.println("The last four digits of the SSN are:" + Dummyssn + Dummyssn + Dummyssn + Dummyssn + Dummyssn + Subssn);
}
}
There are several issues here that make it unclear exactly what you are trying to do. For one thing, you read in multiple int values (ssn1, ssn2...ssn9) then add them to a queue. You then call Integer.toString(ssn) . . . I would expect an error on that line. It seems like what you want to do there is use a loop to read the values back out of the queue, assign them to a temporary String variable each time, and then call the substring function on your temporary variable and print out the result. As it is right now, you are calling Integer.toString(ssn) which is on the entire queue and I don't think that will do what you want. The queue is still typed to Integer (Queue). Not to mention that the toString method returns a value which you are supposed to read into another variable or use at the time you call it. Calling it on its own line like that doesn't really achieve anything because even if it is returning some value, it is not being kept by your code for later use.

Resources