Compare a list of strings: Difference between revisions

→‎{{header|R}}: Shorter and simpler
(→‎{{header|R}}: Shorter and simpler)
Line 2,520:
=={{header|R}}==
 
We can test, first, whether all elements of vector `strings` are equal to the first element; and, second, whether the sorted order of the vector is equal to the original vector.
Let's start with a function that splits a vector into
sub-vectors; it starts a new vector whenever the comparison
function yields false.
 
<syntaxhighlight lang="r">
all(strings == strings[1])
chunks <- function (compare, xs) {
all(strings == sort(strings))
starts = which(c(T, !compare(head(xs, -1), xs[-1]), T))
lapply(seq(1,length(starts)-1),
function(i) xs[starts[i]:(starts[i+1]-1)] )
</syntaxhighlight>
 
Line 2,535 ⟶ 2,530:
 
<syntaxhighlight lang="r">
manyStrings=list(
> chunks(`<`, c(0,4,8,1,3,5,7,9))
"a",
[[1]]
c("a", "b", "c"),
[1] 0 4 8
c("a", "c", "b"),
c("A", "A"),
c("a", "A"),
c(123, "A", "Aaron", "beryllium", "z"),
c(123, "A", "z", "Aaron", "beryllium", "z")
)
 
for (strings in manyStrings) {
[[2]]
print(strings)
[1] 1 3 5 7 9
print(all(strings == strings[1]))
print(all(strings == sort(strings)))
</syntaxhighlight>
 
Result:
R displays the results in a very prolix manner, so let's simplify it.
</syntaxhighlight>
 
"a"
<syntaxhighlight lang="r">
[1] TRUE
> toString(chunks(`<`, c(0,4,8,1,3,5,7,9,-2,0,88)))
[1] TRUE
[1] "c(0, 4, 8), c(1, 3, 5, 7, 9), c(-2, 0, 88)"
"a" "b" "c"
> toString(chunks(`==`, c(0,0,0,5,5,8)))
[1] FALSE
[1] "c(0, 0, 0), c(5, 5), 8"
[1] TRUE
"a" "c" "b"
[1] FALSE
[1] FALSE
"A" "A"
[1] TRUE
TRUE
"a" "A"
FALSE
TRUE
"123" "A" "Aaron" "beryllium" "z"
FALSE
TRUE
"123" "A" "z" "Aaron" "beryllium" "z"
FALSE
FALSE
</syntaxhighlight>
 
For `NULL` input returns `TRUE` to both tests, for all missing (`NA`) input returns `NA` to first test, `TRUE` to second.
Defining the required functions:
 
<syntaxhighlight lang="r">
all.eq <- function(xs) 1 == length( chunks(`==`, xs))
ascending <- function(xs) 1 == length( chunks(`<`, xs))
</syntaxhighlight>
 
Testing:
 
<syntaxhighlight lang="r">
> all.eq(c('by'))
[1] TRUE
> all.eq(c('by','by','by'))
[1] TRUE
> all.eq(c('by','by','by','zoo'))
[1] FALSE
> ascending(c("at", "even", "once", "run", "zoo"))
[1] TRUE
> ascending(c("at", "even", "once", "run", "zoo", "we"))
[1] FALSE
> ascending(c("at", "even", "go", "go"))
[1] FALSE
> ascending(c("at"))
[1] TRUE
</syntaxhighlight>
 
=={{header|Racket}}==
1

edit