6 Programming Exercises by Kodejuice: 5:25pm On Jan 13, 2016 |
1. String lengthLanguage: Any Language Determine the length of a string without using the default function provided by the programming language you're using. FUNCTION stringLength(){ //... } stringLength("hello" ); //=> 5
2. Closed ParenthesisLanguage: Any Language Write a function that takes a string containing opened and closed brackets, your function should be able to determined if the brackets are well placed, if there are not then fix it and return the fixed version. closedBracket("(2+2)" ); //=> true closedBracket("(5+3)*2)" ); => false, ((5+3)*2)
3. Vowel countLanguage: Any Language Count the number of vowels that appear in a string and also return the counted vowels. countVowel("sample" ); //=> 2, ae
4. argSwitchLanguage: Any Language Create a function named "argSwitch", this function will take 2 arguments and return each of the argument one after the other, when the function is called, the same argument should not be returned twice 1st call: argSwitch("me", "you" ) //=> me 2nd call: argSwitch("me", "you" ) //=> you 3rd call: argSwitch("me", "you" ); //=> me
5. Color validateLanguage: JavaScript Create a function named "isValidColor", this function would test if the string passed to it is a valid color or not. Rule: Do not use any list of valid colors to validate. isValidColor( "red" ); //=>true isValidColor( "asshy" ); //=> false isValidColor( "#f7c" ); //=> true
6. String replaceLanguage: Any Language Create a function that replaces strings without the use of the default function provided by the language you're using. No RegExp support. But if you feel you're a geek, include RegExp replacing. stringReplace("Hello world", "world", "Nairalanders" //=>Hello Nairalanders
Post your solutions. 2 Likes |
Re: 6 Programming Exercises by Fulaman198(m): 7:22pm On Jan 13, 2016 |
Nice exercises, I'll take a look at these soon |
Re: 6 Programming Exercises by ChinenyeN(m): 7:04am On Jan 14, 2016 |
6. String ReplaceLanguage: C int strreplace(char *str, const char *oldstr, const char *newstr) { /** * Recursive function. Reads char *str from left to right and replaces all occurrences of * const char *oldstr. Upon completion, the function returns the number of times * const char *oldstr had been successfully replaced. */
int count = 0; char *tmp = strcasestr(str, oldstr); if(tmp) { // get strlens int len = strlen(str); int oldstrlen = strlen(oldstr); int newstrlen = strlen(newstr);
// build new char array char tmpstr[len - strlen(tmp) + newstrlen + strlen(&tmp[oldstrlen - 1]) + 1]; memset(tmpstr, '\0', sizeof(tmpstr)); // initialize char array // systematically copy strings strncpy(tmpstr, str, len - strlen(tmp)); // copy first part of string up until occurrence of const char *oldstr strncpy(&tmpstr[strlen(tmpstr)], newstr, newstrlen); // copy the new string strncpy(&tmpstr[strlen(tmpstr)], &tmp[oldstrlen], strlen(&tmp[oldstrlen])); // copy rest of string // resize original string str[strlen(tmpstr) + 1]; memset(str, '\0', sizeof(str)); // initialize
// copy tmpstr over to str strcpy(str, tmpstr);
// recursive call to continue on to the next occurrence of const char *oldstr count = strreplace(str, oldstr, newstr);
// change value of count to reflect string replacement count += 1; }
return count; }
|
Re: 6 Programming Exercises by Fulaman198(m): 7:32am On Jan 14, 2016 |
Programme: VowelCount Language: Java import java.util.Scanner;
public class VowelCount {
public static void main(String[] args) { String myText; int vowelsTotal = 0; countVowels cntVwl = new countVowels(); Scanner scan = new Scanner(System.in); System.out.println("Please Enter a String with vowels: " ); myText = scan.nextLine(); vowelsTotal = cntVwl.vowelsCounted(myText); System.out.println(myText + " has " + vowelsTotal + " vowels" ); } }
class countVowels { public int vowelsCounted(String myString){ int numVowels = 0; for (int i = 0; i < myString.length(); i++) { if (myString.charAt(i) == 'a'|| myString.charAt(i) == 'e'|| myString.charAt(i)=='i' || myString.charAt(i)=='o'|| myString.charAt(i) == 'u') { numVowels++; } } return numVowels; } }
Below is programme output |
Re: 6 Programming Exercises by Fulaman198(m): 7:34am On Jan 14, 2016 |
ChinenyeN decided to add comments to his programme, it makes me feel bad. I should have done the same. I will in the future.
Good programming ethics ChinenyeN |
Re: 6 Programming Exercises by ChinenyeN(m): 8:08am On Jan 14, 2016 |
If it's any consolation, Fulaman198, I don't think your program needs any comments. It's very self-explanatory. But you are right. It's always good to make a habit of commenting one's code. I added comments to mine mostly to make it easier to read on NL, since NL's code tag doesn't come with syntax highlighting (unless there's something I don't know). 2 Likes |
Re: 6 Programming Exercises by Fulaman198(m): 8:22am On Jan 14, 2016 |
ChinenyeN: If it's any consolation, Fulaman198, I don't think your program needs any comments. It's very self-explanatory. But you are right. It's always good to make a habit of commenting one's code. I added comments to mine mostly to make it easier to read on NL, since NL's code tag doesn't come with syntax highlighting (unless there's something I don't know). You are right about that my friend. |
Re: 6 Programming Exercises by DonSegmond(m): 12:44pm On Jan 14, 2016 |
php // problem 3 function countvowels($string) { return count(array_filter(str_split($string), function($k) { return in_array($k, str_split("aeiou" )); })); }
// problem 6 function strreplace($str, $search, $replace) { return preg_replace("/$search/", $replace, $str); }
|
Re: 6 Programming Exercises by Kodejuice: 3:52pm On Jan 14, 2016 |
Fulaman198: Programme: VowelCount Language: Java
import java.util.Scanner;
public class VowelCount {
public static void main(String[] args) { String myText; int vowelsTotal = 0; countVowels cntVwl = new countVowels(); Scanner scan = new Scanner(System.in); System.out.println("Please Enter a String with vowels: " ); myText = scan.nextLine(); vowelsTotal = cntVwl.vowelsCounted(myText); System.out.println(myText + " has " + vowelsTotal + " vowels" ); } }
class countVowels { public int vowelsCounted(String myString){ int numVowels = 0; for (int i = 0; i < myString.length(); i++) { if (myString.charAt(i) == 'a'|| myString.charAt(i) == 'e'|| myString.charAt(i)=='i' || myString.charAt(i)=='o'|| myString.charAt(i) == 'u') { numVowels++; } } return numVowels; } }
Below is programme output You approach to solve the problem is yucky, and doesnt follow the rule completely, return the vowels! Language: JavaScript function vowelCount(str){ var vowels = ["a","e","i","o","u"], count = 0, seen = ""; for(var i=0;i<str.length;i+=1){ if(vowels.indexOf(str[i])>-1){ //a vowel, increment count variable and add to seen string count += 1; seen += str[i]; } } return count + " vowels,("+seen+""; }
vowelCount("this is a simple vowel test" //=>8 vowels,(iiaieoee)
|
Re: 6 Programming Exercises by ChinenyeN(m): 3:56pm On Jan 14, 2016 |
3. Vowel CountLanguage: C char *countvowels(const char *str) { // setup int i = 0; // iterate through string int count = 0; // to hold the count char *vowels = NULL; // to hold the vowels
// iterate through each character in const char *str while(str[i] != '\0') {
// check for vowel if(str[i] == 'a' || str[i] == 'A' || str[i] == 'e' || str[i] == 'E' || str[i] == 'i' || str[i] == 'I' || str[i] == 'o' || str[i] == 'O' || str[i] == 'u' || str[i] == 'U') { count += 1; // increase count vowels = realloc(vowels, count + 1); // reallocate memory vowels[count] = '\0'; // initialize byte vowels[count - 1] = str[i]; // assign newly found vowel
} i++; }
// print total vowels found printf("Found %i vowels ... %s\n", count, vowels);
// will have to be manually freed by user later on in the program return vowels;
}
|
Re: 6 Programming Exercises by robby1(m): 4:34pm On Jan 14, 2016 |
[size=14pt] Language: Scala[/size] 3. Vowel Count Solutiondef countVowel(word: String): String = { val vowels = word.toCharArray.filter(List('a', 'e', 'i', 'o', 'u').contains(_)).toList.mkString vowels.length + ", " + vowels } Result on the repl is:scala> countVowel('robert') res1: String = 2, oe 6. String Replace Solutiondef stringReplace(orig: String, toReplace: String, replaceWith: String) = { orig.split(' ').toList.map(x => if(x == toReplace) replaceWith else x).mkString(' ') } Result on the repl is:scala> stringReplace('hello world', 'world', 'nairalander') res2: String = hello nairalander 1 Like |
Re: 6 Programming Exercises by Fulaman198(m): 5:04pm On Jan 14, 2016 |
Kodejuice:
You approach to solve the problem is yucky, and doesnt follow the rule completely, return the vowels! Language: JavaScript
function vowelCount(str){ var vowels = ["a","e","i","o","u"], count = 0, seen = ""; for(var i=0;i<str.length;i+=1){ if(vowels.indexOf(str[i])>-1){ //a vowel, increment count variable and add to seen string count += 1; seen += str[i]; } } return count + " vowels,("+seen+""; }
vowelCount("this is a simple vowel test" //=>8 vowels,(iiaieoee)
Look at the method vowelsCounted(), that is what it's for. Java and JavaScript are different languages. I created the main class to illustrate how it works. EDIT: In case you don't know what I'm referring to, I'm talking about the method here
public int vowelsCounted(String myString){ int numVowels = 0; for (int i = 0; i < myString.length(); i++) { if (myString.charAt(i) == 'a'|| myString.charAt(i) == 'e'|| myString.charAt(i)=='i' || myString.charAt(i)=='o'|| myString.charAt(i) == 'u') { numVowels++; } } return numVowels; }
In Java, functions are referred to as Methods. |
Re: 6 Programming Exercises by ChinenyeN(m): 5:32pm On Jan 14, 2016 |
1. String LengthLanguage: C size_t stringlength(const char *str) {
size_t i = 0; // to iterate over string characters while(str[i] != '\0') i++; // iterate over string return i; // return value of i
}
|
Re: 6 Programming Exercises by Nobody: 8:59pm On Jan 14, 2016 |
|
Re: 6 Programming Exercises by Kodejuice: 10:35am On Jan 16, 2016 |
//exercise 2, Closed Parenthesis //Language: javascript
function closedBracket(str){ var openedBraces = str.match(/\(/g), closedBraces = str.match(/\)/g), opened = openedBraces.length, closed = closedBraces.length; if(opened===closed){ return true; } else if(opened>closed){ //not well placed, eg "(()" var needed = opened - closed, fix = br(needed, "" return str + fix; } else if(opened<closed){ //not well placed, eg "())" var needed = closed - opened, fix = br(needed, "(" return fix + str; } else{ return str; //?! } function br(n, b){ //br(2,"(" => (( var s = ""; while(s.length!==n){ s += b; } return s; } }
|
Re: 6 Programming Exercises by Kodejuice: 10:41am On Jan 16, 2016 |
Fulaman198:
Look at the method vowelsCounted(), that is what it's for. Java and JavaScript are different languages. I created the main class to illustrate how it works.
EDIT: In case you don't know what I'm referring to, I'm talking about the method here
public int vowelsCounted(String myString){ int numVowels = 0; for (int i = 0; i < myString.length(); i++) { if (myString.charAt(i) == 'a'|| myString.charAt(i) == 'e'|| myString.charAt(i)=='i' || myString.charAt(i)=='o'|| myString.charAt(i) == 'u') { numVowels++; } } return numVowels; }
In Java, functions are referred to as Methods. You dont get, return all vowels in the passed string not just the number of vowels. vowelsCount("hello world" //=> 3, eoo
|
Re: 6 Programming Exercises by Fulaman198(m): 6:34pm On Jan 16, 2016 |
Kodejuice:
You dont get, return all vowels in the passed string not just the number of vowels.
vowelsCount("hello world" //=> 3, eoo
Oh ok, I didn't follow the instructions properly. Sorry about that. |
Re: 6 Programming Exercises by Nobody: 9:09pm On Jan 16, 2016 |
Kodejuice:
//exercise 2, Closed Parenthesis
//Language: javascript
[code]
function closedBracket(str){
var openedBraces = str.match(/\(/g),
closedBraces = str.match(/\)/g),
opened = openedBraces.length, closed = closedBraces.length;
if(opened===closed){
return true;
}
else if(opened>closed){
//not well placed, eg "(()"
var needed = opened - closed,
fix = br(needed, ""
return str + fix;
}
else if(opened<closed){
//not well placed, eg "())"
var needed = closed - opened,
fix = br(needed, "("
return fix + str;
}
else{
return str; //?!
}
function br(n, b){
//br(2,"(" => ((
var s = "";
while(s.length!==n){
s += b;
}
return s;
}
}
|
Re: 6 Programming Exercises by Nobody: 9:09pm On Jan 16, 2016 |
.. |
Re: 6 Programming Exercises by ChinenyeN(m): 1:08am On Jan 17, 2016 |
2. Closed Parenthesis -- I want so badly to try an implementation of this in Standard C, but I just know it will take a whole bunch of code (especially so, if I want to add some fool-proofing) and I doubt anyone would be willing to read through it all. |
Re: 6 Programming Exercises by ChinenyeN(m): 4:48am On Jan 17, 2016 |
Ah, whatever. I decided I'd do it anyway, complete with comments. I decided I'd go with a simpler implementation than what I originally had in mind. We can all be grateful, I guess. 2. Closed ParenthesisLanguage: C bool closeparens(char *str, int pass, int opened, int closed) { /** * This is a simple implementation. It makes two assumptions: 1) that the final output will always be * enclosed in brackets .. i.e. "(*)". 2) that the whomever is making the parenthetical statements at * leaset knows how parentheses works and is more or less using them correctly. This function makes * use of a helper function void addparen(char *str, int position). The initial call to bool closeparens * should always pass in 0 for int pass, int opened and int closed.. i.e. closeparen(str, 0, 0, 0); */
// set up bool fixed = false; // to return status of parenthetical statement if(pass == 0) { // ensure that string starts with opening parenthesis if(*str != '(') { addparen(str, 0); opened += 1; fixed = true; } // maintain hold of start of string char *tmp = str; // get number of opened and closed parentheses // *str is like lazy way of saying int i = 0; ... while(str[i] ..) // but I wasn't lazy for no reason. *str has a useul purpose while(*str) { if(*str == '(') opened++; if(*str == ')') closed++; *str++; } *str--; // to go back to the last character in string // ensure that last character is a closing parenthesis // see *str was useful if(*str != ')') { addparen(tmp, 1); closed += 1; fixed = true; } if(fixed) closeparens(tmp, pass += 1, opened, closed); else fixed = closeparens(tmp, pass += 1, opened, closed);
} else { // we've gone past the first pass // check number of parens and add if necessary if(opened > closed) { addparen(str, 1); fixed = true; } if(closed > opened) { addparen(str, 0); fixed = true; } } return fixed;
}
void addparen(char *str, int position) { /** * Helper function to add parenthesis to either beginning or end of string. * value of 0 for int position denotes beginning, while a value of * 1 for int position denotes the end of the string. */ // create temporary char array char tmpstr[strlen(str) + 2]; memset(tmpstr, '\0', sizeof(tmpstr));
// run check if(position == 0) { // beginning of the string tmpstr[0] = '('; strcpy(&tmpstr[1], str); } else if(position == 1) { // end of the string strcpy(tmpstr, str); tmpstr[strlen(tmpstr)] = ')'; }
// resize and copy data str[strlen(tmpstr) + 1]; memset(str, '\0', sizeof(str)); strcpy(str, tmpstr);
}
|
Re: 6 Programming Exercises by tr3y(m): 8:09pm On Jan 17, 2016 |
Nice. |
Re: 6 Programming Exercises by Naijaepic: 10:55pm On Jan 26, 2016 |
ChinenyeN: 6. String Replace Language: C
int strreplace(char *str, const char *oldstr, const char *newstr) { /** * Recursive function. Reads char *str from left to right and replaces all occurrences of * const char *oldstr. Upon completion, the function returns the number of times * const char *oldstr had been successfully replaced. */
int count = 0; char *tmp = strcasestr(str, oldstr); if(tmp) { // get strlens int len = strlen(str); int oldstrlen = strlen(oldstr); int newstrlen = strlen(newstr);
// build new char array char tmpstr[len - strlen(tmp) + newstrlen + strlen(&tmp[oldstrlen - 1]) + 1]; memset(tmpstr, '\0', sizeof(tmpstr)); // initialize char array // systematically copy strings strncpy(tmpstr, str, len - strlen(tmp)); // copy first part of string up until occurrence of const char *oldstr strncpy(&tmpstr[strlen(tmpstr)], newstr, newstrlen); // copy the new string strncpy(&tmpstr[strlen(tmpstr)], &tmp[oldstrlen], strlen(&tmp[oldstrlen])); // copy rest of string // resize original string str[strlen(tmpstr) + 1]; memset(str, '\0', sizeof(str)); // initialize
// copy tmpstr over to str strcpy(str, tmpstr);
// recursive call to continue on to the next occurrence of const char *oldstr count = strreplace(str, oldstr, newstr);
// change value of count to reflect string replacement count += 1; }
return count; }
Here is my three attempt to solve three of the exercises Language: Python |
Re: 6 Programming Exercises by danvery2k6(m): 12:23am On Jan 28, 2016 |
Java - stringLength
class StringLength { public static void main(String[] args) { int len = stringLength("Hello there" System.out.println(len); } public static int stringLength(String word) { return word.split("".length; } }
|
Re: 6 Programming Exercises by danvery2k6(m): 9:48am On Jan 28, 2016 |
Vowel Count import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.List; import java.util.ArrayList;
class Main { private static List<String> vowels; static { vowels = new ArrayList<String>(); } public static void main(String[] args) { int numVowels = vowelCount("sample for the test" System.out.println("Number of Vowels found: "+numVowels); System.out.printf("Vowels found in the string: " for(int i = 0; i < vowels.size(); i++) { System.out.printf("%s ", vowels.get(i)); } System.out.println(); } public static int vowelCount(String string) { String regex = "[aeiou]";
Pattern pattern = Pattern.compile(regex); int counter = 0; Matcher matcher = pattern.matcher(string);
while(matcher.find()) { counter++; saveLetter(matcher.group()); } return counter; } public static void saveLetter(String group) { vowels.add(group); } }
|
Re: 6 Programming Exercises by danvery2k6(m): 10:04am On Jan 28, 2016 |
|
Re: 6 Programming Exercises by Naijaepic: 12:47pm On Jan 28, 2016 |
Name: Python
argSwitch function with Python |
Re: 6 Programming Exercises by timtoday: 2:41pm On Jan 28, 2016 |
Language: Perl - one-liner #1 perl -we "print scalar split// => $ARGV[0]" hello # print 5
to use the default function provided by Perl is like so: perl -we "print length $ARGV[0]" hello # 5, notice the length function
# 3 perl -we "print join ', ' => map {$_, scalar split//} join '' => grep /[aeiou]/ => split// => $ARGV[0]" "Hello, world"
# 4 perl -we "print $ARGV[argSwitch(@ARGV)] for 1 .. 3; sub argSwitch{ @m=@_;$n = 0; print sub {$m[$n++]}->()}" me you
# 6 perl -we "print join ' ' => grep {!/$ARGV[1]/i} (split/\s+/ => $ARGV[0]), $ARGV[2]" "Hello, World" world Nairalanders
All are one-liner Perl Scripts. 1 Like |
Re: 6 Programming Exercises by timtoday: 5:32pm On Jan 28, 2016 |
# 2 #!/usr/bin/perl use warnings; use strict;
# call the closedBracket subroutine # on the first argument on the command line interface print closedBracket( $ARGV[0] );
# closedBracket subroutine sub closedBracket {
# get the variable my $str = shift; my $open_bracket = 0; my $close_bracket = 0; my $state = "true";
# split the variable for ( split //, $str ) {
# if the variable matches open bracket if (/\(/) { $open_bracket++; $close_bracket--; } elsif (/\)/) { # else if it matches closed bracket $open_bracket--; $close_bracket++; } }
# check if the value open bracket and # close bracket is 0, if not, take the absolute # of the variable with negative value if ( $open_bracket != 0 and $close_bracket != 0 ) { if ( $open_bracket < 0 ) { $open_bracket = abs $open_bracket; $str = join '' => '(' x $open_bracket, $str; } else { $close_bracket = abs $close_bracket; $str = join '' => $str, ')' x $close_bracket; } return join ', ' => "false", $str; } return $state; }
Used the following input (3+3), (5+2)*3), (2+2(( I might not have tested this enough though! Enjoy!!! |
Re: 6 Programming Exercises by unphilaz(m): 6:12pm On Jan 28, 2016 |
nice thread how a problem can be solved using different programs
kudos guys |
Re: 6 Programming Exercises by Naijaepic: 5:34pm On Feb 19, 2016 |
Language Python Exercise: closedBracket Solution: This python function had been rigorous test to work on any mathematical expression irrespective of number of parenthesis in the expression and it will do the needful. Below is the python code def closedBracket(string_input): """ This function was implemented by NaijaEpic in response to online exercise on Nairaland 1. This function is name closedBracket(), it take mathematical expression, iterate over the expression to determine the number of both open and closing parenthesis, if there is unbalance number of parenthesis, the function will return a balance version of the mathematical expression 2. The function take on parameter 3. """ import unicodedata, re left_bracket = re.compile('[\u0028]') # compiling unicode of left bracket right_bracket = re.compile('[\u0029]') # compiling unicode of right bracket string_holder = [] # Declaring empty List to hold split string string_holder[:0] = string_input # Change the input string to list left_bracket = string_holder.count('\u0028') # Checking how many left bracket exist in the string_holder list right_bracket = string_holder.count('\u0029') final_string = [] # Accumulator of if left_bracket > right_bracket: # Remove some leftmost brackets or add more right brackets count = 0 while count < (left_bracket - right_bracket): final_string.append('\u0029',) # Generating number of right_bracket (i.e. '\u0029') that is need to balance the deficit count += 1 final_string = ''.join(final_string) print('False', string_input + final_string) elif left_bracket < right_bracket: # Remove the last Rightmost Brackets or add another leftmost brackets count = 0 number_right_bracket = (right_bracket - left_bracket) while count < number_right_bracket: final_string.append('\u0028',) # Generating number of left_bracket (i.e. '\u0028') that is need to balance the deficit count += 1 final_string = ''.join(final_string) print('False', final_string + string_input) else: return True closedBracket("5+((3)*2)))))" |
Re: 6 Programming Exercises by Sirnuel: 5:21am On Feb 22, 2016 |
. |