001 /*
002 * Java Genetic Algorithm Library (jenetics-7.1.1).
003 * Copyright (c) 2007-2022 Franz Wilhelmstötter
004 *
005 * Licensed under the Apache License, Version 2.0 (the "License");
006 * you may not use this file except in compliance with the License.
007 * You may obtain a copy of the License at
008 *
009 * http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 *
017 * Author:
018 * Franz Wilhelmstötter (franz.wilhelmstoetter@gmail.com)
019 */
020 package io.jenetics.prog.regression;
021
022 import static java.lang.String.format;
023 import static java.util.Objects.requireNonNull;
024
025 import java.io.Serial;
026 import java.io.Serializable;
027 import java.util.Arrays;
028
029 /**
030 * @author <a href="mailto:franz.wilhelmstoetter@gmail.com">Franz Wilhelmstötter</a>
031 * @version 5.0
032 * @since 5.0
033 */
034 final class ObjectSample<T> implements Sample<T>, Serializable {
035
036 @Serial
037 private static final long serialVersionUID = 1L;
038
039 private final T[] _sample;
040
041 /**
042 * Create a new sample point with the given argument array and result value.
043 *
044 * @param sample the arguments of the sample point
045 * @throws IllegalArgumentException if the argument array is empty
046 * @throws NullPointerException if the argument array is {@code null}
047 */
048 @SafeVarargs
049 ObjectSample(final T... sample) {
050 if (sample.length < 2) {
051 throw new IllegalArgumentException(format(
052 "Argument sample must contain at least two values: %s",
053 sample.length
054 ));
055 }
056
057 _sample = requireNonNull(sample);
058 }
059
060 @Override
061 public int arity() {
062 return _sample.length - 1;
063 }
064
065 @Override
066 public T argAt(final int index) {
067 if (index < 0 || index >= arity()) {
068 throw new ArrayIndexOutOfBoundsException(format(
069 "Argument index out or range [0, %s): %s", arity(), index
070 ));
071 }
072
073 return _sample[index];
074 }
075
076 public T[] args() {
077 return Arrays.copyOfRange(_sample, 0, _sample.length - 1);
078 }
079
080 @Override
081 public T result() {
082 return _sample[_sample.length - 1];
083 }
084
085 @Override
086 public int hashCode() {
087 return Arrays.hashCode(_sample);
088 }
089
090 @Override
091 public boolean equals(final Object obj) {
092 return obj == this ||
093 obj instanceof ObjectSample<?> other &&
094 Arrays.equals(_sample, other._sample);
095 }
096
097 @Override
098 public String toString() {
099 return format("%s -> %s", Arrays.toString(args()), result());
100 }
101
102 }
|