1 /* 2 * Copyright (C) 2024 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.android.ondevicepersonalization.services.util; 18 19 import com.android.ondevicepersonalization.internal.util.LoggerFactory; 20 import com.android.ondevicepersonalization.services.FlagsFactory; 21 22 import java.util.concurrent.ThreadLocalRandom; 23 24 /** Util class for adding noise to returned result. */ 25 public class NoiseUtil { 26 private static final LoggerFactory.Logger sLogger = LoggerFactory.getLogger(); 27 private static final String TAG = NoiseUtil.class.getSimpleName(); 28 29 /** 30 * Add noise to {@link OnDevicePersonalizationManager#executeInIsolatedService} with best value 31 * option. 32 */ applyNoiseToBestValue(int actualValue, int maxValue, ThreadLocalRandom random)33 public int applyNoiseToBestValue(int actualValue, int maxValue, ThreadLocalRandom random) { 34 if (actualValue < 0 || actualValue > maxValue) { 35 sLogger.e( 36 TAG + ": returned int value %d is not in the range [0, %d].", 37 actualValue, 38 maxValue); 39 return -1; 40 } 41 int noisedValue = actualValue; 42 boolean shouldSelectRandomValue = 43 random.nextDouble() < FlagsFactory.getFlags().getNoiseForExecuteBestValue(); 44 if (shouldSelectRandomValue) { 45 while (noisedValue == actualValue) { 46 noisedValue = random.nextInt(maxValue); 47 } 48 } 49 return noisedValue; 50 } 51 } 52