Skip to content

Instantly share code, notes, and snippets.

@regnerjr
Created May 8, 2015 17:57
Show Gist options
  • Select an option

  • Save regnerjr/1ff4d5314ae4922f0605 to your computer and use it in GitHub Desktop.

Select an option

Save regnerjr/1ff4d5314ae4922f0605 to your computer and use it in GitHub Desktop.
Given a string, returns only the unique characters. i.e. abacb -> abc
#include <stdio.h>
#include <stdlib.h>
int in(char value, char* list){
for (char *i = list; *i != '\0'; i++){
if ( *i == value ){
return 1;
}
}
return 0;
}
char * uniqueChars(char *input) {
char *result = calloc(100 ,sizeof(char*));
char *p = result; // point to the beginning of the array for returning
for( char *i = input; *i != '\0'; i++) {
if ( in(*i, p) == 0) {
// append i to result
*result=*i;
result++;
}
}
return p;
}
int main(void) {
char *one = "abc";
char *two = "abca";
char *three = "do androids dream of electric sheep?";
printf("Testing %s\n", one);
printf("%s\n", uniqueChars(one));
printf("Testing %s\n", two);
printf("%s\n", uniqueChars(two));
printf("Testing %s\n", three);
printf("%s\n", uniqueChars(three));
}
#!/usr/bin/env python
def uniqueChars(input):
result = ""
for char in input:
if not char in result:
result += char
return result
one = "abc"
two = "abca"
three = "do androids dream of electric sheep?"
print( uniqueChars(one))
print( uniqueChars(two))
print( uniqueChars(three))
#!/usr/bin/env xcrun swift
func uniqueChars(input: String) -> String{
return reduce(input, ""){
return $0 + ( contains($0,$1) ? "" : String($1) )
}
}
let one = "abc"
let two = "abca"
let three = "do androids dream of electric sheep?"
println( uniqueChars(one) )
println( uniqueChars(two) )
println( uniqueChars(three) )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment